diff --git a/libs/data/duckdb/test/duckdb-market-data-store.test.ts b/libs/data/duckdb/test/duckdb-market-data-store.test.ts index d43bd44c..dfe3259c 100644 --- a/libs/data/duckdb/test/duckdb-market-data-store.test.ts +++ b/libs/data/duckdb/test/duckdb-market-data-store.test.ts @@ -247,4 +247,685 @@ describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => { await opened.close(); } }); + + test('fundamentalsAsOf enforces restatement non-overwrite, multi-year Hive glob, Vault microsecond fence, and allowEstimatedLag semantics', async () => { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + + await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2023'), { recursive: true }); + await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2024'), { recursive: true }); + await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2025'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + // Vault cutoff = 2025-02-13T00:00:00.000Z + const vaultCutoffTs = computeVaultCutoffTs('2025-08-13'); + const s1KnownMs = Date.UTC(2024, 4, 1, 20, 0, 0, 0); // 2024-05-01T20:00:00Z + const s2KnownMs = Date.UTC(2024, 7, 1, 20, 0, 0, 0); // 2024-08-01T20:00:00Z + const s3KnownMs = Date.UTC(2024, 8, 15, 20, 0, 0, 0); // 2024-09-15T20:00:00Z + + const writer = await createNodeDuckDbExecutor(); + try { + // year=2023 partition: listing 50 (only exists in 2023 partition) + await writer.run(` + COPY ( + SELECT * FROM (VALUES + ( + 50::INTEGER, + TIMESTAMPTZ '2023-11-05 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2023-09-30', + 'Q3'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2023-11-05 20:00:00+00', + 80.0::DOUBLE, + 8.0::DOUBLE, + 12.0::DOUBLE, + 500.0::DOUBLE, + 250.0::DOUBLE, + 10.0::DOUBLE, + DATE '2023-09-30', + 'USD'::VARCHAR, + 310.0::DOUBLE, + 31.0::DOUBLE, + 46.0::DOUBLE, + FALSE::BOOLEAN + ) + ) AS t( + listing_id, effective_known_at, known_at_source, has_estimated_lag, + period_end, fiscal_period, currency, period_known_at, + revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, + ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag + ) + ) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2023', 'part.parquet')}' (FORMAT PARQUET) + `); + + // year=2024 partition: + // - listing 101: S1 (Q1), S2 (Q2), S3 (Q1 restatement known after Q2 -> latest period stays Q2, TTM changes) + // - listing 201: older verified snapshot + newer estimated-lag snapshot (strict mode must omit without fallback) + // - listing 202: verified snapshot with estimated-lag TTM only (strict mode keeps row, nulls ttm_* + ttm_period_end + ttm_currency, preserves ttm_has_estimated_lag) + await writer.run(` + COPY ( + SELECT * FROM (VALUES + ( + 101::INTEGER, + TIMESTAMPTZ '2024-05-01 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-03-31', + 'Q1'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2024-05-01 20:00:00+00', + 100.0::DOUBLE, + 10.0::DOUBLE, + 15.0::DOUBLE, + 1000.0::DOUBLE, + 500.0::DOUBLE, + 50.0::DOUBLE, + DATE '2024-03-31', + 'USD'::VARCHAR, + 380.0::DOUBLE, + 38.0::DOUBLE, + 55.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 101::INTEGER, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-06-30', + 'Q2'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 120.0::DOUBLE, + 14.0::DOUBLE, + 20.0::DOUBLE, + 1050.0::DOUBLE, + 520.0::DOUBLE, + 50.0::DOUBLE, + DATE '2024-06-30', + 'USD'::VARCHAR, + 420.0::DOUBLE, + 44.0::DOUBLE, + 65.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 101::INTEGER, + TIMESTAMPTZ '2024-09-15 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-06-30', + 'Q2'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 120.0::DOUBLE, + 14.0::DOUBLE, + 20.0::DOUBLE, + 1050.0::DOUBLE, + 520.0::DOUBLE, + 50.0::DOUBLE, + DATE '2024-06-30', + 'USD'::VARCHAR, + 415.0::DOUBLE, + 42.0::DOUBLE, + 63.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 201::INTEGER, + TIMESTAMPTZ '2024-05-01 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-03-31', + 'Q1'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2024-05-01 20:00:00+00', + 50.0::DOUBLE, + 5.0::DOUBLE, + 7.0::DOUBLE, + 400.0::DOUBLE, + 200.0::DOUBLE, + 20.0::DOUBLE, + DATE '2024-03-31', + 'USD'::VARCHAR, + 190.0::DOUBLE, + 19.0::DOUBLE, + 27.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 201::INTEGER, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 'estimated_lag'::VARCHAR, + TRUE::BOOLEAN, + DATE '2024-06-30', + 'Q2'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 60.0::DOUBLE, + 6.0::DOUBLE, + 8.0::DOUBLE, + 420.0::DOUBLE, + 210.0::DOUBLE, + 20.0::DOUBLE, + DATE '2024-06-30', + 'USD'::VARCHAR, + 210.0::DOUBLE, + 21.0::DOUBLE, + 30.0::DOUBLE, + TRUE::BOOLEAN + ), + ( + 202::INTEGER, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-06-30', + 'Q2'::VARCHAR, + 'CAD'::VARCHAR, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 75.0::DOUBLE, + 9.0::DOUBLE, + 11.0::DOUBLE, + 600.0::DOUBLE, + 300.0::DOUBLE, + 30.0::DOUBLE, + DATE '2024-06-30', + 'CAD'::VARCHAR, + 300.0::DOUBLE, + 30.0::DOUBLE, + 45.0::DOUBLE, + TRUE::BOOLEAN + ) + ) AS t( + listing_id, effective_known_at, known_at_source, has_estimated_lag, + period_end, fiscal_period, currency, period_known_at, + revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, + ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag + ) + ) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2024', 'part.parquet')}' (FORMAT PARQUET) + `); + + // year=2025 partition: Vault microsecond boundary rows + // - listing 102: 1 microsecond before cutoff (eligible), exact cutoff (excluded), post-cutoff (excluded) + // - listing 103: exact cutoff only (must return 0 rows) + await writer.run(` + COPY ( + SELECT * FROM (VALUES + ( + 102::INTEGER, + TIMESTAMPTZ '2025-02-12 23:59:59.999999+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-12-31', + 'Q4'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2025-02-12 23:59:59.999999+00', + 210.0::DOUBLE, + 21.0::DOUBLE, + 31.0::DOUBLE, + 1500.0::DOUBLE, + 750.0::DOUBLE, + 60.0::DOUBLE, + DATE '2024-12-31', + 'USD'::VARCHAR, + 800.0::DOUBLE, + 80.0::DOUBLE, + 120.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 102::INTEGER, + TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-12-31', + 'Q4'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', + 999.0::DOUBLE, + 99.0::DOUBLE, + 99.0::DOUBLE, + 9999.0::DOUBLE, + 4999.0::DOUBLE, + 60.0::DOUBLE, + DATE '2024-12-31', + 'USD'::VARCHAR, + 9999.0::DOUBLE, + 999.0::DOUBLE, + 999.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 102::INTEGER, + TIMESTAMPTZ '2025-02-14 12:00:00.000000+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2025-03-31', + 'Q1'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2025-02-14 12:00:00.000000+00', + 1111.0::DOUBLE, + 111.0::DOUBLE, + 111.0::DOUBLE, + 11111.0::DOUBLE, + 5555.0::DOUBLE, + 60.0::DOUBLE, + DATE '2025-03-31', + 'USD'::VARCHAR, + 11111.0::DOUBLE, + 1111.0::DOUBLE, + 1111.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 103::INTEGER, + TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-12-31', + 'Q4'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', + 777.0::DOUBLE, + 77.0::DOUBLE, + 77.0::DOUBLE, + 7777.0::DOUBLE, + 3333.0::DOUBLE, + 40.0::DOUBLE, + DATE '2024-12-31', + 'USD'::VARCHAR, + 7777.0::DOUBLE, + 777.0::DOUBLE, + 777.0::DOUBLE, + FALSE::BOOLEAN + ) + ) AS t( + listing_id, effective_known_at, known_at_source, has_estimated_lag, + period_end, fiscal_period, currency, period_known_at, + revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, + ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag + ) + ) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + + try { + // 1. Before S1: no row for listing 101 + const beforeS1 = await opened.store.fundamentalsAsOf({ + listingIds: [101], + fields: ['revenue', 'ttm_revenue'], + asOf: '2024-04-30T23:59:59Z', + }); + expect(beforeS1.rows).toEqual([]); + + // 2. Between S1 and S2: Q1 row (revenue 100, ttm_revenue 380) + const betweenS1S2 = await opened.store.fundamentalsAsOf({ + listingIds: [101], + fields: ['revenue', 'ttm_revenue'], + asOf: '2024-06-15', + }); + expect(betweenS1S2.rows).toHaveLength(1); + expect(betweenS1S2.rows[0]).toEqual({ + listing_id: 101, + effective_known_at: s1KnownMs, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-03-31', + fiscal_period: 'Q1', + currency: 'USD', + period_known_at: s1KnownMs, + revenue: 100, + ttm_revenue: 380, + ttm_period_end: '2024-03-31', + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }); + + // 3. Between S2 and S3: Q2 baseline (revenue 120, period_known_at = S2, pre-restatement TTM 420) + const betweenS2S3 = await opened.store.fundamentalsAsOf({ + listingIds: [101], + fields: ['revenue', 'ttm_revenue'], + asOf: '2024-08-15', + }); + expect(betweenS2S3.rows).toHaveLength(1); + expect(betweenS2S3.rows[0]).toEqual({ + listing_id: 101, + effective_known_at: s2KnownMs, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: s2KnownMs, + revenue: 120, + ttm_revenue: 420, + ttm_period_end: '2024-06-30', + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }); + + // 4. At and after S3 (Q1 restatement with known_at > Q2): Q2 period_end, revenue, and period_known_at stay fixed while ttm_revenue updates to 415 + for (const asOf of ['2024-09-15T20:00:00Z', '2024-10-01']) { + const afterS3 = await opened.store.fundamentalsAsOf({ + listingIds: [101], + fields: ['revenue', 'ttm_revenue'], + asOf, + }); + expect(afterS3.rows).toHaveLength(1); + expect(afterS3.rows[0]).toEqual({ + listing_id: 101, + effective_known_at: s3KnownMs, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: s2KnownMs, + revenue: 120, + ttm_revenue: 415, + ttm_period_end: '2024-06-30', + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }); + } + + // 5. Multi-partition glob (year=2023 + year=2024) sorted by listing_id ASC, with non-TTM projection omitting TTM metadata columns + const multiYear = await opened.store.fundamentalsAsOf({ + listingIds: [101, 50], + fields: ['revenue'], + asOf: '2024-10-01', + }); + expect(multiYear.columns).toEqual([ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + 'revenue', + ]); + expect(multiYear.rows.map(r => r.listing_id)).toEqual([50, 101]); + expect(multiYear.rows[0]!.period_end).toBe('2023-09-30'); + expect(multiYear.rows[0]!.revenue).toBe(80); + expect(multiYear.rows[1]!.revenue).toBe(120); + + // 6. Vault microsecond fence: last pre-cutoff microsecond is eligible; exact cutoff and post-cutoff are excluded + for (const asOf of ['2025-02-13T00:00:00.000Z', '2025-06-01']) { + const fenced = await opened.store.fundamentalsAsOf({ + listingIds: [103, 102], + fields: ['revenue'], + asOf, + }); + expect(fenced.rows).toHaveLength(1); + expect(fenced.rows[0]!.listing_id).toBe(102); + expect(fenced.rows[0]!.revenue).toBe(210); + expect(fenced.rows[0]!.period_end).toBe('2024-12-31'); + } + + // 7. allowEstimatedLag default (true) vs strict (false): + // - listing 201 (has_estimated_lag = true on latest snapshot) returned by default, omitted in strict mode without falling back to older verified Q1 row + // - listing 202 (has_estimated_lag = false, ttm_has_estimated_lag = true) kept in strict mode with all ttm_* values + ttm_period_end + ttm_currency nulled and ttm_has_estimated_lag preserved + const lagAllowed = await opened.store.fundamentalsAsOf({ + listingIds: [202, 201], + fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'], + asOf: '2024-09-01', + }); + expect(lagAllowed.rows.map(r => r.listing_id)).toEqual([201, 202]); + expect(lagAllowed.rows[0]!.revenue).toBe(60); + expect(lagAllowed.rows[0]!.has_estimated_lag).toBe(true); + expect(lagAllowed.rows[1]!.revenue).toBe(75); + expect(lagAllowed.rows[1]!.ttm_revenue).toBe(300); + expect(lagAllowed.rows[1]!.ttm_net_income).toBe(30); + expect(lagAllowed.rows[1]!.ttm_operating_cash_flow).toBe(45); + expect(lagAllowed.rows[1]!.ttm_period_end).toBe('2024-06-30'); + expect(lagAllowed.rows[1]!.ttm_currency).toBe('CAD'); + expect(lagAllowed.rows[1]!.ttm_has_estimated_lag).toBe(true); + + const lagStrict = await opened.store.fundamentalsAsOf({ + listingIds: [202, 201], + fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'], + asOf: '2024-09-01', + allowEstimatedLag: false, + }); + expect(lagStrict.rows).toHaveLength(1); + expect(lagStrict.rows[0]).toEqual({ + listing_id: 202, + effective_known_at: s2KnownMs, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'CAD', + period_known_at: s2KnownMs, + revenue: 75, + ttm_revenue: null, + ttm_net_income: null, + ttm_operating_cash_flow: null, + ttm_period_end: null, + ttm_currency: null, + ttm_has_estimated_lag: true, + }); + } finally { + await opened.close(); + } + }); +}); + +interface FundamentalsFixtureRow { + readonly listingId: number; + readonly effectiveKnownAt: string; + readonly hasEstimatedLag?: boolean; + readonly periodEnd: string; + readonly fiscalPeriod: string; + readonly periodKnownAt?: string; + readonly revenue: number | null; + readonly ttmRevenue: number | null; + readonly ttmHasEstimatedLag: boolean | null; +} + +function fundamentalsRowSql(r: FundamentalsFixtureRow): string { + const num = (v: number | null): string => (v === null ? 'NULL::DOUBLE' : `${v}::DOUBLE`); + const bool = (v: boolean | null): string => (v === null ? 'NULL::BOOLEAN' : `${v ? 'TRUE' : 'FALSE'}::BOOLEAN`); + const ttmMissing = r.ttmRevenue === null; + return `( + ${r.listingId}::INTEGER, TIMESTAMPTZ '${r.effectiveKnownAt}', 'filing_date'::VARCHAR, ${bool(r.hasEstimatedLag ?? false)}, + DATE '${r.periodEnd}', '${r.fiscalPeriod}'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${r.periodKnownAt ?? r.effectiveKnownAt}', + ${num(r.revenue)}, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, + ${ttmMissing ? 'NULL::DATE' : `DATE '${r.periodEnd}'`}, ${ttmMissing ? 'NULL::VARCHAR' : `'USD'::VARCHAR`}, + ${num(r.ttmRevenue)}, NULL::DOUBLE, NULL::DOUBLE, ${bool(r.ttmHasEstimatedLag)} + )`; +} + +async function writeFundamentalsPartition( + curatedRoot: string, + year: number, + rows: readonly FundamentalsFixtureRow[] +): Promise { + const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`); + await mkdir(dir, { recursive: true }); + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES ${rows.map(fundamentalsRowSql).join(', ')}) AS t( + listing_id, effective_known_at, known_at_source, has_estimated_lag, + period_end, fiscal_period, currency, period_known_at, + revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, + ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag + ) + ) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } +} + +describe('openDuckDbMarketDataStore fundamentalsAsOf edge cases (@duckdb/node-api)', () => { + async function openFundamentalsStore(): Promise>> { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-edge-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(duckTempDir, { recursive: true }); + + // Partition directory does not drive ranking: listing 7's newest snapshot sits in + // year=2023 while its older one sits in year=2024; listing 8 is the reverse. + await writeFundamentalsPartition(curatedRoot, 2023, [ + { listingId: 7, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 70, ttmRevenue: 270, ttmHasEstimatedLag: false }, + { listingId: 8, effectiveKnownAt: '2023-11-01 12:00:00+00', periodEnd: '2023-09-30', fiscalPeriod: 'Q3', revenue: 80, ttmRevenue: 300, ttmHasEstimatedLag: false }, + ]); + await writeFundamentalsPartition(curatedRoot, 2024, [ + { listingId: 7, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 65, ttmRevenue: 260, ttmHasEstimatedLag: false }, + { listingId: 8, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 85, ttmRevenue: 310, ttmHasEstimatedLag: false }, + // Sub-millisecond neighbours: only the microsecond distinguishes them. + { listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000500+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 90, ttmRevenue: 360, ttmHasEstimatedLag: false }, + { listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000501+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 91, ttmRevenue: 361, ttmHasEstimatedLag: false }, + // Verified Q1, then estimated Q2. + { listingId: 10, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 100, ttmRevenue: 400, ttmHasEstimatedLag: false }, + { listingId: 10, effectiveKnownAt: '2024-08-01 12:00:00+00', hasEstimatedLag: true, periodEnd: '2024-06-30', fiscalPeriod: 'Q2', revenue: 110, ttmRevenue: 410, ttmHasEstimatedLag: true }, + // TTM-only estimated lag. + { listingId: 11, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 111, ttmRevenue: 444, ttmHasEstimatedLag: true }, + // No TTM yet (fewer than four quarters): TTM values and flag are NULL. + { listingId: 12, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 12, ttmRevenue: null, ttmHasEstimatedLag: null }, + ]); + + return openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs: computeVaultCutoffTs('2025-08-13'), + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + } + + test('selects the latest effective_known_at across Hive partitions regardless of partition directory', async () => { + const opened = await openFundamentalsStore(); + try { + const result = await opened.store.fundamentalsAsOf({ + listingIds: [8, 7], + fields: ['revenue'], + asOf: '2024-06-01', + }); + expect(result.rows.map(r => [r.listing_id, r.fiscal_period, r.revenue])).toEqual([ + [7, 'Q1', 70], + [8, 'Q4', 85], + ]); + + const earlier = await opened.store.fundamentalsAsOf({ + listingIds: [7, 8], + fields: ['revenue'], + asOf: '2024-01-01', + }); + expect(earlier.rows.map(r => [r.listing_id, r.fiscal_period])).toEqual([[8, 'Q3']]); + } finally { + await opened.close(); + } + }); + + test('binds explicit sub-millisecond asOf so microsecond-adjacent snapshots are separated', async () => { + const opened = await openFundamentalsStore(); + try { + const at = async (asOf: string): Promise => + (await opened.store.fundamentalsAsOf({ listingIds: [9], fields: ['revenue'], asOf })).rows.map( + r => r.revenue + ); + expect(await at('2024-03-01T12:00:00.000499Z')).toEqual([]); + expect(await at('2024-03-01T12:00:00.000500Z')).toEqual([90]); + expect(await at('2024-03-01T14:00:00.000500+02:00')).toEqual([90]); + expect(await at('2024-03-01T12:00:00.000501Z')).toEqual([91]); + } finally { + await opened.close(); + } + }); + + test('strict allowEstimatedLag returns the verified snapshot that was latest at an earlier asOf, and omits the listing once an estimated snapshot is latest', async () => { + const opened = await openFundamentalsStore(); + try { + const beforeEstimate = await opened.store.fundamentalsAsOf({ + listingIds: [10], + fields: ['revenue'], + asOf: '2024-07-31', + allowEstimatedLag: false, + }); + expect(beforeEstimate.rows.map(r => [r.fiscal_period, r.revenue])).toEqual([['Q1', 100]]); + + const afterEstimate = await opened.store.fundamentalsAsOf({ + listingIds: [10], + fields: ['revenue'], + asOf: '2024-08-02', + allowEstimatedLag: false, + }); + expect(afterEstimate.rows).toEqual([]); + } finally { + await opened.close(); + } + }); + + test('strict mode keeps TTM-estimated rows without TTM columns when no ttm_* field is requested, and passes through NULL TTM flags', async () => { + const opened = await openFundamentalsStore(); + try { + const noTtm = await opened.store.fundamentalsAsOf({ + listingIds: [11], + fields: ['revenue'], + asOf: '2024-06-01', + allowEstimatedLag: false, + }); + expect(noTtm.columns).not.toContain('ttm_has_estimated_lag'); + expect(noTtm.rows).toEqual([ + expect.objectContaining({ listing_id: 11, revenue: 111, has_estimated_lag: false }), + ]); + expect(Object.keys(noTtm.rows[0]!)).toEqual(noTtm.columns as string[]); + + const nullTtm = await opened.store.fundamentalsAsOf({ + listingIds: [12, 11], + fields: ['ttm_revenue'], + asOf: '2024-06-01', + allowEstimatedLag: false, + }); + expect(nullTtm.rows.map(r => [r.listing_id, r.ttm_revenue, r.ttm_period_end, r.ttm_currency, r.ttm_has_estimated_lag])).toEqual([ + [11, null, null, null, true], + [12, null, null, null, null], + ]); + } finally { + await opened.close(); + } + }); + + test('returns only requested listings and is reproducible across repeated identical queries', async () => { + const opened = await openFundamentalsStore(); + try { + const q = { + listingIds: [12, 999, 7], + fields: ['ttm_revenue', 'revenue'], + asOf: '2024-09-01T00:00:00.000001Z', + }; + const first = await opened.store.fundamentalsAsOf(q); + const second = await opened.store.fundamentalsAsOf(q); + expect(first.rows.map(r => r.listing_id)).toEqual([7, 12]); + expect(second).toEqual(first); + } finally { + await opened.close(); + } + }); }); diff --git a/libs/research/README.md b/libs/research/README.md index c4c1dae2..93e29a1d 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -85,9 +85,10 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-st - **`planAdjFactorsMetadataQuery(adjPath)`** / **`parseAdjFactorsSnapshotMetadata(adjPath, kvRows)`** — Plans the `parquet_kv_metadata('')` query for `stock_bot.adj_factors.*` footer keys and strictly parses/validates them (mirroring `tools/curate-etl/src/curate_adj.rs`). - **`planEventsQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `/events/year=*/part.parquet` (`hive_partitioning = true`) filtered by allow-listed `kinds` and optional `listingIds`, preserving the Parquet writer's total sort order `(listing_id, ts, kind, subtype, payload_json, known_at, known_at_source)`. - **`planShortsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `/shorts/part.parquet`, binding UTC `YYYY-MM-DD` `report_date` bounds and microsecond UTC ISO-8601 `known_at <= ?`. +- **`planFundamentalsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` point-in-time query over `/fundamentals_pit/year=*/part.parquet` (`hive_partitioning = true`) selecting at most one latest snapshot (`effective_known_at <= asOf`, clamped strictly below `vaultCutoffTs`) per requested `listing_id` across allow-listed `FUNDAMENTALS_PIT_VALUE_FIELDS`, with `allowEstimatedLag` (default `true`) failing closed on snapshot-level `has_estimated_lag` without fallback and masking `ttm_*` values/date/currency when `ttm_has_estimated_lag` is `true`. - **`planFx1dQuery(q, ctx)`** — Plans a `'vault_fenced'` query (with default `asOf = vaultCutoffTs * 1000 - 1` µs) over `/fx_1d/part.parquet` for `timeframe: '1d'`, mapping `'USD.CAD'` to the stored bound parameter `'USDCAD'`. Rejects `'1m'` with `MarketDataStoreNotImplementedError`. - **`planUniverseQuery(q, ctx)`** — Plans a `'vault_fenced'`, survivorship-free query over `/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) returning `SELECT DISTINCT b.listing_id ... ORDER BY b.listing_id ASC` for supported `UNIVERSE_REFS` (`'US_EQ'`, `'CA_EQ'`, `'US_CA_EQ'`) within `[date - lookbackDays, date]` (default `DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7`, configurable via `ctx.universeLookbackDays`). -- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `fundamentalsAsOf`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls. +- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls. ### Mandatory Vault, PIT, Microsecond & Boundary Validation Rules @@ -123,6 +124,37 @@ Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across - **Mixed planners (`120,000` queries):** `elapsedMs = 225.79 ms`, `queriesPerSec = 531,470 queries/s` (`758,061` bound params, pinned checksum `8606c98c`) - **`universe` plan + adapter mapping (`200` calls × `15,000` listings):** `elapsedMs = 23.44 ms`, `callsPerSec = 8,534 calls/s`, `rowsPerSec = 128,011,137 rows/s` (`3,000,000` mapped IDs, pinned checksum `ef5f1136`) +## Routed `MarketDataStore` (DuckDB Daily + QuestDB `1m` Intraday) + +Exported from `@stock-bot/research` and `@stock-bot/research/market-data-store-routed` (`libs/research/src/market-data-store-routed.ts`). The QuestDB intraday reader is also exported from `@stock-bot/research/market-data-store-questdb`. Both modules are pure, dependency-free, and browser-safe. + +- **`createRoutedMarketDataStore({ daily, intraday })`** — Composes a full daily `MarketDataStore` (e.g. `createDuckDbMarketDataStore`) with an intraday `bars` reader (`Pick`, e.g. `createQuestDbIntradayBarsReader`). + - `bars(q)` with `timeframe: '1m'` delegates directly to `intraday.bars(q)` (preserving lazy iteration, receiver, query identity, and error propagation). Note that `createQuestDbIntradayBarsReader` supports split-unadjusted raw (`adjustment: 'raw'`) `1m` bars. + - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed inputs) and all other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly to `daily`. + - **Shared Vault fence requirement:** The router adds no Vault logic of its own; each delegate enforces its own fence. Always construct `daily` and `intraday` with the exact same `vaultCutoffTs` and `vaultOperatorAuthorized`, and pass that same `vaultCutoffTs` to `createQueryDataTool` (which is always Vault-fenced and accepts only `{ vaultCutoffTs }`): + +```ts +const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); +const vaultOperatorAuthorized = false; + +const daily = createDuckDbMarketDataStore({ + executor: duckDbExecutor, + curatedRoot: '/mnt/data/stockbot/curated', + vaultCutoffTs, + vaultOperatorAuthorized, +}); +const intraday = createQuestDbIntradayBarsReader({ + executor: questDbExecutor, + vaultCutoffTs, + vaultOperatorAuthorized, +}); +const store = createRoutedMarketDataStore({ daily, intraday }); +const queryDataTool = createQueryDataTool({ + store, + vaultContext: { vaultCutoffTs }, +}); +``` + ## Signal Panel Builder Exported from both `@stock-bot/research` and `@stock-bot/research/signal-panel` (`libs/research/src/signal-panel.ts`). The module is pure, synchronous (except `collectBars`), dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers). diff --git a/libs/research/package.json b/libs/research/package.json index e5cf853d..eb1522e3 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -14,6 +14,8 @@ "./feature-library": "./src/feature-library.ts", "./market-data-store": "./src/market-data-store.ts", "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", + "./market-data-store-questdb": "./src/market-data-store-questdb.ts", + "./market-data-store-routed": "./src/market-data-store-routed.ts", "./mcp": "./src/mcp/index.ts", "./results": "./src/results.ts", "./signal-panel": "./src/signal-panel.ts", diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index 0a9f6987..bb5e7062 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -4,6 +4,8 @@ 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 './market-data-store-routed'; export * from './signal-panel'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/market-data-store-duckdb.ts b/libs/research/src/market-data-store-duckdb.ts index 0d3013ba..fd6dd8ae 100644 --- a/libs/research/src/market-data-store-duckdb.ts +++ b/libs/research/src/market-data-store-duckdb.ts @@ -14,6 +14,7 @@ * - `/events/year=*\/part.parquet` (`hive_partitioning = true`) * - `/shorts/part.parquet` * - `/fx_1d/part.parquet` + * - `/fundamentals_pit/year=*\/part.parquet` (`hive_partitioning = true`) * * `bars` (`timeframe: '1d'`) adjustment formulas (`tools/curate-etl/README.md`): * - `bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share @@ -74,6 +75,7 @@ import { type Table, type TableCell, type TableRow, + VaultHoldoutFenceError, applyVaultFence, resolveDuckDbConnectionBudget, } from './market-data-store'; @@ -155,7 +157,29 @@ export const FX_1D_COLUMNS = [ 'known_at', ] as const; -type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string'; +export const FUNDAMENTALS_PIT_VALUE_FIELDS = [ + 'revenue', + 'net_income', + 'operating_cash_flow', + 'total_assets', + 'total_equity', + 'shares_outstanding', + 'ttm_revenue', + 'ttm_net_income', + 'ttm_operating_cash_flow', +] as const; +export type FundamentalsPitValueField = (typeof FUNDAMENTALS_PIT_VALUE_FIELDS)[number]; + +const FUNDAMENTALS_PIT_VALUE_FIELD_MAP: ReadonlyMap = new Map( + FUNDAMENTALS_PIT_VALUE_FIELDS.map(field => [field, field]) +); +const FUNDAMENTALS_TTM_VALUE_FIELD_SET: ReadonlySet = new Set([ + 'ttm_revenue', + 'ttm_net_income', + 'ttm_operating_cash_flow', +]); + +type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string' | 'boolean'; interface TableColumnSpec { readonly name: string; @@ -195,6 +219,23 @@ const FX_1D_SCHEMA: readonly TableColumnSpec[] = [ { name: 'known_at', kind: 'safe_int', nullable: false }, ]; +const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [ + { name: 'listing_id', kind: 'int32', nullable: false }, + { name: 'effective_known_at', kind: 'safe_int', nullable: false }, + { name: 'known_at_source', kind: 'string', nullable: false }, + { name: 'has_estimated_lag', kind: 'boolean', nullable: false }, + { name: 'period_end', kind: 'string', nullable: false }, + { name: 'fiscal_period', kind: 'string', nullable: false }, + { name: 'currency', kind: 'string', nullable: false }, + { name: 'period_known_at', kind: 'safe_int', nullable: false }, +]; + +const FUNDAMENTALS_TTM_META_SCHEMA: readonly TableColumnSpec[] = [ + { name: 'ttm_period_end', kind: 'string', nullable: true }, + { name: 'ttm_currency', kind: 'string', nullable: true }, + { name: 'ttm_has_estimated_lag', kind: 'boolean', nullable: true }, +]; + /** Scalar parameter value bound separately from SQL text. */ export type DuckDbParam = string | number | boolean | null; @@ -357,6 +398,7 @@ export type EventsQuery = Parameters[0]; export type ShortsAsOfQuery = Parameters[0]; export type FxQuery = Parameters[0]; export type UniverseQuery = Parameters[0]; +export type FundamentalsAsOfQuery = Parameters[0]; /** * Thrown when a `MarketDataStore` method or timeframe is outside the curated @@ -577,6 +619,50 @@ function validateEventKinds(raw: readonly EventKind[], field = 'kinds'): EventKi return normalized; } +function validateFundamentalsFields( + raw: readonly string[], + field = 'fields' +): FundamentalsPitValueField[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + `Expected a non-empty array of fundamentals value fields for "${field}".`, + field + ); + } + + const seen = new Set(); + const normalized: FundamentalsPitValueField[] = []; + for (let i = 0; i < raw.length; i += 1) { + const name: unknown = raw[i]; + const canonical = + typeof name === 'string' ? FUNDAMENTALS_PIT_VALUE_FIELD_MAP.get(name) : undefined; + if (canonical === undefined) { + throw new MarketDataStoreValidationError( + `Unknown fundamentals field "${String(name)}". Expected one of: ${FUNDAMENTALS_PIT_VALUE_FIELDS.join(', ')}.`, + field + ); + } + if (!seen.has(canonical)) { + seen.add(canonical); + normalized.push(canonical); + } + } + return normalized; +} + +function validateAllowEstimatedLag(raw: unknown): boolean { + if (raw === undefined) { + return true; + } + if (typeof raw !== 'boolean') { + throw new MarketDataStoreValidationError( + `Invalid allowEstimatedLag "${String(raw)}". Expected a boolean.`, + 'allowEstimatedLag' + ); + } + return raw; +} + function validateAdjustment(raw: unknown): (typeof BARS_ADJUSTMENTS)[number] { if (typeof raw !== 'string' || !BARS_ADJUSTMENT_SET.has(raw)) { throw new MarketDataStoreValidationError( @@ -1575,6 +1661,158 @@ export function planUniverseQuery(q: UniverseQuery, ctx: DuckDbPlanContext): Pla }; } +interface PlannedFundamentalsAsOfInternal { + readonly planned: PlannedDuckDbQuery; + readonly columns: readonly string[]; + readonly schema: readonly TableColumnSpec[]; +} + +function planFundamentalsAsOfInternal( + q: FundamentalsAsOfQuery, + ctx: DuckDbPlanContext +): PlannedFundamentalsAsOfInternal { + const curatedRoot = validateContext(ctx); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError( + 'Expected a fundamentalsAsOf query object.', + 'query' + ); + } + + const listingIds = validateListingIds(q.listingIds); + const fields = validateFundamentalsFields(q.fields); + const allowEstimatedLag = validateAllowEstimatedLag(q.allowEstimatedLag); + + let fenced: FencedTimeRange; + try { + fenced = applyVaultFence( + { + from: q.asOf, + to: q.asOf, + asOf: q.asOf, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + } + ); + } catch (err: unknown) { + if (err instanceof VaultHoldoutFenceError) { + const maxAllowedMs = ctx.vaultCutoffTs - 1; + fenced = { + fromMs: maxAllowedMs, + toMs: maxAllowedMs, + asOfMs: maxAllowedMs, + scope: 'vault_fenced', + clampedTo: true, + clampedAsOf: true, + }; + } else if ( + err instanceof MarketDataStoreValidationError && + (err.field === 'from' || err.field === 'to') + ) { + throw new MarketDataStoreValidationError(err.message, 'asOf'); + } else { + throw err; + } + } + + const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.asOf, fenced); + const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); + const fundamentalsPath = joinCuratedPath(curatedRoot, 'fundamentals_pit/year=*/part.parquet'); + const listingPlaceholders = buildPlaceholders(listingIds.length); + + let hasTtmField = false; + for (const field of fields) { + if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) { + hasTtmField = true; + break; + } + } + + const innerCols: string[] = [ + 'f.listing_id', + 'f.effective_known_at', + 'f.known_at_source', + 'f.has_estimated_lag', + 'f.period_end', + 'f.fiscal_period', + 'f.currency', + 'f.period_known_at', + ]; + const outerCols: string[] = [ + 's.listing_id', + 'epoch_ms(s.effective_known_at) AS effective_known_at', + 's.known_at_source', + 's.has_estimated_lag', + 'CAST(s.period_end AS VARCHAR) AS period_end', + 's.fiscal_period', + 's.currency', + 'epoch_ms(s.period_known_at) AS period_known_at', + ]; + const schema: TableColumnSpec[] = [...FUNDAMENTALS_BASE_SCHEMA]; + + for (const field of fields) { + innerCols.push(`f.${field}`); + if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) { + outerCols.push( + `CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.${field} ELSE NULL END AS ${field}` + ); + } else { + outerCols.push(`s.${field}`); + } + schema.push({ name: field, kind: 'number', nullable: true }); + } + + if (hasTtmField) { + innerCols.push('f.ttm_period_end', 'f.ttm_currency', 'f.ttm_has_estimated_lag'); + outerCols.push( + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end', + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency', + 's.ttm_has_estimated_lag' + ); + schema.push(...FUNDAMENTALS_TTM_META_SCHEMA); + } + + const columns = schema.map(spec => spec.name); + const sql = + `WITH latest AS (SELECT ${innerCols.join(', ')} ` + + 'FROM read_parquet(?, hive_partitioning = true) AS f ' + + `WHERE f.listing_id IN (${listingPlaceholders}) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ` + + 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + + `SELECT ${outerCols.join(', ')} ` + + 'FROM latest AS s ' + + 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + + 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + + 'ORDER BY s.listing_id ASC'; + const params: DuckDbParam[] = [fundamentalsPath, ...listingIds, asOfIso, allowEstimatedLag]; + + return { + planned: { sql, params, fenced }, + columns, + schema, + }; +} + +/** + * Plans a Vault-fenced point-in-time DuckDB SQL query over curated + * `fundamentals_pit/year=*\/part.parquet` snapshots. + * + * Selects at most one snapshot per requested `listing_id` — the latest with + * `effective_known_at <= asOf` (clamped strictly below `vaultCutoffTs`). When + * `allowEstimatedLag` is `false`, listings whose selected snapshot has + * `has_estimated_lag = true` are omitted without falling back to an older + * snapshot, and requested `ttm_*` value fields plus `ttm_period_end` / + * `ttm_currency` are masked to `NULL` when `ttm_has_estimated_lag` is `true` + * while preserving `ttm_has_estimated_lag`. + */ +export function planFundamentalsAsOfQuery( + q: FundamentalsAsOfQuery, + ctx: DuckDbPlanContext +): PlannedDuckDbQuery { + return planFundamentalsAsOfInternal(q, ctx).planned; +} + function readRequiredInt32(row: Record, key: string, rowIndex: number): number { const val = row[key]; if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) { @@ -1712,6 +1950,14 @@ function readValidatedTableCell( ); } return val; + case 'boolean': + if (typeof val !== 'boolean') { + throw new MarketDataStoreValidationError( + `Expected boolean for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, + spec.name + ); + } + return val; } } @@ -2038,8 +2284,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption return Promise.reject(new MarketDataStoreNotImplementedError('crossSection')); }, - fundamentalsAsOf(): Promise { - return Promise.reject(new MarketDataStoreNotImplementedError('fundamentalsAsOf')); + async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ + const { planned, columns, schema } = planFundamentalsAsOfInternal(q, planCtx); + await ensureBudgetInitialized(); + const rawRows = await typedExecutor.query(planned.sql, planned.params); + return mapTableRows(columns, schema, rawRows); }, macroAsOf(): Promise
{ 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..c6da320c --- /dev/null +++ b/libs/research/src/market-data-store-questdb.ts @@ -0,0 +1,462 @@ +/** + * 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, + rounding: 'floor' | 'ceil' +): number { + const quotient = us / 1000n; + const remainder = us % 1000n; + const msBigInt = + rounding === 'ceil' + ? remainder > 0n + ? quotient + 1n + : quotient + : 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, 'floor'), + 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), + // Round sub-millisecond availability up so replay never treats a bar as known before arrival. + knownAt: microsToEpochMs(knownAtUs, 'known_at', i, 'ceil'), + }; + } + + 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 === undefined ? DEFAULT_QUESTDB_BARS_BATCH_SIZE : options.batchSize; + 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/src/market-data-store-routed.ts b/libs/research/src/market-data-store-routed.ts new file mode 100644 index 00000000..a7b52608 --- /dev/null +++ b/libs/research/src/market-data-store-routed.ts @@ -0,0 +1,192 @@ +/** + * Pure, dependency-free `MarketDataStore` router that dispatches intraday + * `bars` queries (`timeframe: '1m'`) to an injected intraday reader (such as + * {@link createQuestDbIntradayBarsReader}) and routes every other `bars` + * timeframe and all other `MarketDataStore` methods to the injected daily + * store (such as {@link createDuckDbMarketDataStore}). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero bare `process` + * access, and no database or filesystem I/O. + * + * Vault & point-in-time semantics: + * - This router adds no Vault logic of its own; each delegate continues to + * enforce its own Vault holdout fence and point-in-time predicates. + * - Callers MUST construct both `daily` and `intraday` with the exact same + * `vaultCutoffTs` and `vaultOperatorAuthorized` values (and pass the same + * `vaultCutoffTs` to MCP tools such as `createQueryDataTool`, which is + * always Vault-fenced) so the holdout boundary is identical across + * timeframes. + * - The QuestDB intraday reader (`createQuestDbIntradayBarsReader`) supports + * split-unadjusted `adjustment: 'raw'` `1m` bars; non-`'raw'` `1m` requests + * and unsupported timeframes (`'5m'`, `'1h'`) are handled by the respective + * delegate without modification. + */ + +import { type MarketDataStore, MarketDataStoreValidationError } from './market-data-store'; + +/** Configuration for {@link createRoutedMarketDataStore}. */ +export interface RoutedMarketDataStoreOptions { + /** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */ + readonly daily: MarketDataStore; + /** Backing intraday reader for `bars` queries with `timeframe: '1m'`. */ + readonly intraday: Pick; +} + +const REQUIRED_DAILY_METHODS = [ + 'bars', + 'crossSection', + 'fundamentalsAsOf', + 'events', + 'shortsAsOf', + 'macroAsOf', + 'fx', + 'universe', +] as const satisfies readonly (keyof MarketDataStore)[]; + +function isPlainObject(value: unknown): value is Record { + if (typeof value !== 'object' || value === null) { + return false; + } + const proto: unknown = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +function isDelegateObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function isIntraday1mBarsQuery(q: unknown): boolean { + return ( + typeof q === 'object' && + q !== null && + !Array.isArray(q) && + (q as { readonly timeframe?: unknown }).timeframe === '1m' + ); +} + +/** + * Composes a daily `MarketDataStore` and an intraday `bars` reader into a + * single read-only `MarketDataStore`. + * + * Routing rules: + * - `bars(q)` with `q.timeframe === '1m'` delegates directly to + * `options.intraday.bars(q)` and returns its `AsyncIterable` + * unchanged (preserving receiver, query identity, lazy iteration, and error + * timing). + * - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed + * runtime inputs) delegates directly to `options.daily.bars(q)`. + * - All other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, + * `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly + * to `options.daily` and return its original promise. + * + * Vault fence note: + * Both `daily` and `intraday` MUST be constructed with the exact same + * `vaultCutoffTs` and `vaultOperatorAuthorized` settings. The QuestDB intraday + * reader serves raw (`adjustment: 'raw'`) `1m` bars. + * + * @example + * ```ts + * const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); + * const vaultOperatorAuthorized = false; + * + * const daily = createDuckDbMarketDataStore({ + * executor: duckDbExecutor, + * curatedRoot: '/mnt/data/stockbot/curated', + * vaultCutoffTs, + * vaultOperatorAuthorized, + * }); + * const intraday = createQuestDbIntradayBarsReader({ + * executor: questDbExecutor, + * vaultCutoffTs, + * vaultOperatorAuthorized, + * }); + * const store = createRoutedMarketDataStore({ daily, intraday }); + * // `createQueryDataTool` is always Vault-fenced and accepts only `vaultCutoffTs`. + * const queryDataTool = createQueryDataTool({ + * store, + * vaultContext: { vaultCutoffTs }, + * }); + * ``` + */ +export function createRoutedMarketDataStore( + options: RoutedMarketDataStoreOptions +): MarketDataStore { + if (!isPlainObject(options)) { + throw new MarketDataStoreValidationError( + 'Expected a plain RoutedMarketDataStoreOptions object.', + 'options' + ); + } + + const rawDaily: unknown = options.daily; + if (!isDelegateObject(rawDaily)) { + throw new MarketDataStoreValidationError( + 'Expected `daily` to be a MarketDataStore object.', + 'daily' + ); + } + + for (const method of REQUIRED_DAILY_METHODS) { + if (typeof rawDaily[method] !== 'function') { + throw new MarketDataStoreValidationError( + `Expected \`daily.${method}\` to be a function.`, + `daily.${method}` + ); + } + } + + const rawIntraday: unknown = options.intraday; + if (!isDelegateObject(rawIntraday)) { + throw new MarketDataStoreValidationError( + 'Expected `intraday` to be an object with a `bars` method.', + 'intraday' + ); + } + + if (typeof rawIntraday.bars !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `intraday.bars` to be a function.', + 'intraday.bars' + ); + } + + const daily = options.daily; + const intraday = options.intraday; + + return { + bars(q) { + if (isIntraday1mBarsQuery(q)) { + return intraday.bars(q); + } + return daily.bars(q); + }, + + crossSection(q) { + return daily.crossSection(q); + }, + + fundamentalsAsOf(q) { + return daily.fundamentalsAsOf(q); + }, + + events(q) { + return daily.events(q); + }, + + shortsAsOf(q) { + return daily.shortsAsOf(q); + }, + + macroAsOf(q) { + return daily.macroAsOf(q); + }, + + fx(q) { + return daily.fx(q); + }, + + universe(q) { + return daily.universe(q); + }, + }; +} diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index fe7922b0..599edece 100644 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -13,6 +13,7 @@ import { type DuckDbPlanContext, EVENT_KINDS, EVENTS_COLUMNS, + FUNDAMENTALS_PIT_VALUE_FIELDS, FX_1D_COLUMNS, FX_PAIR_MAP, MarketDataStoreNotImplementedError, @@ -28,6 +29,7 @@ import { planAdjFactorsMetadataQuery, planBars1dQuery, planEventsQuery, + planFundamentalsAsOfQuery, planFx1dQuery, planShortsAsOfQuery, planUniverseQuery, @@ -44,6 +46,7 @@ import { DEFAULT_UNIVERSE_LOOKBACK_DAYS as subpathDefaultUniverseLookbackDays, EVENT_KINDS as subpathEventKinds, EVENTS_COLUMNS as subpathEventsColumns, + FUNDAMENTALS_PIT_VALUE_FIELDS as subpathFundamentalsPitValueFields, FX_1D_COLUMNS as subpathFx1dColumns, FX_PAIR_MAP as subpathFxPairMap, MarketDataStoreNotImplementedError as SubpathNotImplementedError, @@ -54,6 +57,7 @@ import { planAdjFactorsMetadataQuery as subpathPlanAdjFactorsMetadataQuery, planBars1dQuery as subpathPlanBars1dQuery, planEventsQuery as subpathPlanEventsQuery, + planFundamentalsAsOfQuery as subpathPlanFundamentalsAsOfQuery, planFx1dQuery as subpathPlanFx1dQuery, planShortsAsOfQuery as subpathPlanShortsAsOfQuery, planUniverseQuery as subpathPlanUniverseQuery, @@ -215,6 +219,8 @@ describe('market-data-store-duckdb exports', () => { expect(planShortsAsOfQuery).toBe(subpathPlanShortsAsOfQuery); expect(planFx1dQuery).toBe(subpathPlanFx1dQuery); expect(planUniverseQuery).toBe(subpathPlanUniverseQuery); + expect(planFundamentalsAsOfQuery).toBe(subpathPlanFundamentalsAsOfQuery); + expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toBe(subpathFundamentalsPitValueFields); expect(planAdjFactorsMetadataQuery).toBe(subpathPlanAdjFactorsMetadataQuery); expect(parseAdjFactorsSnapshotMetadata).toBe(subpathParseAdjFactorsSnapshotMetadata); expect(createDuckDbMarketDataStore).toBe(subpathCreateDuckDbMarketDataStore); @@ -2421,15 +2427,6 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { universe: 'US_EQ', }), }, - { - method: 'fundamentalsAsOf', - run: () => - store.fundamentalsAsOf({ - listingIds: [1], - fields: ['revenue'], - asOf: '2025-01-15', - }), - }, { method: 'macroAsOf', run: () => @@ -2868,3 +2865,415 @@ describe('planUniverseQuery & createDuckDbMarketDataStore().universe()', () => { } }); }); + +describe('planFundamentalsAsOfQuery & createDuckDbMarketDataStore().fundamentalsAsOf()', () => { + const EXPECTED_GLOB = `${CURATED_ROOT}/fundamentals_pit/year=*/part.parquet`; + + it('exports the exact 9 allow-listed FUNDAMENTALS_PIT_VALUE_FIELDS and plans parameterized Hive Parquet SQL', () => { + expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toEqual([ + 'revenue', + 'net_income', + 'operating_cash_flow', + 'total_assets', + 'total_equity', + 'shares_outstanding', + 'ttm_revenue', + 'ttm_net_income', + 'ttm_operating_cash_flow', + ]); + + const nonTtm = planFundamentalsAsOfQuery( + { + listingIds: [202, 101, 202], + fields: ['net_income', 'revenue', 'net_income'], + asOf: '2025-06-15', + }, + DEFAULT_CTX + ); + + expect(nonTtm.sql).toBe( + 'WITH latest AS (SELECT f.listing_id, f.effective_known_at, f.known_at_source, f.has_estimated_lag, f.period_end, f.fiscal_period, f.currency, f.period_known_at, f.net_income, f.revenue ' + + 'FROM read_parquet(?, hive_partitioning = true) AS f ' + + 'WHERE f.listing_id IN (?, ?) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ' + + 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + + 'SELECT s.listing_id, epoch_ms(s.effective_known_at) AS effective_known_at, s.known_at_source, s.has_estimated_lag, CAST(s.period_end AS VARCHAR) AS period_end, s.fiscal_period, s.currency, epoch_ms(s.period_known_at) AS period_known_at, s.net_income, s.revenue ' + + 'FROM latest AS s ' + + 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + + 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + + 'ORDER BY s.listing_id ASC' + ); + expect(nonTtm.params).toEqual([ + EXPECTED_GLOB, + 202, + 101, + '2025-06-15T23:59:59.999999Z', + true, + ]); + expect(nonTtm.fenced).toEqual({ + fromMs: Date.UTC(2025, 5, 15, 0, 0, 0, 0), + toMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999), + asOfMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999), + scope: 'vault_fenced', + clampedTo: false, + clampedAsOf: false, + }); + expect(nonTtm.sql).not.toContain(CURATED_ROOT); + expect(nonTtm.sql).not.toContain('2025-06-15'); + expect(nonTtm.sql).not.toContain('ttm_period_end'); + expect(nonTtm.sql).not.toContain('ttm_currency'); + expect(nonTtm.sql).not.toContain('ttm_has_estimated_lag'); + + const withTtm = planFundamentalsAsOfQuery( + { + listingIds: [101], + fields: ['revenue', 'ttm_revenue', 'ttm_operating_cash_flow', 'revenue', 'ttm_revenue'], + asOf: '2025-06-15T14:30:00.123456+02:00', + allowEstimatedLag: false, + }, + DEFAULT_CTX + ); + + expect(withTtm.sql).toBe( + 'WITH latest AS (SELECT f.listing_id, f.effective_known_at, f.known_at_source, f.has_estimated_lag, f.period_end, f.fiscal_period, f.currency, f.period_known_at, f.revenue, f.ttm_revenue, f.ttm_operating_cash_flow, f.ttm_period_end, f.ttm_currency, f.ttm_has_estimated_lag ' + + 'FROM read_parquet(?, hive_partitioning = true) AS f ' + + 'WHERE f.listing_id IN (?) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ' + + 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + + 'SELECT s.listing_id, epoch_ms(s.effective_known_at) AS effective_known_at, s.known_at_source, s.has_estimated_lag, CAST(s.period_end AS VARCHAR) AS period_end, s.fiscal_period, s.currency, epoch_ms(s.period_known_at) AS period_known_at, s.revenue, ' + + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_revenue ELSE NULL END AS ttm_revenue, ' + + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_operating_cash_flow ELSE NULL END AS ttm_operating_cash_flow, ' + + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end, ' + + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency, ' + + 's.ttm_has_estimated_lag ' + + 'FROM latest AS s ' + + 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + + 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + + 'ORDER BY s.listing_id ASC' + ); + expect(withTtm.params).toEqual([ + EXPECTED_GLOB, + 101, + '2025-06-15T12:30:00.123456Z', + false, + ]); + expect(withTtm.fenced.asOfMs).toBe(Date.UTC(2025, 5, 15, 12, 30, 0, 123)); + expect(withTtm.fenced.clampedAsOf).toBe(false); + }); + + it('clamps asOf at or after vaultCutoffTs to vaultCutoffTs * 1000 - 1 micros even when vaultOperatorAuthorized is true', () => { + const authorizedCtx: DuckDbPlanContext = { + ...DEFAULT_CTX, + vaultOperatorAuthorized: true, + }; + + for (const clampedAsOf of [ + '2026-05-28', + '2026-05-28T00:00:00.000Z', + '2026-05-28T00:00:00.000001Z', + '2026-09-01T15:00:00Z', + ]) { + const planned = planFundamentalsAsOfQuery( + { listingIds: [1], fields: ['revenue'], asOf: clampedAsOf }, + authorizedCtx + ); + expect(planned.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]); + expect(planned.fenced).toEqual({ + fromMs: CUTOFF_MS - 1, + toMs: CUTOFF_MS - 1, + asOfMs: CUTOFF_MS - 1, + scope: 'vault_fenced', + clampedTo: true, + clampedAsOf: true, + }); + } + + // Mid-day cutoff with a date-only asOf on the cutoff date clamps cleanly to 1 microsecond before cutoff. + const midDayCutoffMs = Date.UTC(2026, 4, 28, 12, 0, 0, 0); + const midDayClamped = planFundamentalsAsOfQuery( + { listingIds: [1], fields: ['revenue'], asOf: '2026-05-28' }, + { curatedRoot: CURATED_ROOT, vaultCutoffTs: midDayCutoffMs } + ); + expect(midDayClamped.params).toEqual([EXPECTED_GLOB, 1, '2026-05-28T11:59:59.999999Z', true]); + expect(midDayClamped.fenced.clampedAsOf).toBe(true); + expect(midDayClamped.fenced.clampedTo).toBe(true); + expect(midDayClamped.fenced.asOfMs).toBe(midDayCutoffMs - 1); + + // One microsecond before cutoff stays unclamped and preserves exact micros. + const preCutoffMicros = planFundamentalsAsOfQuery( + { listingIds: [1], fields: ['revenue'], asOf: MAX_ALLOWED_ISO_MICROS }, + DEFAULT_CTX + ); + expect(preCutoffMicros.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]); + expect(preCutoffMicros.fenced.clampedAsOf).toBe(false); + }); + + it('validates fields allow-list, allowEstimatedLag, listingIds, and asOf with zero executor calls on invalid input', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + + const invalidFieldsCases: unknown[] = [ + [], + 'revenue', + null, + undefined, + ['unknown_field'], + ['revenue', 'period_end'], + ['toString'], + ['revenue; DROP TABLE x'], + [123], + ]; + for (const badFields of invalidFieldsCases) { + let caught: unknown; + try { + await store.fundamentalsAsOf({ + listingIds: [1], + fields: badFields as string[], + asOf: '2025-06-15', + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('fields'); + } + + const invalidLagCases: unknown[] = [null, 1, 0, 'true', 'false', {}]; + for (const badLag of invalidLagCases) { + let caught: unknown; + try { + await store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue'], + asOf: '2025-06-15', + allowEstimatedLag: badLag as boolean, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('allowEstimatedLag'); + } + + const invalidAsOfCases: unknown[] = ['', 'not-a-date', '2024-02-30', '2025-06-15T12:00:00', null, undefined]; + for (const badAsOf of invalidAsOfCases) { + let caught: unknown; + try { + await store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue'], + asOf: badAsOf as string, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('asOf'); + } + + await expect( + store.fundamentalsAsOf({ listingIds: [], fields: ['revenue'], asOf: '2025-06-15' }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + await expect( + store.fundamentalsAsOf(null as unknown as Parameters[0]) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + + expect(fake.calls).toHaveLength(0); + }); + + it('initializes DuckDB budget once and maps fundamentalsAsOf columns in exact projection order with strict scalar validation', async () => { + const t1 = Date.UTC(2024, 7, 1, 20, 0, 0, 0); + const t2 = Date.UTC(2024, 7, 15, 20, 0, 0, 0); + let callIndex = 0; + const fake = createRecordingExecutor({ + onQuery: () => { + callIndex += 1; + if (callIndex === 1) { + return [ + { + listing_id: 101, + effective_known_at: t1, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: t1, + total_assets: null, + revenue: 120.5, + }, + ]; + } + return [ + { + listing_id: 101, + effective_known_at: t2, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: t1, + revenue: 120.5, + ttm_revenue: 450.25, + ttm_period_end: '2024-06-30', + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }, + ]; + }, + }); + + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + const expectedBudget = resolveDuckDbConnectionBudget().statements; + + const first = await store.fundamentalsAsOf({ + listingIds: [101], + fields: ['total_assets', 'revenue', 'total_assets'], + asOf: '2024-08-05', + }); + expect(first.columns).toEqual([ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + 'total_assets', + 'revenue', + ]); + expect(first.rows).toEqual([ + { + listing_id: 101, + effective_known_at: t1, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: t1, + total_assets: null, + revenue: 120.5, + }, + ]); + expect(fake.runCalls).toEqual(expectedBudget); + + const second = await store.fundamentalsAsOf({ + listingIds: [101], + fields: ['revenue', 'ttm_revenue'], + asOf: '2024-08-20', + allowEstimatedLag: false, + }); + expect(second.columns).toEqual([ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + 'revenue', + 'ttm_revenue', + 'ttm_period_end', + 'ttm_currency', + 'ttm_has_estimated_lag', + ]); + expect(second.rows).toHaveLength(1); + expect(second.rows[0]?.ttm_revenue).toBe(450.25); + expect(second.rows[0]?.ttm_has_estimated_lag).toBe(false); + // Budget SET statements must not re-run on second query. + expect(fake.runCalls).toHaveLength(3); + expect(fake.queryCalls).toHaveLength(2); + + // Rejects non-boolean has_estimated_lag from a misbehaving executor. + const badBoolFake = createRecordingExecutor({ + onQuery: () => [ + { + listing_id: 101, + effective_known_at: t1, + known_at_source: 'filing_date', + has_estimated_lag: 'false' as unknown as boolean, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: t1, + revenue: 120.5, + }, + ], + }); + const badStore = createDuckDbMarketDataStore({ + executor: badBoolFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + await expect( + badStore.fundamentalsAsOf({ listingIds: [101], fields: ['revenue'], asOf: '2024-08-05' }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + }); +}); + +describe('fundamentalsAsOf hostile request inputs', () => { + it('fails closed with zero executor calls for JSON-decoded object, symbol, and sparse field entries', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + + const hostileFields: unknown[] = [ + JSON.parse('[{"toString": 1}]'), + [Object.create(null)], + [Symbol('revenue')], + // eslint-disable-next-line no-sparse-arrays + [, 'revenue'], + ['REVENUE'], + [' revenue'], + ]; + for (const fields of hostileFields) { + await expect( + store.fundamentalsAsOf({ listingIds: [1], fields: fields as string[], asOf: '2025-06-15' }) + ).rejects.toThrow(); + } + + const hostileLag = JSON.parse('{"toString": 1}'); + await expect( + store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue'], + asOf: '2025-06-15', + allowEstimatedLag: hostileLag as boolean, + }) + ).rejects.toThrow(); + + expect(fake.calls).toHaveLength(0); + expect(fake.runCalls).toHaveLength(0); + }); + + it('plans a request asOf with an offset that crosses the cutoff as a clamped bound', () => { + // 2026-05-28T01:00:00+02:00 === 2026-05-27T23:00:00Z, i.e. before the cutoff: not clamped. + const beforeCutoff = planFundamentalsAsOfQuery( + { listingIds: [1], fields: ['revenue'], asOf: '2026-05-28T01:00:00+02:00' }, + DEFAULT_CTX + ); + expect(Date.parse(beforeCutoff.params[2] as string)).toBe(Date.UTC(2026, 4, 27, 23, 0, 0, 0)); + expect(beforeCutoff.fenced.clampedAsOf).toBe(false); + + // 2026-05-27T23:00:00-02:00 === 2026-05-28T01:00:00Z, i.e. after the cutoff: clamped. + const afterCutoff = planFundamentalsAsOfQuery( + { listingIds: [1], fields: ['revenue'], asOf: '2026-05-27T23:00:00-02:00' }, + DEFAULT_CTX + ); + expect(afterCutoff.params[2]).toBe(MAX_ALLOWED_ISO_MICROS); + expect(afterCutoff.fenced.clampedAsOf).toBe(true); + }); +}); diff --git a/libs/research/test/market-data-store-questdb.qa.test.ts b/libs/research/test/market-data-store-questdb.qa.test.ts new file mode 100644 index 00000000..bbe68fb6 --- /dev/null +++ b/libs/research/test/market-data-store-questdb.qa.test.ts @@ -0,0 +1,346 @@ +import { describe, expect, it } from 'bun:test'; +import { + createQuestDbIntradayBarsReader, + MarketDataStoreValidationError, + planBars1mQuery, + VaultScopeNotAuthorizedError, + type BarBatch, + type QuestDbBars1mQuery, + type QuestDbQueryExecutor, +} from '@stock-bot/research'; + +// QA edge cases for T-146 (QuestDB `bars_1m` reader) beyond the programmer suite. + +const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); + +type QueryResult = { readonly rows: readonly Record[] }; + +class ScriptedExecutor implements QuestDbQueryExecutor { + readonly calls: Array<{ sql: string; params: unknown[] }> = []; + constructor(private readonly respond: () => Promise) {} + async query(sql: string, params: readonly unknown[]): Promise { + this.calls.push({ sql, params: [...params] }); + return this.respond(); + } +} + +function executorReturning(result: unknown): ScriptedExecutor { + return new ScriptedExecutor(async () => result as QueryResult); +} + +async function collect(iterable: AsyncIterable): Promise { + const out: BarBatch[] = []; + for await (const batch of iterable) { + out.push(batch); + } + return out; +} + +function us(ms: number, extraMicros = 0n): string { + return (BigInt(ms) * 1000n + extraMicros).toString(); +} + +function row(overrides: Record): Record { + return { + listing_id: '7', + open: 10, + high: 11, + low: 9, + close: 10.5, + volume: 100, + vwap: 10.2, + ...overrides, + }; +} + +const sessionQuery: QuestDbBars1mQuery = { + listingIds: [7], + timeframe: '1m', + from: '2024-03-01T14:30:00Z', + to: '2024-03-01T21:00:00Z', + asOf: '2024-03-01T21:00:00Z', + adjustment: 'raw', +}; + +describe('QuestDB bars_1m reader QA: planner purity and param binding', () => { + it('is deterministic and binds INT32_MAX as a decimal SYMBOL string only in params', () => { + const q: QuestDbBars1mQuery = { ...sessionQuery, listingIds: [2_147_483_647, 1] }; + const a = planBars1mQuery(q, { vaultCutoffTs: VAULT_CUTOFF_TS }); + const b = planBars1mQuery(q, { vaultCutoffTs: VAULT_CUTOFF_TS }); + + expect(a).toEqual(b); + expect(a.params).toEqual([ + '2024-03-01T14:30:00.000Z', + '2024-03-01T21:00:00.000Z', + '1', + '2147483647', + '2024-03-01T21:00:00.000Z', + ]); + expect(a.sql).not.toContain('2147483647'); + expect(a.sql).toContain('listing_id IN ($3, $4) AND known_at <= $5'); + // Only ordinal placeholders and fixed identifiers: no quotes or digits outside `$n` tokens. + expect(a.sql.replace(/\$\d+/g, '').replace('bars_1m', '')).not.toMatch(/[0-9'";]/); + }); + + it('normalizes offset timestamps to UTC ISO-8601 params', () => { + const planned = planBars1mQuery( + { + ...sessionQuery, + from: '2024-03-01T09:30:00-05:00', + to: '2024-03-01T16:00:00.250-05:00', + asOf: '2024-03-01T17:00:00-05:00', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ); + expect(planned.params).toEqual([ + '2024-03-01T14:30:00.000Z', + '2024-03-01T21:00:00.250Z', + '7', + '2024-03-01T22:00:00.000Z', + ]); + }); + + it('passes the executor a copy of params so executor mutation cannot alter later plans', async () => { + const executor = new ScriptedExecutor(async () => ({ rows: [] })); + const mutating: QuestDbQueryExecutor = { + async query(sql, params) { + (params as unknown[]).splice(0, params.length, 'tampered'); + return executor.query(sql, params); + }, + }; + const reader = createQuestDbIntradayBarsReader({ + executor: mutating, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + await collect(reader.bars(sessionQuery)); + await collect(reader.bars(sessionQuery)); + + expect(executor.calls).toHaveLength(2); + expect(executor.calls[1]?.params).toEqual(['tampered']); + expect(planBars1mQuery(sessionQuery, { vaultCutoffTs: VAULT_CUTOFF_TS }).params).toHaveLength( + 4 + ); + }); + + it('rejects numeric-looking string listing IDs and non-array listingIds before querying', async () => { + const executor = executorReturning({ rows: [] }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + const bad: unknown[] = [ + { ...sessionQuery, listingIds: ['7'] }, + { ...sessionQuery, listingIds: [7n] }, + { ...sessionQuery, listingIds: 7 }, + { ...sessionQuery, listingIds: undefined }, + { ...sessionQuery, listingIds: [7, Number.POSITIVE_INFINITY] }, + null, + ]; + for (const q of bad) { + await expect(collect(reader.bars(q as QuestDbBars1mQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + expect(executor.calls).toHaveLength(0); + }); +}); + +describe('QuestDB bars_1m reader QA: Vault and trusted context', () => { + it('planner ignores a vaultOperatorAuthorized flag smuggled on the query object', () => { + const spoofed = { + ...sessionQuery, + from: '2025-07-02', + to: '2025-07-03', + asOf: undefined, + scope: 'vault_evaluation_only', + vaultOperatorAuthorized: true, + } as unknown as QuestDbBars1mQuery; + expect(() => planBars1mQuery(spoofed, { vaultCutoffTs: VAULT_CUTOFF_TS })).toThrow( + VaultScopeNotAuthorizedError + ); + }); + + it('rejects non-boolean truthy vaultOperatorAuthorized in factory options', () => { + for (const flag of ['true', 1, {}]) { + expect(() => + createQuestDbIntradayBarsReader({ + executor: executorReturning({ rows: [] }), + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: flag as unknown as boolean, + }) + ).toThrow(MarketDataStoreValidationError); + } + }); + + it('rejects a non-object planner context', () => { + expect(() => + planBars1mQuery(sessionQuery, null as unknown as { vaultCutoffTs: number }) + ).toThrow(MarketDataStoreValidationError); + }); + + it('rejects unknown scope values before querying', async () => { + const executor = executorReturning({ rows: [] }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + await expect( + collect(reader.bars({ ...sessionQuery, scope: 'all' } as unknown as QuestDbBars1mQuery)) + ).rejects.toThrow(MarketDataStoreValidationError); + expect(executor.calls).toHaveLength(0); + }); + + it('a row known one microsecond before a clamped asOf maps to knownAt exactly at the fence, never past it', async () => { + const executor = executorReturning({ + rows: [ + row({ + ts_us: us(VAULT_CUTOFF_TS - 60_000), + known_at_us: us(VAULT_CUTOFF_TS - 1, -1n), + }), + ], + }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + const rows = ( + await collect( + reader.bars({ + ...sessionQuery, + from: '2025-06-30T23:00:00Z', + to: '2025-12-31', + asOf: '2025-12-31', + }) + ) + ).flatMap(b => b.rows); + expect(rows).toHaveLength(1); + expect(rows[0]?.knownAt).toBe(VAULT_CUTOFF_TS - 1); + expect(rows[0]!.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + }); +}); + +describe('QuestDB bars_1m reader QA: executor result and row defence-in-depth', () => { + it('rejects malformed executor results with a validation error', async () => { + for (const result of [ + null, + undefined, + {}, + { rows: null }, + { rows: 'x' }, + [], + { rows: [null] }, + { rows: [[1]] }, + ]) { + const reader = createQuestDbIntradayBarsReader({ + executor: executorReturning(result), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + await expect(collect(reader.bars(sessionQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + }); + + it('propagates executor failures unchanged and yields nothing', async () => { + const boom = new Error('pgwire connection reset'); + const reader = createQuestDbIntradayBarsReader({ + executor: new ScriptedExecutor(async () => { + throw boom; + }), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + await expect(collect(reader.bars(sessionQuery))).rejects.toBe(boom); + }); + + it('does not call the executor until iteration starts (lazy plan + query)', async () => { + const executor = executorReturning({ rows: [] }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + const iterable = reader.bars(sessionQuery); + expect(executor.calls).toHaveLength(0); + await collect(iterable); + expect(executor.calls).toHaveLength(1); + }); + + it('maps multi-listing rows, undefined vwap to null, and -0 to 0', async () => { + const t0 = Date.UTC(2024, 2, 1, 14, 30); + const executor = executorReturning({ + rows: [ + row({ listing_id: '3', ts_us: us(t0), known_at_us: us(t0 + 60_000), vwap: undefined }), + row({ listing_id: '7', ts_us: us(t0), known_at_us: us(t0 + 60_000), volume: -0, vwap: 0 }), + ], + }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + const rows = (await collect(reader.bars({ ...sessionQuery, listingIds: [7, 3] }))).flatMap( + b => b.rows + ); + expect(rows.map(r => r.listingId)).toEqual([3, 7]); + expect(rows[0]?.vwap).toBeNull(); + expect(Object.is(rows[1]?.volume, 0)).toBe(true); + expect(rows[1]?.vwap).toBe(0); + expect(executor.calls[0]?.params.slice(2, 4)).toEqual(['3', '7']); + }); + + it('rejects timestamp wire values that are unsafe numbers, padded strings, or missing', async () => { + const t0 = Date.UTC(2024, 2, 1, 14, 30); + const bad: Record[] = [ + row({ ts_us: Number.MAX_SAFE_INTEGER + 2, known_at_us: us(t0) }), + row({ ts_us: ` ${us(t0)}`, known_at_us: us(t0) }), + row({ ts_us: `+${us(t0)}`, known_at_us: us(t0) }), + row({ ts_us: us(t0) }), + row({ ts_us: new Date(t0), known_at_us: us(t0) }), + ]; + for (const r of bad) { + const reader = createQuestDbIntradayBarsReader({ + executor: executorReturning({ rows: [r] }), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + await expect(collect(reader.bars(sessionQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + }); + + it('floors sub-millisecond ts and ceils sub-millisecond known_at for pre-1970 instants', async () => { + // ts = -1.5 ms -> floor -2 ms; known_at = -1.5 ms -> ceil -1 ms. + const executor = executorReturning({ + rows: [row({ ts_us: '-1500', known_at_us: -1500n })], + }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + const rows = ( + await collect( + reader.bars({ + ...sessionQuery, + from: '1969-12-31T23:59:59.000Z', + to: '1970-01-01T00:00:00.000Z', + asOf: '1970-01-01T00:00:00.000Z', + }) + ) + ).flatMap(b => b.rows); + expect(rows).toEqual([ + { + listingId: 7, + ts: -2, + open: 10, + high: 11, + low: 9, + close: 10.5, + volume: 100, + vwap: 10.2, + knownAt: -1, + }, + ]); + }); + + it('batch size equal to row count yields one batch; batch size 1 yields one row per batch in order', async () => { + const t0 = Date.UTC(2024, 2, 1, 14, 30); + const rows = Array.from({ length: 4 }, (_, i) => + row({ ts_us: us(t0 + i * 60_000), known_at_us: us(t0 + (i + 1) * 60_000), open: 10 + i }) + ); + const exact = createQuestDbIntradayBarsReader({ + executor: executorReturning({ rows }), + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: 4, + }); + expect((await collect(exact.bars(sessionQuery))).map(b => b.rows.length)).toEqual([4]); + + const single = createQuestDbIntradayBarsReader({ + executor: executorReturning({ rows }), + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: 1, + }); + const batches = await collect(single.bars(sessionQuery)); + expect(batches.map(b => b.rows.length)).toEqual([1, 1, 1, 1]); + expect(batches.map(b => b.rows[0]?.open)).toEqual([10, 11, 12, 13]); + }); +}); 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..b17e06a2 --- /dev/null +++ b/libs/research/test/market-data-store-questdb.test.ts @@ -0,0 +1,768 @@ +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); + }); +}); diff --git a/libs/research/test/market-data-store-routed.test.ts b/libs/research/test/market-data-store-routed.test.ts new file mode 100644 index 00000000..81b38fb6 --- /dev/null +++ b/libs/research/test/market-data-store-routed.test.ts @@ -0,0 +1,1098 @@ +import { describe, expect, it } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + type DuckDbExecutor, + type DuckDbParam, + type MarketDataStore, + MarketDataStoreNotImplementedError, + MarketDataStoreValidationError, + type QuestDbQueryExecutor, + type RoutedMarketDataStoreOptions, + type Table, + type TableRow, + createDuckDbMarketDataStore, + createQuestDbIntradayBarsReader, + createRoutedMarketDataStore, +} from '@stock-bot/research'; +import { createQuestDbIntradayBarsReader as subpathCreateQuestDbIntradayBarsReader } from '@stock-bot/research/market-data-store-questdb'; +import { createRoutedMarketDataStore as subpathCreateRoutedMarketDataStore } from '@stock-bot/research/market-data-store-routed'; +import { + type QueryDataResultPayload, + createMcpServer, + createQueryDataTool, +} from '../src/mcp/index'; + +type BarsQuery = Parameters[0]; +type CrossSectionQuery = Parameters[0]; +type FundamentalsQuery = Parameters[0]; +type EventsQuery = Parameters[0]; +type ShortsQuery = Parameters[0]; +type MacroQuery = Parameters[0]; +type FxQuery = Parameters[0]; +type UniverseQuery = Parameters[0]; + +const LISTING_ID = 42; +const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z +const VAULT_CUTOFF_US = VAULT_CUTOFF_TS * 1000; +const CLAMPED_END_ISO = '2025-06-30T23:59:59.999Z'; +const CURATED_ROOT = '/mnt/data/stockbot/curated'; + +function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { + return { + listingId, + ts, + open: close - 0.5, + high: close + 0.5, + low: close - 1, + close, + volume: 1_000, + vwap: close, + knownAt, + }; +} + +async function collectBatches(iterable: AsyncIterable): Promise { + const batches: BarBatch[] = []; + for await (const batch of iterable) { + batches.push(batch); + } + return batches; +} + +class PrototypeDailyStore implements MarketDataStore { + readonly calls: { method: keyof MarketDataStore; arg: unknown }[] = []; + readonly returnedPromises = new Map>(); + readonly barsBatches: BarBatch[]; + + constructor(barsBatches: BarBatch[] = []) { + this.barsBatches = barsBatches; + } + + private assertReceiver(): void { + if (!(this instanceof PrototypeDailyStore)) { + throw new Error('Lost daily receiver (`this`).'); + } + } + + bars(q: BarsQuery): AsyncIterable { + this.assertReceiver(); + this.calls.push({ method: 'bars', arg: q }); + const batches = this.barsBatches; + return { + async *[Symbol.asyncIterator]() { + for (const batch of batches) { + yield batch; + } + }, + }; + } + + crossSection(q: CrossSectionQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'crossSection', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id'], rows: [{ listing_id: 42 }] }); + this.returnedPromises.set('crossSection', p); + return p; + } + + fundamentalsAsOf(q: FundamentalsQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'fundamentalsAsOf', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id', 'revenue'], rows: [] }); + this.returnedPromises.set('fundamentalsAsOf', p); + return p; + } + + events(q: EventsQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'events', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id', 'kind'], rows: [] }); + this.returnedPromises.set('events', p); + return p; + } + + shortsAsOf(q: ShortsQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'shortsAsOf', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id', 'shares_short'], rows: [] }); + this.returnedPromises.set('shortsAsOf', p); + return p; + } + + macroAsOf(q: MacroQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'macroAsOf', arg: q }); + const p = Promise.resolve
({ columns: ['country', 'value'], rows: [] }); + this.returnedPromises.set('macroAsOf', p); + return p; + } + + fx(q: FxQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'fx', arg: q }); + const p = Promise.resolve
({ columns: ['pair', 'close'], rows: [] }); + this.returnedPromises.set('fx', p); + return p; + } + + universe(q: UniverseQuery): Promise { + this.assertReceiver(); + this.calls.push({ method: 'universe', arg: q }); + const p = Promise.resolve([42, 101]); + this.returnedPromises.set('universe', p); + return p; + } +} + +class PrototypeIntradayReader implements Pick { + readonly calls: BarsQuery[] = []; + readonly barsBatches: BarBatch[]; + + constructor(barsBatches: BarBatch[] = []) { + this.barsBatches = barsBatches; + } + + bars(q: BarsQuery): AsyncIterable { + if (!(this instanceof PrototypeIntradayReader)) { + throw new Error('Lost intraday receiver (`this`).'); + } + this.calls.push(q); + const batches = this.barsBatches; + return { + async *[Symbol.asyncIterator]() { + for (const batch of batches) { + yield batch; + } + }, + }; + } +} + +interface QuestDbFixtureRow { + readonly listing_id: string; + readonly ts_us: number; + readonly open: number; + readonly high: number; + readonly low: number; + readonly close: number; + readonly volume: number; + readonly vwap: number | null; + readonly known_at_us: number; +} + +class PredicateAwareQuestDbExecutor implements QuestDbQueryExecutor { + readonly calls: { readonly sql: string; readonly params: readonly unknown[] }[] = []; + private readonly rows: readonly QuestDbFixtureRow[]; + private readonly leaky: boolean; + + constructor(rows: readonly QuestDbFixtureRow[], options?: { leaky?: boolean }) { + this.rows = rows; + this.leaky = options?.leaky === true; + } + + async query( + sql: string, + params: readonly unknown[] + ): Promise<{ readonly rows: readonly Record[] }> { + this.calls.push({ sql, params: [...params] }); + if (this.leaky) { + return { rows: this.rows as unknown as readonly Record[] }; + } + const fromUs = Date.parse(String(params[0])) * 1000; + const toUs = Date.parse(String(params[1])) * 1000; + const asOfUs = Date.parse(String(params[params.length - 1])) * 1000; + const listingIds = new Set(params.slice(2, params.length - 1).map(String)); + + const filtered = this.rows.filter( + row => + row.ts_us >= fromUs && + row.ts_us <= toUs && + row.known_at_us <= asOfUs && + listingIds.has(row.listing_id) + ); + return { rows: filtered as unknown as readonly Record[] }; + } +} + +class RecordingDuckDbExecutor implements DuckDbExecutor { + readonly runCalls: string[] = []; + readonly queryCalls: { readonly sql: string; readonly params: readonly DuckDbParam[] }[] = []; + private readonly rows: readonly TableRow[]; + + constructor(rows: readonly TableRow[] = []) { + this.rows = rows; + } + + async run(sql: string): Promise { + this.runCalls.push(sql); + } + + async query(sql: string, params: readonly DuckDbParam[]): Promise { + this.queryCalls.push({ sql, params: [...params] }); + return this.rows; + } +} + +describe('package exports', () => { + it('re-exports createRoutedMarketDataStore and createQuestDbIntradayBarsReader from root and subpaths', () => { + expect(createRoutedMarketDataStore).toBe(subpathCreateRoutedMarketDataStore); + expect(createQuestDbIntradayBarsReader).toBe(subpathCreateQuestDbIntradayBarsReader); + }); +}); + +describe('createRoutedMarketDataStore', () => { + describe('constructor validation', () => { + it('rejects null, primitives, arrays, and class instances for options', () => { + const invalidOptions: unknown[] = [ + null, + undefined, + 42, + 'options', + true, + [], + new Date(), + new (class OptionsClass { + daily = new PrototypeDailyStore(); + intraday = new PrototypeIntradayReader(); + })(), + ]; + + for (const bad of invalidOptions) { + let caught: unknown; + try { + createRoutedMarketDataStore(bad as RoutedMarketDataStoreOptions); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('options'); + } + }); + + it('accepts a null-prototype options object and prototype-backed delegates', () => { + const options = Object.create(null) as { + daily: MarketDataStore; + intraday: Pick; + }; + options.daily = new PrototypeDailyStore(); + options.intraday = new PrototypeIntradayReader(); + + const store = createRoutedMarketDataStore(options); + expect(typeof store.bars).toBe('function'); + }); + + it('rejects missing or malformed daily delegate and each missing daily method', () => { + const intraday = new PrototypeIntradayReader(); + + for (const badDaily of [null, undefined, 'daily', 123, []]) { + let caught: unknown; + try { + createRoutedMarketDataStore({ + daily: badDaily as unknown as MarketDataStore, + intraday, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('daily'); + } + + const requiredMethods: (keyof MarketDataStore)[] = [ + 'bars', + 'crossSection', + 'fundamentalsAsOf', + 'events', + 'shortsAsOf', + 'macroAsOf', + 'fx', + 'universe', + ]; + + for (const missingMethod of requiredMethods) { + const base = new PrototypeDailyStore(); + const incomplete: Record = { + bars: base.bars.bind(base), + crossSection: base.crossSection.bind(base), + fundamentalsAsOf: base.fundamentalsAsOf.bind(base), + events: base.events.bind(base), + shortsAsOf: base.shortsAsOf.bind(base), + macroAsOf: base.macroAsOf.bind(base), + fx: base.fx.bind(base), + universe: base.universe.bind(base), + }; + delete incomplete[missingMethod]; + + let caughtMissing: unknown; + try { + createRoutedMarketDataStore({ + daily: incomplete as unknown as MarketDataStore, + intraday, + }); + } catch (err) { + caughtMissing = err; + } + expect(caughtMissing).toBeInstanceOf(MarketDataStoreValidationError); + expect((caughtMissing as MarketDataStoreValidationError).field).toBe( + `daily.${missingMethod}` + ); + + incomplete[missingMethod] = 'not-a-function'; + let caughtNonFn: unknown; + try { + createRoutedMarketDataStore({ + daily: incomplete as unknown as MarketDataStore, + intraday, + }); + } catch (err) { + caughtNonFn = err; + } + expect(caughtNonFn).toBeInstanceOf(MarketDataStoreValidationError); + expect((caughtNonFn as MarketDataStoreValidationError).field).toBe( + `daily.${missingMethod}` + ); + } + }); + + it('rejects missing or non-callable intraday delegate and intraday.bars', () => { + const daily = new PrototypeDailyStore(); + + for (const badIntraday of [null, undefined, 'intraday', 99, []]) { + let caught: unknown; + try { + createRoutedMarketDataStore({ + daily, + intraday: badIntraday as unknown as Pick, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('intraday'); + } + + for (const badBars of [undefined, null, 'bars', 42, {}]) { + let caught: unknown; + try { + createRoutedMarketDataStore({ + daily, + intraday: { bars: badBars } as unknown as Pick, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('intraday.bars'); + } + }); + }); + + describe('routing and delegation', () => { + it('routes 1m bars exclusively to intraday and 1d bars exclusively to daily with exact query identity', async () => { + const intradayBatch: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 101.25)], + }; + const dailyBatch: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 20, 0, 0), 102.5)], + }; + const daily = new PrototypeDailyStore([dailyBatch]); + const intraday = new PrototypeIntradayReader([intradayBatch]); + const store = createRoutedMarketDataStore({ daily, intraday }); + + const q1m: BarsQuery = { + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + }; + const q1d: BarsQuery = { + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-01', + to: '2025-06-30', + adjustment: 'raw', + }; + + const intradayOut = await collectBatches(store.bars(q1m)); + expect(intraday.calls).toHaveLength(1); + expect(intraday.calls[0]).toBe(q1m); + expect(daily.calls).toHaveLength(0); + expect(intradayOut).toHaveLength(1); + expect(intradayOut[0]).toBe(intradayBatch); + + const dailyOut = await collectBatches(store.bars(q1d)); + expect(daily.calls).toHaveLength(1); + expect(daily.calls[0]?.method).toBe('bars'); + expect(daily.calls[0]?.arg).toBe(q1d); + expect(intraday.calls).toHaveLength(1); + expect(dailyOut).toHaveLength(1); + expect(dailyOut[0]).toBe(dailyBatch); + }); + + it('forwards invalid timeframe values and non-object inputs to daily unchanged', async () => { + const daily = new PrototypeDailyStore(); + const intraday = new PrototypeIntradayReader(); + const store = createRoutedMarketDataStore({ daily, intraday }); + + const arrayWithTimeframe = Object.assign(['1m'], { timeframe: '1m' }); + const malformedInputs: unknown[] = [ + null, + undefined, + '1m', + 42, + ['1m'], + arrayWithTimeframe, + { listingIds: [42], timeframe: '2m', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, + { listingIds: [42], timeframe: '', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, + ]; + + for (const badInput of malformedInputs) { + await collectBatches(store.bars(badInput as BarsQuery)); + } + + expect(intraday.calls).toHaveLength(0); + expect(daily.calls).toHaveLength(malformedInputs.length); + for (let i = 0; i < malformedInputs.length; i += 1) { + expect(daily.calls[i]?.method).toBe('bars'); + expect(daily.calls[i]?.arg).toBe(malformedInputs[i]); + } + }); + + it('preserves DuckDB MarketDataStoreNotImplementedError for 5m and 1h with zero executor or intraday calls', async () => { + const duckExecutor = new RecordingDuckDbExecutor(); + const daily = createDuckDbMarketDataStore({ + executor: duckExecutor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const intraday = new PrototypeIntradayReader(); + const store = createRoutedMarketDataStore({ daily, intraday }); + + for (const timeframe of ['5m', '1h'] as const) { + let caught: unknown; + try { + for await (const _batch of store.bars({ + listingIds: [LISTING_ID], + timeframe, + from: '2025-06-01', + to: '2025-06-30', + adjustment: 'raw', + })) { + // unreachable + } + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreNotImplementedError); + } + + expect(duckExecutor.runCalls).toHaveLength(0); + expect(duckExecutor.queryCalls).toHaveLength(0); + expect(intraday.calls).toHaveLength(0); + }); + + it('delegates all seven non-bars methods (including fx 1m) to daily with argument, receiver, and promise identity', async () => { + const daily = new PrototypeDailyStore(); + const intraday = new PrototypeIntradayReader(); + const store = createRoutedMarketDataStore({ daily, intraday }); + + const crossSectionArg: CrossSectionQuery = { + features: ['ret_1d@v1'], + date: '2025-06-30', + universe: 'US_EQ', + }; + const fundamentalsArg: FundamentalsQuery = { + listingIds: [LISTING_ID], + fields: ['revenue'], + asOf: '2025-06-30', + }; + const eventsArg: EventsQuery = { + kinds: ['filing'], + listingIds: [LISTING_ID], + from: '2025-06-01', + to: '2025-06-30', + }; + const shortsArg: ShortsQuery = { + listingIds: [LISTING_ID], + from: '2025-06-01', + to: '2025-06-30', + }; + const macroArg: MacroQuery = { + countries: ['US'], + indicators: ['CPI'], + from: '2025-06-01', + to: '2025-06-30', + }; + const fxArg: FxQuery = { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-06-01', + to: '2025-06-30', + }; + const universeArg: UniverseQuery = { + ref: 'US_EQ', + date: '2025-06-30', + }; + + const pCrossSection = store.crossSection(crossSectionArg); + const pFundamentals = store.fundamentalsAsOf(fundamentalsArg); + const pEvents = store.events(eventsArg); + const pShorts = store.shortsAsOf(shortsArg); + const pMacro = store.macroAsOf(macroArg); + const pFx = store.fx(fxArg); + const pUniverse = store.universe(universeArg); + + expect(pCrossSection).toBe(daily.returnedPromises.get('crossSection') as Promise
); + expect(pFundamentals).toBe(daily.returnedPromises.get('fundamentalsAsOf') as Promise
); + expect(pEvents).toBe(daily.returnedPromises.get('events') as Promise
); + expect(pShorts).toBe(daily.returnedPromises.get('shortsAsOf') as Promise
); + expect(pMacro).toBe(daily.returnedPromises.get('macroAsOf') as Promise
); + expect(pFx).toBe(daily.returnedPromises.get('fx') as Promise
); + expect(pUniverse).toBe(daily.returnedPromises.get('universe') as Promise); + + await Promise.all([ + pCrossSection, + pFundamentals, + pEvents, + pShorts, + pMacro, + pFx, + pUniverse, + ]); + + expect(intraday.calls).toHaveLength(0); + expect(daily.calls).toHaveLength(7); + expect(daily.calls[0]).toEqual({ method: 'crossSection', arg: crossSectionArg }); + expect(daily.calls[0]?.arg).toBe(crossSectionArg); + expect(daily.calls[1]).toEqual({ method: 'fundamentalsAsOf', arg: fundamentalsArg }); + expect(daily.calls[1]?.arg).toBe(fundamentalsArg); + expect(daily.calls[2]).toEqual({ method: 'events', arg: eventsArg }); + expect(daily.calls[2]?.arg).toBe(eventsArg); + expect(daily.calls[3]).toEqual({ method: 'shortsAsOf', arg: shortsArg }); + expect(daily.calls[3]?.arg).toBe(shortsArg); + expect(daily.calls[4]).toEqual({ method: 'macroAsOf', arg: macroArg }); + expect(daily.calls[4]?.arg).toBe(macroArg); + expect(daily.calls[5]).toEqual({ method: 'fx', arg: fxArg }); + expect(daily.calls[5]?.arg).toBe(fxArg); + expect(daily.calls[6]).toEqual({ method: 'universe', arg: universeArg }); + expect(daily.calls[6]?.arg).toBe(universeArg); + }); + }); + + describe('error propagation and lazy iteration', () => { + it('propagates exact error instances for sync throws, promise rejections, and mid-iteration failures', async () => { + const syncIntradayErr = new Error('sync intraday boom'); + const syncDailyErr = new Error('sync daily boom'); + const rejectedUniverseErr = new Error('async universe boom'); + const iterErr = new Error('mid-iteration boom'); + + const baseDaily = new PrototypeDailyStore(); + const firstBatch: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], + }; + + const dailySyncStore = createRoutedMarketDataStore({ + daily: { + bars: () => { + throw syncDailyErr; + }, + crossSection: baseDaily.crossSection.bind(baseDaily), + fundamentalsAsOf: baseDaily.fundamentalsAsOf.bind(baseDaily), + events: baseDaily.events.bind(baseDaily), + shortsAsOf: baseDaily.shortsAsOf.bind(baseDaily), + macroAsOf: baseDaily.macroAsOf.bind(baseDaily), + fx: baseDaily.fx.bind(baseDaily), + universe: () => Promise.reject(rejectedUniverseErr), + }, + intraday: { + bars: () => { + throw syncIntradayErr; + }, + }, + }); + + let caughtSyncIntraday: unknown; + try { + dailySyncStore.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + }); + } catch (err) { + caughtSyncIntraday = err; + } + expect(caughtSyncIntraday).toBe(syncIntradayErr); + + let caughtSyncDaily: unknown; + try { + dailySyncStore.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + }); + } catch (err) { + caughtSyncDaily = err; + } + expect(caughtSyncDaily).toBe(syncDailyErr); + + let caughtRejected: unknown; + try { + await dailySyncStore.universe({ ref: 'US_EQ', date: '2025-06-30' }); + } catch (err) { + caughtRejected = err; + } + expect(caughtRejected).toBe(rejectedUniverseErr); + + const iterFailStore = createRoutedMarketDataStore({ + daily: baseDaily, + intraday: { + bars() { + return { + async *[Symbol.asyncIterator]() { + yield firstBatch; + throw iterErr; + }, + }; + }, + }, + }); + + const received: BarBatch[] = []; + let caughtIter: unknown; + try { + for await (const batch of iterFailStore.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + })) { + received.push(batch); + } + } catch (err) { + caughtIter = err; + } + expect(received).toHaveLength(1); + expect(received[0]).toBe(firstBatch); + expect(caughtIter).toBe(iterErr); + }); + + it('preserves lazy iteration and closes the delegate iterator on early exit', async () => { + const batch1: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], + }; + const batch2: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 31, 0), 101)], + }; + let nextCalls = 0; + let returnCalls = 0; + + const store = createRoutedMarketDataStore({ + daily: new PrototypeDailyStore(), + intraday: { + bars() { + return { + [Symbol.asyncIterator]() { + const batches = [batch1, batch2]; + return { + async next() { + const idx = nextCalls; + nextCalls += 1; + const value = batches[idx]; + if (value === undefined) { + return { done: true as const, value: undefined }; + } + return { done: false as const, value }; + }, + async return() { + returnCalls += 1; + return { done: true as const, value: undefined }; + }, + }; + }, + }; + }, + }, + }); + + const consumed: BarBatch[] = []; + for await (const batch of store.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + })) { + consumed.push(batch); + break; + } + + expect(consumed).toHaveLength(1); + expect(consumed[0]).toBe(batch1); + expect(nextCalls).toBe(1); + expect(returnCalls).toBe(1); + }); + }); + + describe('QuestDB intraday reader integration and Vault fence', () => { + const preCutoffTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; + const preCutoffTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; + const fixtureRows: readonly QuestDbFixtureRow[] = [ + { + listing_id: String(LISTING_ID), + ts_us: preCutoffTs1Us, + open: 100.0, + high: 101.0, + low: 99.5, + close: 100.5, + volume: 500, + vwap: 100.25, + known_at_us: preCutoffTs1Us + 60_000_000, + }, + { + listing_id: String(LISTING_ID), + ts_us: preCutoffTs2Us, + open: 100.5, + high: 101.5, + low: 100.25, + close: 101.25, + volume: 750, + vwap: 101.0, + known_at_us: preCutoffTs2Us + 60_000_000, + }, + // Row with ts exactly at Vault cutoff (must be excluded by fence) + { + listing_id: String(LISTING_ID), + ts_us: VAULT_CUTOFF_US, + open: 102.0, + high: 103.0, + low: 101.5, + close: 102.5, + volume: 900, + vwap: 102.25, + known_at_us: preCutoffTs2Us + 60_000_000, + }, + // Row with known_at exactly at Vault cutoff (must be excluded by fence) + { + listing_id: String(LISTING_ID), + ts_us: preCutoffTs2Us + 60_000_000, + open: 101.25, + high: 102.0, + low: 101.0, + close: 101.75, + volume: 600, + vwap: 101.5, + known_at_us: VAULT_CUTOFF_US, + }, + ]; + + const straddlingQuery: BarsQuery = { + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30T13:30:00Z', + to: '2025-07-05T20:00:00Z', + adjustment: 'raw', + asOf: '2025-07-10T00:00:00Z', + }; + + it('streams batches unchanged from createQuestDbIntradayBarsReader and clamps to/asOf strictly below vaultCutoffTs', async () => { + const directExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); + const directReader = createQuestDbIntradayBarsReader({ + executor: directExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + batchSize: 1, + }); + + const routedExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); + const underlyingIntraday = createQuestDbIntradayBarsReader({ + executor: routedExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + batchSize: 1, + }); + + const yieldedByIntraday: BarBatch[] = []; + const recordingIntraday: Pick = { + bars(q) { + const inner = underlyingIntraday.bars(q); + return { + async *[Symbol.asyncIterator]() { + for await (const batch of inner) { + yieldedByIntraday.push(batch); + yield batch; + } + }, + }; + }, + }; + + const daily = new PrototypeDailyStore(); + const store = createRoutedMarketDataStore({ daily, intraday: recordingIntraday }); + + const directBatches = await collectBatches(directReader.bars(straddlingQuery)); + const routedBatches = await collectBatches(store.bars(straddlingQuery)); + + expect(daily.calls).toHaveLength(0); + expect(routedExecutor.calls).toHaveLength(1); + expect(routedExecutor.calls[0]?.params[1]).toBe(CLAMPED_END_ISO); + expect(routedExecutor.calls[0]?.params[3]).toBe(CLAMPED_END_ISO); + + expect(routedBatches).toEqual(directBatches); + expect(routedBatches).toHaveLength(2); + expect(routedBatches[0]).toBe(yieldedByIntraday[0]); + expect(routedBatches[1]).toBe(yieldedByIntraday[1]); + + for (const batch of routedBatches) { + for (const row of batch.rows) { + expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); + expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + } + } + }); + + it('rejects a leaky QuestDB executor returning a row with ts or known_at at vaultCutoffTs before yielding any batch', async () => { + const tsCutoffRow = fixtureRows[2] as QuestDbFixtureRow; + const knownAtCutoffRow = fixtureRows[3] as QuestDbFixtureRow; + const preCutoffRow = fixtureRows[0] as QuestDbFixtureRow; + + for (const leakyRows of [ + [preCutoffRow, tsCutoffRow], + [preCutoffRow, knownAtCutoffRow], + ]) { + const leakyExecutor = new PredicateAwareQuestDbExecutor(leakyRows, { leaky: true }); + const intraday = createQuestDbIntradayBarsReader({ + executor: leakyExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + batchSize: 1, + }); + const store = createRoutedMarketDataStore({ + daily: new PrototypeDailyStore(), + intraday, + }); + + const yielded: BarBatch[] = []; + let caught: unknown; + try { + for await (const batch of store.bars(straddlingQuery)) { + yielded.push(batch); + } + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect(yielded).toHaveLength(0); + } + }); + }); + + describe('MCP query_data end-to-end over routed store', () => { + it('routes 1m calls to fake QuestDB and 1d calls to fake DuckDB, enforcing the Vault cutoff deterministically', async () => { + const intradayTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; + const intradayTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; + const questDbRows: readonly QuestDbFixtureRow[] = [ + { + listing_id: String(LISTING_ID), + ts_us: intradayTs1Us, + open: 100.0, + high: 100.75, + low: 99.5, + close: 100.5, + volume: 1_200, + vwap: 100.2, + known_at_us: intradayTs1Us + 60_000_000, + }, + { + listing_id: String(LISTING_ID), + ts_us: intradayTs2Us, + open: 100.5, + high: 101.25, + low: 100.25, + close: 101.0, + volume: 1_500, + vwap: 100.8, + known_at_us: intradayTs2Us + 60_000_000, + }, + // Out-of-fence rows at exact cutoff (filtered by predicate-aware executor) + { + listing_id: String(LISTING_ID), + ts_us: VAULT_CUTOFF_US, + open: 105.0, + high: 106.0, + low: 104.0, + close: 105.5, + volume: 2_000, + vwap: 105.2, + known_at_us: intradayTs2Us + 60_000_000, + }, + { + listing_id: String(LISTING_ID), + ts_us: intradayTs2Us + 60_000_000, + open: 101.0, + high: 101.5, + low: 100.75, + close: 101.25, + volume: 1_100, + vwap: 101.1, + known_at_us: VAULT_CUTOFF_US, + }, + ]; + + const dailyBarTs = Date.UTC(2025, 5, 30, 20, 0, 0, 0); + const duckDbRows: readonly TableRow[] = [ + { + listing_id: LISTING_ID, + ts: dailyBarTs, + open: 99.0, + high: 102.0, + low: 98.5, + close: 101.5, + volume: 250_000, + vwap: 100.75, + known_at: dailyBarTs, + }, + ]; + + const questExecutor = new PredicateAwareQuestDbExecutor(questDbRows); + const duckExecutor = new RecordingDuckDbExecutor(duckDbRows); + + const daily = createDuckDbMarketDataStore({ + executor: duckExecutor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }); + const intraday = createQuestDbIntradayBarsReader({ + executor: questExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }); + const routedStore = createRoutedMarketDataStore({ daily, intraday }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: routedStore, + vaultContext: { + vaultCutoffTs: VAULT_CUTOFF_TS, + }, + }), + ], + }); + + const direct1mBatches = await collectBatches( + createQuestDbIntradayBarsReader({ + executor: new PredicateAwareQuestDbExecutor(questDbRows), + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }).bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-07-05', + adjustment: 'raw', + }) + ); + const expected1mRows = direct1mBatches.flatMap(b => b.rows); + + const req1m = JSON.stringify({ + jsonrpc: '2.0', + id: 'mcp-1m', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [LISTING_ID], + from: '2025-06-30', + to: '2025-07-05', + timeframe: '1m', + adjustment: 'raw', + }, + }, + }); + + const raw1mFirst = await server.handleMessage(req1m); + const raw1mSecond = await server.handleMessage(req1m); + expect(raw1mFirst).not.toBeNull(); + expect(raw1mSecond).toBe(raw1mFirst); + + expect(questExecutor.calls).toHaveLength(2); + expect(duckExecutor.queryCalls).toHaveLength(0); + expect(duckExecutor.runCalls).toHaveLength(0); + + const resp1m = JSON.parse(raw1mFirst as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(resp1m.result.isError).toBeUndefined(); + const payload1m = JSON.parse(resp1m.result.content[0]?.text ?? '') as QueryDataResultPayload; + expect(payload1m.rows).toEqual(expected1mRows); + expect(payload1m.rows).toHaveLength(2); + for (const row of payload1m.rows) { + expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); + expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + } + + const direct1dBatches = await collectBatches( + createDuckDbMarketDataStore({ + executor: new RecordingDuckDbExecutor(duckDbRows), + curatedRoot: CURATED_ROOT, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }).bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-25', + to: '2025-07-05', + adjustment: 'raw', + }) + ); + const expected1dRows = direct1dBatches.flatMap(b => b.rows); + + const req1d = JSON.stringify({ + jsonrpc: '2.0', + id: 'mcp-1d', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [LISTING_ID], + from: '2025-06-25', + to: '2025-07-05', + timeframe: '1d', + adjustment: 'raw', + }, + }, + }); + + const raw1dFirst = await server.handleMessage(req1d); + const raw1dSecond = await server.handleMessage(req1d); + expect(raw1dFirst).not.toBeNull(); + expect(raw1dSecond).toBe(raw1dFirst); + + expect(questExecutor.calls).toHaveLength(2); + expect(duckExecutor.queryCalls).toHaveLength(2); + + const resp1d = JSON.parse(raw1dFirst as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(resp1d.result.isError).toBeUndefined(); + const payload1d = JSON.parse(resp1d.result.content[0]?.text ?? '') as QueryDataResultPayload; + expect(payload1d.rows).toEqual(expected1dRows); + expect(payload1d.rows).toHaveLength(1); + for (const row of payload1d.rows) { + expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); + expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + } + }); + }); +});