import { describe, expect, it } from 'bun:test'; import { type BarBatch, type BarRecord, DEFAULT_QUESTDB_BARS_BATCH_SIZE, MarketDataStoreNotImplementedError, MarketDataStoreValidationError, type QuestDbBars1mQuery, type QuestDbQueryExecutor, VaultHoldoutFenceError, VaultScopeNotAuthorizedError, createQuestDbIntradayBarsReader, planBars1mQuery, } from '@stock-bot/research'; interface RecordedCall { readonly sql: string; readonly params: readonly unknown[]; } class RecordingQuestDbExecutor implements QuestDbQueryExecutor { readonly calls: RecordedCall[] = []; private nextResult: { readonly rows: readonly Record[] } = { rows: [] }; setRows(rows: readonly Record[]): void { this.nextResult = { rows }; } setRawResult(result: unknown): void { this.nextResult = result as { readonly rows: readonly Record[] }; } async query( sql: string, params: readonly unknown[] ): Promise<{ readonly rows: readonly Record[] }> { this.calls.push({ sql, params: [...params] }); return this.nextResult; } } async function collectBatches(iterable: AsyncIterable): Promise { const batches: BarBatch[] = []; for await (const batch of iterable) { batches.push(batch); } return batches; } const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z describe('planBars1mQuery', () => { it('snapshots exact parameterized SQL and bound params for a 1-listing, 1-year query', () => { const query: QuestDbBars1mQuery = { listingIds: [42], timeframe: '1m', from: '2024-01-02', to: '2024-12-31', adjustment: 'raw', asOf: '2025-01-01T00:00:00Z', }; const planned = planBars1mQuery(query, { vaultCutoffTs: VAULT_CUTOFF_TS }); expect(planned.sql).toBe( 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + 'FROM bars_1m ' + 'WHERE ts >= $1 AND ts <= $2 AND listing_id IN ($3) AND known_at <= $4 ' + 'ORDER BY ts, listing_id' ); expect(planned.params).toEqual([ '2024-01-02T00:00:00.000Z', '2024-12-31T23:59:59.999Z', '42', '2025-01-01T00:00:00.000Z', ]); expect(planned.fence).toEqual({ fromMs: Date.UTC(2024, 0, 2, 0, 0, 0, 0), toMs: Date.UTC(2024, 11, 31, 23, 59, 59, 999), asOfMs: Date.UTC(2025, 0, 1, 0, 0, 0, 0), scope: 'vault_fenced', clampedTo: false, clampedAsOf: false, }); // No caller-supplied values appear in SQL text. for (const boundValue of planned.params) { expect(planned.sql).not.toContain(boundValue); } expect(planned.sql).not.toContain('42'); expect(planned.sql).not.toContain('2024'); expect(planned.sql).not.toContain('2025'); }); it('deduplicates and sorts multi-listing IDs numerically without mutating caller input', () => { const callerListingIds = [100, 2, 10, 2, 1]; const snapshotBefore = [...callerListingIds]; const planned = planBars1mQuery( { listingIds: callerListingIds, timeframe: '1m', from: '2024-06-03T13:30:00Z', to: '2024-06-03T20:00:00Z', adjustment: 'raw', asOf: '2024-06-04T00:00:00Z', }, { vaultCutoffTs: VAULT_CUTOFF_TS } ); expect(callerListingIds).toEqual(snapshotBefore); expect(planned.sql).toBe( 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + 'FROM bars_1m ' + 'WHERE ts >= $1 AND ts <= $2 AND listing_id IN ($3, $4, $5, $6) AND known_at <= $7 ' + 'ORDER BY ts, listing_id' ); expect(planned.params).toEqual([ '2024-06-03T13:30:00.000Z', '2024-06-03T20:00:00.000Z', '1', '2', '10', '100', '2024-06-04T00:00:00.000Z', ]); }); it('port is structurally compatible with QuestDBClient.query generic signature', async () => { class QuestDbClientLike { readonly calls: RecordedCall[] = []; async query>( sql: string, params?: unknown[] ): Promise<{ rows: T[]; rowCount: number; executionTime: number; }> { this.calls.push({ sql, params: params ? [...params] : [] }); return { rows: [], rowCount: 0, executionTime: 1 }; } } const clientLike = new QuestDbClientLike(); const executorPort: QuestDbQueryExecutor = clientLike; const reader = createQuestDbIntradayBarsReader({ executor: executorPort, vaultCutoffTs: VAULT_CUTOFF_TS, }); const batches = await collectBatches( reader.bars({ listingIds: [7], timeframe: '1m', from: '2024-05-01T13:30:00Z', to: '2024-05-01T13:35:00Z', adjustment: 'raw', }) ); expect(batches).toEqual([]); expect(clientLike.calls).toHaveLength(1); }); }); describe('Vault fence enforcement', () => { it('rejects from at or past cutoff with VaultHoldoutFenceError and zero executor calls', async () => { const executor = new RecordingQuestDbExecutor(); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, }); await expect( collectBatches( reader.bars({ listingIds: [1], timeframe: '1m', from: '2025-07-01T00:00:00.000Z', to: '2025-07-02T00:00:00.000Z', adjustment: 'raw', }) ) ).rejects.toThrow(VaultHoldoutFenceError); await expect( collectBatches( reader.bars({ listingIds: [1], timeframe: '1m', from: '2025-07-15', to: '2025-08-01', adjustment: 'raw', }) ) ).rejects.toThrow(VaultHoldoutFenceError); expect(executor.calls).toHaveLength(0); }); it('clamps to and asOf past cutoff and defaults omitted asOf to cutoff - 1ms', () => { const clampedPlan = planBars1mQuery( { listingIds: [9], timeframe: '1m', from: '2025-06-01', to: '2025-09-01', asOf: '2025-09-02', adjustment: 'raw', }, { vaultCutoffTs: VAULT_CUTOFF_TS } ); expect(clampedPlan.fence.clampedTo).toBe(true); expect(clampedPlan.fence.clampedAsOf).toBe(true); expect(clampedPlan.fence.toMs).toBe(VAULT_CUTOFF_TS - 1); expect(clampedPlan.fence.asOfMs).toBe(VAULT_CUTOFF_TS - 1); expect(clampedPlan.params).toEqual([ '2025-06-01T00:00:00.000Z', '2025-06-30T23:59:59.999Z', '9', '2025-06-30T23:59:59.999Z', ]); const omittedAsOfPlan = planBars1mQuery( { listingIds: [9], timeframe: '1m', from: '2025-06-01', to: '2025-06-15', adjustment: 'raw', }, { vaultCutoffTs: VAULT_CUTOFF_TS } ); expect(omittedAsOfPlan.fence.clampedTo).toBe(false); expect(omittedAsOfPlan.fence.clampedAsOf).toBe(false); expect(omittedAsOfPlan.fence.asOfMs).toBe(VAULT_CUTOFF_TS - 1); expect(omittedAsOfPlan.params[3]).toBe('2025-06-30T23:59:59.999Z'); }); it('rejects unauthorized vault_evaluation_only even if caller attaches authorization flag on query', async () => { const executor = new RecordingQuestDbExecutor(); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, }); const spoofedQuery = { listingIds: [1], timeframe: '1m', from: '2025-07-01', to: '2025-07-10', adjustment: 'raw', scope: 'vault_evaluation_only', vaultOperatorAuthorized: true, } as unknown as QuestDbBars1mQuery; await expect(collectBatches(reader.bars(spoofedQuery))).rejects.toThrow( VaultScopeNotAuthorizedError ); expect(executor.calls).toHaveLength(0); }); it('permits vault_evaluation_only when trusted factory context is operator-authorized', async () => { const executor = new RecordingQuestDbExecutor(); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, vaultOperatorAuthorized: true, }); const batches = await collectBatches( reader.bars({ listingIds: [5], timeframe: '1m', from: '2025-07-02T13:30:00Z', to: '2025-07-02T13:31:00Z', adjustment: 'raw', scope: 'vault_evaluation_only', }) ); expect(batches).toEqual([]); expect(executor.calls).toHaveLength(1); expect(executor.calls[0]?.params).toEqual([ '2025-07-02T13:30:00.000Z', '2025-07-02T13:31:00.000Z', '5', '2025-07-02T13:31:00.000Z', ]); }); }); describe('Input validation and injection rejection', () => { it('rejects split and total adjustments with MarketDataStoreNotImplementedError and zero executor calls', async () => { const executor = new RecordingQuestDbExecutor(); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, }); for (const adjustment of ['split', 'total'] as const) { await expect( collectBatches( reader.bars({ listingIds: [1], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment, }) ) ).rejects.toThrow(MarketDataStoreNotImplementedError); } expect(executor.calls).toHaveLength(0); }); it('rejects invalid timeframe, adjustment, dates, listingIds, and SQL injection before any executor call', async () => { const executor = new RecordingQuestDbExecutor(); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, }); const invalidQueries: unknown[] = [ // Wrong timeframes { listingIds: [1], timeframe: '1d', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, { listingIds: [1], timeframe: '5m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, { listingIds: [1], timeframe: '1h', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, // Invalid adjustment { listingIds: [1], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'dividend', }, // Reversed or invalid dates { listingIds: [1], timeframe: '1m', from: '2024-02-01', to: '2024-01-01', adjustment: 'raw' }, { listingIds: [1], timeframe: '1m', from: '2024-01-02T13:30:00', to: '2024-01-03T13:30:00Z', adjustment: 'raw', }, { listingIds: [1], timeframe: '1m', from: 'not-a-date', to: '2024-01-03', adjustment: 'raw' }, // Invalid listingIds { listingIds: [], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, { listingIds: [0], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, { listingIds: [-5], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw', }, { listingIds: [2_147_483_648], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw', }, { listingIds: [1.5], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw', }, { listingIds: [Number.NaN], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw', }, // SQL injection attempt cast through unknown { listingIds: ['1; DROP TABLE bars_1m'], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw', }, ]; for (const badQuery of invalidQueries) { await expect(collectBatches(reader.bars(badQuery as QuestDbBars1mQuery))).rejects.toThrow( MarketDataStoreValidationError ); } expect(executor.calls).toHaveLength(0); }); it('rejects invalid factory options (executor, vaultCutoffTs, batchSize)', () => { const executor = new RecordingQuestDbExecutor(); expect(() => createQuestDbIntradayBarsReader({ executor: {} as unknown as QuestDbQueryExecutor, vaultCutoffTs: VAULT_CUTOFF_TS, }) ).toThrow(MarketDataStoreValidationError); expect(() => createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: Number.NaN, }) ).toThrow(MarketDataStoreValidationError); for (const badBatchSize of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, null]) { expect(() => createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, batchSize: badBatchSize as unknown as number, }) ).toThrow(MarketDataStoreValidationError); } }); }); describe('1-year single-listing replay, row mapping, and batching', () => { it('streams 98,280 synthetic 1m rows (252 sessions x 390 min) in exact order across default 50k batches', async () => { expect(DEFAULT_QUESTDB_BARS_BATCH_SIZE).toBe(50_000); const sessions = 252; const minutesPerSession = 390; const totalRows = sessions * minutesPerSession; // 98,280 const listingId = 101; const listingIdSymbol = String(listingId); const baseSessionStartMs = Date.UTC(2024, 0, 2, 14, 30, 0, 0); const msPerDay = 86_400_000; const msPerMinute = 60_000; const rawRows: Record[] = new Array(totalRows); const expected: BarRecord[] = new Array(totalRows); let idx = 0; for (let s = 0; s < sessions; s += 1) { const sessionStartMs = baseSessionStartMs + s * msPerDay; for (let m = 0; m < minutesPerSession; m += 1) { const tsMs = sessionStartMs + m * msPerMinute; const knownAtMs = tsMs + msPerMinute; const tsUs = BigInt(tsMs) * 1000n; const knownAtUs = BigInt(knownAtMs) * 1000n; const open = 100 + s * 0.25 + m * 0.01; const high = open + 0.15; const low = open - 0.1; const close = open + 0.05; const volume = 1_000 + ((s * 390 + m) % 500); const vwap = m % 10 === 0 ? null : open + 0.02; // Exercise all three supported LONG wire representations: decimal string, bigint, safe int. const tsWire: unknown = idx % 3 === 0 ? tsUs.toString() : idx % 3 === 1 ? tsUs : Number(tsUs); const knownAtWire: unknown = idx % 3 === 0 ? knownAtUs.toString() : idx % 3 === 1 ? knownAtUs : Number(knownAtUs); rawRows[idx] = { listing_id: listingIdSymbol, ts_us: tsWire, open, high, low, close, volume, vwap, known_at_us: knownAtWire, }; expected[idx] = { listingId, ts: tsMs, open, high, low, close, volume, vwap, knownAt: knownAtMs, }; idx += 1; } } const executor = new RecordingQuestDbExecutor(); executor.setRows(rawRows); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, }); const query: QuestDbBars1mQuery = { listingIds: [listingId], timeframe: '1m', from: '2024-01-02', to: '2024-12-31', asOf: '2025-01-01T00:00:00Z', adjustment: 'raw', }; const run1Batches = await collectBatches(reader.bars(query)); const run2Batches = await collectBatches(reader.bars(query)); expect(executor.calls).toHaveLength(2); expect(run1Batches.map(b => b.rows.length)).toEqual([50_000, 48_280]); expect(run2Batches.map(b => b.rows.length)).toEqual([50_000, 48_280]); const flat1 = run1Batches.flatMap(b => b.rows); const flat2 = run2Batches.flatMap(b => b.rows); expect(flat1).toHaveLength(totalRows); expect(flat1).toEqual(expected); expect(flat2).toEqual(flat1); }); it('supports custom small batch sizes and yields zero batches for empty results', async () => { const executor = new RecordingQuestDbExecutor(); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, batchSize: 3, }); const query: QuestDbBars1mQuery = { listingIds: [12], timeframe: '1m', from: '2024-03-01T14:30:00Z', to: '2024-03-01T14:40:00Z', asOf: '2024-03-01T15:00:00Z', adjustment: 'raw', }; executor.setRows([]); expect(await collectBatches(reader.bars(query))).toEqual([]); expect(executor.calls).toHaveLength(1); const startMs = Date.UTC(2024, 2, 1, 14, 30, 0, 0); const rows = Array.from({ length: 7 }, (_, i) => { const tsMs = startMs + i * 60_000; return { listing_id: '12', ts_us: (BigInt(tsMs) * 1000n).toString(), open: 10 + i, high: 11 + i, low: 9 + i, close: 10.5 + i, volume: 100 + i, vwap: i % 2 === 0 ? null : 10.25 + i, known_at_us: (BigInt(tsMs + 60_000) * 1000n).toString(), }; }); executor.setRows(rows); const batches = await collectBatches(reader.bars(query)); expect(batches.map(b => b.rows.length)).toEqual([3, 3, 1]); expect(executor.calls).toHaveLength(2); expect(batches[0]?.rows[0]?.vwap).toBeNull(); expect(batches[0]?.rows[1]?.vwap).toBe(11.25); }); }); describe('Malformed and out-of-fence row defence-in-depth', () => { const baseQuery: QuestDbBars1mQuery = { listingIds: [101], timeframe: '1m', from: '2025-06-30T23:58:00.000Z', to: '2025-07-05T00:00:00.000Z', // clamped to VAULT_CUTOFF_TS - 1 (2025-06-30T23:59:59.999Z) asOf: '2025-07-05T00:00:00.000Z', // clamped to VAULT_CUTOFF_TS - 1 adjustment: 'raw', }; const fromUs = BigInt(Date.UTC(2025, 5, 30, 23, 58, 0, 0)) * 1000n; const clampedToUs = BigInt(VAULT_CUTOFF_TS - 1) * 1000n; const clampedAsOfUs = BigInt(VAULT_CUTOFF_TS - 1) * 1000n; function makeValidRow(overrides: Record = {}): Record { return { listing_id: '101', ts_us: fromUs.toString(), open: 150, high: 151, low: 149.5, close: 150.25, volume: 2500, vwap: 150.1, known_at_us: clampedAsOfUs.toString(), ...overrides, }; } it('accepts rows at exact fenced microsecond endpoints', async () => { const executor = new RecordingQuestDbExecutor(); executor.setRows([ makeValidRow({ ts_us: fromUs.toString(), known_at_us: clampedAsOfUs.toString() }), makeValidRow({ ts_us: clampedToUs.toString(), known_at_us: clampedAsOfUs.toString() }), ]); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, }); const batches = await collectBatches(reader.bars(baseQuery)); expect(batches).toHaveLength(1); expect(batches[0]?.rows).toHaveLength(2); expect(batches[0]?.rows[0]?.ts).toBe(Date.UTC(2025, 5, 30, 23, 58, 0, 0)); expect(batches[0]?.rows[1]?.ts).toBe(VAULT_CUTOFF_TS - 1); }); it('rejects rows 1 microsecond before from, 1 microsecond after clamped to, or 1 microsecond after fenced asOf', async () => { const executor = new RecordingQuestDbExecutor(); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, }); const outOfFenceRows: Array<{ label: string; row: Record }> = [ { label: 'ts 1us before from', row: makeValidRow({ ts_us: (fromUs - 1n).toString() }) }, { label: 'ts 1us after clamped to', row: makeValidRow({ ts_us: (clampedToUs + 1n).toString() }) }, { label: 'known_at 1us after clamped asOf', row: makeValidRow({ known_at_us: (clampedAsOfUs + 1n).toString() }), }, ]; for (const testCase of outOfFenceRows) { executor.setRows([testCase.row]); await expect(collectBatches(reader.bars(baseQuery))).rejects.toThrow( MarketDataStoreValidationError ); } }); it('rejects invalid SYMBOLs, unrequested listings, non-finite OHLCV/vwap, and invalid timestamps', async () => { const executor = new RecordingQuestDbExecutor(); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, }); const malformedRows: Record[] = [ makeValidRow({ listing_id: '0101' }), makeValidRow({ listing_id: '-101' }), makeValidRow({ listing_id: '0' }), makeValidRow({ listing_id: '2147483648' }), makeValidRow({ listing_id: 101 }), makeValidRow({ listing_id: '102' }), // valid INT32 SYMBOL, but unrequested makeValidRow({ open: Number.NaN }), makeValidRow({ high: Number.POSITIVE_INFINITY }), makeValidRow({ low: Number.NEGATIVE_INFINITY }), makeValidRow({ close: '150.25' }), makeValidRow({ volume: Number.NaN }), makeValidRow({ vwap: Number.NaN }), makeValidRow({ vwap: Number.POSITIVE_INFINITY }), makeValidRow({ ts_us: 'not-a-timestamp' }), makeValidRow({ ts_us: 1.5 }), makeValidRow({ known_at_us: null }), ]; for (const badRow of malformedRows) { executor.setRows([badRow]); await expect(collectBatches(reader.bars(baseQuery))).rejects.toThrow( MarketDataStoreValidationError ); } }); it('fails before yielding any batch when a malformed row appears beyond the first batch boundary', async () => { const executor = new RecordingQuestDbExecutor(); executor.setRows([ makeValidRow(), makeValidRow(), makeValidRow({ close: Number.NaN }), // row index 2 is past batchSize: 2 ]); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, batchSize: 2, }); const yielded: BarBatch[] = []; let caught: unknown; try { for await (const batch of reader.bars(baseQuery)) { yielded.push(batch); } } catch (err) { caught = err; } expect(caught).toBeInstanceOf(MarketDataStoreValidationError); expect(yielded).toHaveLength(0); }); it('rounds sub-millisecond known_at up so wider-window replay never exposes a bar before arrival', async () => { // Matches the QuestDB storage fixture: // ts = 2024-01-02T14:30:00.000000Z (1704205800000000 us) // known_at = 2024-01-02T14:31:00.000700Z (1704205860000700 us) const executor = new RecordingQuestDbExecutor(); executor.setRows([ { listing_id: '1042', ts_us: '1704205800000000', open: 185.1, high: 185.5, low: 184.9, close: 185.4, volume: 12500, vwap: 185.28, known_at_us: '1704205860000700', }, { listing_id: '1042', ts_us: '1704205860000000', open: 185.4, high: 185.6, low: 185.3, close: 185.55, volume: 8200, vwap: null, known_at_us: '1704205920000000', // exact millisecond: 2024-01-02T14:32:00.000000Z }, ]); const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, }); const query: QuestDbBars1mQuery = { listingIds: [1042], timeframe: '1m', from: '2024-01-02T14:30:00.000Z', to: '2024-01-02T21:00:00.000Z', asOf: '2024-01-02T21:00:00.000Z', adjustment: 'raw', }; const run1 = (await collectBatches(reader.bars(query))).flatMap(b => b.rows); const run2 = (await collectBatches(reader.bars(query))).flatMap(b => b.rows); expect(run1).toEqual(run2); expect(run1).toHaveLength(2); const decisionAt143100000 = Date.UTC(2024, 0, 2, 14, 31, 0, 0); const decisionAt143100001 = Date.UTC(2024, 0, 2, 14, 31, 0, 1); const exactKnownAt143200000 = Date.UTC(2024, 0, 2, 14, 32, 0, 0); const subMsBar = run1[0]!; expect(subMsBar.knownAt).toBe(decisionAt143100001); // Ineligible at 14:31:00.000 UTC, eligible at 14:31:00.001 UTC. expect(subMsBar.knownAt <= decisionAt143100000).toBe(false); expect(subMsBar.knownAt <= decisionAt143100001).toBe(true); // Exact whole-millisecond known_at is not pushed forward. const exactMsBar = run1[1]!; expect(exactMsBar.knownAt).toBe(exactKnownAt143200000); expect(exactMsBar.knownAt <= exactKnownAt143200000).toBe(true); }); });