diff --git a/backend/api/history.py b/backend/api/history.py index fbdddac..3b343cf 100644 --- a/backend/api/history.py +++ b/backend/api/history.py @@ -3,6 +3,8 @@ from datetime import datetime from fastapi import Depends, HTTPException, Query from backend.storage.history import HistoryFilters +from backend.storage.scalable import cursor_page, stream_export +from fastapi.responses import StreamingResponse def history_filters( @@ -23,6 +25,23 @@ def history_filters( def install_history(app, scoped_store): + @app.get("/api/history/cursor") + def cursor_history(filters=Depends(history_filters), cursor: str | None = Query(None, max_length=2048), + page_size: int = Query(50, ge=1, le=200), store=Depends(scoped_store)): + try: + return cursor_page(store, filters, cursor, page_size) + except ValueError as error: + raise HTTPException(422, str(error)) from None + + @app.get("/api/history/export") + def streaming_export(filters=Depends(history_filters), store=Depends(scoped_store)): + return StreamingResponse(stream_export(store, filters), media_type="application/json", + headers={"Content-Disposition": 'attachment; filename="tokenscope-history.json"'}) + + @app.get("/api/history/analysis") + def full_analysis(filters=Depends(history_filters), store=Depends(scoped_store)): + return store.history(filters, 1, 1)["analytics"] + @app.get("/api/history") def history( filters=Depends(history_filters), diff --git a/backend/storage/scalable.py b/backend/storage/scalable.py new file mode 100644 index 0000000..453f347 --- /dev/null +++ b/backend/storage/scalable.py @@ -0,0 +1,137 @@ +"""Bounded history retrieval and SQLite aggregate queries for retained archives.""" +import base64 +import hashlib +import json +import sqlite3 +from pathlib import Path + + +def _fingerprint(filters): + return hashlib.sha256(json.dumps(filters.public(), sort_keys=True).encode()).hexdigest() + + +def _prepare(store): + with store.lock, store.db: + if getattr(store, '_history_indexes_ready', False): + return + columns = {r[1] for r in store.db.execute('PRAGMA table_info(events)')} + if 'history_seq' not in columns: + store.db.execute('ALTER TABLE events ADD COLUMN history_seq INTEGER') + store.db.execute('UPDATE events SET history_seq=rowid WHERE history_seq IS NULL') + store.db.execute('CREATE TABLE IF NOT EXISTS history_sequence (singleton INTEGER PRIMARY KEY CHECK(singleton=1), value INTEGER NOT NULL)') + store.db.execute('INSERT OR IGNORE INTO history_sequence SELECT 1,COALESCE(MAX(history_seq),0) FROM events') + store.db.executescript(""" + CREATE TRIGGER IF NOT EXISTS history_arrival AFTER INSERT ON events BEGIN + UPDATE history_sequence SET value=value+1 WHERE singleton=1; + UPDATE events SET history_seq=(SELECT value FROM history_sequence WHERE singleton=1) WHERE id=NEW.id; + END; + CREATE TRIGGER IF NOT EXISTS history_revision AFTER UPDATE OF payload ON events BEGIN + UPDATE history_sequence SET value=value+1 WHERE singleton=1; + UPDATE events SET history_seq=(SELECT value FROM history_sequence WHERE singleton=1) WHERE id=NEW.id; + END; + """) + for field in ('provider', 'model', 'project', 'device_id', 'request_id', 'tool'): + store.db.execute(f"CREATE INDEX IF NOT EXISTS history_{field} ON events(json_extract(payload,'$.{field}'),occurred_us DESC,id DESC)") + store._history_indexes_ready = True + + +def _connection(store): + _prepare(store) + with store.lock: + path = store.db.execute('PRAGMA database_list').fetchone()[2] + if not path: + raise ValueError('History streaming requires a persistent ledger') + db = sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True, check_same_thread=False) + db.execute('BEGIN') + return db + + +def _where(filters, watermark, position=None): + where, args = filters.sql() + where += (' AND ' if where else ' WHERE ') + 'history_seq<=?' + args.append(watermark) + if position is not None: + where += ' AND (occurred_us,id)<(?,?)' + args.extend(position) + return where, args + + +def sql_summary(db, where, args): + """Match analytics.summarize accounting without materializing event payloads.""" + def field(name, fallback='0'): + return f"COALESCE(json_extract(payload,'$.{name}'),{fallback})" + reads, writes, reasoning = [field(k) for k in ('cache_read_tokens', 'cache_creation_tokens', 'reasoning_tokens')] + inputs = f"({field('input_tokens')} + CASE WHEN {field('input_includes_cache','1')}=0 THEN {reads}+{writes} ELSE 0 END)" + outputs = f"({field('output_tokens')} + CASE WHEN {field('output_includes_reasoning','1')}=0 THEN {reasoning} ELSE 0 END)" + invalid = f'({reads}+{writes}>{inputs} OR {reasoning}>{outputs})' + sums = {'total_tokens':field('total_tokens'), 'input_total_tokens':inputs, + 'uncached_input_tokens':f'max(0,{inputs}-{reads}-{writes})', 'cache_read_tokens':reads, + 'cache_creation_tokens':writes, 'output_total_tokens':outputs, 'reasoning_tokens':reasoning, + 'invalid_decomposition_requests':invalid, + 'provider_total_residual_tokens':f"{field('total_tokens')}-{inputs}-{outputs}"} + expressions = ['COUNT(*) AS requests'] + [f'COALESCE(SUM({v}),0) AS {k}' for k,v in sums.items()] + expressions += ["SUM(json_extract(payload,'$.cost_usd')) AS known_cost_usd", + "SUM(json_extract(payload,'$.billed_cost_usd')) AS billed_cost_usd", + "COUNT(json_extract(payload,'$.cost_usd')) AS priced_requests"] + usage_where = where + (' AND ' if where else ' WHERE ') + "json_extract(payload,'$.kind')='usage'" + cursor = db.execute('SELECT '+','.join(expressions)+' FROM events'+usage_where, args) + result = dict(zip([c[0] for c in cursor.description], cursor.fetchone())) + result['unpriced_requests'] = result['requests']-result['priced_requests'] + result['cache_read_ratio'] = result['cache_read_tokens']/result['input_total_tokens'] if result['input_total_tokens'] and not result['invalid_decomposition_requests'] else None + result['reasoning_output_ratio'] = result['reasoning_tokens']/result['output_total_tokens'] if result['output_total_tokens'] and not result['invalid_decomposition_requests'] else None + return result + + +def cursor_page(store, filters, cursor=None, page_size=50): + if not 1 <= page_size <= 200: + raise ValueError('Invalid page size') + state = None + if cursor: + try: + if len(cursor)>2048: + raise ValueError() + state=json.loads(base64.urlsafe_b64decode(cursor.encode())) + if (not isinstance(state.get('position'), list) or len(state['position']) != 2 + or state['filter'] != _fingerprint(filters) or type(state['watermark']) is not int + or not 0 <= state['watermark'] <= 2**63-1 or type(state['position'][0]) is not int + or not -(2**63) <= state['position'][0] <= 2**63-1 + or not isinstance(state['position'][1],str) or len(state['position'][1])>256): + raise ValueError() + except (ValueError, KeyError, TypeError, IndexError, AttributeError): + raise ValueError('Invalid cursor or changed filters; restart history') from None + db=_connection(store) + try: + watermark = state['watermark'] if state else db.execute('SELECT value FROM history_sequence WHERE singleton=1').fetchone()[0] + where,args=_where(filters,watermark) + total=db.execute('SELECT COUNT(*) FROM events'+where,args).fetchone()[0] + totals=sql_summary(db,where,args) + page_where,page_args=_where(filters,watermark,state['position'] if state else None) + rows=db.execute('SELECT occurred_us,id,payload FROM events'+page_where+' ORDER BY occurred_us DESC,id DESC LIMIT ?',[*page_args,page_size+1]).fetchall() + next_cursor=None + if len(rows)>page_size: + last=rows[page_size-1] + next_cursor=base64.urlsafe_b64encode(json.dumps({'filter':_fingerprint(filters),'watermark':watermark,'position':[last[0],last[1]]}).encode()).decode() + return {'items':[json.loads(r[2]) for r in rows[:page_size]],'total_items':total, + 'totals':totals,'next_cursor':next_cursor,'page_size':page_size,'filters':filters.public()} + finally: + db.close() + + +def stream_export(store, filters): + """One consistent read snapshot; close on completion or consumer cancellation.""" + db=_connection(store) + try: + where,args=filters.sql() + cursor=db.execute('SELECT payload FROM events'+where+' ORDER BY occurred_us,id',args) + yield '{"schema_version":1,"filters":'+json.dumps(filters.public())+',"events":[' + first=True + while True: + rows=cursor.fetchmany(256) + if not rows: + break + for row in rows: + yield ('' if first else ',')+row[0] + first=False + yield ']}' + finally: + db.close() diff --git a/docs/history-scaling.md b/docs/history-scaling.md new file mode 100644 index 0000000..06b3a2e --- /dev/null +++ b/docs/history-scaling.md @@ -0,0 +1,13 @@ +# Large retained archives + +The history dashboard uses `GET /api/history/cursor` with the existing filters, optional opaque `cursor`, and `page_size` (1–200). It retrieves a bounded page in descending UTC microsecond timestamp/event-ID order. SQL aggregates calculate matching request totals using the same inclusive-cache/reasoning semantics as detailed analytics. Unpriced costs remain unavailable. Lifecycle events appear in the event list but are excluded from request totals. + +The first page establishes an arrival watermark. Subsequent pages exclude new arrivals, including backdated telemetry, so ingestion does not shift offset pages. Refresh starts a new window. A persistent monotonic arrival sequence also survives deletions and SQLite ROWID reuse. Corrections and deletions to existing records may remove them from that window: this is not a retained historical database snapshot. Filter changes require a fresh cursor. Cursors contain no credentials and cannot select another account; every query resolves the store from the authenticated account. Previous-page navigation retains cursor positions locally. + +Indexes support timestamp order and exact provider/model/tool/project/device/request filters. Initial index/sequence setup can take time on an existing large ledger and uses the store lock. Subsequent page responses avoid constructing full event or optimization-report lists. SQL aggregation still scans matching records; this is bounded Python memory, not constant database work. Free-text exact filter inputs avoid transferring an unbounded list of historical session identifiers. + +Detailed optimization analysis is an explicit **Run detailed filtered analysis** action using `/api/history/analysis`. It retains the existing full-history evidence analysis and can use substantial memory on large archives. It examines the current ledger, which may differ from a cursor browsing window. Individual request investigation remains available. + +`GET /api/history/export` streams the complete filtered JSON ledger using a separate read-only SQLite connection, one consistent read transaction, and batches of 256 rows. It never builds the full export in Python memory. Long downloads can retain WAL pages until their read snapshot closes; operators should monitor disk space. The browser downloads a Blob without parsing/re-serializing the JSON, but still holds the download bytes. For very large exports use an authenticated HTTP client and stream directly to disk. Export uses current retained history, independently of browsing cursors. Existing `/api/export` and offset `/api/history` remain compatibility endpoints; clients should migrate to the new routes for bounded retrieval. + +Validation includes SQL/reference accounting parity, 1,051-event tied timestamp traversal, concurrent backdated arrivals, deletion/ROWID reuse, malformed cursors, authenticated tenant isolation, date filtering, and consistent streamed snapshots without full-ledger helpers. Frontend tests cover cursor/filter encoding and UTC end-day semantics. No distributed-load or browser memory SLA is claimed. diff --git a/docs/history.md b/docs/history.md index a316de0..e885057 100644 --- a/docs/history.md +++ b/docs/history.md @@ -40,6 +40,6 @@ Account changes, logout, authorization expiry and filter/page changes clear stal ## Limits and verification -Date filtering and list pagination use SQLite queries/indexes; full filtered analytics and exports still materialize matching history in memory. Context-growth checks also consult the same account's unfiltered boundary timeline so filtering out a compaction/model-switch record cannot fabricate growth. Very large archives still require SQL aggregation, streaming exports and cursor pagination work; no distributed-load SLA is claimed. +The dashboard now uses cursor pagination, SQL aggregate totals and streamed exports; see [large archive behavior and limits](history-scaling.md). Detailed optimization analysis is an explicit action that still materializes matching history in memory. Context-growth checks consult the same account's unfiltered boundary timeline so filtering out a compaction/model-switch record cannot fabricate growth. Legacy offset endpoints remain available for compatibility; no distributed-load SLA is claimed. Synthetic tests cover more than 1,000 events, all exact filters, microsecond and timezone-offset boundaries, deterministic ties, empty pages, old/partially migrated ledgers, retention boundary precision, scoped totals/price provenance, duplicate evidence, all-matching exports, invalid query rejection and server account isolation. Frontend tests exercise UTC-day conversion, encoded filters, cancellation/generation guards and rendered evidence. Live vendor, remote proxy and browser-driven E2E remain separate deployment checks. diff --git a/frontend/src/HistoryPanel.tsx b/frontend/src/HistoryPanel.tsx index d71c1d5..d36abd2 100644 --- a/frontend/src/HistoryPanel.tsx +++ b/frontend/src/HistoryPanel.tsx @@ -1,8 +1,8 @@ import {useEffect,useRef,useState} from 'react'; import {ApiRequest,responseJson} from './api'; -import {AnalyticsPanel} from './AnalyticsPanel'; +import {AnalyticsPanel,AnalyticsReport} from './AnalyticsPanel'; import {UsageEvent,exactTokens,money} from './data'; -import {HistoryFilters,HistoryPage,LatestRequest,RelatedRequest,RequestDetail,emptyHistoryFilters,historyQuery} from './history'; +import {HistoryFilters,CursorHistoryPage,LatestRequest,RelatedRequest,RequestDetail,emptyHistoryFilters,historyQuery,historyCursorQuery} from './history'; const value=(n:unknown)=>n==null?'Unavailable':String(n); function Related({title,items,total,onSelect}:{title:string;items:RelatedRequest[];total?:number;onSelect:(id:string)=>void}){return

{title} Showing {items.length} of {total??items.length}

{items.length?:

No related evidence reported.

}
;} export function HistoryRequestDetail({detail,onClose,onSelect}:{detail:RequestDetail;onClose:()=>void;onSelect:(id:string)=>void}){ @@ -12,15 +12,17 @@ export function HistoryRequestDetail({detail,onClose,onSelect}:{detail:RequestDe } export function HistoryRows({items,onSelect}:{items:UsageEvent[];onSelect:(id:string)=>void}){return
{items.map(e=>)}
TIME / EVENTPROVIDER / MODELSESSION / DEVICEKINDTOTAL TOKENSEST. COST
{e.event_id}{e.provider}{e.model}{e.session_id}{value(e.device_id)}{value(e.kind)}{e.total_tokens==null?'Unavailable':exactTokens(e.total_tokens)}{money(e.cost_usd)}
{!items.length&&

No retained events match these filters.

}
;} export function HistoryPanel({request}:{request:ApiRequest}){ - const [draft,setDraft]=useState({...emptyHistoryFilters}),[filters,setFilters]=useState({...emptyHistoryFilters}),[page,setPage]=useState(1),[result,setResult]=useState(null),[error,setError]=useState(''),[loading,setLoading]=useState(false),[refresh,setRefresh]=useState(0),[selected,setSelected]=useState(null),[detail,setDetail]=useState(null),[detailError,setDetailError]=useState(''),[detailLoading,setDetailLoading]=useState(false),[exporting,setExporting]=useState(false); + const [draft,setDraft]=useState({...emptyHistoryFilters}),[filters,setFilters]=useState({...emptyHistoryFilters}),[cursors,setCursors]=useState<(string|null)[]>([null]),[result,setResult]=useState(null),[error,setError]=useState(''),[loading,setLoading]=useState(false),[refresh,setRefresh]=useState(0),[selected,setSelected]=useState(null),[detail,setDetail]=useState(null),[detailError,setDetailError]=useState(''),[detailLoading,setDetailLoading]=useState(false),[exporting,setExporting]=useState(false); + const page=cursors.length;const [analysis,setAnalysis]=useState(null),[analyzing,setAnalyzing]=useState(false);const analysisRequests=useRef(new LatestRequest()); const listRequests=useRef(new LatestRequest()),detailRequests=useRef(new LatestRequest()),exports=useRef(new LatestRequest()); - useEffect(()=>{const pending=listRequests.current.begin();setLoading(true);setError('');setResult(null);setSelected(null);setDetail(null);setDetailError('');setDetailLoading(false);detailRequests.current.cancel();exports.current.cancel();setExporting(false);let path:string;try{path='/api/history?'+historyQuery(filters,page);}catch(e){setError(e instanceof Error?e.message:'Invalid filters.');setLoading(false);return;} - request(path,{signal:pending.signal}).then(responseJson).then(data=>{if(pending.current())setResult(data);}).catch(e=>{if(pending.current()&&e.name!=='AbortError')setError(e.message);}).finally(()=>{if(pending.current())setLoading(false);});return()=>listRequests.current.cancel();},[request,filters,page,refresh]); + useEffect(()=>{const pending=listRequests.current.begin();setLoading(true);setError('');setResult(null);setAnalysis(null);setAnalyzing(false);analysisRequests.current.cancel();setSelected(null);setDetail(null);setDetailError('');setDetailLoading(false);detailRequests.current.cancel();exports.current.cancel();setExporting(false);let path:string;try{path='/api/history/cursor?'+historyCursorQuery(filters,cursors.at(-1));}catch(e){setError(e instanceof Error?e.message:'Invalid filters.');setLoading(false);return;} + request(path,{signal:pending.signal}).then(responseJson).then(data=>{if(pending.current())setResult(data);}).catch(e=>{if(pending.current()&&e.name!=='AbortError')setError(e.message);}).finally(()=>{if(pending.current())setLoading(false);});return()=>listRequests.current.cancel();},[request,filters,cursors,refresh]); useEffect(()=>{if(!selected)return;const pending=detailRequests.current.begin();setDetail(null);setDetailError('');setDetailLoading(true);request('/api/history/requests/'+encodeURIComponent(selected),{signal:pending.signal}).then(responseJson).then(data=>{if(pending.current())setDetail(data);}).catch(e=>{if(pending.current()&&e.name!=='AbortError')setDetailError(e.message);}).finally(()=>{if(pending.current())setDetailLoading(false);});return()=>detailRequests.current.cancel();},[request,selected]); - useEffect(()=>()=>{listRequests.current.cancel();detailRequests.current.cancel();exports.current.cancel();},[]); - async function exportMatches(){const pending=exports.current.begin();setExporting(true);setError('');try{const data=await responseJson<{schema_version:number;events:UsageEvent[];filters:Record}>(await request('/api/export?'+historyQuery(filters),{signal:pending.signal}));if(!pending.current())return;const url=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));const link=document.createElement('a');link.href=url;link.download='tokenscope-filtered-history.json';link.click();URL.revokeObjectURL(url);}catch(e){if(pending.current()&&!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Export failed.');}finally{if(pending.current())setExporting(false);}} - function cancelView(){listRequests.current.cancel();detailRequests.current.cancel();exports.current.cancel();setResult(null);setSelected(null);setDetail(null);setDetailError('');setDetailLoading(false);setExporting(false);} + useEffect(()=>()=>{listRequests.current.cancel();detailRequests.current.cancel();exports.current.cancel();analysisRequests.current.cancel();},[]); + async function exportMatches(){const pending=exports.current.begin();setExporting(true);setError('');try{const response=await request('/api/history/export?'+historyQuery(filters),{signal:pending.signal});if(!response.ok)throw Error('Export failed ('+response.status+').');const data=await response.blob();if(!pending.current())return;const url=URL.createObjectURL(data);const link=document.createElement('a');link.href=url;link.download='tokenscope-filtered-history.json';link.click();URL.revokeObjectURL(url);}catch(e){if(pending.current()&&!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Export failed.');}finally{if(pending.current())setExporting(false);}} + function cancelView(){listRequests.current.cancel();detailRequests.current.cancel();exports.current.cancel();setResult(null);setAnalysis(null);setAnalyzing(false);analysisRequests.current.cancel();setSelected(null);setDetail(null);setDetailError('');setDetailLoading(false);setExporting(false);} function selectEvent(id:string){if(id===selected)return;detailRequests.current.cancel();setDetail(null);setDetailError('');setDetailLoading(false);setSelected(id);} - const options=result?.options;const fields:[keyof HistoryFilters,string,string[]|undefined][]=[['provider','Provider',options?.providers],['model','Model',options?.models],['tool','Tool',options?.tools],['session_id','Session',options?.sessions],['project','Project',options?.projects],['device_id','Device',options?.devices]]; - return
FOLLOW THE EVIDENCE

Historical usage investigation

Search your full retained ledger, independently of overview filters. No prompt content is collected.

{e.preventDefault();try{historyQuery(draft);cancelView();setFilters({...draft});setPage(1);}catch(err){setError(err instanceof Error?err.message:'Invalid filters.');}}}>{fields.map(([key,label,values])=>)}
{error&&

{error}

}{loading&&

Loading retained history…

}{result&&<>

{exactTokens(result.total_items)} matching events

Newest first · page {result.page} of {Math.max(result.total_pages,1)}

Totals and analysis below include every filtered match, beyond the current page. Date boundaries use UTC; the selected final day is included.

{result.items.length} displayed · {result.page_size} per page
}{detailLoading&&

Loading request evidence…

}{detailError&&

Request details: {detailError}

}{detail&&{detailRequests.current.cancel();setSelected(null);setDetail(null);setDetailError('');setDetailLoading(false);}} onSelect={selectEvent}/>}
; + async function analyzeMatches(){const pending=analysisRequests.current.begin();setAnalyzing(true);try{const report=await responseJson(await request('/api/history/analysis?'+historyQuery(filters),{signal:pending.signal}));if(pending.current())setAnalysis(report);}catch(e){if(pending.current())setError(e instanceof Error?e.message:'Analysis failed.');}finally{if(pending.current())setAnalyzing(false);}} + const options:Record={};const fields:[keyof HistoryFilters,string,string[]|undefined][]=[['provider','Provider',options?.providers],['model','Model',options?.models],['tool','Tool',options?.tools],['session_id','Session',options?.sessions],['project','Project',options?.projects],['device_id','Device',options?.devices]]; + return
FOLLOW THE EVIDENCE

