diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index 0a9f6987..dcc88deb 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -4,6 +4,7 @@ export * from './event-panel'; export * from './feature-library'; export * from './market-data-store'; export * from './market-data-store-duckdb'; +export * from './market-data-store-questdb'; export * from './signal-panel'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/market-data-store-questdb.ts b/libs/research/src/market-data-store-questdb.ts new file mode 100644 index 00000000..08006f3b --- /dev/null +++ b/libs/research/src/market-data-store-questdb.ts @@ -0,0 +1,448 @@ +/** + * Pure, dependency-free QuestDB `bars_1m` query planner and injected-executor + * intraday reader for `MarketDataStore.bars` (`timeframe: '1m'`, + * `design/DATA-CONTRACTS.md` §3.B & §4). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero `pg` or + * `@stock-bot/questdb` dependency, zero bare `process` access. SQL execution + * is injected via {@link QuestDbQueryExecutor}, which is structurally + * compatible with `QuestDBClient.query(sql, params)`. + * + * Storage and point-in-time semantics: + * - `bars_1m` stores split-unadjusted raw 1-minute OHLCV, nullable `vwap`, + * `listing_id` (`SYMBOL`, canonical positive decimal string), `known_at` + * (`TIMESTAMP`), and designated timestamp `ts` (`TIMESTAMP`, + * `PARTITION BY MONTH`). + * - Only `adjustment: 'raw'` is supported; `'split'` and `'total'` throw + * {@link MarketDataStoreNotImplementedError}. + * - Query bounds are Vault-fenced via {@link applyVaultFence} before SQL + * planning. Every user-supplied value is bound via `$1..$n` placeholders; + * only ordinal placeholder tokens are generated in SQL text. + * - `ts` and `known_at` are projected as `CAST(... AS LONG)` (UTC epoch + * microseconds) and verified in exact microseconds against the fenced bounds + * before converting to epoch milliseconds or yielding any batch. + */ + +import { + type BarBatch, + type BarRecord, + type FencedTimeRange, + type MarketDataStore, + MarketDataStoreValidationError, + type VaultFenceContext, + applyVaultFence, +} from './market-data-store'; +import { MarketDataStoreNotImplementedError } from './market-data-store-duckdb'; + +const INT32_MAX = 2_147_483_647; +const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; +const CANONICAL_POSITIVE_INT_RE = /^[1-9]\d*$/; +const CANONICAL_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/; + +/** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */ +export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000; + +/** Input query type derived from `MarketDataStore['bars']`. */ +export type QuestDbBars1mQuery = Parameters[0]; + +/** + * Injected PGWire SQL executor port, structurally compatible with + * `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`. + */ +export interface QuestDbQueryExecutor { + query( + sql: string, + params: readonly unknown[] + ): Promise<{ readonly rows: readonly Record[] }>; +} + +/** Pure output of {@link planBars1mQuery}. */ +export interface PlannedQuestDbBars1mQuery { + readonly sql: string; + readonly params: readonly string[]; + readonly fence: FencedTimeRange; +} + +/** Configuration for {@link createQuestDbIntradayBarsReader}. */ +export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext { + readonly executor: QuestDbQueryExecutor; + /** Maximum number of bars per yielded `BarBatch`. Defaults to `50_000`. */ + readonly batchSize?: number; +} + +interface InternalPlannedBars1mQuery { + readonly planned: PlannedQuestDbBars1mQuery; + readonly requestedListingIds: ReadonlySet; +} + +function isPlainRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function validateVaultCutoffTs(vaultCutoffTs: unknown): number { + if ( + typeof vaultCutoffTs !== 'number' || + !Number.isSafeInteger(vaultCutoffTs) || + Math.abs(vaultCutoffTs) > MAX_ECMASCRIPT_EPOCH_MS || + vaultCutoffTs <= -MAX_ECMASCRIPT_EPOCH_MS + ) { + throw new MarketDataStoreValidationError( + `Invalid epoch millisecond timestamp for "vaultCutoffTs": ${String(vaultCutoffTs)}.`, + 'vaultCutoffTs' + ); + } + return vaultCutoffTs === 0 ? 0 : vaultCutoffTs; +} + +function validatePositiveInt32ListingIds(raw: unknown): number[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + 'Expected a non-empty array of positive INT32 listing IDs for "listingIds".', + 'listingIds' + ); + } + + const seen = new Set(); + const normalized: number[] = []; + for (let i = 0; i < raw.length; i += 1) { + const id: unknown = raw[i]; + if ( + typeof id !== 'number' || + !Number.isSafeInteger(id) || + id < 1 || + id > INT32_MAX + ) { + throw new MarketDataStoreValidationError( + `Invalid positive INT32 listing ID at listingIds[${i}]: ${String(id)}.`, + 'listingIds' + ); + } + if (!seen.has(id)) { + seen.add(id); + normalized.push(id); + } + } + + normalized.sort((a, b) => a - b); + return normalized; +} + +function formatUtcIsoMs(epochMs: number): string { + return new Date(epochMs).toISOString(); +} + +function planBars1mQueryInternal( + q: QuestDbBars1mQuery, + ctx: VaultFenceContext +): InternalPlannedBars1mQuery { + if (!isPlainRecord(ctx)) { + throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx'); + } + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); + } + + const timeframe: unknown = q.timeframe; + if (timeframe !== '1m') { + throw new MarketDataStoreValidationError( + `Invalid bars timeframe "${String(timeframe)}". Expected '1m'.`, + 'timeframe' + ); + } + + const adjustment: unknown = q.adjustment; + if (adjustment === 'split' || adjustment === 'total') { + throw new MarketDataStoreNotImplementedError( + 'bars', + `Adjustment '${adjustment}' is not supported for intraday '1m' bars; bars_1m stores raw split-unadjusted values.` + ); + } + if (adjustment !== 'raw') { + throw new MarketDataStoreValidationError( + `Invalid bars adjustment "${String(adjustment)}". Expected 'raw'.`, + 'adjustment' + ); + } + + const sortedListingIds = validatePositiveInt32ListingIds(q.listingIds); + + const fence = applyVaultFence( + { + from: q.from, + to: q.to, + asOf: q.asOf, + scope: q.scope, + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + vaultOperatorAuthorized: ctx.vaultOperatorAuthorized === true, + } + ); + + const listingPlaceholders = sortedListingIds.map((_, index) => `$${index + 3}`).join(', '); + const asOfPlaceholder = `$${sortedListingIds.length + 3}`; + + const sql = + '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 (${listingPlaceholders}) AND known_at <= ${asOfPlaceholder} ` + + 'ORDER BY ts, listing_id'; + + const params: string[] = [ + formatUtcIsoMs(fence.fromMs), + formatUtcIsoMs(fence.toMs), + ...sortedListingIds.map(id => String(id)), + formatUtcIsoMs(fence.asOfMs), + ]; + + return { + planned: { sql, params, fence }, + requestedListingIds: new Set(sortedListingIds), + }; +} + +/** + * Pure, Vault-fenced, parameterized SQL planner for QuestDB `bars_1m`. + * + * Binds `from`, `to`, and `asOf` as exact millisecond UTC ISO-8601 strings and + * deduplicated, numerically sorted positive INT32 `listingIds` as canonical + * decimal `SYMBOL` strings. + */ +export function planBars1mQuery( + q: QuestDbBars1mQuery, + ctx: VaultFenceContext +): PlannedQuestDbBars1mQuery { + return planBars1mQueryInternal(q, ctx).planned; +} + +function parseListingIdSymbol( + row: Record, + rowIndex: number, + requestedListingIds: ReadonlySet +): number { + const raw = row.listing_id; + if (typeof raw !== 'string' || !CANONICAL_POSITIVE_INT_RE.test(raw)) { + throw new MarketDataStoreValidationError( + `Invalid bars_1m listing_id SYMBOL in result row ${rowIndex}: ${String(raw)}.`, + 'listing_id' + ); + } + const parsed = Number(raw); + if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > INT32_MAX) { + throw new MarketDataStoreValidationError( + `Out-of-range bars_1m listing_id SYMBOL in result row ${rowIndex}: "${raw}".`, + 'listing_id' + ); + } + if (!requestedListingIds.has(parsed)) { + throw new MarketDataStoreValidationError( + `Unexpected unrequested listing_id ${parsed} in bars_1m result row ${rowIndex}.`, + 'listing_id' + ); + } + return parsed; +} + +function parseTimestampMicros( + row: Record, + column: 'ts_us' | 'known_at_us', + field: 'ts' | 'known_at', + rowIndex: number +): bigint { + const raw = row[column]; + if (typeof raw === 'bigint') { + return raw; + } + if (typeof raw === 'string' && CANONICAL_SIGNED_INT_RE.test(raw)) { + return BigInt(raw); + } + if (typeof raw === 'number' && Number.isSafeInteger(raw)) { + return BigInt(raw); + } + throw new MarketDataStoreValidationError( + `Invalid bars_1m timestamp column "${column}" in result row ${rowIndex}: ${String(raw)}.`, + field + ); +} + +function microsToEpochMs(us: bigint, field: 'ts' | 'known_at', rowIndex: number): number { + const quotient = us / 1000n; + const remainder = us % 1000n; + const msBigInt = remainder < 0n ? quotient - 1n : quotient; + const ms = Number(msBigInt); + if (!Number.isSafeInteger(ms) || Math.abs(ms) > MAX_ECMASCRIPT_EPOCH_MS) { + throw new MarketDataStoreValidationError( + `Out-of-range bars_1m timestamp "${field}" (${us.toString()} us) in result row ${rowIndex}.`, + field + ); + } + return ms === 0 ? 0 : ms; +} + +function readRequiredFiniteNumber( + row: Record, + key: 'open' | 'high' | 'low' | 'close' | 'volume', + rowIndex: number +): number { + const val = row[key]; + if (typeof val !== 'number' || !Number.isFinite(val)) { + throw new MarketDataStoreValidationError( + `Invalid numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`, + key + ); + } + return val === 0 ? 0 : val; +} + +function readNullableFiniteNumber( + row: Record, + key: 'vwap', + rowIndex: number +): number | null { + const val = row[key]; + if (val === null || val === undefined) { + return null; + } + if (typeof val !== 'number' || !Number.isFinite(val)) { + throw new MarketDataStoreValidationError( + `Invalid nullable numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`, + key + ); + } + return val === 0 ? 0 : val; +} + +function mapBars1mRows( + rows: readonly Record[], + fence: FencedTimeRange, + requestedListingIds: ReadonlySet +): BarRecord[] { + const fromUs = BigInt(fence.fromMs) * 1000n; + const toUs = BigInt(fence.toMs) * 1000n; + const asOfUs = BigInt(fence.asOfMs) * 1000n; + + const out: BarRecord[] = new Array(rows.length); + for (let i = 0; i < rows.length; i += 1) { + const raw = rows[i]; + if (!isPlainRecord(raw)) { + throw new MarketDataStoreValidationError( + `Executor returned a non-object bar row at index ${i}.`, + 'rows' + ); + } + + const listingId = parseListingIdSymbol(raw, i, requestedListingIds); + const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i); + if (tsUs < fromUs || tsUs > toUs) { + throw new MarketDataStoreValidationError( + `Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us.`, + 'ts' + ); + } + + const knownAtUs = parseTimestampMicros(raw, 'known_at_us', 'known_at', i); + if (knownAtUs > asOfUs) { + throw new MarketDataStoreValidationError( + `Row ${i} availability timestamp known_at (${knownAtUs.toString()} us) exceeds fenced asOf (${asOfUs.toString()} us).`, + 'known_at' + ); + } + + out[i] = { + listingId, + ts: microsToEpochMs(tsUs, 'ts', i), + open: readRequiredFiniteNumber(raw, 'open', i), + high: readRequiredFiniteNumber(raw, 'high', i), + low: readRequiredFiniteNumber(raw, 'low', i), + close: readRequiredFiniteNumber(raw, 'close', i), + volume: readRequiredFiniteNumber(raw, 'volume', i), + vwap: readNullableFiniteNumber(raw, 'vwap', i), + knownAt: microsToEpochMs(knownAtUs, 'known_at', i), + }; + } + + return out; +} + +/** + * Creates a read-only intraday `bars` reader backed by an injected + * {@link QuestDbQueryExecutor} over QuestDB `bars_1m`. + * + * Validates all inputs and applies the Vault fence before invoking + * `executor.query(...)`. Validates and maps all returned rows (including + * exact-microsecond defence-in-depth checks against `fence`) before yielding + * batches of at most `batchSize` rows (default `50_000`). + */ +export function createQuestDbIntradayBarsReader( + options: QuestDbIntradayBarsReaderOptions +): Pick { + if (!isPlainRecord(options)) { + throw new MarketDataStoreValidationError( + 'Expected a QuestDbIntradayBarsReaderOptions object.', + 'options' + ); + } + + const executor: unknown = options.executor; + if (!isPlainRecord(executor) || typeof executor.query !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `executor` with a `query(sql, params)` method.', + 'executor' + ); + } + const typedExecutor = executor as unknown as QuestDbQueryExecutor; + + const vaultCutoffTs = validateVaultCutoffTs(options.vaultCutoffTs); + + if ( + options.vaultOperatorAuthorized !== undefined && + typeof options.vaultOperatorAuthorized !== 'boolean' + ) { + throw new MarketDataStoreValidationError( + `Invalid vaultOperatorAuthorized "${String(options.vaultOperatorAuthorized)}". Expected a boolean.`, + 'vaultOperatorAuthorized' + ); + } + + const batchSize = options.batchSize ?? DEFAULT_QUESTDB_BARS_BATCH_SIZE; + if (typeof batchSize !== 'number' || !Number.isSafeInteger(batchSize) || batchSize < 1) { + throw new MarketDataStoreValidationError( + `Invalid batchSize "${String(options.batchSize)}". Expected a positive safe integer.`, + 'batchSize' + ); + } + + const planCtx: VaultFenceContext = { + vaultCutoffTs, + vaultOperatorAuthorized: options.vaultOperatorAuthorized === true, + }; + + return { + async *bars(q: QuestDbBars1mQuery): AsyncIterable { + const { planned, requestedListingIds } = planBars1mQueryInternal(q, planCtx); + const result: unknown = await typedExecutor.query(planned.sql, [...planned.params]); + if (!isPlainRecord(result) || !Array.isArray(result.rows)) { + throw new MarketDataStoreValidationError( + 'Executor returned a malformed result; expected `{ rows: Record[] }`.', + 'rows' + ); + } + + const mapped = mapBars1mRows( + result.rows as readonly Record[], + planned.fence, + requestedListingIds + ); + if (mapped.length === 0) { + return; + } + if (mapped.length <= batchSize) { + yield { rows: mapped }; + return; + } + for (let offset = 0; offset < mapped.length; offset += batchSize) { + yield { rows: mapped.slice(offset, offset + batchSize) }; + } + }, + }; +} diff --git a/libs/research/test/market-data-store-questdb.test.ts b/libs/research/test/market-data-store-questdb.test.ts new file mode 100644 index 00000000..22c030ec --- /dev/null +++ b/libs/research/test/market-data-store-questdb.test.ts @@ -0,0 +1,703 @@ +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]) { + expect(() => + createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: badBatchSize, + }) + ).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); + }); +});