import { afterEach, describe, expect, test } from 'bun:test'; import { mkdir, mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { computeVaultCutoffTs, VaultHoldoutFenceError, type BarRecord, } from '@stock-bot/research/market-data-store'; import { createNodeDuckDbExecutor, openDuckDbMarketDataStore, } from '../src/index'; const tempDirs: string[] = []; afterEach(async () => { while (tempDirs.length > 0) { const dir = tempDirs.pop(); if (dir !== undefined) { await rm(dir, { recursive: true, force: true }); } } }); async function buildCuratedFixture(): Promise<{ curatedRoot: string; duckTempDir: string; vaultCutoffTs: number; }> { const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-mds-')); tempDirs.push(root); const curatedRoot = join(root, 'curated'); const duckTempDir = join(root, 'duckdb-tmp'); await mkdir(join(curatedRoot, 'bars_1d', 'year=2024'), { recursive: true }); await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); await mkdir(join(curatedRoot, 'adj_factors'), { recursive: true }); await mkdir(join(curatedRoot, 'events', 'year=2024'), { recursive: true }); await mkdir(join(curatedRoot, 'shorts'), { recursive: true }); await mkdir(join(curatedRoot, 'fx_1d'), { recursive: true }); await mkdir(duckTempDir, { recursive: true }); // Max ingested = 2025-08-13 -> Vault cutoff = 2025-02-13T00:00:00.000Z const vaultCutoffTs = computeVaultCutoffTs('2025-08-13'); const vaultCutoffMicros = vaultCutoffTs * 1000; const asOfMicros = vaultCutoffMicros - 1; const writer = await createNodeDuckDbExecutor(); try { // 2024 bars (pre-Vault): listing 101 (USD, NVDA 10:1 split on 2024-06-10) + listing 202 (CAD) await writer.run(` COPY ( SELECT * FROM (VALUES (101::INTEGER, DATE '2024-06-07', TIMESTAMPTZ '2024-06-07 20:00:00+00', 1200.0::DOUBLE, 1220.0::DOUBLE, 1190.0::DOUBLE, 1208.88::DOUBLE, 41238600.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-07 20:00:00+00'), (101::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 120.37::DOUBLE, 123.10::DOUBLE, 117.01::DOUBLE, 121.79::DOUBLE, 314162700.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00'), (202::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 140.0::DOUBLE, 142.0::DOUBLE, 139.0::DOUBLE, 141.5::DOUBLE, 1200000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00') ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) ) TO '${join(curatedRoot, 'bars_1d', 'year=2024', 'part.parquet')}' (FORMAT PARQUET) `); // 2025 bars: one pre-Vault bar (2025-02-12) and one Vault bar (2025-02-14) await writer.run(` COPY ( SELECT * FROM (VALUES (101::INTEGER, DATE '2025-02-12', TIMESTAMPTZ '2025-02-12 20:00:00+00', 130.0::DOUBLE, 132.0::DOUBLE, 129.0::DOUBLE, 131.0::DOUBLE, 200000000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-12 20:00:00+00'), (101::INTEGER, DATE '2025-02-14', TIMESTAMPTZ '2025-02-14 20:00:00+00', 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 1.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-14 20:00:00+00') ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) `); // Point-in-time fenced adj_factors snapshot (10:1 split on 2024-06-10) await writer.run(` COPY ( SELECT * FROM (VALUES (101::INTEGER, DATE '2024-06-10', 10.0::DOUBLE, 10.05::DOUBLE, TIMESTAMPTZ '2024-06-10 00:00:00+00') ) AS t(listing_id, ex_date, cum_split_factor, cum_total_factor, known_at) ) TO '${join(curatedRoot, 'adj_factors', 'part.parquet')}' ( FORMAT PARQUET, KV_METADATA { 'stock_bot.adj_factors.format_version': '1', 'stock_bot.adj_factors.snapshot_kind': 'point_in_time_fenced', 'stock_bot.adj_factors.as_of_micros': '${asOfMicros}', 'stock_bot.adj_factors.vault_cutoff_micros': '${vaultCutoffMicros}', 'stock_bot.adj_factors.rows_written': '1', 'stock_bot.adj_factors.snapshot_checksum': '0x0123456789abcdef' } ) `); // Events (2024 filing) await writer.run(` COPY ( SELECT * FROM (VALUES (202::INTEGER, TIMESTAMPTZ '2024-06-05 14:30:00+00', TIMESTAMPTZ '2024-06-05 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, 'MD&A'::VARCHAR, '{"filing_id":"f1"}'::VARCHAR) ) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json) ) TO '${join(curatedRoot, 'events', 'year=2024', 'part.parquet')}' (FORMAT PARQUET) `); // Canadian shorts (+4 biz day known_at) await writer.run(` COPY ( SELECT * FROM (VALUES (202::INTEGER, DATE '2024-06-15', TIMESTAMPTZ '2024-06-21 21:00:00+00', 500000.0::DOUBLE, 25000.0::DOUBLE, NULL::DOUBLE, 'ceo_shorts'::VARCHAR) ) AS t(listing_id, report_date, known_at, shares_short, net_change, pct_float, source) ) TO '${join(curatedRoot, 'shorts', 'part.parquet')}' (FORMAT PARQUET) `); // FX 1d (USDCAD) await writer.run(` COPY ( SELECT * FROM (VALUES ('USDCAD'::VARCHAR, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 23:59:59.999999+00', 1.375::DOUBLE, 1.378::DOUBLE, 1.372::DOUBLE, 1.376::DOUBLE, 'eod_forex'::VARCHAR, TIMESTAMPTZ '2024-06-10 23:59:59.999999+00') ) AS t(pair, session_date, ts, open, high, low, close, source, known_at) ) TO '${join(curatedRoot, 'fx_1d', 'part.parquet')}' (FORMAT PARQUET) `); } finally { await writer.close(); } return { curatedRoot, duckTempDir, vaultCutoffTs }; } describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => { test('reads real Parquet bars (raw, split, total), events, shorts, fx, universe and enforces Vault fence', async () => { const { curatedRoot, duckTempDir, vaultCutoffTs } = await buildCuratedFixture(); 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. Raw bars: request through 2025-12-31 must clamp before Vault cutoff (2025-02-13) and never return 2025-02-14! const rawBars: BarRecord[] = []; for await (const batch of opened.store.bars({ listingIds: [101], timeframe: '1d', from: '2024-06-01', to: '2025-12-31', adjustment: 'raw', })) { rawBars.push(...batch.rows); } expect(rawBars.length).toBe(3); expect(rawBars.every(r => r.ts < vaultCutoffTs)).toBe(true); expect(rawBars[0]!.close).toBeCloseTo(1208.88, 6); expect(rawBars[0]!.volume).toBeCloseTo(41_238_600, 1); // 2. Vault rejection when from >= vaultCutoffTs let rejected = false; try { for await (const _batch of opened.store.bars({ listingIds: [101], timeframe: '1d', from: '2025-02-13', to: '2025-08-01', adjustment: 'raw', })) { // should not yield } } catch (err) { rejected = err instanceof VaultHoldoutFenceError; } expect(rejected).toBe(true); // 3. Split-adjusted bars via pinned point_in_time_fenced adj_factors snapshot const splitBars: BarRecord[] = []; for await (const batch of opened.store.bars({ listingIds: [101], timeframe: '1d', from: '2024-06-01', to: '2024-06-15', adjustment: 'split', })) { splitBars.push(...batch.rows); } expect(splitBars.length).toBe(2); expect(splitBars[0]!.close).toBeCloseTo(120.888, 6); expect(splitBars[0]!.volume).toBeCloseTo(412_386_000, 1); expect(splitBars[1]!.close).toBeCloseTo(121.79, 6); // 4. Total-return-adjusted bars (price divided by cum_total_factor, volume scaled by cum_split_factor) const totalBars: BarRecord[] = []; for await (const batch of opened.store.bars({ listingIds: [101], timeframe: '1d', from: '2024-06-01', to: '2024-06-15', adjustment: 'total', })) { totalBars.push(...batch.rows); } expect(totalBars.length).toBe(2); expect(totalBars[0]!.close).toBeCloseTo(1208.88 / 10.05, 6); expect(totalBars[0]!.volume).toBeCloseTo(412_386_000, 1); // 5. Events const events = await opened.store.events({ kinds: ['filing'], listingIds: [202], from: '2024-06-01', to: '2024-06-30', }); expect(events.rows.length).toBe(1); expect(events.rows[0]!.subtype).toBe('MD&A'); // 6. Shorts (known_at fence) const shortsBeforeKnown = await opened.store.shortsAsOf({ listingIds: [202], from: '2024-06-01', to: '2024-06-30', asOf: '2024-06-18', }); expect(shortsBeforeKnown.rows.length).toBe(0); const shortsAfterKnown = await opened.store.shortsAsOf({ listingIds: [202], from: '2024-06-01', to: '2024-06-30', asOf: '2024-06-25', }); expect(shortsAfterKnown.rows.length).toBe(1); expect(shortsAfterKnown.rows[0]!.shares_short).toBe(500_000); // 7. FX const fx = await opened.store.fx({ pair: 'USD.CAD', timeframe: '1d', from: '2024-06-01', to: '2024-06-30', }); expect(fx.rows.length).toBe(1); expect(fx.rows[0]!.close).toBeCloseTo(1.376, 6); // 8. Universe expect(await opened.store.universe({ ref: 'US_EQ', date: '2024-06-10' })).toEqual([101]); expect(await opened.store.universe({ ref: 'CA_EQ', date: '2024-06-10' })).toEqual([202]); expect(await opened.store.universe({ ref: 'US_CA_EQ', date: '2024-06-10' })).toEqual([ 101, 202, ]); } finally { 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(); } }); });