Historical usage investigation

Search your full retained ledger, independently of overview filters. No prompt content is collected.

{e.preventDefault();try{historyQuery(draft);cancelView();setFilters({...draft});setCursors([null]);}catch(err){setError(err instanceof Error?err.message:'Invalid filters.');}}}>{fields.map(([key,label,values])=>)}
{error&&

{error}

}{loading&&

Loading retained history…

}{result&&<>

{exactTokens(result.total_items)} matching events

Newest first · page {page}

Totals include all filtered matches in this browsing window. New arrivals appear after Refresh history. Date boundaries use UTC; the selected final day is included.

{result.items.length} displayed · {result.page_size} per page

All matching usage totals

Requests
{exactTokens(result.totals.requests)}
Total tokens
{exactTokens(result.totals.total_tokens)}
Known API-equivalent cost
{money(result.totals.known_cost_usd)}
Unpriced requests
{exactTokens(result.totals.unpriced_requests)}

Detailed optimization analysis scans current matching history and can take longer for large archives. Cursor totals use SQL aggregates; exported history reflects the current ledger.

{analysis&&}}{detailLoading&&

Loading request evidence…

}{detailError&&

Request details: {detailError}

}{detail&&{detailRequests.current.cancel();setSelected(null);setDetail(null);setDetailError('');setDetailLoading(false);}} onSelect={selectEvent}/>}
; } diff --git a/frontend/src/history.ts b/frontend/src/history.ts index 86984fd..9387bc3 100644 --- a/frontend/src/history.ts +++ b/frontend/src/history.ts @@ -27,3 +27,11 @@ export class LatestRequest { begin(){this.controller?.abort();const controller=new AbortController(),serial=++this.serial;this.controller=controller;return {signal:controller.signal,current:()=>this.serial===serial&&!controller.signal.aborted};} cancel(){this.serial++;this.controller?.abort();this.controller=null;} } + +export type CursorHistoryPage={items:UsageEvent[];page_size:number;total_items:number;totals:AnalyticsSummary;next_cursor:string|null;filters:Record}; + +export function historyCursorQuery(filters:HistoryFilters,cursor:string|null=null){ + const query=new URLSearchParams(historyQuery(filters)); + if(cursor)query.set('cursor',cursor); + return query.toString(); +} diff --git a/frontend/tests/history-cursor.test.ts b/frontend/tests/history-cursor.test.ts new file mode 100644 index 0000000..6642781 --- /dev/null +++ b/frontend/tests/history-cursor.test.ts @@ -0,0 +1,10 @@ +import {describe,it,expect} from 'vitest'; +import {emptyHistoryFilters,historyCursorQuery} from '../src/history'; +describe('cursor history queries',()=>{ + it('retains exact filters and encodes opaque cursors without offsets',()=>{ + const query=new URLSearchParams(historyCursorQuery({...emptyHistoryFilters,model:'model/a',end:'2026-11-15'},'opaque=+/')); + expect(query.get('cursor')).toBe('opaque=+/');expect(query.get('model')).toBe('model/a'); + expect(query.get('end')).toBe('2026-11-16T00:00:00.000Z');expect(query.has('page')).toBe(false); + }); + it('starts a new browsing window without a cursor',()=>{expect(historyCursorQuery(emptyHistoryFilters)).toBe('');}); +}); diff --git a/tests/test_scalable_history.py b/tests/test_scalable_history.py new file mode 100644 index 0000000..67abcd1 --- /dev/null +++ b/tests/test_scalable_history.py @@ -0,0 +1,141 @@ +import json +from datetime import datetime, timezone, timedelta + +import pytest +from fastapi.testclient import TestClient + +from backend.analytics.report import summarize +from backend.api.app import create_app +from backend.core.schema import UsageEvent +from backend.storage.history import HistoryFilters +from backend.storage.scalable import cursor_page, stream_export +from backend.storage.store import Store + +STAMP = datetime(2026, 11, 15, tzinfo=timezone.utc) + + +def event(i, **changes): + data = dict(event_id=f'e{i:05}', session_id='session', provider='openai', tool='codex', + timestamp=STAMP + timedelta(seconds=i // 3), model='model', input_tokens=100, + output_tokens=10, cache_read_tokens=20, reasoning_tokens=5) + data.update(changes) + return UsageEvent(**data) + + +def test_cursor_all_rows_with_ties_and_backdated_arrivals(tmp_path, monkeypatch): + store = Store(tmp_path / 'db') + for i in range(1051): + store.ingest(event(i)) + monkeypatch.setattr(store, 'filtered_events', lambda *a: pytest.fail('materialized history')) + first = cursor_page(store, HistoryFilters(), page_size=200) + ids = [e['event_id'] for e in first['items']] + # New arrivals, even backdated, must not shift or enter this browsing window. + store.ingest(event(2000, timestamp=STAMP)) + cursor = first['next_cursor'] + while cursor: + page = cursor_page(store, HistoryFilters(), cursor, 200) + assert page['total_items'] == 1051 + ids += [e['event_id'] for e in page['items']] + cursor = page['next_cursor'] + assert len(ids) == len(set(ids)) == 1051 + assert cursor_page(store, HistoryFilters())['total_items'] == 1052 + store.close() + + +def test_sql_summary_matches_accounting_reference(tmp_path): + store = Store(tmp_path / 'db') + store.ingest(event(1)) + store.ingest(event(2, input_includes_cache=False, output_includes_reasoning=False, billed_cost_usd=0.2)) + store.ingest(event(3, input_tokens=1, output_tokens=1)) + store.ingest(event(4, kind='completed')) + rows = store.events() + expected = summarize([e for e in rows if e['kind'] == 'usage']) + assert cursor_page(store, HistoryFilters())['totals'] == expected + assert cursor_page(store, HistoryFilters(model='absent'))['totals'] == summarize([]) + store.close() + + +def test_cursor_validation_filters_and_delete_rowid_reuse(tmp_path): + store = Store(tmp_path / 'db') + for i in range(4): + store.ingest(event(i)) + page = cursor_page(store, HistoryFilters(), page_size=1) + store.delete(session_id='session') + store.ingest(event(10, timestamp=STAMP)) + assert cursor_page(store, HistoryFilters(), page['next_cursor'])['items'] == [] + with pytest.raises(ValueError): + cursor_page(store, HistoryFilters(model='different'), page['next_cursor']) + with pytest.raises(ValueError): + cursor_page(store, HistoryFilters(), 'garbage') + store.close() + + +def test_stream_snapshot_bounded_chunks_and_close(tmp_path, monkeypatch): + store = Store(tmp_path / 'db') + for i in range(1051): + store.ingest(event(i)) + monkeypatch.setattr(store, 'filtered_events', lambda *a: pytest.fail('materialized export')) + stream = stream_export(store, HistoryFilters()) + prefix = next(stream) + store.ingest(event(2000)) + chunks = list(stream) + result = json.loads(prefix + ''.join(chunks)) + assert len(result['events']) == 1051 + assert max(map(len, chunks)) < 5000 + # Cancelling a consumer releases its read transaction. + stream = stream_export(store, HistoryFilters()) + next(stream) + stream.close() + store.db.execute('PRAGMA wal_checkpoint(TRUNCATE)') + store.close() + + +class Empty: + def poll(self): + return [] + + +def test_cursor_export_auth_and_dates(tmp_path): + app = create_app(tmp_path, scanner=Empty(), token='secret') + with TestClient(app) as client: + headers = {'Authorization': 'Bearer secret'} + assert client.get('/api/history/cursor').status_code == 401 + assert client.get('/api/history/export').status_code == 401 + for i in range(5): + assert client.post('/api/events', headers=headers, json=event(i).model_dump(mode='json')).status_code == 200 + params = {'start': STAMP.isoformat(), 'end': (STAMP+timedelta(seconds=1)).isoformat()} + page = client.get('/api/history/cursor', params=params, headers=headers).json() + exported = client.get('/api/history/export', params=params, headers=headers) + assert page['total_items'] == len(exported.json()['events']) == 3 + assert 'attachment' in exported.headers['content-disposition'] + assert client.get('/api/history/cursor?cursor=garbage', headers=headers).status_code == 422 + + +def test_server_cursor_and_stream_remain_tenant_scoped(tmp_path): + from backend.server.app import create_server_app + origin = 'https://testserver' + app = create_server_app(tmp_path, origin) + alice = app.state.auth.create_user('alice', 'test-password-one!') + bob = app.state.auth.create_user('bob', 'test-password-two!') + app.state.tenants.ledger(alice['id']).ingest(event(1)) + app.state.tenants.ledger(bob['id']).ingest(event(2, model='private-bob')) + with TestClient(app, base_url=origin, headers={'Origin': origin}) as client: + assert client.post('/api/auth/login', json={'username':'alice','password':'test-password-one!'}).status_code == 200 + page = client.get('/api/history/cursor').json() + exported = client.get('/api/history/export').json() + assert page['total_items'] == 1 + assert exported['events'][0]['model'] == 'model' + assert client.get('/api/history/cursor?model=private-bob').json()['total_items'] == 0 + assert client.get('/api/history/requests/e00002').status_code == 404 + +def test_cursor_rejects_extra_position_fields(tmp_path): + import base64 + import json + from backend.storage.scalable import _fingerprint + store = Store(tmp_path/'bad-cursor.db') + filters = HistoryFilters() + value = dict(filter=_fingerprint(filters), watermark=0, position=[0,'id','extra']) + cursor = base64.urlsafe_b64encode(json.dumps(value).encode()).decode() + with pytest.raises(ValueError): + cursor_page(store, filters, cursor) + store.close()