From 279f425835cdc524e962a4a896660bd7561aff4f Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:25:46 -0500 Subject: [PATCH 01/15] =?UTF-8?q?T-145:=20M2.2d=20=E2=80=94=20`fundamental?= =?UTF-8?q?sAsOf`=20in=20the=20DuckDB=20`MarketDataStore`:=20Vault-fenced?= =?UTF-8?q?=20point-in-time=20read=20of=20`fundamentals=5Fpit/year=3D*/par?= =?UTF-8?q?t.parquet`=20with=20a=20real-DuckDB=20restatement=20fixture=20t?= =?UTF-8?q?est=20(no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test/duckdb-market-data-store.test.ts | 481 ++++++++++++++++++ libs/research/README.md | 3 +- libs/research/src/market-data-store-duckdb.ts | 255 +++++++++- .../test/market-data-store-duckdb.test.ts | 370 +++++++++++++- 4 files changed, 1096 insertions(+), 13 deletions(-) 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..abd4c3be 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,485 @@ 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(); + } + }); }); diff --git a/libs/research/README.md b/libs/research/README.md index c4c1dae2..dd076551 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 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/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index fe7922b0..6bd7c290 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,358 @@ 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); + }); +}); From fb1c32c5681e950812a7360f797d8381b4a30869 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:32:25 -0500 Subject: [PATCH 02/15] T-145: tests --- .../test/duckdb-market-data-store.test.ts | 200 ++++++++++++++++++ .../test/market-data-store-duckdb.test.ts | 57 +++++ 2 files changed, 257 insertions(+) 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 abd4c3be..dfe3259c 100644 --- a/libs/data/duckdb/test/duckdb-market-data-store.test.ts +++ b/libs/data/duckdb/test/duckdb-market-data-store.test.ts @@ -729,3 +729,203 @@ describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => { } }); }); + +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/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index 6bd7c290..599edece 100644 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -3220,3 +3220,60 @@ describe('planFundamentalsAsOfQuery & createDuckDbMarketDataStore().fundamentals ).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); + }); +}); From adf28209c6309fad7488e47534f9511efde80627 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:40:36 -0500 Subject: [PATCH 03/15] =?UTF-8?q?T-146:=20M2.3f=20=E2=80=94=20QuestDB=20`b?= =?UTF-8?q?ars=5F1m`=20intraday=20reader=20for=20`MarketDataStore.bars`=20?= =?UTF-8?q?(`timeframe:=20'1m'`):=20Vault-fenced,=20parameterized=20`planB?= =?UTF-8?q?ars1mQuery`=20+=20batch=20iterator=20over=20an=20injected=20PGW?= =?UTF-8?q?ire=20query=20port=20in=20`libs/research/src/market-data-store-?= =?UTF-8?q?questdb.ts`=20(pure,=20no=20new=20deps,=20no=20live=20QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/index.ts | 1 + .../research/src/market-data-store-questdb.ts | 448 +++++++++++ .../test/market-data-store-questdb.test.ts | 703 ++++++++++++++++++ 3 files changed, 1152 insertions(+) create mode 100644 libs/research/src/market-data-store-questdb.ts create mode 100644 libs/research/test/market-data-store-questdb.test.ts diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index 0a9f6987..dcc88deb 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -4,6 +4,7 @@ export * from './event-panel'; export * from './feature-library'; export * from './market-data-store'; export * from './market-data-store-duckdb'; +export * from './market-data-store-questdb'; export * from './signal-panel'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/market-data-store-questdb.ts b/libs/research/src/market-data-store-questdb.ts new file mode 100644 index 00000000..08006f3b --- /dev/null +++ b/libs/research/src/market-data-store-questdb.ts @@ -0,0 +1,448 @@ +/** + * Pure, dependency-free QuestDB `bars_1m` query planner and injected-executor + * intraday reader for `MarketDataStore.bars` (`timeframe: '1m'`, + * `design/DATA-CONTRACTS.md` §3.B & §4). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero `pg` or + * `@stock-bot/questdb` dependency, zero bare `process` access. SQL execution + * is injected via {@link QuestDbQueryExecutor}, which is structurally + * compatible with `QuestDBClient.query(sql, params)`. + * + * Storage and point-in-time semantics: + * - `bars_1m` stores split-unadjusted raw 1-minute OHLCV, nullable `vwap`, + * `listing_id` (`SYMBOL`, canonical positive decimal string), `known_at` + * (`TIMESTAMP`), and designated timestamp `ts` (`TIMESTAMP`, + * `PARTITION BY MONTH`). + * - Only `adjustment: 'raw'` is supported; `'split'` and `'total'` throw + * {@link MarketDataStoreNotImplementedError}. + * - Query bounds are Vault-fenced via {@link applyVaultFence} before SQL + * planning. Every user-supplied value is bound via `$1..$n` placeholders; + * only ordinal placeholder tokens are generated in SQL text. + * - `ts` and `known_at` are projected as `CAST(... AS LONG)` (UTC epoch + * microseconds) and verified in exact microseconds against the fenced bounds + * before converting to epoch milliseconds or yielding any batch. + */ + +import { + type BarBatch, + type BarRecord, + type FencedTimeRange, + type MarketDataStore, + MarketDataStoreValidationError, + type VaultFenceContext, + applyVaultFence, +} from './market-data-store'; +import { MarketDataStoreNotImplementedError } from './market-data-store-duckdb'; + +const INT32_MAX = 2_147_483_647; +const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; +const CANONICAL_POSITIVE_INT_RE = /^[1-9]\d*$/; +const CANONICAL_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/; + +/** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */ +export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000; + +/** Input query type derived from `MarketDataStore['bars']`. */ +export type QuestDbBars1mQuery = Parameters[0]; + +/** + * Injected PGWire SQL executor port, structurally compatible with + * `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`. + */ +export interface QuestDbQueryExecutor { + query( + sql: string, + params: readonly unknown[] + ): Promise<{ readonly rows: readonly Record[] }>; +} + +/** Pure output of {@link planBars1mQuery}. */ +export interface PlannedQuestDbBars1mQuery { + readonly sql: string; + readonly params: readonly string[]; + readonly fence: FencedTimeRange; +} + +/** Configuration for {@link createQuestDbIntradayBarsReader}. */ +export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext { + readonly executor: QuestDbQueryExecutor; + /** Maximum number of bars per yielded `BarBatch`. Defaults to `50_000`. */ + readonly batchSize?: number; +} + +interface InternalPlannedBars1mQuery { + readonly planned: PlannedQuestDbBars1mQuery; + readonly requestedListingIds: ReadonlySet; +} + +function isPlainRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function validateVaultCutoffTs(vaultCutoffTs: unknown): number { + if ( + typeof vaultCutoffTs !== 'number' || + !Number.isSafeInteger(vaultCutoffTs) || + Math.abs(vaultCutoffTs) > MAX_ECMASCRIPT_EPOCH_MS || + vaultCutoffTs <= -MAX_ECMASCRIPT_EPOCH_MS + ) { + throw new MarketDataStoreValidationError( + `Invalid epoch millisecond timestamp for "vaultCutoffTs": ${String(vaultCutoffTs)}.`, + 'vaultCutoffTs' + ); + } + return vaultCutoffTs === 0 ? 0 : vaultCutoffTs; +} + +function validatePositiveInt32ListingIds(raw: unknown): number[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + 'Expected a non-empty array of positive INT32 listing IDs for "listingIds".', + 'listingIds' + ); + } + + const seen = new Set(); + const normalized: number[] = []; + for (let i = 0; i < raw.length; i += 1) { + const id: unknown = raw[i]; + if ( + typeof id !== 'number' || + !Number.isSafeInteger(id) || + id < 1 || + id > INT32_MAX + ) { + throw new MarketDataStoreValidationError( + `Invalid positive INT32 listing ID at listingIds[${i}]: ${String(id)}.`, + 'listingIds' + ); + } + if (!seen.has(id)) { + seen.add(id); + normalized.push(id); + } + } + + normalized.sort((a, b) => a - b); + return normalized; +} + +function formatUtcIsoMs(epochMs: number): string { + return new Date(epochMs).toISOString(); +} + +function planBars1mQueryInternal( + q: QuestDbBars1mQuery, + ctx: VaultFenceContext +): InternalPlannedBars1mQuery { + if (!isPlainRecord(ctx)) { + throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx'); + } + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); + } + + const timeframe: unknown = q.timeframe; + if (timeframe !== '1m') { + throw new MarketDataStoreValidationError( + `Invalid bars timeframe "${String(timeframe)}". Expected '1m'.`, + 'timeframe' + ); + } + + const adjustment: unknown = q.adjustment; + if (adjustment === 'split' || adjustment === 'total') { + throw new MarketDataStoreNotImplementedError( + 'bars', + `Adjustment '${adjustment}' is not supported for intraday '1m' bars; bars_1m stores raw split-unadjusted values.` + ); + } + if (adjustment !== 'raw') { + throw new MarketDataStoreValidationError( + `Invalid bars adjustment "${String(adjustment)}". Expected 'raw'.`, + 'adjustment' + ); + } + + const sortedListingIds = validatePositiveInt32ListingIds(q.listingIds); + + const fence = applyVaultFence( + { + from: q.from, + to: q.to, + asOf: q.asOf, + scope: q.scope, + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + vaultOperatorAuthorized: ctx.vaultOperatorAuthorized === true, + } + ); + + const listingPlaceholders = sortedListingIds.map((_, index) => `$${index + 3}`).join(', '); + const asOfPlaceholder = `$${sortedListingIds.length + 3}`; + + const sql = + 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + + 'FROM bars_1m ' + + `WHERE ts >= $1 AND ts <= $2 AND listing_id IN (${listingPlaceholders}) AND known_at <= ${asOfPlaceholder} ` + + 'ORDER BY ts, listing_id'; + + const params: string[] = [ + formatUtcIsoMs(fence.fromMs), + formatUtcIsoMs(fence.toMs), + ...sortedListingIds.map(id => String(id)), + formatUtcIsoMs(fence.asOfMs), + ]; + + return { + planned: { sql, params, fence }, + requestedListingIds: new Set(sortedListingIds), + }; +} + +/** + * Pure, Vault-fenced, parameterized SQL planner for QuestDB `bars_1m`. + * + * Binds `from`, `to`, and `asOf` as exact millisecond UTC ISO-8601 strings and + * deduplicated, numerically sorted positive INT32 `listingIds` as canonical + * decimal `SYMBOL` strings. + */ +export function planBars1mQuery( + q: QuestDbBars1mQuery, + ctx: VaultFenceContext +): PlannedQuestDbBars1mQuery { + return planBars1mQueryInternal(q, ctx).planned; +} + +function parseListingIdSymbol( + row: Record, + rowIndex: number, + requestedListingIds: ReadonlySet +): number { + const raw = row.listing_id; + if (typeof raw !== 'string' || !CANONICAL_POSITIVE_INT_RE.test(raw)) { + throw new MarketDataStoreValidationError( + `Invalid bars_1m listing_id SYMBOL in result row ${rowIndex}: ${String(raw)}.`, + 'listing_id' + ); + } + const parsed = Number(raw); + if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > INT32_MAX) { + throw new MarketDataStoreValidationError( + `Out-of-range bars_1m listing_id SYMBOL in result row ${rowIndex}: "${raw}".`, + 'listing_id' + ); + } + if (!requestedListingIds.has(parsed)) { + throw new MarketDataStoreValidationError( + `Unexpected unrequested listing_id ${parsed} in bars_1m result row ${rowIndex}.`, + 'listing_id' + ); + } + return parsed; +} + +function parseTimestampMicros( + row: Record, + column: 'ts_us' | 'known_at_us', + field: 'ts' | 'known_at', + rowIndex: number +): bigint { + const raw = row[column]; + if (typeof raw === 'bigint') { + return raw; + } + if (typeof raw === 'string' && CANONICAL_SIGNED_INT_RE.test(raw)) { + return BigInt(raw); + } + if (typeof raw === 'number' && Number.isSafeInteger(raw)) { + return BigInt(raw); + } + throw new MarketDataStoreValidationError( + `Invalid bars_1m timestamp column "${column}" in result row ${rowIndex}: ${String(raw)}.`, + field + ); +} + +function microsToEpochMs(us: bigint, field: 'ts' | 'known_at', rowIndex: number): number { + const quotient = us / 1000n; + const remainder = us % 1000n; + const msBigInt = remainder < 0n ? quotient - 1n : quotient; + const ms = Number(msBigInt); + if (!Number.isSafeInteger(ms) || Math.abs(ms) > MAX_ECMASCRIPT_EPOCH_MS) { + throw new MarketDataStoreValidationError( + `Out-of-range bars_1m timestamp "${field}" (${us.toString()} us) in result row ${rowIndex}.`, + field + ); + } + return ms === 0 ? 0 : ms; +} + +function readRequiredFiniteNumber( + row: Record, + key: 'open' | 'high' | 'low' | 'close' | 'volume', + rowIndex: number +): number { + const val = row[key]; + if (typeof val !== 'number' || !Number.isFinite(val)) { + throw new MarketDataStoreValidationError( + `Invalid numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`, + key + ); + } + return val === 0 ? 0 : val; +} + +function readNullableFiniteNumber( + row: Record, + key: 'vwap', + rowIndex: number +): number | null { + const val = row[key]; + if (val === null || val === undefined) { + return null; + } + if (typeof val !== 'number' || !Number.isFinite(val)) { + throw new MarketDataStoreValidationError( + `Invalid nullable numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`, + key + ); + } + return val === 0 ? 0 : val; +} + +function mapBars1mRows( + rows: readonly Record[], + fence: FencedTimeRange, + requestedListingIds: ReadonlySet +): BarRecord[] { + const fromUs = BigInt(fence.fromMs) * 1000n; + const toUs = BigInt(fence.toMs) * 1000n; + const asOfUs = BigInt(fence.asOfMs) * 1000n; + + const out: BarRecord[] = new Array(rows.length); + for (let i = 0; i < rows.length; i += 1) { + const raw = rows[i]; + if (!isPlainRecord(raw)) { + throw new MarketDataStoreValidationError( + `Executor returned a non-object bar row at index ${i}.`, + 'rows' + ); + } + + const listingId = parseListingIdSymbol(raw, i, requestedListingIds); + const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i); + if (tsUs < fromUs || tsUs > toUs) { + throw new MarketDataStoreValidationError( + `Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us.`, + 'ts' + ); + } + + const knownAtUs = parseTimestampMicros(raw, 'known_at_us', 'known_at', i); + if (knownAtUs > asOfUs) { + throw new MarketDataStoreValidationError( + `Row ${i} availability timestamp known_at (${knownAtUs.toString()} us) exceeds fenced asOf (${asOfUs.toString()} us).`, + 'known_at' + ); + } + + out[i] = { + listingId, + ts: microsToEpochMs(tsUs, 'ts', i), + open: readRequiredFiniteNumber(raw, 'open', i), + high: readRequiredFiniteNumber(raw, 'high', i), + low: readRequiredFiniteNumber(raw, 'low', i), + close: readRequiredFiniteNumber(raw, 'close', i), + volume: readRequiredFiniteNumber(raw, 'volume', i), + vwap: readNullableFiniteNumber(raw, 'vwap', i), + knownAt: microsToEpochMs(knownAtUs, 'known_at', i), + }; + } + + return out; +} + +/** + * Creates a read-only intraday `bars` reader backed by an injected + * {@link QuestDbQueryExecutor} over QuestDB `bars_1m`. + * + * Validates all inputs and applies the Vault fence before invoking + * `executor.query(...)`. Validates and maps all returned rows (including + * exact-microsecond defence-in-depth checks against `fence`) before yielding + * batches of at most `batchSize` rows (default `50_000`). + */ +export function createQuestDbIntradayBarsReader( + options: QuestDbIntradayBarsReaderOptions +): Pick { + if (!isPlainRecord(options)) { + throw new MarketDataStoreValidationError( + 'Expected a QuestDbIntradayBarsReaderOptions object.', + 'options' + ); + } + + const executor: unknown = options.executor; + if (!isPlainRecord(executor) || typeof executor.query !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `executor` with a `query(sql, params)` method.', + 'executor' + ); + } + const typedExecutor = executor as unknown as QuestDbQueryExecutor; + + const vaultCutoffTs = validateVaultCutoffTs(options.vaultCutoffTs); + + if ( + options.vaultOperatorAuthorized !== undefined && + typeof options.vaultOperatorAuthorized !== 'boolean' + ) { + throw new MarketDataStoreValidationError( + `Invalid vaultOperatorAuthorized "${String(options.vaultOperatorAuthorized)}". Expected a boolean.`, + 'vaultOperatorAuthorized' + ); + } + + const batchSize = options.batchSize ?? DEFAULT_QUESTDB_BARS_BATCH_SIZE; + if (typeof batchSize !== 'number' || !Number.isSafeInteger(batchSize) || batchSize < 1) { + throw new MarketDataStoreValidationError( + `Invalid batchSize "${String(options.batchSize)}". Expected a positive safe integer.`, + 'batchSize' + ); + } + + const planCtx: VaultFenceContext = { + vaultCutoffTs, + vaultOperatorAuthorized: options.vaultOperatorAuthorized === true, + }; + + return { + async *bars(q: QuestDbBars1mQuery): AsyncIterable { + const { planned, requestedListingIds } = planBars1mQueryInternal(q, planCtx); + const result: unknown = await typedExecutor.query(planned.sql, [...planned.params]); + if (!isPlainRecord(result) || !Array.isArray(result.rows)) { + throw new MarketDataStoreValidationError( + 'Executor returned a malformed result; expected `{ rows: Record[] }`.', + 'rows' + ); + } + + const mapped = mapBars1mRows( + result.rows as readonly Record[], + planned.fence, + requestedListingIds + ); + if (mapped.length === 0) { + return; + } + if (mapped.length <= batchSize) { + yield { rows: mapped }; + return; + } + for (let offset = 0; offset < mapped.length; offset += batchSize) { + yield { rows: mapped.slice(offset, offset + batchSize) }; + } + }, + }; +} diff --git a/libs/research/test/market-data-store-questdb.test.ts b/libs/research/test/market-data-store-questdb.test.ts new file mode 100644 index 00000000..22c030ec --- /dev/null +++ b/libs/research/test/market-data-store-questdb.test.ts @@ -0,0 +1,703 @@ +import { describe, expect, it } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + DEFAULT_QUESTDB_BARS_BATCH_SIZE, + MarketDataStoreNotImplementedError, + MarketDataStoreValidationError, + type QuestDbBars1mQuery, + type QuestDbQueryExecutor, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, + createQuestDbIntradayBarsReader, + planBars1mQuery, +} from '@stock-bot/research'; + +interface RecordedCall { + readonly sql: string; + readonly params: readonly unknown[]; +} + +class RecordingQuestDbExecutor implements QuestDbQueryExecutor { + readonly calls: RecordedCall[] = []; + private nextResult: { readonly rows: readonly Record[] } = { rows: [] }; + + setRows(rows: readonly Record[]): void { + this.nextResult = { rows }; + } + + setRawResult(result: unknown): void { + this.nextResult = result as { readonly rows: readonly Record[] }; + } + + async query( + sql: string, + params: readonly unknown[] + ): Promise<{ readonly rows: readonly Record[] }> { + this.calls.push({ sql, params: [...params] }); + return this.nextResult; + } +} + +async function collectBatches(iterable: AsyncIterable): Promise { + const batches: BarBatch[] = []; + for await (const batch of iterable) { + batches.push(batch); + } + return batches; +} + +const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z + +describe('planBars1mQuery', () => { + it('snapshots exact parameterized SQL and bound params for a 1-listing, 1-year query', () => { + const query: QuestDbBars1mQuery = { + listingIds: [42], + timeframe: '1m', + from: '2024-01-02', + to: '2024-12-31', + adjustment: 'raw', + asOf: '2025-01-01T00:00:00Z', + }; + + const planned = planBars1mQuery(query, { vaultCutoffTs: VAULT_CUTOFF_TS }); + + expect(planned.sql).toBe( + 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + + 'FROM bars_1m ' + + 'WHERE ts >= $1 AND ts <= $2 AND listing_id IN ($3) AND known_at <= $4 ' + + 'ORDER BY ts, listing_id' + ); + expect(planned.params).toEqual([ + '2024-01-02T00:00:00.000Z', + '2024-12-31T23:59:59.999Z', + '42', + '2025-01-01T00:00:00.000Z', + ]); + expect(planned.fence).toEqual({ + fromMs: Date.UTC(2024, 0, 2, 0, 0, 0, 0), + toMs: Date.UTC(2024, 11, 31, 23, 59, 59, 999), + asOfMs: Date.UTC(2025, 0, 1, 0, 0, 0, 0), + scope: 'vault_fenced', + clampedTo: false, + clampedAsOf: false, + }); + + // No caller-supplied values appear in SQL text. + for (const boundValue of planned.params) { + expect(planned.sql).not.toContain(boundValue); + } + expect(planned.sql).not.toContain('42'); + expect(planned.sql).not.toContain('2024'); + expect(planned.sql).not.toContain('2025'); + }); + + it('deduplicates and sorts multi-listing IDs numerically without mutating caller input', () => { + const callerListingIds = [100, 2, 10, 2, 1]; + const snapshotBefore = [...callerListingIds]; + + const planned = planBars1mQuery( + { + listingIds: callerListingIds, + timeframe: '1m', + from: '2024-06-03T13:30:00Z', + to: '2024-06-03T20:00:00Z', + adjustment: 'raw', + asOf: '2024-06-04T00:00:00Z', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ); + + expect(callerListingIds).toEqual(snapshotBefore); + expect(planned.sql).toBe( + 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + + 'FROM bars_1m ' + + 'WHERE ts >= $1 AND ts <= $2 AND listing_id IN ($3, $4, $5, $6) AND known_at <= $7 ' + + 'ORDER BY ts, listing_id' + ); + expect(planned.params).toEqual([ + '2024-06-03T13:30:00.000Z', + '2024-06-03T20:00:00.000Z', + '1', + '2', + '10', + '100', + '2024-06-04T00:00:00.000Z', + ]); + }); + + it('port is structurally compatible with QuestDBClient.query generic signature', async () => { + class QuestDbClientLike { + readonly calls: RecordedCall[] = []; + async query>( + sql: string, + params?: unknown[] + ): Promise<{ + rows: T[]; + rowCount: number; + executionTime: number; + }> { + this.calls.push({ sql, params: params ? [...params] : [] }); + return { rows: [], rowCount: 0, executionTime: 1 }; + } + } + + const clientLike = new QuestDbClientLike(); + const executorPort: QuestDbQueryExecutor = clientLike; + const reader = createQuestDbIntradayBarsReader({ + executor: executorPort, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const batches = await collectBatches( + reader.bars({ + listingIds: [7], + timeframe: '1m', + from: '2024-05-01T13:30:00Z', + to: '2024-05-01T13:35:00Z', + adjustment: 'raw', + }) + ); + + expect(batches).toEqual([]); + expect(clientLike.calls).toHaveLength(1); + }); +}); + +describe('Vault fence enforcement', () => { + it('rejects from at or past cutoff with VaultHoldoutFenceError and zero executor calls', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + await expect( + collectBatches( + reader.bars({ + listingIds: [1], + timeframe: '1m', + from: '2025-07-01T00:00:00.000Z', + to: '2025-07-02T00:00:00.000Z', + adjustment: 'raw', + }) + ) + ).rejects.toThrow(VaultHoldoutFenceError); + + await expect( + collectBatches( + reader.bars({ + listingIds: [1], + timeframe: '1m', + from: '2025-07-15', + to: '2025-08-01', + adjustment: 'raw', + }) + ) + ).rejects.toThrow(VaultHoldoutFenceError); + + expect(executor.calls).toHaveLength(0); + }); + + it('clamps to and asOf past cutoff and defaults omitted asOf to cutoff - 1ms', () => { + const clampedPlan = planBars1mQuery( + { + listingIds: [9], + timeframe: '1m', + from: '2025-06-01', + to: '2025-09-01', + asOf: '2025-09-02', + adjustment: 'raw', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ); + + expect(clampedPlan.fence.clampedTo).toBe(true); + expect(clampedPlan.fence.clampedAsOf).toBe(true); + expect(clampedPlan.fence.toMs).toBe(VAULT_CUTOFF_TS - 1); + expect(clampedPlan.fence.asOfMs).toBe(VAULT_CUTOFF_TS - 1); + expect(clampedPlan.params).toEqual([ + '2025-06-01T00:00:00.000Z', + '2025-06-30T23:59:59.999Z', + '9', + '2025-06-30T23:59:59.999Z', + ]); + + const omittedAsOfPlan = planBars1mQuery( + { + listingIds: [9], + timeframe: '1m', + from: '2025-06-01', + to: '2025-06-15', + adjustment: 'raw', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ); + + expect(omittedAsOfPlan.fence.clampedTo).toBe(false); + expect(omittedAsOfPlan.fence.clampedAsOf).toBe(false); + expect(omittedAsOfPlan.fence.asOfMs).toBe(VAULT_CUTOFF_TS - 1); + expect(omittedAsOfPlan.params[3]).toBe('2025-06-30T23:59:59.999Z'); + }); + + it('rejects unauthorized vault_evaluation_only even if caller attaches authorization flag on query', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const spoofedQuery = { + listingIds: [1], + timeframe: '1m', + from: '2025-07-01', + to: '2025-07-10', + adjustment: 'raw', + scope: 'vault_evaluation_only', + vaultOperatorAuthorized: true, + } as unknown as QuestDbBars1mQuery; + + await expect(collectBatches(reader.bars(spoofedQuery))).rejects.toThrow( + VaultScopeNotAuthorizedError + ); + expect(executor.calls).toHaveLength(0); + }); + + it('permits vault_evaluation_only when trusted factory context is operator-authorized', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: true, + }); + + const batches = await collectBatches( + reader.bars({ + listingIds: [5], + timeframe: '1m', + from: '2025-07-02T13:30:00Z', + to: '2025-07-02T13:31:00Z', + adjustment: 'raw', + scope: 'vault_evaluation_only', + }) + ); + + expect(batches).toEqual([]); + expect(executor.calls).toHaveLength(1); + expect(executor.calls[0]?.params).toEqual([ + '2025-07-02T13:30:00.000Z', + '2025-07-02T13:31:00.000Z', + '5', + '2025-07-02T13:31:00.000Z', + ]); + }); +}); + +describe('Input validation and injection rejection', () => { + it('rejects split and total adjustments with MarketDataStoreNotImplementedError and zero executor calls', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + for (const adjustment of ['split', 'total'] as const) { + await expect( + collectBatches( + reader.bars({ + listingIds: [1], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment, + }) + ) + ).rejects.toThrow(MarketDataStoreNotImplementedError); + } + + expect(executor.calls).toHaveLength(0); + }); + + it('rejects invalid timeframe, adjustment, dates, listingIds, and SQL injection before any executor call', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const invalidQueries: unknown[] = [ + // Wrong timeframes + { listingIds: [1], timeframe: '1d', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, + { listingIds: [1], timeframe: '5m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, + { listingIds: [1], timeframe: '1h', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, + // Invalid adjustment + { + listingIds: [1], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'dividend', + }, + // Reversed or invalid dates + { listingIds: [1], timeframe: '1m', from: '2024-02-01', to: '2024-01-01', adjustment: 'raw' }, + { + listingIds: [1], + timeframe: '1m', + from: '2024-01-02T13:30:00', + to: '2024-01-03T13:30:00Z', + adjustment: 'raw', + }, + { listingIds: [1], timeframe: '1m', from: 'not-a-date', to: '2024-01-03', adjustment: 'raw' }, + // Invalid listingIds + { listingIds: [], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, + { listingIds: [0], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, + { + listingIds: [-5], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'raw', + }, + { + listingIds: [2_147_483_648], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'raw', + }, + { + listingIds: [1.5], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'raw', + }, + { + listingIds: [Number.NaN], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'raw', + }, + // SQL injection attempt cast through unknown + { + listingIds: ['1; DROP TABLE bars_1m'], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'raw', + }, + ]; + + for (const badQuery of invalidQueries) { + await expect(collectBatches(reader.bars(badQuery as QuestDbBars1mQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + + expect(executor.calls).toHaveLength(0); + }); + + it('rejects invalid factory options (executor, vaultCutoffTs, batchSize)', () => { + const executor = new RecordingQuestDbExecutor(); + + expect(() => + createQuestDbIntradayBarsReader({ + executor: {} as unknown as QuestDbQueryExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: Number.NaN, + }) + ).toThrow(MarketDataStoreValidationError); + + for (const badBatchSize of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => + createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: badBatchSize, + }) + ).toThrow(MarketDataStoreValidationError); + } + }); +}); + +describe('1-year single-listing replay, row mapping, and batching', () => { + it('streams 98,280 synthetic 1m rows (252 sessions x 390 min) in exact order across default 50k batches', async () => { + expect(DEFAULT_QUESTDB_BARS_BATCH_SIZE).toBe(50_000); + + const sessions = 252; + const minutesPerSession = 390; + const totalRows = sessions * minutesPerSession; // 98,280 + const listingId = 101; + const listingIdSymbol = String(listingId); + const baseSessionStartMs = Date.UTC(2024, 0, 2, 14, 30, 0, 0); + const msPerDay = 86_400_000; + const msPerMinute = 60_000; + + const rawRows: Record[] = new Array(totalRows); + const expected: BarRecord[] = new Array(totalRows); + + let idx = 0; + for (let s = 0; s < sessions; s += 1) { + const sessionStartMs = baseSessionStartMs + s * msPerDay; + for (let m = 0; m < minutesPerSession; m += 1) { + const tsMs = sessionStartMs + m * msPerMinute; + const knownAtMs = tsMs + msPerMinute; + const tsUs = BigInt(tsMs) * 1000n; + const knownAtUs = BigInt(knownAtMs) * 1000n; + + const open = 100 + s * 0.25 + m * 0.01; + const high = open + 0.15; + const low = open - 0.1; + const close = open + 0.05; + const volume = 1_000 + ((s * 390 + m) % 500); + const vwap = m % 10 === 0 ? null : open + 0.02; + + // Exercise all three supported LONG wire representations: decimal string, bigint, safe int. + const tsWire: unknown = + idx % 3 === 0 ? tsUs.toString() : idx % 3 === 1 ? tsUs : Number(tsUs); + const knownAtWire: unknown = + idx % 3 === 0 ? knownAtUs.toString() : idx % 3 === 1 ? knownAtUs : Number(knownAtUs); + + rawRows[idx] = { + listing_id: listingIdSymbol, + ts_us: tsWire, + open, + high, + low, + close, + volume, + vwap, + known_at_us: knownAtWire, + }; + expected[idx] = { + listingId, + ts: tsMs, + open, + high, + low, + close, + volume, + vwap, + knownAt: knownAtMs, + }; + idx += 1; + } + } + + const executor = new RecordingQuestDbExecutor(); + executor.setRows(rawRows); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const query: QuestDbBars1mQuery = { + listingIds: [listingId], + timeframe: '1m', + from: '2024-01-02', + to: '2024-12-31', + asOf: '2025-01-01T00:00:00Z', + adjustment: 'raw', + }; + + const run1Batches = await collectBatches(reader.bars(query)); + const run2Batches = await collectBatches(reader.bars(query)); + + expect(executor.calls).toHaveLength(2); + expect(run1Batches.map(b => b.rows.length)).toEqual([50_000, 48_280]); + expect(run2Batches.map(b => b.rows.length)).toEqual([50_000, 48_280]); + + const flat1 = run1Batches.flatMap(b => b.rows); + const flat2 = run2Batches.flatMap(b => b.rows); + expect(flat1).toHaveLength(totalRows); + expect(flat1).toEqual(expected); + expect(flat2).toEqual(flat1); + }); + + it('supports custom small batch sizes and yields zero batches for empty results', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: 3, + }); + + const query: QuestDbBars1mQuery = { + listingIds: [12], + timeframe: '1m', + from: '2024-03-01T14:30:00Z', + to: '2024-03-01T14:40:00Z', + asOf: '2024-03-01T15:00:00Z', + adjustment: 'raw', + }; + + executor.setRows([]); + expect(await collectBatches(reader.bars(query))).toEqual([]); + expect(executor.calls).toHaveLength(1); + + const startMs = Date.UTC(2024, 2, 1, 14, 30, 0, 0); + const rows = Array.from({ length: 7 }, (_, i) => { + const tsMs = startMs + i * 60_000; + return { + listing_id: '12', + ts_us: (BigInt(tsMs) * 1000n).toString(), + open: 10 + i, + high: 11 + i, + low: 9 + i, + close: 10.5 + i, + volume: 100 + i, + vwap: i % 2 === 0 ? null : 10.25 + i, + known_at_us: (BigInt(tsMs + 60_000) * 1000n).toString(), + }; + }); + + executor.setRows(rows); + const batches = await collectBatches(reader.bars(query)); + expect(batches.map(b => b.rows.length)).toEqual([3, 3, 1]); + expect(executor.calls).toHaveLength(2); + expect(batches[0]?.rows[0]?.vwap).toBeNull(); + expect(batches[0]?.rows[1]?.vwap).toBe(11.25); + }); +}); + +describe('Malformed and out-of-fence row defence-in-depth', () => { + const baseQuery: QuestDbBars1mQuery = { + listingIds: [101], + timeframe: '1m', + from: '2025-06-30T23:58:00.000Z', + to: '2025-07-05T00:00:00.000Z', // clamped to VAULT_CUTOFF_TS - 1 (2025-06-30T23:59:59.999Z) + asOf: '2025-07-05T00:00:00.000Z', // clamped to VAULT_CUTOFF_TS - 1 + adjustment: 'raw', + }; + + const fromUs = BigInt(Date.UTC(2025, 5, 30, 23, 58, 0, 0)) * 1000n; + const clampedToUs = BigInt(VAULT_CUTOFF_TS - 1) * 1000n; + const clampedAsOfUs = BigInt(VAULT_CUTOFF_TS - 1) * 1000n; + + function makeValidRow(overrides: Record = {}): Record { + return { + listing_id: '101', + ts_us: fromUs.toString(), + open: 150, + high: 151, + low: 149.5, + close: 150.25, + volume: 2500, + vwap: 150.1, + known_at_us: clampedAsOfUs.toString(), + ...overrides, + }; + } + + it('accepts rows at exact fenced microsecond endpoints', async () => { + const executor = new RecordingQuestDbExecutor(); + executor.setRows([ + makeValidRow({ ts_us: fromUs.toString(), known_at_us: clampedAsOfUs.toString() }), + makeValidRow({ ts_us: clampedToUs.toString(), known_at_us: clampedAsOfUs.toString() }), + ]); + + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const batches = await collectBatches(reader.bars(baseQuery)); + expect(batches).toHaveLength(1); + expect(batches[0]?.rows).toHaveLength(2); + expect(batches[0]?.rows[0]?.ts).toBe(Date.UTC(2025, 5, 30, 23, 58, 0, 0)); + expect(batches[0]?.rows[1]?.ts).toBe(VAULT_CUTOFF_TS - 1); + }); + + it('rejects rows 1 microsecond before from, 1 microsecond after clamped to, or 1 microsecond after fenced asOf', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const outOfFenceRows: Array<{ label: string; row: Record }> = [ + { label: 'ts 1us before from', row: makeValidRow({ ts_us: (fromUs - 1n).toString() }) }, + { label: 'ts 1us after clamped to', row: makeValidRow({ ts_us: (clampedToUs + 1n).toString() }) }, + { + label: 'known_at 1us after clamped asOf', + row: makeValidRow({ known_at_us: (clampedAsOfUs + 1n).toString() }), + }, + ]; + + for (const testCase of outOfFenceRows) { + executor.setRows([testCase.row]); + await expect(collectBatches(reader.bars(baseQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + }); + + it('rejects invalid SYMBOLs, unrequested listings, non-finite OHLCV/vwap, and invalid timestamps', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const malformedRows: Record[] = [ + makeValidRow({ listing_id: '0101' }), + makeValidRow({ listing_id: '-101' }), + makeValidRow({ listing_id: '0' }), + makeValidRow({ listing_id: '2147483648' }), + makeValidRow({ listing_id: 101 }), + makeValidRow({ listing_id: '102' }), // valid INT32 SYMBOL, but unrequested + makeValidRow({ open: Number.NaN }), + makeValidRow({ high: Number.POSITIVE_INFINITY }), + makeValidRow({ low: Number.NEGATIVE_INFINITY }), + makeValidRow({ close: '150.25' }), + makeValidRow({ volume: Number.NaN }), + makeValidRow({ vwap: Number.NaN }), + makeValidRow({ vwap: Number.POSITIVE_INFINITY }), + makeValidRow({ ts_us: 'not-a-timestamp' }), + makeValidRow({ ts_us: 1.5 }), + makeValidRow({ known_at_us: null }), + ]; + + for (const badRow of malformedRows) { + executor.setRows([badRow]); + await expect(collectBatches(reader.bars(baseQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + }); + + it('fails before yielding any batch when a malformed row appears beyond the first batch boundary', async () => { + const executor = new RecordingQuestDbExecutor(); + executor.setRows([ + makeValidRow(), + makeValidRow(), + makeValidRow({ close: Number.NaN }), // row index 2 is past batchSize: 2 + ]); + + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: 2, + }); + + const yielded: BarBatch[] = []; + let caught: unknown; + try { + for await (const batch of reader.bars(baseQuery)) { + yielded.push(batch); + } + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect(yielded).toHaveLength(0); + }); +}); From 2e5cc2e43dd005658eb0ccb18e7f7eb73f6476c9 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:46:56 -0500 Subject: [PATCH 04/15] =?UTF-8?q?T-146:=20M2.3f=20=E2=80=94=20QuestDB=20`b?= =?UTF-8?q?ars=5F1m`=20intraday=20reader=20for=20`MarketDataStore.bars`=20?= =?UTF-8?q?(`timeframe:=20'1m'`):=20Vault-fenced,=20parameterized=20`planB?= =?UTF-8?q?ars1mQuery`=20+=20batch=20iterator=20over=20an=20injected=20PGW?= =?UTF-8?q?ire=20query=20port=20in=20`libs/research/src/market-data-store-?= =?UTF-8?q?questdb.ts`=20(pure,=20no=20new=20deps,=20no=20live=20QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../research/src/market-data-store-questdb.ts | 24 +++++-- .../test/market-data-store-questdb.test.ts | 69 ++++++++++++++++++- 2 files changed, 86 insertions(+), 7 deletions(-) diff --git a/libs/research/src/market-data-store-questdb.ts b/libs/research/src/market-data-store-questdb.ts index 08006f3b..c6da320c 100644 --- a/libs/research/src/market-data-store-questdb.ts +++ b/libs/research/src/market-data-store-questdb.ts @@ -265,10 +265,22 @@ function parseTimestampMicros( ); } -function microsToEpochMs(us: bigint, field: 'ts' | 'known_at', rowIndex: number): number { +function microsToEpochMs( + us: bigint, + field: 'ts' | 'known_at', + rowIndex: number, + rounding: 'floor' | 'ceil' +): number { const quotient = us / 1000n; const remainder = us % 1000n; - const msBigInt = remainder < 0n ? quotient - 1n : quotient; + 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( @@ -350,14 +362,15 @@ function mapBars1mRows( out[i] = { listingId, - ts: microsToEpochMs(tsUs, 'ts', i), + 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), - knownAt: microsToEpochMs(knownAtUs, 'known_at', i), + // Round sub-millisecond availability up so replay never treats a bar as known before arrival. + knownAt: microsToEpochMs(knownAtUs, 'known_at', i, 'ceil'), }; } @@ -404,7 +417,8 @@ export function createQuestDbIntradayBarsReader( ); } - const batchSize = options.batchSize ?? DEFAULT_QUESTDB_BARS_BATCH_SIZE; + 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.`, diff --git a/libs/research/test/market-data-store-questdb.test.ts b/libs/research/test/market-data-store-questdb.test.ts index 22c030ec..b17e06a2 100644 --- a/libs/research/test/market-data-store-questdb.test.ts +++ b/libs/research/test/market-data-store-questdb.test.ts @@ -415,12 +415,12 @@ describe('Input validation and injection rejection', () => { }) ).toThrow(MarketDataStoreValidationError); - for (const badBatchSize of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + for (const badBatchSize of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, null]) { expect(() => createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: badBatchSize, + batchSize: badBatchSize as unknown as number, }) ).toThrow(MarketDataStoreValidationError); } @@ -700,4 +700,69 @@ describe('Malformed and out-of-fence row defence-in-depth', () => { 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); + }); }); From 60d347dd1b9dfd6afe52ffeee31bd0d5d7f627cb Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:52:38 -0500 Subject: [PATCH 05/15] T-146: tests --- .../test/market-data-store-questdb.qa.test.ts | 346 ++++++++++++++++++ 1 file changed, 346 insertions(+) create mode 100644 libs/research/test/market-data-store-questdb.qa.test.ts 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]); + }); +}); From 41feb16e5ff2a87f5f9af20689f0541a920961b5 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:38:56 -0500 Subject: [PATCH 06/15] =?UTF-8?q?T-150:=20M2.3i=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20zero-copy=20raw=20BSON=20decoder=20for=20`qmIntraday`?= =?UTF-8?q?=20raw=20`1m`=20bars=20(`bson=5Fqm=5Fintraday.rs`,=20pure,=20wi?= =?UTF-8?q?th=20tests;=20no=20new=20crates,=20no=20CLI/bench=20changes,=20?= =?UTF-8?q?no=20live=20Mongo/QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/bson_qm_intraday.rs | 641 +++++++++++++++ .../curate-etl/src/bson_qm_intraday_tests.rs | 757 ++++++++++++++++++ tools/curate-etl/src/lib.rs | 1 + 3 files changed, 1399 insertions(+) create mode 100644 tools/curate-etl/src/bson_qm_intraday.rs create mode 100644 tools/curate-etl/src/bson_qm_intraday_tests.rs diff --git a/tools/curate-etl/src/bson_qm_intraday.rs b/tools/curate-etl/src/bson_qm_intraday.rs new file mode 100644 index 00000000..491d4138 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_intraday.rs @@ -0,0 +1,641 @@ +//! Zero-copy raw BSON decoder for MongoDB `qmIntraday` documents (`M2.3i`). +//! +//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into +//! borrowed [`RawQmIntradayBar`] views without allocating a `String` or `bson::Document` per row. +//! Callers can convert borrowed views into [`crate::bars_1m::EodIntradayBar`] via a +//! caller-supplied key mapper without per-row `String` allocations, keeping in mind that +//! `qmIntraday` raw fields are already un-adjusted (see [`RawQmIntradayBar::into_eod_intraday_bar`]). +//! +//! # Empirical Field Contract & Cited Sources +//! +//! Field names and semantics are grounded in the repository's ingestion writer and empirical data +//! contract: +//! - `apps/stock/data-ingestion/src/handlers/qm/actions/intraday-crawl.action.ts:119-131,165-173` +//! (requests 1-minute bars via `interval: '1'`, spreads the provider bar payload, adds +//! `qmSearchCode`, `symbol`, `exchange`, and +//! `timestamp: new Date(bar.startdatetime || bar.date || bar.datetime)`, and upserts into +//! `qmIntraday` keyed by `['qmSearchCode', 'timestamp']`) +//! - `design/DATA-CONTRACTS.md:16` (§1 row `qmIntraday`, ~173.3M docs): stores **both** raw +//! (`open..close`, `sharevolume`) and split-adjusted (`adjustedopen..adjustedclose`, `avolume`) +//! fields. This decoder reads the raw fields only; all adjusted fields are validated as borrowed +//! `RawBsonRef` payloads and otherwise ignored. +//! +//! `ts` is decoded as bar-start UTC microseconds (`DateTime` milliseconds × `1_000`). Downstream +//! research/curation owns availability (`known_at`) decisions. +//! +//! # Accepted BSON Representations & Decoder Conventions +//! +//! Following [`crate::bson_eod_intraday`] and [`crate::bson_qm_prices`]: +//! - `qmSearchCode`: BSON UTF-8 `String`, borrowed verbatim (never trimmed). Empty or +//! whitespace-only strings are rejected as [`BsonQmIntradayError::EmptyField`]; non-string +//! values (including BSON `Null`) are rejected as [`BsonQmIntradayError::WrongType`]. +//! - `timestamp`: BSON `DateTime` (UTC milliseconds since Unix epoch), converted to UTC +//! microseconds via checked multiplication by `1_000`. Non-`DateTime` types (including `Null`, +//! integers, doubles, strings, and BSON `Timestamp`) are rejected as +//! [`BsonQmIntradayError::WrongType`]; negative millisecond values or values overflowing `i64` +//! microseconds are rejected as [`BsonQmIntradayError::InvalidTimestamp`]. +//! - `open`, `high`, `low`, `close`: BSON `Double`, `Int32`, or `Int64`; must be finite and +//! strictly positive (`> 0.0`). Non-numeric types (including `Null`) are rejected as +//! [`BsonQmIntradayError::WrongType`]; `NaN`, `±inf`, `0.0`, `-0.0`, and `< 0.0` are rejected +//! as [`BsonQmIntradayError::InvalidNumber`]. +//! - `sharevolume`: BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` is +//! normalized to `+0.0`). Non-numeric types (including `Null`) are rejected as +//! [`BsonQmIntradayError::WrongType`]; `NaN`, `±inf`, and `< 0.0` are rejected as +//! [`BsonQmIntradayError::InvalidNumber`]. +//! - All other top-level fields (`_id`, `symbol`, `exchange`, `adjustedopen`, `adjustedhigh`, +//! `adjustedlow`, `adjustedclose`, `avolume`, `startdatetime`, nested objects/arrays, etc.) are +//! validated as borrowed `RawBsonRef` views (zero allocation) and otherwise ignored, so malformed +//! bytes in skipped fields still surface as [`BsonQmIntradayError::CorruptBson`]. +//! - Duplicate fields and error precedence: later valid duplicates replace earlier valid values, +//! the first semantic error is retained (a later valid duplicate cannot clear an earlier semantic +//! error), and malformed BSON bytes take precedence immediately as `CorruptBson`. After the scan, +//! the first semantic error is returned, or else the first missing required field in +//! `qmSearchCode`, `timestamp`, `open`, `high`, `low`, `close`, `sharevolume` order. + +use std::error::Error; +use std::fmt; + +use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement}; +use bson::spec::ElementType; + +use crate::bars_1m::EodIntradayBar; +use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError}; + +/// MongoDB field name for the QuoteMedia security key (`intraday-crawl.action.ts:167,173`). +pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode"; +/// MongoDB field name for the bar-start BSON `DateTime` (`intraday-crawl.action.ts:170,173`). +pub const FIELD_TIMESTAMP: &str = "timestamp"; +/// MongoDB field name for raw bar open price (`DATA-CONTRACTS.md:16`). +pub const FIELD_OPEN: &str = "open"; +/// MongoDB field name for raw bar high price (`DATA-CONTRACTS.md:16`). +pub const FIELD_HIGH: &str = "high"; +/// MongoDB field name for raw bar low price (`DATA-CONTRACTS.md:16`). +pub const FIELD_LOW: &str = "low"; +/// MongoDB field name for raw bar close price (`DATA-CONTRACTS.md:16`). +pub const FIELD_CLOSE: &str = "close"; +/// MongoDB field name for raw bar share volume (`DATA-CONTRACTS.md:16`). +pub const FIELD_SHARE_VOLUME: &str = "sharevolume"; + +const MICROS_PER_MILLI: i64 = 1_000; +/// Largest UTC millisecond timestamp that fits in signed `i64` microseconds (`9_223_372_036_854_775`). +#[cfg(test)] +pub(crate) const MAX_TIMESTAMP_MILLIS: i64 = i64::MAX / MICROS_PER_MILLI; + +/// Borrowed zero-copy view of a single decoded `qmIntraday` BSON document. +/// +/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice. +/// `open`, `high`, `low`, `close`, and `volume` are the provider's already-raw values +/// (`open..close`, `sharevolume`); adjusted fields are ignored. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RawQmIntradayBar<'a> { + pub qm_search_code: &'a str, + /// Bar start timestamp in UTC microseconds since the Unix epoch. + pub ts: i64, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub volume: f64, +} + +impl<'a> RawQmIntradayBar<'a> { + /// Converts this borrowed view into an [`EodIntradayBar`] using a caller-supplied key + /// mapper. + /// + /// `map_key` receives `(qm_search_code, ts)` (provider code and UTC bar-start microseconds) + /// and this method only maps the key and copies the raw OHLCV fields verbatim. + /// + /// **Important:** [`crate::bars_1m::build_bars_1m`] applies split un-adjustment to + /// [`EodIntradayBar`] inputs (which is required for retroactively split-adjusted + /// `eodIntraday1M` bars). Passing already-raw `qmIntraday` bars through a split-unadjusting + /// path with non-empty splits would distort raw prices and volumes; downstream `qmIntraday` + /// curation must ingest raw values without split un-adjustment. + #[inline] + pub fn into_eod_intraday_bar(self, map_key: F) -> EodIntradayBar + where + F: FnOnce(&'a str, i64) -> K, + { + EodIntradayBar { + key: map_key(self.qm_search_code, self.ts), + ts: self.ts, + open: self.open, + high: self.high, + low: self.low, + close: self.close, + volume: self.volume, + } + } + + /// Fallible conversion into [`EodIntradayBar`] using a caller-supplied key resolver. + /// + /// Maps `(qm_search_code, ts)` and copies the raw OHLCV fields verbatim without applying any + /// split adjustment. See [`Self::into_eod_intraday_bar`] for the split un-adjustment caveat. + #[inline] + pub fn try_into_eod_intraday_bar(self, map_key: F) -> Option> + where + F: FnOnce(&'a str, i64) -> Option, + { + let key = map_key(self.qm_search_code, self.ts)?; + Some(EodIntradayBar { + key, + ts: self.ts, + open: self.open, + high: self.high, + low: self.low, + close: self.close, + volume: self.volume, + }) + } +} + +/// Typed errors returned while decoding raw `qmIntraday` BSON documents or length-prefixed +/// buffers. +/// +/// Every field-level error names the offending BSON field in both its structure and `Display` +/// output; malformed and truncated BSON framing errors report `CorruptBson` with byte offset and +/// framing detail; no input path panics. +#[derive(Debug, Clone, PartialEq)] +pub enum BsonQmIntradayError { + /// A required field was absent from the document. + MissingField { field: &'static str }, + /// A required string field was empty or contained only whitespace. + EmptyField { field: &'static str }, + /// A required field had an unexpected BSON element type (including `Null`). + WrongType { + field: &'static str, + actual: ElementType, + }, + /// `timestamp` BSON `DateTime` was negative or overflowed `i64` microseconds. + InvalidTimestamp { field: &'static str }, + /// An OHLC field was non-finite or `<= 0.0`, or `sharevolume` was non-finite or `< 0.0`. + InvalidNumber { field: &'static str, value: f64 }, + /// Underlying BSON framing, truncation, document length, or element bytes were malformed. + CorruptBson { offset: usize, detail: String }, +} + +impl fmt::Display for BsonQmIntradayError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MissingField { field } => { + write!(f, "qmIntraday BSON missing required field '{field}'") + } + Self::EmptyField { field } => { + write!( + f, + "qmIntraday BSON field '{field}' must not be empty or blank" + ) + } + Self::WrongType { field, actual } => { + write!( + f, + "qmIntraday BSON field '{field}' has unexpected BSON type {actual:?}" + ) + } + Self::InvalidTimestamp { field } => { + write!( + f, + "qmIntraday BSON field '{field}' is not a valid non-negative DateTime within i64 microsecond range" + ) + } + Self::InvalidNumber { field, value } => { + if *field == FIELD_SHARE_VOLUME { + write!( + f, + "qmIntraday BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0" + ) + } else { + write!( + f, + "qmIntraday BSON field '{field}' has invalid numeric value {value}: must be finite and > 0" + ) + } + } + Self::CorruptBson { offset, detail } => { + write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") + } + } + } +} + +impl Error for BsonQmIntradayError {} + +#[inline] +fn map_framing_error(err: BsonEodPriceError) -> BsonQmIntradayError { + match err { + BsonEodPriceError::TruncatedDocument { offset, .. } + | BsonEodPriceError::CorruptDocumentLength { offset, .. } => { + BsonQmIntradayError::CorruptBson { + offset, + detail: err.to_string(), + } + } + BsonEodPriceError::CorruptBson { offset, detail } => { + BsonQmIntradayError::CorruptBson { offset, detail } + } + BsonEodPriceError::MissingField { field } => BsonQmIntradayError::MissingField { field }, + BsonEodPriceError::EmptyField { field } => BsonQmIntradayError::EmptyField { field }, + BsonEodPriceError::WrongType { field, actual } => { + BsonQmIntradayError::WrongType { field, actual } + } + BsonEodPriceError::MalformedDate { field } => { + BsonQmIntradayError::InvalidTimestamp { field } + } + BsonEodPriceError::InvalidNumber { field, value } => { + BsonQmIntradayError::InvalidNumber { field, value } + } + } +} + +/// Per-batch decode and rejection accounting for [`decode_qm_intraday_buffer`]. +/// +/// Conservation invariant: `rows_decoded + rejected_total() == docs_seen`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BsonQmIntradayDecodeStats { + pub docs_seen: usize, + pub rows_decoded: usize, + pub rejected_missing_field: usize, + pub rejected_empty_field: usize, + pub rejected_wrong_type: usize, + pub rejected_invalid_timestamp: usize, + pub rejected_invalid_number: usize, + pub rejected_corrupt_document: usize, +} + +impl BsonQmIntradayDecodeStats { + /// Total number of rejected documents across all error categories. + #[inline] + pub fn rejected_total(&self) -> usize { + self.rejected_missing_field + + self.rejected_empty_field + + self.rejected_wrong_type + + self.rejected_invalid_timestamp + + self.rejected_invalid_number + + self.rejected_corrupt_document + } + + /// Increments the rejection counter corresponding to `err`. + #[inline] + pub fn record_error(&mut self, err: &BsonQmIntradayError) { + match err { + BsonQmIntradayError::MissingField { .. } => self.rejected_missing_field += 1, + BsonQmIntradayError::EmptyField { .. } => self.rejected_empty_field += 1, + BsonQmIntradayError::WrongType { .. } => self.rejected_wrong_type += 1, + BsonQmIntradayError::InvalidTimestamp { .. } => self.rejected_invalid_timestamp += 1, + BsonQmIntradayError::InvalidNumber { .. } => self.rejected_invalid_number += 1, + BsonQmIntradayError::CorruptBson { .. } => self.rejected_corrupt_document += 1, + } + } + + /// Accumulates counters from another batch into `self`. + #[inline] + pub fn merge(&mut self, other: &Self) { + self.docs_seen += other.docs_seen; + self.rows_decoded += other.rows_decoded; + self.rejected_missing_field += other.rejected_missing_field; + self.rejected_empty_field += other.rejected_empty_field; + self.rejected_wrong_type += other.rejected_wrong_type; + self.rejected_invalid_timestamp += other.rejected_invalid_timestamp; + self.rejected_invalid_number += other.rejected_invalid_number; + self.rejected_corrupt_document += other.rejected_corrupt_document; + } +} + +impl std::ops::AddAssign for BsonQmIntradayDecodeStats { + #[inline] + fn add_assign(&mut self, rhs: Self) { + self.merge(&rhs); + } +} + +#[inline] +fn decode_element_value<'a>( + field: &'static str, + elem: RawElement<'a>, + offset: usize, +) -> Result, BsonQmIntradayError> { + elem.value().map_err(|err| BsonQmIntradayError::CorruptBson { + offset, + detail: format!("field '{field}': {err}"), + }) +} + +#[inline] +fn decode_timestamp_datetime_to_micros(val: RawBsonRef<'_>) -> Result { + match val { + RawBsonRef::DateTime(dt) => { + let millis = dt.timestamp_millis(); + if millis < 0 { + return Err(BsonQmIntradayError::InvalidTimestamp { + field: FIELD_TIMESTAMP, + }); + } + millis + .checked_mul(MICROS_PER_MILLI) + .ok_or(BsonQmIntradayError::InvalidTimestamp { + field: FIELD_TIMESTAMP, + }) + } + other => Err(BsonQmIntradayError::WrongType { + field: FIELD_TIMESTAMP, + actual: other.element_type(), + }), + } +} + +#[inline] +fn decode_positive_number( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::Double(v) => { + if !v.is_finite() || v <= 0.0 { + return Err(BsonQmIntradayError::InvalidNumber { field, value: v }); + } + Ok(v) + } + RawBsonRef::Int32(v) => { + if v <= 0 { + return Err(BsonQmIntradayError::InvalidNumber { + field, + value: f64::from(v), + }); + } + Ok(f64::from(v)) + } + RawBsonRef::Int64(v) => { + if v <= 0 { + return Err(BsonQmIntradayError::InvalidNumber { + field, + value: v as f64, + }); + } + Ok(v as f64) + } + other => Err(BsonQmIntradayError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +#[inline] +fn decode_non_negative_number( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::Double(v) => { + if !v.is_finite() || v < 0.0 { + return Err(BsonQmIntradayError::InvalidNumber { field, value: v }); + } + if v == 0.0 { + Ok(0.0) + } else { + Ok(v) + } + } + RawBsonRef::Int32(v) => { + if v < 0 { + return Err(BsonQmIntradayError::InvalidNumber { + field, + value: f64::from(v), + }); + } + Ok(f64::from(v)) + } + RawBsonRef::Int64(v) => { + if v < 0 { + return Err(BsonQmIntradayError::InvalidNumber { + field, + value: v as f64, + }); + } + Ok(v as f64) + } + other => Err(BsonQmIntradayError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +fn decode_qm_intraday_doc_at<'a>( + doc: &'a RawDocument, + offset: usize, +) -> Result, BsonQmIntradayError> { + let mut qm_search_code: Option<&'a str> = None; + let mut ts: Option = None; + let mut open: Option = None; + let mut high: Option = None; + let mut low: Option = None; + let mut close: Option = None; + let mut volume: Option = None; + let mut first_semantic_err: Option = None; + + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonQmIntradayError::CorruptBson { + offset, + detail: err.to_string(), + })?; + let key = elem.key(); + + if key == cstr!("qmSearchCode") { + match decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)? { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + if first_semantic_err.is_none() { + first_semantic_err = Some(BsonQmIntradayError::EmptyField { + field: FIELD_QM_SEARCH_CODE, + }); + } + } else { + qm_search_code = Some(s); + } + } + other => { + if first_semantic_err.is_none() { + first_semantic_err = Some(BsonQmIntradayError::WrongType { + field: FIELD_QM_SEARCH_CODE, + actual: other.element_type(), + }); + } + } + } + } else if key == cstr!("timestamp") { + let val = decode_element_value(FIELD_TIMESTAMP, elem, offset)?; + match decode_timestamp_datetime_to_micros(val) { + Ok(micros) => ts = Some(micros), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("open") { + let val = decode_element_value(FIELD_OPEN, elem, offset)?; + match decode_positive_number(FIELD_OPEN, val) { + Ok(v) => open = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("high") { + let val = decode_element_value(FIELD_HIGH, elem, offset)?; + match decode_positive_number(FIELD_HIGH, val) { + Ok(v) => high = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("low") { + let val = decode_element_value(FIELD_LOW, elem, offset)?; + match decode_positive_number(FIELD_LOW, val) { + Ok(v) => low = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("close") { + let val = decode_element_value(FIELD_CLOSE, elem, offset)?; + match decode_positive_number(FIELD_CLOSE, val) { + Ok(v) => close = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("sharevolume") { + let val = decode_element_value(FIELD_SHARE_VOLUME, elem, offset)?; + match decode_non_negative_number(FIELD_SHARE_VOLUME, val) { + Ok(v) => volume = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else { + // Validate skipped top-level payloads (including adjustedopen..adjustedclose and + // avolume) via borrowed `RawBsonRef` views (zero allocation) so malformed bytes still + // reject the document as `CorruptBson` at its frame offset. + elem.value().map_err(|err| BsonQmIntradayError::CorruptBson { + offset, + detail: format!("field '{}': {err}", key.as_str()), + })?; + } + } + + if let Some(err) = first_semantic_err { + return Err(err); + } + + let Some(qm_search_code) = qm_search_code else { + return Err(BsonQmIntradayError::MissingField { + field: FIELD_QM_SEARCH_CODE, + }); + }; + let Some(ts) = ts else { + return Err(BsonQmIntradayError::MissingField { + field: FIELD_TIMESTAMP, + }); + }; + let Some(open) = open else { + return Err(BsonQmIntradayError::MissingField { field: FIELD_OPEN }); + }; + let Some(high) = high else { + return Err(BsonQmIntradayError::MissingField { field: FIELD_HIGH }); + }; + let Some(low) = low else { + return Err(BsonQmIntradayError::MissingField { field: FIELD_LOW }); + }; + let Some(close) = close else { + return Err(BsonQmIntradayError::MissingField { field: FIELD_CLOSE }); + }; + let Some(volume) = volume else { + return Err(BsonQmIntradayError::MissingField { + field: FIELD_SHARE_VOLUME, + }); + }; + + Ok(RawQmIntradayBar { + qm_search_code, + ts, + open, + high, + low, + close, + volume, + }) +} + +/// Decodes a single `&RawDocument` representing a `qmIntraday` MongoDB document in one forward +/// pass without allocating a `String` or owned `bson::Document`. +#[inline] +pub fn decode_qm_intraday_doc<'a>( + doc: &'a RawDocument, +) -> Result, BsonQmIntradayError> { + decode_qm_intraday_doc_at(doc, 0) +} + +/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed +/// [`RawQmIntradayBar`]. +pub fn decode_qm_intraday_bytes<'a>( + bytes: &'a [u8], +) -> Result, BsonQmIntradayError> { + let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; + decode_qm_intraday_doc_at(doc, 0) +} + +/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_intraday_doc`], +/// invoking `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected +/// document without aborting the stream on recoverable per-document errors. +/// +/// Stops at an unrecoverable frame length or truncated tail and counts it once. +/// Always maintains `stats.rows_decoded + stats.rejected_total() == stats.docs_seen`. +pub fn decode_qm_intraday_buffer<'a, F, E>( + buf: &'a [u8], + mut on_bar: F, + mut on_error: E, +) -> BsonQmIntradayDecodeStats +where + F: FnMut(RawQmIntradayBar<'a>), + E: FnMut(usize, BsonQmIntradayError), +{ + let mut stats = BsonQmIntradayDecodeStats::default(); + let mut iter = iter_raw_bson_docs(buf); + + while let Some(item) = iter.next_with_offset() { + stats.docs_seen += 1; + match item { + Ok((doc_offset, doc)) => match decode_qm_intraday_doc_at(doc, doc_offset) { + Ok(bar) => { + stats.rows_decoded += 1; + on_bar(bar); + } + Err(err) => { + stats.record_error(&err); + on_error(doc_offset, err); + } + }, + Err((doc_offset, err)) => { + let mapped = map_framing_error(err); + stats.record_error(&mapped); + on_error(doc_offset, mapped); + } + } + } + + stats +} + +#[cfg(test)] +#[path = "bson_qm_intraday_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bson_qm_intraday_tests.rs b/tools/curate-etl/src/bson_qm_intraday_tests.rs new file mode 100644 index 00000000..e9c78fe3 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_intraday_tests.rs @@ -0,0 +1,757 @@ +use bson::oid::ObjectId; +use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; +use bson::spec::ElementType; +use bson::{DateTime, Timestamp}; + +use super::*; + +fn make_valid_doc( + code: &str, + timestamp_ms: i64, + open: f64, + high: f64, + low: f64, + close: f64, + sharevolume: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), DateTime::from_millis(timestamp_ms)); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("sharevolume"), sharevolume); + doc +} + +fn make_doc_with_timestamp(timestamp: RawBsonRef<'_>) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), timestamp); + doc.append(cstr!("open"), 84.10_f64); + doc.append(cstr!("high"), 84.55_f64); + doc.append(cstr!("low"), 84.02_f64); + doc.append(cstr!("close"), 84.40_f64); + doc.append(cstr!("sharevolume"), 12_500.0_f64); + doc +} + +#[test] +fn decodes_raw_fields_ignoring_differing_adjusted_fields_with_zero_copy_key_and_mappers() { + // 2024-06-07T13:30:00.375Z (nonzero milliseconds to verify exact * 1_000 scaling) + const TS_MS: i64 = 1_717_767_000_375; + const EXPECTED_TS_MICROS: i64 = 1_717_767_000_375_000; + const VERBATIM_KEY: &str = " SHOP:CA "; + + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("provider"), "quotemedia"); + nested.append(cstr!("interval"), 1_i32); + + let mut tags = RawArrayBuf::new(); + tags.push("ca"); + tags.push("1m"); + + let mut doc = RawDocumentBuf::new(); + doc.append( + cstr!("_id"), + ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), + ); + doc.append(cstr!("symbol"), "SHOP"); + doc.append(cstr!("exchange"), "TSX"); + doc.append(cstr!("qmSearchCode"), VERBATIM_KEY); + doc.append(cstr!("startdatetime"), "2024-06-07 09:30:00"); + doc.append(cstr!("timestamp"), DateTime::from_millis(TS_MS)); + // Mixed numeric encodings for raw fields: + doc.append(cstr!("open"), 84_i32); + doc.append(cstr!("high"), 85_i64); + doc.append(cstr!("low"), 83.75_f64); + doc.append(cstr!("close"), 84.50_f64); + doc.append(cstr!("sharevolume"), 12_500_i64); + // Deliberately different adjusted fields that must be ignored: + doc.append(cstr!("adjustedopen"), 8.40_f64); + doc.append(cstr!("adjustedhigh"), 8.50_f64); + doc.append(cstr!("adjustedlow"), 8.375_f64); + doc.append(cstr!("adjustedclose"), 8.45_f64); + doc.append(cstr!("avolume"), 125_000.0_f64); + doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); + + let bytes = doc.as_bytes(); + let buf_start = bytes.as_ptr() as usize; + let buf_end = buf_start + bytes.len(); + + let from_doc = decode_qm_intraday_doc(&doc).unwrap(); + let from_bytes = decode_qm_intraday_bytes(bytes).unwrap(); + assert_eq!(from_doc, from_bytes); + + for bar in [from_doc, from_bytes] { + assert_eq!(bar.qm_search_code, VERBATIM_KEY); + assert_eq!(bar.ts, EXPECTED_TS_MICROS); + assert_eq!(bar.open.to_bits(), 84.0_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 85.0_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 83.75_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 84.50_f64.to_bits()); + assert_eq!(bar.volume.to_bits(), 12_500.0_f64.to_bits()); + + // Zero-copy proof: borrowed key slice points inside the input BSON buffer. + let key_start = bar.qm_search_code.as_ptr() as usize; + let key_end = key_start + bar.qm_search_code.len(); + assert!( + key_start >= buf_start && key_end <= buf_end, + "expected qm_search_code pointer {key_start:#x}..{key_end:#x} inside input buffer {buf_start:#x}..{buf_end:#x}" + ); + } + + // Verify into_eod_intraday_bar and try_into_eod_intraday_bar preserve raw OHLCV verbatim. + let mut seen_into: Option<(&str, i64)> = None; + let mapped = from_doc.into_eod_intraday_bar(|code, ts| { + seen_into = Some((code, ts)); + 42_u64 + }); + assert_eq!(seen_into, Some((VERBATIM_KEY, EXPECTED_TS_MICROS))); + assert_eq!(mapped.key, 42_u64); + assert_eq!(mapped.ts, EXPECTED_TS_MICROS); + assert_eq!(mapped.open.to_bits(), 84.0_f64.to_bits()); + assert_eq!(mapped.high.to_bits(), 85.0_f64.to_bits()); + assert_eq!(mapped.low.to_bits(), 83.75_f64.to_bits()); + assert_eq!(mapped.close.to_bits(), 84.50_f64.to_bits()); + assert_eq!(mapped.volume.to_bits(), 12_500.0_f64.to_bits()); + + let mut seen_try_some: Option<(&str, i64)> = None; + let try_some = from_doc.try_into_eod_intraday_bar(|code, ts| { + seen_try_some = Some((code, ts)); + Some(99_u64) + }); + assert_eq!(seen_try_some, Some((VERBATIM_KEY, EXPECTED_TS_MICROS))); + let try_some = try_some.unwrap(); + assert_eq!(try_some.key, 99_u64); + assert_eq!(try_some.ts, EXPECTED_TS_MICROS); + assert_eq!(try_some.open.to_bits(), 84.0_f64.to_bits()); + assert_eq!(try_some.high.to_bits(), 85.0_f64.to_bits()); + assert_eq!(try_some.low.to_bits(), 83.75_f64.to_bits()); + assert_eq!(try_some.close.to_bits(), 84.50_f64.to_bits()); + assert_eq!(try_some.volume.to_bits(), 12_500.0_f64.to_bits()); + + let try_none: Option> = from_doc.try_into_eod_intraday_bar(|code, ts| { + assert_eq!(code, VERBATIM_KEY); + assert_eq!(ts, EXPECTED_TS_MICROS); + None + }); + assert!(try_none.is_none()); +} + +#[test] +fn table_tests_all_seven_required_fields_for_omission_null_and_wrong_type() { + const ALL_FIELDS: [&str; 7] = [ + FIELD_QM_SEARCH_CODE, + FIELD_TIMESTAMP, + FIELD_OPEN, + FIELD_HIGH, + FIELD_LOW, + FIELD_CLOSE, + FIELD_SHARE_VOLUME, + ]; + + let append_valid = |doc: &mut RawDocumentBuf, field: &str| match field { + FIELD_QM_SEARCH_CODE => doc.append(cstr!("qmSearchCode"), "SHOP:CA"), + FIELD_TIMESTAMP => doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)), + FIELD_OPEN => doc.append(cstr!("open"), 10.0_f64), + FIELD_HIGH => doc.append(cstr!("high"), 11.0_f64), + FIELD_LOW => doc.append(cstr!("low"), 9.5_f64), + FIELD_CLOSE => doc.append(cstr!("close"), 10.5_f64), + FIELD_SHARE_VOLUME => doc.append(cstr!("sharevolume"), 100.0_f64), + other => unreachable!("unexpected field {other}"), + }; + + let append_override = |doc: &mut RawDocumentBuf, field: &str, val: RawBsonRef<'_>| match field { + FIELD_QM_SEARCH_CODE => doc.append(cstr!("qmSearchCode"), val), + FIELD_TIMESTAMP => doc.append(cstr!("timestamp"), val), + FIELD_OPEN => doc.append(cstr!("open"), val), + FIELD_HIGH => doc.append(cstr!("high"), val), + FIELD_LOW => doc.append(cstr!("low"), val), + FIELD_CLOSE => doc.append(cstr!("close"), val), + FIELD_SHARE_VOLUME => doc.append(cstr!("sharevolume"), val), + other => unreachable!("unexpected field {other}"), + }; + + for target in ALL_FIELDS { + // 1. Omission -> MissingField + let mut missing = RawDocumentBuf::new(); + for f in ALL_FIELDS { + if f != target { + append_valid(&mut missing, f); + } + } + let err = decode_qm_intraday_doc(&missing).unwrap_err(); + assert_eq!(err, BsonQmIntradayError::MissingField { field: target }); + assert!(err.to_string().contains(target)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_missing_field, 1); + assert_eq!(st.rejected_total(), 1); + + // 2. Null -> WrongType(Null) + let mut with_null = RawDocumentBuf::new(); + for f in ALL_FIELDS { + if f == target { + append_override(&mut with_null, f, RawBsonRef::Null); + } else { + append_valid(&mut with_null, f); + } + } + let err = decode_qm_intraday_doc(&with_null).unwrap_err(); + assert_eq!( + err, + BsonQmIntradayError::WrongType { + field: target, + actual: ElementType::Null, + } + ); + assert!(err.to_string().contains(target)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_wrong_type, 1); + assert_eq!(st.rejected_total(), 1); + + // 3. Another inappropriate BSON type -> WrongType + let (bad_val, expected_type) = match target { + FIELD_QM_SEARCH_CODE => (RawBsonRef::Int32(123), ElementType::Int32), + FIELD_TIMESTAMP => (RawBsonRef::Boolean(true), ElementType::Boolean), + _ => (RawBsonRef::String("10.0"), ElementType::String), + }; + let mut with_wrong = RawDocumentBuf::new(); + for f in ALL_FIELDS { + if f == target { + append_override(&mut with_wrong, f, bad_val); + } else { + append_valid(&mut with_wrong, f); + } + } + let err = decode_qm_intraday_doc(&with_wrong).unwrap_err(); + assert_eq!( + err, + BsonQmIntradayError::WrongType { + field: target, + actual: expected_type, + } + ); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_wrong_type, 1); + assert_eq!(st.rejected_total(), 1); + } + + // Empty document checks missing-field order starts at qmSearchCode. + let empty_doc = RawDocumentBuf::new(); + assert_eq!( + decode_qm_intraday_doc(&empty_doc).unwrap_err(), + BsonQmIntradayError::MissingField { + field: FIELD_QM_SEARCH_CODE + } + ); +} + +#[test] +fn rejects_empty_and_whitespace_only_qm_search_code() { + for blank in ["", " ", " ", "\t\n\r "] { + let doc = make_valid_doc(blank, 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmIntradayError::EmptyField { + field: FIELD_QM_SEARCH_CODE + } + ); + assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_empty_field, 1); + assert_eq!(st.rejected_total(), 1); + } +} + +#[test] +fn validates_timestamp_datetime_boundaries_and_rejects_substitutes() { + // Epoch zero is valid. + let epoch_doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(0))); + assert_eq!(decode_qm_intraday_doc(&epoch_doc).unwrap().ts, 0); + + // Largest in-range millisecond timestamp (i64::MAX / 1_000) is valid. + let max_doc = + make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(MAX_TIMESTAMP_MILLIS))); + assert_eq!( + decode_qm_intraday_doc(&max_doc).unwrap().ts, + MAX_TIMESTAMP_MILLIS * 1_000 + ); + + // Negative and overflowing DateTime values -> InvalidTimestamp. + for bad_ms in [-1_i64, i64::MIN, MAX_TIMESTAMP_MILLIS + 1, i64::MAX] { + let doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(bad_ms))); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmIntradayError::InvalidTimestamp { + field: FIELD_TIMESTAMP + } + ); + assert!(err.to_string().contains(FIELD_TIMESTAMP)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_invalid_timestamp, 1); + assert_eq!(st.rejected_total(), 1); + } + + // Numeric, string, and BSON Timestamp substitutes -> WrongType. + let wrong_ts: [(RawBsonRef<'_>, ElementType); 6] = [ + (RawBsonRef::Int32(1_717_767_000), ElementType::Int32), + (RawBsonRef::Int64(1_717_767_000_000), ElementType::Int64), + (RawBsonRef::Double(1_717_767_000_000.0), ElementType::Double), + ( + RawBsonRef::String("2024-06-07T13:30:00Z"), + ElementType::String, + ), + ( + RawBsonRef::Timestamp(Timestamp { + time: 1_717_767_000, + increment: 1, + }), + ElementType::Timestamp, + ), + (RawBsonRef::Null, ElementType::Null), + ]; + for (val, expected_type) in wrong_ts { + let doc = make_doc_with_timestamp(val); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmIntradayError::WrongType { + field: FIELD_TIMESTAMP, + actual: expected_type, + } + ); + } +} + +#[test] +fn validates_ohlc_and_sharevolume_domains_and_normalizes_negative_zero_volume() { + let ohlc_fields = [FIELD_OPEN, FIELD_HIGH, FIELD_LOW, FIELD_CLOSE]; + + for target in ohlc_fields { + let build_with = |val: RawBsonRef<'_>| { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + for (name, key) in [ + (FIELD_OPEN, cstr!("open")), + (FIELD_HIGH, cstr!("high")), + (FIELD_LOW, cstr!("low")), + (FIELD_CLOSE, cstr!("close")), + (FIELD_SHARE_VOLUME, cstr!("sharevolume")), + ] { + if name == target { + doc.append(key, val); + } else { + doc.append(key, 10.0_f64); + } + } + doc + }; + + for bad_num in [ + RawBsonRef::Double(0.0), + RawBsonRef::Double(-0.0), + RawBsonRef::Double(-1.25), + RawBsonRef::Double(f64::NAN), + RawBsonRef::Double(f64::INFINITY), + RawBsonRef::Double(f64::NEG_INFINITY), + RawBsonRef::Int32(0), + RawBsonRef::Int32(-5), + RawBsonRef::Int64(0), + RawBsonRef::Int64(-5), + ] { + let doc = build_with(bad_num); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + match &err { + BsonQmIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, target), + other => panic!("expected InvalidNumber for {target}, got {other:?}"), + } + assert!(err.to_string().contains(target)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_invalid_number, 1); + assert_eq!(st.rejected_total(), 1); + } + } + + let build_with_vol = |val: RawBsonRef<'_>| { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.5_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("sharevolume"), val); + doc + }; + + // Zero sharevolume in +0.0, -0.0, Int32(0), Int64(0) canonicalizes to +0.0. + for zero_vol in [ + RawBsonRef::Double(0.0), + RawBsonRef::Double(-0.0), + RawBsonRef::Int32(0), + RawBsonRef::Int64(0), + ] { + let doc = build_with_vol(zero_vol); + let decoded = decode_qm_intraday_doc(&doc).unwrap(); + assert_eq!(decoded.volume.to_bits(), 0.0_f64.to_bits()); + } + + // Negative and non-finite sharevolume -> InvalidNumber. + for bad_vol in [ + RawBsonRef::Double(-0.01), + RawBsonRef::Double(f64::NAN), + RawBsonRef::Double(f64::INFINITY), + RawBsonRef::Double(f64::NEG_INFINITY), + RawBsonRef::Int32(-1), + RawBsonRef::Int64(-1), + ] { + let doc = build_with_vol(bad_vol); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + match &err { + BsonQmIntradayError::InvalidNumber { field, .. } => { + assert_eq!(*field, FIELD_SHARE_VOLUME) + } + other => panic!("expected InvalidNumber for sharevolume, got {other:?}"), + } + assert!(err.to_string().contains(FIELD_SHARE_VOLUME)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_invalid_number, 1); + assert_eq!(st.rejected_total(), 1); + } +} + +#[test] +fn duplicate_fields_and_semantic_vs_corrupt_precedence() { + // 1. All duplicate occurrences valid -> last valid value wins. + let mut dup_valid = RawDocumentBuf::new(); + dup_valid.append(cstr!("qmSearchCode"), "FIRST:CA"); + dup_valid.append(cstr!("timestamp"), DateTime::from_millis(1_000)); + dup_valid.append(cstr!("open"), 10.0_f64); + dup_valid.append(cstr!("high"), 11.0_f64); + dup_valid.append(cstr!("low"), 9.0_f64); + dup_valid.append(cstr!("close"), 10.5_f64); + dup_valid.append(cstr!("sharevolume"), 100.0_f64); + dup_valid.append(cstr!("qmSearchCode"), "SECOND:CA"); + dup_valid.append(cstr!("timestamp"), DateTime::from_millis(2_500)); + dup_valid.append(cstr!("open"), 20.0_f64); + dup_valid.append(cstr!("high"), 22.0_f64); + dup_valid.append(cstr!("low"), 19.0_f64); + dup_valid.append(cstr!("close"), 21.5_f64); + dup_valid.append(cstr!("sharevolume"), 250_i32); + + let bar = decode_qm_intraday_doc(&dup_valid).unwrap(); + assert_eq!(bar.qm_search_code, "SECOND:CA"); + assert_eq!(bar.ts, 2_500_000); + assert_eq!(bar.open.to_bits(), 20.0_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 22.0_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 19.0_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 21.5_f64.to_bits()); + assert_eq!(bar.volume.to_bits(), 250.0_f64.to_bits()); + + // 2. A valid duplicate cannot erase an earlier semantic error. + let mut err_then_valid = RawDocumentBuf::new(); + err_then_valid.append(cstr!("qmSearchCode"), " "); + err_then_valid.append(cstr!("qmSearchCode"), "SHOP:CA"); + err_then_valid.append(cstr!("timestamp"), DateTime::from_millis(1_000)); + err_then_valid.append(cstr!("open"), 10.0_f64); + err_then_valid.append(cstr!("high"), 11.0_f64); + err_then_valid.append(cstr!("low"), 9.0_f64); + err_then_valid.append(cstr!("close"), 10.5_f64); + err_then_valid.append(cstr!("sharevolume"), 100.0_f64); + assert_eq!( + decode_qm_intraday_doc(&err_then_valid).unwrap_err(), + BsonQmIntradayError::EmptyField { + field: FIELD_QM_SEARCH_CODE + } + ); + + // 3. First semantic error survives a second semantic error. + let mut two_errors = RawDocumentBuf::new(); + two_errors.append(cstr!("qmSearchCode"), "SHOP:CA"); + two_errors.append(cstr!("timestamp"), DateTime::from_millis(-1)); + two_errors.append(cstr!("open"), -5.0_f64); + two_errors.append(cstr!("high"), RawBsonRef::Null); + two_errors.append(cstr!("low"), 9.0_f64); + two_errors.append(cstr!("close"), 10.5_f64); + two_errors.append(cstr!("sharevolume"), 100.0_f64); + assert_eq!( + decode_qm_intraday_doc(&two_errors).unwrap_err(), + BsonQmIntradayError::InvalidTimestamp { + field: FIELD_TIMESTAMP + } + ); + + // 4. Malformed UTF-8 in a later skipped field overrides an earlier semantic error as CorruptBson. + const MARKER: &[u8] = b"2024-06-07 09:30:00"; + let mut semantic_then_corrupt = RawDocumentBuf::new(); + semantic_then_corrupt.append(cstr!("qmSearchCode"), " "); // earlier EmptyField + semantic_then_corrupt.append(cstr!("timestamp"), DateTime::from_millis(-5)); // second semantic err + semantic_then_corrupt.append(cstr!("open"), 10.0_f64); + semantic_then_corrupt.append(cstr!("high"), 11.0_f64); + semantic_then_corrupt.append(cstr!("low"), 9.0_f64); + semantic_then_corrupt.append(cstr!("close"), 10.5_f64); + semantic_then_corrupt.append(cstr!("sharevolume"), 100.0_f64); + semantic_then_corrupt.append(cstr!("startdatetime"), "2024-06-07 09:30:00"); + + let mut corrupt_bytes = semantic_then_corrupt.as_bytes().to_vec(); + let pos = corrupt_bytes + .windows(MARKER.len()) + .position(|w| w == MARKER) + .expect("startdatetime marker must exist"); + corrupt_bytes[pos + 4] = 0xFF; + + match decode_qm_intraday_bytes(&corrupt_bytes) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!( + detail.contains("startdatetime"), + "expected offending skipped field name in detail, got: {detail}" + ); + } + other => panic!("expected CorruptBson overriding earlier semantic error, got {other:?}"), + } +} + +#[test] +fn rejects_truncated_corrupt_and_trailing_single_doc_bytes_as_corrupt_bson() { + // Truncated header (< 4 bytes) + match decode_qm_intraday_bytes(&[0x10, 0x00]) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!(detail.contains("truncated"), "detail={detail}"); + } + other => panic!("expected CorruptBson for truncated header, got {other:?}"), + } + + // Declared length < 5 + match decode_qm_intraday_bytes(&[4, 0, 0, 0]) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!(detail.contains('4'), "detail={detail}"); + } + other => panic!("expected CorruptBson for length < 5, got {other:?}"), + } + + let valid = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); + + // Truncated body + let truncated = &valid.as_bytes()[..valid.as_bytes().len() - 3]; + match decode_qm_intraday_bytes(truncated) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!(detail.contains("truncated"), "detail={detail}"); + } + other => panic!("expected CorruptBson for truncated body, got {other:?}"), + } + + // Trailing extra bytes on single-doc decode + let mut with_trailing = valid.as_bytes().to_vec(); + with_trailing.push(0x00); + match decode_qm_intraday_bytes(&with_trailing) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!(detail.contains("length"), "detail={detail}"); + } + other => panic!("expected CorruptBson for trailing bytes, got {other:?}"), + } + + // Malformed BSON (bad trailing NUL terminator) + let mut bad_term = valid.as_bytes().to_vec(); + *bad_term.last_mut().unwrap() = 0xFF; + match decode_qm_intraday_bytes(&bad_term) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, .. }) => {} + other => panic!("expected CorruptBson for bad terminator, got {other:?}"), + } +} + +#[test] +fn decodes_mixed_buffer_deterministically_recovers_past_corrupt_frame_and_merges_stats() { + // Empty buffer -> zero stats and no callbacks. + let mut empty_rows = 0usize; + let mut empty_errs = 0usize; + let empty_stats = decode_qm_intraday_buffer(&[], |_| empty_rows += 1, |_, _| empty_errs += 1); + assert_eq!(empty_stats, BsonQmIntradayDecodeStats::default()); + assert_eq!(empty_stats.rejected_total(), 0); + assert_eq!(empty_rows, 0); + assert_eq!(empty_errs, 0); + + let valid1 = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); + let empty_key = make_valid_doc(" ", 1_717_767_060_000, 84.5, 85.0, 84.0, 84.8, 500.0); + let bad_ts = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(-10))); + let bad_price = make_valid_doc("SHOP:CA", 1_717_767_180_000, 0.0, 85.0, 83.0, 84.0, 200.0); + + let mut wrong_type = RawDocumentBuf::new(); + wrong_type.append(cstr!("qmSearchCode"), "SHOP:CA"); + wrong_type.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_240_000)); + wrong_type.append(cstr!("open"), RawBsonRef::Null); + wrong_type.append(cstr!("high"), 85.0_f64); + wrong_type.append(cstr!("low"), 83.0_f64); + wrong_type.append(cstr!("close"), 84.0_f64); + wrong_type.append(cstr!("sharevolume"), 200.0_f64); + + let mut missing_field = RawDocumentBuf::new(); + missing_field.append(cstr!("qmSearchCode"), "SHOP:CA"); + missing_field.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_300_000)); + missing_field.append(cstr!("open"), 84.0_f64); + missing_field.append(cstr!("high"), 85.0_f64); + missing_field.append(cstr!("low"), 83.0_f64); + missing_field.append(cstr!("close"), 84.0_f64); + + // Valid length-framed doc whose trailing terminator is corrupt -> CorruptBson, but buffer + // iteration recovers past the known frame boundary and decodes valid2 after it. + let mut corrupt_framed = valid1.as_bytes().to_vec(); + *corrupt_framed.last_mut().unwrap() = 0xAA; + + let valid2 = make_valid_doc("X:CA", 1_717_767_360_000, 39.5, 40.0, 39.25, 39.75, -0.0); + + let mut batch1 = Vec::new(); + batch1.extend_from_slice(valid1.as_bytes()); + let off_empty = batch1.len(); + batch1.extend_from_slice(empty_key.as_bytes()); + let off_bad_ts = batch1.len(); + batch1.extend_from_slice(bad_ts.as_bytes()); + let off_bad_price = batch1.len(); + batch1.extend_from_slice(bad_price.as_bytes()); + + let mut batch2 = Vec::new(); + batch2.extend_from_slice(wrong_type.as_bytes()); + batch2.extend_from_slice(missing_field.as_bytes()); + batch2.extend_from_slice(&corrupt_framed); + batch2.extend_from_slice(valid2.as_bytes()); + + let mut full_buf = Vec::new(); + full_buf.extend_from_slice(&batch1); + let off_wrong_type = full_buf.len(); + full_buf.extend_from_slice(wrong_type.as_bytes()); + let off_missing = full_buf.len(); + full_buf.extend_from_slice(missing_field.as_bytes()); + let off_corrupt = full_buf.len(); + full_buf.extend_from_slice(&corrupt_framed); + full_buf.extend_from_slice(valid2.as_bytes()); + let off_trunc = full_buf.len(); + // Truncated tail: stops cleanly and is counted once. + full_buf.extend_from_slice(&valid2.as_bytes()[..10]); + + let run_once = |buf: &[u8]| { + let mut rows = Vec::new(); + let mut errors = Vec::new(); + let stats = decode_qm_intraday_buffer( + buf, + |bar| { + rows.push(( + bar.qm_search_code.to_owned(), + bar.ts, + bar.close.to_bits(), + bar.volume.to_bits(), + )) + }, + |offset, err| errors.push((offset, err)), + ); + (rows, errors, stats) + }; + + let (rows_a, errs_a, stats_a) = run_once(&full_buf); + let (rows_b, errs_b, stats_b) = run_once(&full_buf); + + // Deterministic replay produces identical rows, errors, offsets, and stats. + assert_eq!(rows_a, rows_b); + assert_eq!(errs_a, errs_b); + assert_eq!(stats_a, stats_b); + + assert_eq!( + rows_a, + vec![ + ( + "SHOP:CA".to_owned(), + 1_717_767_000_000_000, + 84.5_f64.to_bits(), + 1000.0_f64.to_bits(), + ), + ( + "X:CA".to_owned(), + 1_717_767_360_000_000, + 39.75_f64.to_bits(), + 0.0_f64.to_bits(), + ), + ] + ); + + assert_eq!(stats_a.docs_seen, 9); + assert_eq!(stats_a.rows_decoded, 2); + assert_eq!(stats_a.rejected_empty_field, 1); + assert_eq!(stats_a.rejected_invalid_timestamp, 1); + assert_eq!(stats_a.rejected_invalid_number, 1); + assert_eq!(stats_a.rejected_wrong_type, 1); + assert_eq!(stats_a.rejected_missing_field, 1); + assert_eq!(stats_a.rejected_corrupt_document, 2); // corrupt_framed + truncated tail + assert_eq!(stats_a.rejected_total(), 7); + assert_eq!(stats_a.docs_seen, stats_a.rows_decoded + stats_a.rejected_total()); + + assert_eq!(errs_a.len(), 7); + assert_eq!(errs_a[0].0, off_empty); + assert_eq!( + errs_a[0].1, + BsonQmIntradayError::EmptyField { + field: FIELD_QM_SEARCH_CODE + } + ); + assert_eq!(errs_a[1].0, off_bad_ts); + assert_eq!( + errs_a[1].1, + BsonQmIntradayError::InvalidTimestamp { + field: FIELD_TIMESTAMP + } + ); + assert_eq!(errs_a[2].0, off_bad_price); + assert!(matches!( + errs_a[2].1, + BsonQmIntradayError::InvalidNumber { field: FIELD_OPEN, .. } + )); + assert_eq!(errs_a[3].0, off_wrong_type); + assert_eq!( + errs_a[3].1, + BsonQmIntradayError::WrongType { + field: FIELD_OPEN, + actual: ElementType::Null, + } + ); + assert_eq!(errs_a[4].0, off_missing); + assert_eq!( + errs_a[4].1, + BsonQmIntradayError::MissingField { + field: FIELD_SHARE_VOLUME + } + ); + assert_eq!(errs_a[5].0, off_corrupt); + assert!(matches!( + &errs_a[5].1, + BsonQmIntradayError::CorruptBson { offset, .. } if *offset == off_corrupt + )); + assert_eq!(errs_a[6].0, off_trunc); + assert!(matches!( + &errs_a[6].1, + BsonQmIntradayError::CorruptBson { offset, detail } + if *offset == off_trunc && detail.contains("truncated") + )); + + // Verify merge and AddAssign match decoding frame-aligned batches separately. + let mut batch2_with_trunc = batch2.clone(); + batch2_with_trunc.extend_from_slice(&valid2.as_bytes()[..10]); + let s1 = decode_qm_intraday_buffer(&batch1, |_| {}, |_, _| {}); + let s2 = decode_qm_intraday_buffer(&batch2_with_trunc, |_| {}, |_, _| {}); + let mut merged = s1; + merged.merge(&s2); + assert_eq!(merged, stats_a); + + let mut added = s1; + added += s2; + assert_eq!(added, stats_a); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 6244dcc7..cee11fe3 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -9,6 +9,7 @@ pub mod bson_eod_intraday; pub mod bson_eod_prices; pub mod bson_qm_actions; pub mod bson_qm_events; +pub mod bson_qm_intraday; pub mod bson_qm_prices; pub mod bson_stream; pub mod bson_te_market_data; From 5527cebc21a4d03a64d2d40d4eab3c138f2b69eb Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:44:56 -0500 Subject: [PATCH 07/15] T-150: tests --- .../curate-etl/src/bson_qm_intraday_tests.rs | 343 +++++++++++++++++- 1 file changed, 339 insertions(+), 4 deletions(-) diff --git a/tools/curate-etl/src/bson_qm_intraday_tests.rs b/tools/curate-etl/src/bson_qm_intraday_tests.rs index e9c78fe3..b4638271 100644 --- a/tools/curate-etl/src/bson_qm_intraday_tests.rs +++ b/tools/curate-etl/src/bson_qm_intraday_tests.rs @@ -278,8 +278,9 @@ fn validates_timestamp_datetime_boundaries_and_rejects_substitutes() { assert_eq!(decode_qm_intraday_doc(&epoch_doc).unwrap().ts, 0); // Largest in-range millisecond timestamp (i64::MAX / 1_000) is valid. - let max_doc = - make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(MAX_TIMESTAMP_MILLIS))); + let max_doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis( + MAX_TIMESTAMP_MILLIS, + ))); assert_eq!( decode_qm_intraday_doc(&max_doc).unwrap().ts, MAX_TIMESTAMP_MILLIS * 1_000 @@ -693,7 +694,10 @@ fn decodes_mixed_buffer_deterministically_recovers_past_corrupt_frame_and_merges assert_eq!(stats_a.rejected_missing_field, 1); assert_eq!(stats_a.rejected_corrupt_document, 2); // corrupt_framed + truncated tail assert_eq!(stats_a.rejected_total(), 7); - assert_eq!(stats_a.docs_seen, stats_a.rows_decoded + stats_a.rejected_total()); + assert_eq!( + stats_a.docs_seen, + stats_a.rows_decoded + stats_a.rejected_total() + ); assert_eq!(errs_a.len(), 7); assert_eq!(errs_a[0].0, off_empty); @@ -713,7 +717,10 @@ fn decodes_mixed_buffer_deterministically_recovers_past_corrupt_frame_and_merges assert_eq!(errs_a[2].0, off_bad_price); assert!(matches!( errs_a[2].1, - BsonQmIntradayError::InvalidNumber { field: FIELD_OPEN, .. } + BsonQmIntradayError::InvalidNumber { + field: FIELD_OPEN, + .. + } )); assert_eq!(errs_a[3].0, off_wrong_type); assert_eq!( @@ -755,3 +762,331 @@ fn decodes_mixed_buffer_deterministically_recovers_past_corrupt_frame_and_merges added += s2; assert_eq!(added, stats_a); } + +// --- QA edge cases (T-150) ------------------------------------------------------------------- + +fn find_marker(bytes: &[u8], marker: &[u8]) -> usize { + bytes + .windows(marker.len()) + .position(|w| w == marker) + .expect("marker must exist in fixture bytes") +} + +#[test] +fn corrupt_bytes_inside_an_adjusted_field_reject_the_document_as_corrupt_bson() { + // Proves adjusted fields are validated (not blindly skipped) even though they are never read: + // flip `adjustedclose` from Double (0x01) to String (0x02) so its 8 payload bytes are read as a + // bogus string length. + let mut doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); + doc.append(cstr!("adjustedclose"), 8.45_f64); + doc.append(cstr!("avolume"), 10_000.0_f64); + let mut bytes = doc.as_bytes().to_vec(); + let key_pos = find_marker(&bytes, b"adjustedclose\0"); + assert_eq!( + bytes[key_pos - 1], + 0x01, + "fixture: element type byte precedes key" + ); + bytes[key_pos - 1] = 0x02; + + match decode_qm_intraday_bytes(&bytes) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, .. }) => {} + other => panic!("expected CorruptBson for corrupt adjustedclose, got {other:?}"), + } +} + +#[test] +fn adjusted_fields_of_any_type_or_value_do_not_affect_raw_decode() { + // Adjusted fields that would fail raw validation (Null, negative, NaN, string) must be ignored. + let mut doc = make_valid_doc( + "RY:CA", + 1_717_767_000_000, + 130.0, + 131.0, + 129.5, + 130.5, + 2_000.0, + ); + doc.append(cstr!("adjustedopen"), RawBsonRef::Null); + doc.append(cstr!("adjustedhigh"), -1.0_f64); + doc.append(cstr!("adjustedlow"), f64::NAN); + doc.append(cstr!("adjustedclose"), "n/a"); + doc.append(cstr!("avolume"), -5_i64); + + let bar = decode_qm_intraday_doc(&doc).unwrap(); + assert_eq!(bar.qm_search_code, "RY:CA"); + assert_eq!(bar.ts, 1_717_767_000_000_000); + assert_eq!(bar.open.to_bits(), 130.0_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 131.0_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 129.5_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 130.5_f64.to_bits()); + assert_eq!(bar.volume.to_bits(), 2_000.0_f64.to_bits()); +} + +#[test] +fn adjusted_only_document_is_missing_raw_fields_not_silently_substituted() { + // A doc carrying only adjusted prices/volume must not fall back to them. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + doc.append(cstr!("adjustedopen"), 8.4_f64); + doc.append(cstr!("adjustedhigh"), 8.5_f64); + doc.append(cstr!("adjustedlow"), 8.3_f64); + doc.append(cstr!("adjustedclose"), 8.45_f64); + doc.append(cstr!("avolume"), 125_000.0_f64); + assert_eq!( + decode_qm_intraday_doc(&doc).unwrap_err(), + BsonQmIntradayError::MissingField { field: FIELD_OPEN } + ); + + // Same with only `volume`/`avolume` instead of `sharevolume`. + let mut doc = make_doc_without_sharevolume(); + doc.append(cstr!("volume"), 100.0_f64); + doc.append(cstr!("avolume"), 100.0_f64); + assert_eq!( + decode_qm_intraday_doc(&doc).unwrap_err(), + BsonQmIntradayError::MissingField { + field: FIELD_SHARE_VOLUME + } + ); +} + +fn make_doc_without_sharevolume() -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc +} + +#[test] +fn field_names_match_case_sensitively() { + // `Open` / `QmSearchCode` are unknown fields, so the real ones are reported missing. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("QmSearchCode"), "SHOP:CA"); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + doc.append(cstr!("Open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("sharevolume"), 1.0_f64); + assert_eq!( + decode_qm_intraday_doc(&doc).unwrap_err(), + BsonQmIntradayError::MissingField { field: FIELD_OPEN } + ); +} + +#[test] +fn field_order_does_not_change_the_decoded_bar() { + let forward = make_valid_doc( + "SHOP:CA", + 1_717_767_000_123, + 84.0, + 85.0, + 83.5, + 84.5, + 1_000.0, + ); + + let mut reversed = RawDocumentBuf::new(); + reversed.append(cstr!("sharevolume"), 1_000.0_f64); + reversed.append(cstr!("close"), 84.5_f64); + reversed.append(cstr!("low"), 83.5_f64); + reversed.append(cstr!("high"), 85.0_f64); + reversed.append(cstr!("open"), 84.0_f64); + reversed.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_123)); + reversed.append(cstr!("qmSearchCode"), "SHOP:CA"); + + assert_eq!( + decode_qm_intraday_doc(&forward).unwrap(), + decode_qm_intraday_doc(&reversed).unwrap() + ); +} + +#[test] +fn missing_field_precedence_follows_declared_order_and_semantic_error_beats_missing() { + // close and sharevolume both missing -> close (earlier in declared order) is reported. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + assert_eq!( + decode_qm_intraday_doc(&doc).unwrap_err(), + BsonQmIntradayError::MissingField { field: FIELD_CLOSE } + ); + + // A semantic error on a late field wins over an earlier-ordered missing field. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + doc.append(cstr!("sharevolume"), -1.0_f64); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + assert!( + matches!( + err, + BsonQmIntradayError::InvalidNumber { + field: FIELD_SHARE_VOLUME, + .. + } + ), + "got {err:?}" + ); +} + +#[test] +fn invalid_duplicate_after_valid_value_still_rejects_the_document() { + // Valid open followed by an invalid duplicate open: the semantic error must be kept. + let mut doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + doc.append(cstr!("open"), 0.0_f64); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + assert!( + matches!(err, BsonQmIntradayError::InvalidNumber { field: FIELD_OPEN, value } if value == 0.0), + "got {err:?}" + ); +} + +#[test] +fn malformed_utf8_in_qm_search_code_is_corrupt_bson_naming_the_field() { + let doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let mut bytes = doc.as_bytes().to_vec(); + let pos = find_marker(&bytes, b"SHOP:CA"); + bytes[pos + 1] = 0xFF; + match decode_qm_intraday_bytes(&bytes) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!(detail.contains(FIELD_QM_SEARCH_CODE), "detail={detail}"); + } + other => panic!("expected CorruptBson for invalid UTF-8 key, got {other:?}"), + } +} + +#[test] +fn non_ascii_and_large_integer_values_are_preserved_exactly() { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "BCE.PR.Ä:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_735_689_599_999)); + doc.append(cstr!("open"), 1_i32); + doc.append(cstr!("high"), i32::MAX); + doc.append(cstr!("low"), 1_i64); + doc.append(cstr!("close"), 9_007_199_254_740_992_i64); // 2^53, exact in f64 + doc.append(cstr!("sharevolume"), i64::MAX); + + let bar = decode_qm_intraday_doc(&doc).unwrap(); + assert_eq!(bar.qm_search_code, "BCE.PR.Ä:CA"); + assert_eq!(bar.ts, 1_735_689_599_999_000); + assert_eq!(bar.open, 1.0); + assert_eq!(bar.high, f64::from(i32::MAX)); + assert_eq!(bar.low, 1.0); + assert_eq!(bar.close, 9_007_199_254_740_992.0); + assert_eq!(bar.volume, i64::MAX as f64); + assert!(bar.volume.is_finite()); +} + +#[test] +fn display_messages_name_field_and_domain() { + let vol = BsonQmIntradayError::InvalidNumber { + field: FIELD_SHARE_VOLUME, + value: -1.0, + } + .to_string(); + assert!(vol.contains("sharevolume") && vol.contains(">= 0"), "{vol}"); + let price = BsonQmIntradayError::InvalidNumber { + field: FIELD_HIGH, + value: 0.0, + } + .to_string(); + assert!( + price.contains("high") && price.contains("> 0") && !price.contains(">= 0"), + "{price}" + ); + let corrupt = BsonQmIntradayError::CorruptBson { + offset: 77, + detail: "x".into(), + } + .to_string(); + assert!(corrupt.contains("77"), "{corrupt}"); +} + +#[test] +fn buffer_stops_at_unrecoverable_frame_length_counting_it_once_and_keeps_earlier_rows() { + let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let b = make_valid_doc("B:CA", 1_717_767_060_000, 20.0, 21.0, 19.0, 20.5, 200.0); + let c = make_valid_doc("C:CA", 1_717_767_120_000, 30.0, 31.0, 29.0, 30.5, 300.0); + + let mut buf = Vec::new(); + buf.extend_from_slice(a.as_bytes()); + buf.extend_from_slice(b.as_bytes()); + let bad_off = buf.len(); + buf.extend_from_slice(&3_i32.to_le_bytes()); // declared length < 5: no boundary known + buf.extend_from_slice(c.as_bytes()); // must NOT be decoded (cannot resync safely) + + let mut codes = Vec::new(); + let mut errors = Vec::new(); + let stats = decode_qm_intraday_buffer( + &buf, + |bar| codes.push(bar.qm_search_code), + |off, err| errors.push((off, err)), + ); + + assert_eq!(codes, vec!["A:CA", "B:CA"]); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].0, bad_off); + assert!(matches!( + &errors[0].1, + BsonQmIntradayError::CorruptBson { offset, .. } if *offset == bad_off + )); + assert_eq!(stats.docs_seen, 3); + assert_eq!(stats.rows_decoded, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); +} + +#[test] +fn buffer_rows_borrow_keys_from_the_input_buffer() { + let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let b = make_valid_doc("B:CA", 1_717_767_060_000, 20.0, 21.0, 19.0, 20.5, 200.0); + let mut buf = Vec::new(); + buf.extend_from_slice(a.as_bytes()); + buf.extend_from_slice(b.as_bytes()); + let range = buf.as_ptr_range(); + + let mut ptrs = Vec::new(); + let stats = decode_qm_intraday_buffer( + &buf, + |bar| ptrs.push(bar.qm_search_code.as_ptr()), + |_, err| panic!("unexpected error {err:?}"), + ); + assert_eq!(stats.rows_decoded, 2); + assert_eq!(ptrs.len(), 2); + for p in ptrs { + assert!( + range.contains(&p), + "key pointer {p:?} outside input buffer {range:?}" + ); + } +} + +#[test] +fn single_valid_doc_buffer_with_short_trailing_bytes_decodes_row_then_counts_truncated_tail() { + let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let mut buf = a.as_bytes().to_vec(); + let tail_off = buf.len(); + buf.extend_from_slice(&[0x00, 0x00]); + + let mut rows = 0usize; + let mut errors = Vec::new(); + let stats = decode_qm_intraday_buffer(&buf, |_| rows += 1, |off, err| errors.push((off, err))); + assert_eq!(rows, 1); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].0, tail_off); + assert!(matches!( + errors[0].1, + BsonQmIntradayError::CorruptBson { .. } + )); + assert_eq!(stats.docs_seen, 2); + assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); +} From ee6137c7700d11313d63a9d80a4743df73bcc4f1 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:17:04 -0500 Subject: [PATCH 08/15] =?UTF-8?q?T-149:=20M2.1h=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`analyze=5Fsignal`:=20add=20a=20Vault-fenced=20`fundamental?= =?UTF-8?q?s`=20signal=20source=20(point-in-time=20`fundamentalsAsOf`=20mo?= =?UTF-8?q?nth-end=20snapshots=20=E2=86=92=20`SignalObservation`s)=20+=20e?= =?UTF-8?q?xtend=20the=20headless=20stdio=20end-to-end=20test=20to=20run?= =?UTF-8?q?=20a=20fundamental=20AND=20a=20shorts=20study=20(pure,=20inject?= =?UTF-8?q?ed=20ports,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/analyze-signal.ts | 340 +++++- libs/research/test/mcp-analyze-signal.test.ts | 1081 ++++++++++++++++- libs/research/test/mcp-copilot-server.test.ts | 220 +++- 3 files changed, 1554 insertions(+), 87 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index 090e9e32..8a803e12 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -14,10 +14,14 @@ import { type TableRow, type VaultFenceContext, } from '../../market-data-store'; -import { UNIVERSE_REFS } from '../../market-data-store-duckdb'; +import { + FUNDAMENTALS_PIT_VALUE_FIELDS, + type FundamentalsPitValueField, + UNIVERSE_REFS, +} from '../../market-data-store-duckdb'; import { SHORTS_SIGNAL_FIELDS, - type ShortsSignalField, + type SignalObservation, type SignalPanelDiagnostics, SignalPanelError, type SignalPanelErrorCode, @@ -44,8 +48,8 @@ import { UNIVERSE_MARKETS, type UniverseMarket, } from '../../trial-ledger'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; +import type { JsonSchemaObject, JsonSchemaProperty, McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool, zodObjectToJsonSchema } from '../server'; import { EXCLUSIVE_LISTING_SELECTOR_MESSAGE, MCP_MAX_LISTING_IDS, @@ -53,6 +57,7 @@ import { createUniverseFieldSchema, fenceVaultQueryBounds, formatMappedStoreError, + formatUtcIsoWithMicros, hasExclusiveListingSelector, isValidUtcBoundString, resolvePreStartUniverseDate, @@ -69,6 +74,9 @@ export const ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS = 252; /** Maximum number of latest dated observations exposed in the tool response preview. */ export const ANALYZE_SIGNAL_MAX_SERIES_POINTS = 100; +/** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */ +export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120; + const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const AGENT_PRINCIPAL_RE = /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; @@ -84,22 +92,37 @@ const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC const shortsSignalSpecSchema = z .object({ - source: z.literal('shorts').describe('Signal data source (currently "shorts").'), + source: z.literal('shorts').describe('Signal data source ("shorts").'), field: z .enum(SHORTS_SIGNAL_FIELDS) .describe('Short-interest field to evaluate (shares_short, net_change, or pct_float).'), }) .strict() - .describe('Discriminated signal source and field specification.'); + .describe('Short-interest signal specification.'); -/** - * Strict Zod input schema for the `analyze_signal` MCP tool. - * - * Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and - * `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them - * or any other unknown top-level or nested key. - */ -export const analyzeSignalInputSchema = z +const fundamentalsSignalSpecSchema = z + .object({ + source: z.literal('fundamentals').describe('Signal data source ("fundamentals").'), + field: z + .enum(FUNDAMENTALS_PIT_VALUE_FIELDS) + .describe( + 'Point-in-time fundamentals value field to evaluate (revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, ttm_revenue, ttm_net_income, or ttm_operating_cash_flow).' + ), + allowEstimatedLag: z + .boolean() + .default(false) + .describe( + 'Whether to include fundamentals snapshots with estimated publication lag (default false).' + ), + }) + .strict() + .describe('Point-in-time fundamentals signal specification.'); + +const signalSpecSchema = z + .discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema]) + .describe('Discriminated signal source and field specification ("shorts" or "fundamentals").'); + +const analyzeSignalSharedFieldsSchema = z .object({ listingIds: createListingIdsFieldSchema( 'Explicit INT32 listing IDs to study (mutually exclusive with universe).' @@ -118,7 +141,6 @@ export const analyzeSignalInputSchema = z .describe( 'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.' ), - signal: shortsSignalSpecSchema, horizonSessions: z .number() .int() @@ -159,6 +181,19 @@ export const analyzeSignalInputSchema = z .default('raw') .describe('Bar price adjustment mode (default raw).'), }) + .strict(); + +/** + * Strict Zod input schema for the `analyze_signal` MCP tool. + * + * Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and + * `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them + * or any other unknown top-level or nested key. + */ +export const analyzeSignalInputSchema = analyzeSignalSharedFieldsSchema + .extend({ + signal: signalSpecSchema, + }) .strict() .superRefine((data, ctx) => { if (!hasExclusiveListingSelector(data)) { @@ -185,18 +220,62 @@ export const analyzeSignalInputSchema = z message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`, }); } - } else if (data.signal.source === 'shorts' && data.universeMarket === 'FX') { + } else if (data.universeMarket === 'FX') { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['universeMarket'], message: - 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', + data.signal.source === 'shorts' + ? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).' + : 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', }); } }); export type AnalyzeSignalInput = z.infer; +function buildAnalyzeSignalJsonSchema(): JsonSchemaObject { + const sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema); + const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema); + const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema); + const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? { + type: 'boolean' as const, + default: false, + }; + const signalProperty: JsonSchemaProperty = { + type: 'object', + description: signalSpecSchema.description, + properties: { + source: { + type: 'string', + enum: ['shorts', 'fundamentals'], + description: 'Signal data source ("shorts" or "fundamentals").', + }, + field: { + type: 'string', + enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS], + description: 'Signal field name valid for the chosen source.', + }, + allowEstimatedLag: allowEstimatedLagProp, + }, + required: ['source', 'field'], + additionalProperties: false, + anyOf: [shortsBranch, fundamentalsBranch], + }; + + return { + type: 'object', + properties: { + ...sharedSchema.properties, + signal: signalProperty, + }, + required: [...(sharedSchema.required ?? []), 'signal'], + additionalProperties: false, + }; +} + +const ANALYZE_SIGNAL_JSON_SCHEMA: JsonSchemaObject = buildAnalyzeSignalJsonSchema(); + /** Server-side injected configuration for {@link createAnalyzeSignalTool}. */ export interface AnalyzeSignalToolOptions { readonly store: MarketDataStore; @@ -250,10 +329,7 @@ interface AnalyzeSignalResultBase { readonly scope: 'vault_fenced'; readonly vaultCutoffTs: number; readonly vaultCutoffDate: string; - readonly signal: { - readonly source: 'shorts'; - readonly field: ShortsSignalField; - }; + readonly signal: AnalyzeSignalInput['signal']; readonly horizonSessions: number; readonly adjustment: 'raw' | 'split' | 'total'; readonly universeMarket: UniverseMarket; @@ -463,6 +539,127 @@ function filterEligibleShortsTable( }; } +function deriveMonthlySnapshotDates(bars: readonly BarRecord[]): string[] { + const latestByMonth = new Map(); + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i]; + if ( + typeof bar !== 'object' || + bar === null || + typeof bar.ts !== 'number' || + !Number.isFinite(bar.ts) + ) { + continue; + } + const sessionDate = utcDateOf(bar.ts); + const monthKey = sessionDate.slice(0, 7); + const prev = latestByMonth.get(monthKey); + if (prev === undefined || sessionDate > prev) { + latestByMonth.set(monthKey, sessionDate); + } + } + return [...latestByMonth.values()].sort(); +} + +function resolveSnapshotAsOf( + snapshotDate: string, + fencedAsOfMs: number, + canonicalAsOf: string +): { readonly asOf: string; readonly asOfMs: number } { + const snapshotDayEndMs = Date.parse(`${snapshotDate}T23:59:59.999Z`); + if (fencedAsOfMs <= snapshotDayEndMs) { + return { + asOf: canonicalAsOf, + asOfMs: fencedAsOfMs, + }; + } + return { + asOf: formatUtcIsoWithMicros(snapshotDayEndMs, 999), + asOfMs: snapshotDayEndMs, + }; +} + +function appendEligibleFundamentalsObservations(params: { + readonly table: Table; + readonly field: FundamentalsPitValueField; + readonly listingIdSet: ReadonlySet; + readonly snapshotAsOfMs: number; + readonly fencedAsOfMs: number; + readonly vaultCutoffTs: number; + readonly seenKeys: Set; + readonly out: SignalObservation[]; +}): void { + const { + table, + field, + listingIdSet, + snapshotAsOfMs, + fencedAsOfMs, + vaultCutoffTs, + seenKeys, + out, + } = params; + + if ( + typeof table !== 'object' || + table === null || + !Array.isArray(table.columns) || + !Array.isArray(table.rows) + ) { + throw new SignalPanelError( + 'invalid_input', + 'Expected a fundamentals Table object with array columns and rows.' + ); + } + + for (let i = 0; i < table.rows.length; i += 1) { + const row = table.rows[i]; + if (typeof row !== 'object' || row === null) { + continue; + } + + const listingId = row.listing_id; + if ( + typeof listingId !== 'number' || + !Number.isSafeInteger(listingId) || + !listingIdSet.has(listingId) + ) { + continue; + } + + const knownAt = row.effective_known_at; + if ( + typeof knownAt !== 'number' || + !Number.isFinite(knownAt) || + !Number.isSafeInteger(knownAt) + ) { + continue; + } + if (knownAt > snapshotAsOfMs || knownAt > fencedAsOfMs || knownAt >= vaultCutoffTs) { + continue; + } + + const rawValue = row[field]; + if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { + continue; + } + + const normalizedListingId = listingId === 0 ? 0 : listingId; + const normalizedKnownAt = knownAt === 0 ? 0 : knownAt; + const normalizedValue = rawValue === 0 ? 0 : rawValue; + const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; + if (seenKeys.has(dedupeKey)) { + continue; + } + seenKeys.add(dedupeKey); + out.push({ + listingId: normalizedListingId, + knownAt: normalizedKnownAt, + value: normalizedValue, + }); + } +} + function buildCanonicalStudyExpression(params: { readonly input: AnalyzeSignalInput; readonly listingIds: readonly number[]; @@ -479,6 +676,9 @@ function buildCanonicalStudyExpression(params: { version: 1, signalSource: input.signal.source, signalField: input.signal.field, + ...(input.signal.source === 'fundamentals' + ? { allowEstimatedLag: input.signal.allowEstimatedLag } + : {}), horizonSessions: input.horizonSessions, maxSignalAgeSessions: input.maxSignalAgeSessions ?? null, adjustment: input.adjustment, @@ -553,10 +753,11 @@ function validateFactoryOptions(options: AnalyzeSignalToolOptions): number { options.store === null || typeof options.store.bars !== 'function' || typeof options.store.shortsAsOf !== 'function' || + typeof options.store.fundamentalsAsOf !== 'function' || typeof options.store.universe !== 'function' ) { throw new MarketDataStoreValidationError( - 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, and `universe`.', + 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.', 'store' ); } @@ -602,8 +803,9 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT return defineMcpTool({ name: 'analyze_signal', description: - 'Run a Vault-fenced cross-sectional short-interest signal study and record eligible trials to trial_ledger.', + 'Run a Vault-fenced cross-sectional short-interest or point-in-time fundamentals signal study and record eligible trials to trial_ledger.', inputSchema: analyzeSignalInputSchema, + jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA, async handler(input: AnalyzeSignalInput): Promise { try { const fenced = fenceVaultQueryBounds( @@ -633,14 +835,23 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT listingIds = sortAndDedupeListingIds(input.listingIds ?? []); } + const signalEcho: AnalyzeSignalInput['signal'] = + input.signal.source === 'shorts' + ? { + source: 'shorts', + field: input.signal.field, + } + : { + source: 'fundamentals', + field: input.signal.field, + allowEstimatedLag: input.signal.allowEstimatedLag, + }; + const basePayloadFields = { scope: 'vault_fenced' as const, vaultCutoffTs, vaultCutoffDate: fenced.vaultCutoffDate, - signal: { - source: input.signal.source, - field: input.signal.field, - }, + signal: signalEcho, horizonSessions: input.horizonSessions, adjustment: input.adjustment, universeMarket: input.universeMarket, @@ -684,13 +895,6 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT }) ); - const rawShortsTable = await store.shortsAsOf({ - listingIds, - from: fenced.canonicalFrom, - to: fenced.canonicalTo, - asOf: fenced.canonicalAsOf, - }); - const listingIdSet = new Set(listingIds); const eligibleBars = filterEligibleBars( rawBars, @@ -702,17 +906,65 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT fenced.vaultCutoffDate ); - const eligibleShortsTable = filterEligibleShortsTable( - rawShortsTable, - listingIdSet, - utcDateOf(fenced.fromMs), - utcDateOf(fenced.toMs), - fenced.asOfMs, - vaultCutoffTs, - fenced.vaultCutoffDate - ); + let signals: SignalObservation[]; + if (input.signal.source === 'shorts') { + const rawShortsTable = await store.shortsAsOf({ + listingIds, + from: fenced.canonicalFrom, + to: fenced.canonicalTo, + asOf: fenced.canonicalAsOf, + }); + const eligibleShortsTable = filterEligibleShortsTable( + rawShortsTable, + listingIdSet, + utcDateOf(fenced.fromMs), + utcDateOf(fenced.toMs), + fenced.asOfMs, + vaultCutoffTs, + fenced.vaultCutoffDate + ); + signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); + } else { + const snapshotDates = deriveMonthlySnapshotDates(eligibleBars); + if (snapshotDates.length > ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS) { + return { + content: [ + { + type: 'text', + text: `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.`, + }, + ], + isError: true, + }; + } + + signals = []; + const seenKeys = new Set(); + for (const snapshotDate of snapshotDates) { + const snapshot = resolveSnapshotAsOf( + snapshotDate, + fenced.asOfMs, + fenced.canonicalAsOf + ); + const rawTable = await store.fundamentalsAsOf({ + listingIds, + fields: [input.signal.field], + asOf: snapshot.asOf, + allowEstimatedLag: input.signal.allowEstimatedLag, + }); + appendEligibleFundamentalsObservations({ + table: rawTable, + field: input.signal.field, + listingIdSet, + snapshotAsOfMs: snapshot.asOfMs, + fencedAsOfMs: fenced.asOfMs, + vaultCutoffTs, + seenKeys, + out: signals, + }); + } + } - const signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); const built = buildForwardReturnPanel({ bars: eligibleBars, signals, diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index e7840a38..40c52efd 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -10,11 +10,14 @@ import { } from '../src/market-data-store'; import { type BarsQuery, + FUNDAMENTALS_PIT_VALUE_FIELDS, + type FundamentalsAsOfQuery, MarketDataStoreNotImplementedError, type ShortsAsOfQuery, type UniverseQuery, } from '../src/market-data-store-duckdb'; import { + ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS, ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS, ANALYZE_SIGNAL_MAX_LISTING_IDS, ANALYZE_SIGNAL_MAX_SERIES_POINTS, @@ -23,9 +26,13 @@ import { createMcpServer, createQueryDataTool, } from '../src/mcp/index'; -import { buildForwardReturnPanel, shortsTableToSignalRows } from '../src/signal-panel'; +import { + type SignalObservation, + buildForwardReturnPanel, + shortsTableToSignalRows, +} from '../src/signal-panel'; import { analyzeSignal } from '../src/signal-study'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; +import { type TrialLedgerExecutor, canonicalExpressionHash } from '../src/trial-ledger'; const SEED = 20261129; const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; @@ -280,6 +287,7 @@ function buildCeoShortsFixture(options?: { interface FakeStoreState { readonly barsCalls: BarsQuery[]; readonly shortsCalls: ShortsAsOfQuery[]; + readonly fundamentalsCalls: FundamentalsAsOfQuery[]; readonly universeCalls: UniverseQuery[]; readonly store: MarketDataStore; } @@ -287,15 +295,18 @@ interface FakeStoreState { function createFakeStore(options?: { bars?: readonly BarRecord[]; shortsTable?: Table; + fundamentalsResolver?: (q: FundamentalsAsOfQuery) => Table | Promise
; universeIds?: readonly number[]; universeResolver?: (q: UniverseQuery) => number[]; leaky?: boolean; barsError?: Error; shortsError?: Error; + fundamentalsError?: Error; universeError?: Error; }): FakeStoreState { const barsCalls: BarsQuery[] = []; const shortsCalls: ShortsAsOfQuery[] = []; + const fundamentalsCalls: FundamentalsAsOfQuery[] = []; const universeCalls: UniverseQuery[] = []; const allBars = options?.bars ?? []; @@ -394,7 +405,14 @@ function createFakeStore(options?: { crossSection() { throw new MarketDataStoreNotImplementedError('crossSection'); }, - fundamentalsAsOf() { + async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ + fundamentalsCalls.push(q); + if (options?.fundamentalsError !== undefined) { + throw options.fundamentalsError; + } + if (options?.fundamentalsResolver !== undefined) { + return options.fundamentalsResolver(q); + } throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); }, events() { @@ -408,7 +426,7 @@ function createFakeStore(options?: { }, }; - return { barsCalls, shortsCalls, universeCalls, store }; + return { barsCalls, shortsCalls, fundamentalsCalls, universeCalls, store }; } async function callAnalyzeSignal(params: { @@ -1593,3 +1611,1058 @@ describe('MCP analyze_signal tool', () => { expect(dsrFailLedger.rows).toHaveLength(1); }); }); + +interface FundamentalsPitFixtureRow { + readonly listing_id: number; + readonly effective_known_at: number; + readonly known_at_source: string; + readonly has_estimated_lag: boolean; + readonly period_end: string; + readonly fiscal_period: string; + readonly currency: string; + readonly period_known_at: number; + readonly revenue: number | null; + readonly net_income: number | null; + readonly operating_cash_flow: number | null; + readonly total_assets: number | null; + readonly total_equity: number | null; + readonly shares_outstanding: number | null; + readonly ttm_revenue: number | null; + readonly ttm_net_income: number | null; + readonly ttm_operating_cash_flow: number | null; + readonly ttm_period_end: string | null; + readonly ttm_currency: string | null; + readonly ttm_has_estimated_lag: boolean; +} + +const FUNDAMENTALS_TTM_FIELDS = new Set([ + 'ttm_revenue', + 'ttm_net_income', + 'ttm_operating_cash_flow', +]); + +function queryFundamentalsFixtureRows( + rows: readonly FundamentalsPitFixtureRow[], + q: FundamentalsAsOfQuery +): Table { + const idSet = new Set(q.listingIds); + const asOfMs = Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf); + const allowEstimatedLag = q.allowEstimatedLag ?? false; + + const latestByListing = new Map(); + for (const row of rows) { + if (!idSet.has(row.listing_id) || row.effective_known_at > asOfMs) { + continue; + } + const prev = latestByListing.get(row.listing_id); + if (prev === undefined || row.effective_known_at > prev.effective_known_at) { + latestByListing.set(row.listing_id, row); + } + } + + const hasTtm = q.fields.some(f => FUNDAMENTALS_TTM_FIELDS.has(f)); + const columns: string[] = [ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + ...q.fields, + ...(hasTtm ? ['ttm_period_end', 'ttm_currency', 'ttm_has_estimated_lag'] : []), + ]; + + const outRows: TableRow[] = []; + const sortedIds = [...latestByListing.keys()].sort((a, b) => a - b); + for (const lid of sortedIds) { + const selected = latestByListing.get(lid)!; + if (!allowEstimatedLag && selected.has_estimated_lag) { + continue; + } + const projected: Record = { + listing_id: selected.listing_id, + effective_known_at: selected.effective_known_at, + known_at_source: selected.known_at_source, + has_estimated_lag: selected.has_estimated_lag, + period_end: selected.period_end, + fiscal_period: selected.fiscal_period, + currency: selected.currency, + period_known_at: selected.period_known_at, + }; + for (const field of q.fields) { + const val = selected[field as keyof FundamentalsPitFixtureRow] as number | null; + if (FUNDAMENTALS_TTM_FIELDS.has(field)) { + projected[field] = allowEstimatedLag || !selected.ttm_has_estimated_lag ? val : null; + } else { + projected[field] = val; + } + } + if (hasTtm) { + projected.ttm_period_end = + allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_period_end : null; + projected.ttm_currency = + allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_currency : null; + projected.ttm_has_estimated_lag = selected.ttm_has_estimated_lag; + } + outRows.push(projected); + } + + return { columns, rows: outRows }; +} + +function makeFundamentalsRow(params: { + listingId: number; + effectiveKnownAt: number; + periodEnd: string; + fiscalPeriod: string; + revenue: number; + ttmRevenue: number; + hasEstimatedLag?: boolean; + ttmHasEstimatedLag?: boolean; +}): FundamentalsPitFixtureRow { + const hasEstimatedLag = params.hasEstimatedLag ?? false; + const ttmHasEstimatedLag = params.ttmHasEstimatedLag ?? false; + return { + listing_id: params.listingId, + effective_known_at: params.effectiveKnownAt, + known_at_source: hasEstimatedLag ? 'estimated_lag' : 'sec_edgar_filing', + has_estimated_lag: hasEstimatedLag, + period_end: params.periodEnd, + fiscal_period: params.fiscalPeriod, + currency: 'USD', + period_known_at: params.effectiveKnownAt, + revenue: params.revenue, + net_income: Number((params.revenue * 0.15).toFixed(2)), + operating_cash_flow: Number((params.revenue * 0.2).toFixed(2)), + total_assets: Number((params.revenue * 4.0).toFixed(2)), + total_equity: Number((params.revenue * 1.8).toFixed(2)), + shares_outstanding: 10_000_000, + ttm_revenue: params.ttmRevenue, + ttm_net_income: Number((params.ttmRevenue * 0.15).toFixed(2)), + ttm_operating_cash_flow: Number((params.ttmRevenue * 0.2).toFixed(2)), + ttm_period_end: params.periodEnd, + ttm_currency: 'USD', + ttm_has_estimated_lag: ttmHasEstimatedLag, + }; +} + +// Seeded fundamentals study fixture metadata (pinned for reproducibility): +// - Dataset ID: `synthetic:mcp-analyze-signal-fundamentals:seed-20261202:v1` +// - Tool version: `mcp:analyze_signal:v1` +// - Seed: `20261202` (Mulberry32 PRNG) +// - Universe: 12 synthetic US equity listings (`70001..70012`, USD, 21:00 UTC close) +// - Pre-Vault window: 2023-01-02..2023-06-30 (130 business sessions), Vault cutoff: 2023-07-03T00:00:00.000Z +// - Adjustment: `raw`, horizon: `5` sessions, modeled execution/transaction costs: `0` +// - Ownership: Quant research owns evidence; Director owns adoption. +const FUNDAMENTALS_FIXTURE_SEED = 20261202; + +function buildFundamentalsStudyFixture(): { + readonly listingIds: number[]; + readonly allDates: string[]; + readonly preCutoffSessions: number; + readonly vaultCutoffDate: string; + readonly vaultCutoffTs: number; + readonly bars: BarRecord[]; + readonly fundamentalsRows: FundamentalsPitFixtureRow[]; +} { + const rand = createSeededRng(FUNDAMENTALS_FIXTURE_SEED); + const listingCount = 12; + const preCutoffSessions = 130; + const postCutoffSessions = 10; + const allDates = makeBusinessDates('2023-01-02', preCutoffSessions + postCutoffSessions); + const vaultCutoffDate = allDates[preCutoffSessions]!; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + const listingIds = Array.from({ length: listingCount }, (_, i) => 70_001 + i); + + const fundamentalsRows: FundamentalsPitFixtureRow[] = []; + // Monthly PIT releases across 6 pre-cutoff months + 1 post-cutoff release + const releaseDates = [ + { date: '2023-01-10', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' }, + { date: '2023-02-15', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' }, + { date: '2023-04-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' }, + { date: '2023-05-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' }, + { date: vaultCutoffDate, periodEnd: '2023-06-30', fiscalPeriod: 'Q2' }, + ]; + + const activeScore = new Float64Array(listingCount); + for (let rIdx = 0; rIdx < releaseDates.length; rIdx += 1) { + const rel = releaseDates[rIdx]!; + const knownAt = makeUtcMs(rel.date, 13); // 08:00 ET pre-close + for (let l = 0; l < listingCount; l += 1) { + const rev = 100 + l * 25 + rIdx * 10 + Math.round((rand() * 2 - 1) * 40); + const ttm = rev * 4 + (l % 3) * 15; + fundamentalsRows.push( + makeFundamentalsRow({ + listingId: listingIds[l]!, + effectiveKnownAt: knownAt, + periodEnd: rel.periodEnd, + fiscalPeriod: rel.fiscalPeriod, + revenue: rev, + ttmRevenue: ttm, + }) + ); + } + } + + const prices = new Float64Array(listingCount); + for (let l = 0; l < listingCount; l += 1) { + prices[l] = 20 + l * 3; + } + + const bars: BarRecord[] = []; + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingCount; l += 1) { + activeScore[l] = (l - listingCount / 2) / listingCount; + const dailyRet = 0.002 * activeScore[l]! + (rand() * 2 - 1) * 0.01; + prices[l] = Math.max(1.0, prices[l]! * (1 + dailyRet)); + const close = Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 80_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + return { + listingIds, + allDates, + preCutoffSessions, + vaultCutoffDate, + vaultCutoffTs, + bars, + fundamentalsRows, + }; +} + +describe('MCP analyze_signal tool — fundamentals source', () => { + test('tools/list advertises strict signal discriminated branches and rejects invalid fundamentals inputs with zero store/ledger calls', async () => { + const cutoffTs = makeUtcMs('2025-03-31', 0); + const fakeStore = createFakeStore(); + const fakeLedger = createFakeTrialLedger(); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createAnalyzeSignalTool({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultContext: { vaultCutoffTs: cutoffTs }, + principalId: AGENT_PRINCIPAL, + }), + ], + }); + + const listRaw = await server.handleMessage( + JSON.stringify({ jsonrpc: '2.0', id: 'list-fund', method: 'tools/list' }) + ); + const listParsed = JSON.parse(listRaw as string) as { + result: { + tools: { + name: string; + description: string; + inputSchema: { + properties: { + signal: { + type: string; + additionalProperties: boolean; + properties: Record; + anyOf: { + additionalProperties: boolean; + properties: Record; + }[]; + }; + }; + }; + }[]; + }; + }; + + const tool = listParsed.result.tools[0]!; + expect(tool.description).toContain('fundamentals'); + expect(tool.description).toContain('short-interest'); + + const signalSchema = tool.inputSchema.properties.signal; + expect(signalSchema.type).toBe('object'); + expect(signalSchema.additionalProperties).toBe(false); + expect(Object.keys(signalSchema.properties).sort()).toEqual([ + 'allowEstimatedLag', + 'field', + 'source', + ]); + expect(signalSchema.anyOf).toHaveLength(2); + expect(signalSchema.anyOf[0]?.additionalProperties).toBe(false); + expect(signalSchema.anyOf[0]?.properties.source?.const).toBe('shorts'); + expect(signalSchema.anyOf[1]?.additionalProperties).toBe(false); + expect(signalSchema.anyOf[1]?.properties.source?.const).toBe('fundamentals'); + expect(signalSchema.anyOf[1]?.properties.field?.enum).toEqual([...FUNDAMENTALS_PIT_VALUE_FIELDS]); + expect(signalSchema.anyOf[1]?.properties.allowEstimatedLag?.default).toBe(false); + + const validBase = { + listingIds: [70_001, 70_002], + from: '2023-01-02', + to: '2023-06-30', + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const invalidCases: readonly [string, Record][] = [ + ['unknown fundamentals field', { ...validBase, signal: { source: 'fundamentals', field: 'ebitda_fake' } }], + ['shorts field on fundamentals source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }], + ['fundamentals field on shorts source', { ...validBase, signal: { source: 'shorts', field: 'ttm_revenue' } }], + ['unknown signal.source', { ...validBase, signal: { source: 'macro', field: 'ttm_revenue' } }], + [ + 'unknown nested key in fundamentals signal', + { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', extraKey: true } }, + ], + [ + 'allowEstimatedLag on shorts source', + { ...validBase, signal: { source: 'shorts', field: 'net_change', allowEstimatedLag: false } }, + ], + [ + 'non-boolean allowEstimatedLag string', + { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 'true' } }, + ], + [ + 'non-boolean allowEstimatedLag number', + { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 1 } }, + ], + ['fundamentals study with FX universeMarket', { ...validBase, universeMarket: 'FX' }], + ]; + + for (const [_label, args] of invalidCases) { + const store = createFakeStore(); + const ledger = createFakeTrialLedger(); + const res = await callAnalyzeSignal({ + store: store.store, + ledger: ledger.executor, + vaultCutoffTs: cutoffTs, + args, + }); + expect(res.isError).toBe(true); + expect(res.text).toContain('Invalid arguments for tool "analyze_signal":'); + expect(store.barsCalls).toHaveLength(0); + expect(store.shortsCalls).toHaveLength(0); + expect(store.fundamentalsCalls).toHaveLength(0); + expect(store.universeCalls).toHaveLength(0); + expect(ledger.insertCalls).toBe(0); + } + }); + + test('executes fundamentals study, records canonical fundamentals expressionHash, forwards allowEstimatedLag verbatim, and preserves identity on append-only retry', async () => { + const fixture = buildFundamentalsStudyFixture(); + const from = fixture.allDates[0]!; + const to = fixture.allDates[fixture.preCutoffSessions - 1]!; + + const store = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const sharedLedger = createFakeTrialLedger(); + + const baseArgs = { + listingIds: fixture.listingIds, + from, + to, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + campaignId: CAMPAIGN_UUID, + hypothesisId: HYPOTHESIS_UUID, + }; + + const res1 = await callAnalyzeSignal({ + store: store.store, + ledger: sharedLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + principalId: AGENT_PRINCIPAL, + args: baseArgs, + }); + expect(res1.isError).toBe(false); + const payload1 = JSON.parse(res1.text) as AnalyzeSignalResultPayload; + expect(payload1.status).toBe('ok'); + if (payload1.status !== 'ok') { + return; + } + + expect(payload1.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: false, + }); + expect(sharedLedger.rows).toHaveLength(1); + expect(sharedLedger.rows[0]?.stage).toBe('signal_ic'); + expect(sharedLedger.rows[0]?.principal_id).toBe(AGENT_PRINCIPAL); + + // Verify canonical expression prefix `mcp:analyze_signal:v1:fundamentals:` via canonicalExpressionHash + const expectedHash = canonicalExpressionHash({ + expression: 'mcp:analyze_signal:v1:fundamentals:ttm_revenue', + params: { + version: 1, + signalSource: 'fundamentals', + signalField: 'ttm_revenue', + allowEstimatedLag: false, + horizonSessions: 5, + maxSignalAgeSessions: null, + adjustment: 'raw', + ledgerSeries: 'rank_ic', + effectiveFrom: payload1.effectiveFrom, + effectiveTo: payload1.effectiveTo, + effectiveAsOf: payload1.effectiveAsOf, + }, + universe: { + kind: 'listingIds', + listingIds: fixture.listingIds, + }, + horizon: '5d', + sampleStart: payload1.trial.sampleStart, + sampleEnd: payload1.trial.sampleEnd, + }); + expect(payload1.trial.expressionHash).toBe(expectedHash); + expect(sharedLedger.rows[0]?.expression_hash).toBe(expectedHash); + + // Default allowEstimatedLag === false forwarded verbatim to every fundamentalsAsOf call + expect(store.fundamentalsCalls.length).toBeGreaterThan(0); + expect(store.shortsCalls).toHaveLength(0); + for (const call of store.fundamentalsCalls) { + expect(call.fields).toEqual(['ttm_revenue']); + expect(call.allowEstimatedLag).toBe(false); + } + + // Re-running identical request against the SAME ledger appends under append-only rules with one distinct expression_hash + const res2 = await callAnalyzeSignal({ + store: store.store, + ledger: sharedLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + principalId: AGENT_PRINCIPAL, + args: baseArgs, + }); + expect(res2.isError).toBe(false); + const payload2 = JSON.parse(res2.text) as AnalyzeSignalResultPayload; + expect(payload2.status).toBe('ok'); + if (payload2.status !== 'ok') { + return; + } + expect(payload2.trial.expressionHash).toBe(payload1.trial.expressionHash); + expect(new Set(sharedLedger.rows.map(r => r.expression_hash)).size).toBe(1); + + // Explicit allowEstimatedLag: false and reordered/duplicated listingIds preserve identity + const explicitFalseStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const explicitFalseLedger = createFakeTrialLedger(); + const reorderedIds = [...fixture.listingIds].reverse(); + reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[2]!); + const resExplicitFalse = await callAnalyzeSignal({ + store: explicitFalseStore.store, + ledger: explicitFalseLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + listingIds: reorderedIds, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: false }, + }, + }); + const payloadExplicitFalse = JSON.parse(resExplicitFalse.text) as AnalyzeSignalResultPayload; + expect(payloadExplicitFalse.status).toBe('ok'); + if (payloadExplicitFalse.status === 'ok') { + expect(payloadExplicitFalse.trial.expressionHash).toBe(payload1.trial.expressionHash); + } + expect(explicitFalseStore.fundamentalsCalls.every(c => c.allowEstimatedLag === false)).toBe(true); + + // allowEstimatedLag: true forwards true verbatim and changes expressionHash + const lagTrueStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const lagTrueLedger = createFakeTrialLedger(); + const resLagTrue = await callAnalyzeSignal({ + store: lagTrueStore.store, + ledger: lagTrueLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, + }, + }); + const payloadLagTrue = JSON.parse(resLagTrue.text) as AnalyzeSignalResultPayload; + expect(payloadLagTrue.status).toBe('ok'); + if (payloadLagTrue.status === 'ok') { + expect(payloadLagTrue.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: true, + }); + expect(payloadLagTrue.trial.expressionHash).not.toBe(payload1.trial.expressionHash); + } + expect(lagTrueStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); + + // Different field changes expressionHash + const otherFieldStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const otherFieldLedger = createFakeTrialLedger(); + const resOtherField = await callAnalyzeSignal({ + store: otherFieldStore.store, + ledger: otherFieldLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + signal: { source: 'fundamentals', field: 'revenue' }, + }, + }); + const payloadOtherField = JSON.parse(resOtherField.text) as AnalyzeSignalResultPayload; + expect(payloadOtherField.status).toBe('ok'); + if (payloadOtherField.status === 'ok') { + expect(payloadOtherField.trial.expressionHash).not.toBe(payload1.trial.expressionHash); + } + + // Shorts study over the same window/listings produces a distinct expressionHash + const shortsRows: TableRow[] = fixture.listingIds.map((lid, i) => ({ + listing_id: lid, + report_date: from, + known_at: makeUtcMs(from, 12), + shares_short: 100_000 + i * 5_000, + net_change: (i - 5) * 1_000, + pct_float: 0.03 + i * 0.005, + source: 'ceoShorts', + })); + const shortsStore = createFakeStore({ + bars: fixture.bars, + shortsTable: { columns: SHORTS_COLUMNS, rows: shortsRows }, + }); + const shortsLedger = createFakeTrialLedger(); + const resShorts = await callAnalyzeSignal({ + store: shortsStore.store, + ledger: shortsLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + signal: { source: 'shorts', field: 'net_change' }, + }, + }); + const payloadShorts = JSON.parse(resShorts.text) as AnalyzeSignalResultPayload; + expect(payloadShorts.status).toBe('ok'); + if (payloadShorts.status === 'ok') { + expect(payloadShorts.trial.expressionHash).not.toBe(payload1.trial.expressionHash); + } + }); + + test('queries month-end snapshots in ascending order from unsorted bars, preserves earlier explicit asOf, enforces 120-snapshot cap, and handles empty bars', async () => { + // 1. Unsorted bars spanning 3 UTC months (2 full + 1 partial final month) with earlier intraday asOf + const janDates = ['2023-01-10', '2023-01-31']; + const febDates = ['2023-02-14', '2023-02-28']; + const marDates = ['2023-03-08', '2023-03-15']; + const unsortedDates = [...marDates, ...janDates, ...febDates].reverse(); + const bars: BarRecord[] = []; + for (const date of unsortedDates) { + const ts = makeUtcMs(date, 21); + for (const lid of [101, 102]) { + bars.push({ + listingId: lid, + ts, + open: 10, + high: 10, + low: 10, + close: 10, + volume: 100, + vwap: 10, + knownAt: ts, + }); + } + } + + const cutoffTs = makeUtcMs('2023-04-01', 0); + const storeOrder = createFakeStore({ + bars, + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const ledgerOrder = createFakeTrialLedger(); + + // Earlier explicit asOf on 2023-03-15T22:30:00.123456Z (after 21:00 bar close, before day end) + const explicitAsOf = '2023-03-15T22:30:00.123456Z'; + const orderRes = await callAnalyzeSignal({ + store: storeOrder.store, + ledger: ledgerOrder.executor, + vaultCutoffTs: cutoffTs, + args: { + listingIds: [102, 101], + from: '2023-01-01', + to: '2023-03-31', + asOf: explicitAsOf, + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(orderRes.isError).toBe(false); + expect(storeOrder.fundamentalsCalls.map(c => c.asOf)).toEqual([ + '2023-01-31T23:59:59.999999Z', + '2023-02-28T23:59:59.999999Z', + explicitAsOf, + ]); + expect(storeOrder.fundamentalsCalls.every(c => c.listingIds[0] === 101 && c.listingIds[1] === 102)).toBe(true); + + // 2. Empty eligible bar sample -> 0 fundamentalsAsOf calls, insufficient_data, 0 ledger writes + const emptyBarsStore = createFakeStore({ + bars: [], + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const emptyBarsLedger = createFakeTrialLedger(); + const emptyRes = await callAnalyzeSignal({ + store: emptyBarsStore.store, + ledger: emptyBarsLedger.executor, + vaultCutoffTs: cutoffTs, + args: { + listingIds: [101, 102], + from: '2023-01-01', + to: '2023-03-31', + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(emptyRes.isError).toBe(false); + const emptyPayload = JSON.parse(emptyRes.text) as AnalyzeSignalResultPayload; + expect(emptyPayload.status).toBe('insufficient_data'); + if (emptyPayload.status === 'insufficient_data') { + expect(emptyPayload.reason).toBe('too_few_observations'); + } + expect(emptyBarsStore.fundamentalsCalls).toHaveLength(0); + expect(emptyBarsLedger.rows).toHaveLength(0); + + // 3. Exactly 120 eligible UTC months is accepted; 121 is rejected with 0 fundamentals calls and 0 ledger inserts + function makeMonthlyBars(monthCount: number): BarRecord[] { + const out: BarRecord[] = []; + for (let m = 0; m < monthCount; m += 1) { + const year = 2010 + Math.floor(m / 12); + const month = (m % 12) + 1; + const date = `${year}-${String(month).padStart(2, '0')}-15`; + const ts = makeUtcMs(date, 21); + out.push({ + listingId: 101, + ts, + open: 10, + high: 10, + low: 10, + close: 10, + volume: 100, + vwap: 10, + knownAt: ts, + }); + } + return out; + } + + const capCutoffTs = makeUtcMs('2025-01-01', 0); + const exactCapStore = createFakeStore({ + bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS), + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const exactCapLedger = createFakeTrialLedger(); + const exactCapRes = await callAnalyzeSignal({ + store: exactCapStore.store, + ledger: exactCapLedger.executor, + vaultCutoffTs: capCutoffTs, + args: { + listingIds: [101], + from: '2010-01-01', + to: '2024-12-31', + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(exactCapRes.isError).toBe(false); + expect(exactCapStore.fundamentalsCalls).toHaveLength(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS); + + const overCapStore = createFakeStore({ + bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS + 1), + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const overCapLedger = createFakeTrialLedger(); + const overCapRes = await callAnalyzeSignal({ + store: overCapStore.store, + ledger: overCapLedger.executor, + vaultCutoffTs: capCutoffTs, + args: { + listingIds: [101], + from: '2010-01-01', + to: '2024-12-31', + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(overCapRes.isError).toBe(true); + expect(overCapRes.text).toBe( + `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.` + ); + expect(overCapStore.fundamentalsCalls).toHaveLength(0); + expect(overCapLedger.insertCalls).toBe(0); + expect(overCapLedger.rows).toHaveLength(0); + }); + + test('restatement replay prevents look-ahead: dates before Q1 restatement use originally known values and appending a future revision leaves prior output unchanged', async () => { + // Explicit deterministic restatement fixture: + // - 6 listings across 2023-01-02..2023-05-31 (108 sessions), Vault cutoff 2023-06-01T00:00:00Z + // - Original Q1 known 2023-01-12T13:00Z (period_end 2022-12-31) + // - Original Q2 known 2023-02-15T13:00Z (period_end 2023-01-31) + // - Q1 restatement known 2023-04-12T13:00Z (AFTER Q2!): period_end stays 2023-01-31 (Q2), + // while ttm_revenue flips cross-sectional ordering for listings 0..5. + // - Unchanged months (March, May) re-emit identical (listing_id, effective_known_at) -> deduped cleanly. + const listingIds = [80_001, 80_002, 80_003, 80_004, 80_005, 80_006]; + const allDates = makeBusinessDates('2023-01-02', 112); + const preCutoffDates = allDates.filter(d => d < '2023-06-01'); + const vaultCutoffDate = '2023-06-01'; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const q1KnownAt = makeUtcMs('2023-01-12', 13); + const q2KnownAt = makeUtcMs('2023-02-15', 13); + const q1RestatedKnownAt = makeUtcMs('2023-04-12', 13); + const futureRevisionKnownAt = makeUtcMs('2023-06-15', 13); // post-cutoff + + const rand = createSeededRng(20261203); + const bars: BarRecord[] = []; + const prices = new Float64Array(listingIds.length).fill(50); + for (let t = 0; t < preCutoffDates.length; t += 1) { + const date = preCutoffDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingIds.length; l += 1) { + const ret = (l - 2.5) * 0.0015 + (rand() * 2 - 1) * 0.008; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 25_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + const basePitRows: FundamentalsPitFixtureRow[] = []; + const expectedDirectObs: SignalObservation[] = []; + + for (let l = 0; l < listingIds.length; l += 1) { + const lid = listingIds[l]!; + const q1Val = 100 + l * 20; + const q2Val = 120 + l * 25; + // Restatement reverses cross-sectional rank ordering after 2023-04-12 + const restatedVal = 300 - l * 30; + + basePitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: q1KnownAt, + periodEnd: '2022-12-31', + fiscalPeriod: 'Q1', + revenue: q1Val / 4, + ttmRevenue: q1Val, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: q2KnownAt, + periodEnd: '2023-01-31', + fiscalPeriod: 'Q2', + revenue: q2Val / 4, + ttmRevenue: q2Val, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: q1RestatedKnownAt, + periodEnd: '2023-01-31', + fiscalPeriod: 'Q2', + revenue: q2Val / 4, + ttmRevenue: restatedVal, + }) + ); + + expectedDirectObs.push( + { listingId: lid, knownAt: q1KnownAt, value: q1Val }, + { listingId: lid, knownAt: q2KnownAt, value: q2Val }, + { listingId: lid, knownAt: q1RestatedKnownAt, value: restatedVal } + ); + } + + // 1. Direct baseline using independently specified eligible observations + const directLedger = createFakeTrialLedger(); + const directBuilt = buildForwardReturnPanel({ + bars, + signals: expectedDirectObs, + horizonSessions: 5, + vaultCutoffDate, + }); + const directStudy = await analyzeSignal(directLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_restatement_baseline', + params: { field: 'ttm_revenue', horizonSessions: 5 }, + universe: listingIds, + horizon: '5d', + }, + panel: directBuilt.panel, + vaultCutoffDate, + }); + expect(directStudy.status).toBe('ok'); + if (directStudy.status !== 'ok') { + return; + } + + // 2. MCP handler run on base rows (before future revision is appended) + const args = { + listingIds, + from: preCutoffDates[0]!, + to: preCutoffDates[preCutoffDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const mcpStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(basePitRows, q), + }); + const mcpLedger = createFakeTrialLedger(); + const mcpRes = await callAnalyzeSignal({ + store: mcpStore.store, + ledger: mcpLedger.executor, + vaultCutoffTs, + args, + }); + expect(mcpRes.isError).toBe(false); + const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; + expect(mcpPayload.status).toBe('ok'); + if (mcpPayload.status !== 'ok') { + return; + } + + // Exact parity between MCP handler and direct baseline (dates, rankIc, ledger daily_series) + expect(mcpPayload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); + expect(mcpPayload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); + expect(mcpLedger.rows[0]?.daily_series).toEqual(directLedger.rows[0]?.daily_series); + expect(mcpPayload.trial.sampleStart).toBe(directStudy.trial.sampleStart); + expect(mcpPayload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd); + // Forward return endpoint remains strictly before vaultCutoffDate + const sampleEndIdx = preCutoffDates.indexOf(mcpPayload.trial.sampleEnd); + expect(sampleEndIdx).toBeGreaterThanOrEqual(0); + expect(sampleEndIdx + 5).toBeLessThan(preCutoffDates.length); + expect(preCutoffDates[sampleEndIdx + 5]! < vaultCutoffDate).toBe(true); + + // Confirm pre-restatement dates (between 2023-02-15 and 2023-04-11) actually differ from a look-ahead study + // that wrongly substitutes the restated values onto Q2's earlier known_at! + const lookAheadObs = expectedDirectObs.map(o => + o.knownAt === q2KnownAt + ? { ...o, value: 300 - (o.listingId - 80_001) * 30 } + : o + ); + const lookAheadBuilt = buildForwardReturnPanel({ + bars, + signals: lookAheadObs, + horizonSessions: 5, + vaultCutoffDate, + }); + const lookAheadLedger = createFakeTrialLedger(); + const lookAheadStudy = await analyzeSignal(lookAheadLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'look_ahead_counterfactual', + params: { field: 'ttm_revenue', horizonSessions: 5 }, + universe: listingIds, + horizon: '5d', + }, + panel: lookAheadBuilt.panel, + vaultCutoffDate, + }); + expect(lookAheadStudy.status).toBe('ok'); + expect(mcpLedger.rows[0]?.daily_series).not.toEqual(lookAheadLedger.rows[0]?.daily_series); + + // 3. Append a future revision (post-cutoff) and verify all prior dated outputs & ledger rows remain bit-identical + const rowsWithFutureRevision: FundamentalsPitFixtureRow[] = [ + ...basePitRows, + ...listingIds.map((lid, l) => + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: futureRevisionKnownAt, + periodEnd: '2023-01-31', + fiscalPeriod: 'Q2', + revenue: 999, + ttmRevenue: 9_999 + l, + }) + ), + ]; + const futureStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(rowsWithFutureRevision, q), + }); + const futureLedger = createFakeTrialLedger(); + const futureRes = await callAnalyzeSignal({ + store: futureStore.store, + ledger: futureLedger.executor, + vaultCutoffTs, + args, + }); + expect(futureRes.isError).toBe(false); + expect(futureRes.text).toBe(mcpRes.text); + expect(futureLedger.rows).toEqual(mcpLedger.rows); + }); + + test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { + const fixture = buildFundamentalsStudyFixture(); + const from = fixture.allDates[0]!; + const postCutoffDate = fixture.allDates[fixture.allDates.length - 1]!; + + const cleanStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const leakyStore = createFakeStore({ + bars: fixture.bars, + leaky: true, + fundamentalsResolver: q => { + const cleanTable = queryFundamentalsFixtureRows(fixture.fundamentalsRows, q); + const snapAsOfMs = Date.parse(q.asOf); + const poisonedRows: TableRow[] = [ + // 1. effective_known_at strictly after individual snapshot asOf (but before vaultCutoffTs) + { + listing_id: fixture.listingIds[0]!, + effective_known_at: snapAsOfMs + 60_000, + ttm_revenue: 999_999, + }, + // 2. effective_known_at at exact vaultCutoffTs + { + listing_id: fixture.listingIds[1]!, + effective_known_at: fixture.vaultCutoffTs, + ttm_revenue: 888_888, + }, + // 3. effective_known_at after vaultCutoffTs + { + listing_id: fixture.listingIds[2]!, + effective_known_at: fixture.vaultCutoffTs + 86_400_000, + ttm_revenue: 777_777, + }, + // 4. unrequested listing_id + { + listing_id: 999_999, + effective_known_at: makeUtcMs(from, 12), + ttm_revenue: 666_666, + }, + // 5. non-safe-integer effective_known_at (float & NaN) + { + listing_id: fixture.listingIds[3]!, + effective_known_at: makeUtcMs(from, 12) + 0.5, + ttm_revenue: 555_555, + }, + { + listing_id: fixture.listingIds[3]!, + effective_known_at: Number.NaN, + ttm_revenue: 555_555, + }, + // 6. null, NaN, and Infinity field values + { + listing_id: fixture.listingIds[4]!, + effective_known_at: makeUtcMs(from, 12), + ttm_revenue: null, + }, + { + listing_id: fixture.listingIds[4]!, + effective_known_at: makeUtcMs(from, 12) + 1_000, + ttm_revenue: Number.NaN, + }, + { + listing_id: fixture.listingIds[4]!, + effective_known_at: makeUtcMs(from, 12) + 2_000, + ttm_revenue: Number.POSITIVE_INFINITY, + }, + ]; + return { + columns: cleanTable.columns, + rows: [...cleanTable.rows, ...poisonedRows], + }; + }, + }); + + const cleanLedger = createFakeTrialLedger(); + const leakyLedger = createFakeTrialLedger(); + const args = { + listingIds: fixture.listingIds, + from, + to: postCutoffDate, + asOf: postCutoffDate, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const cleanRes = await callAnalyzeSignal({ + store: cleanStore.store, + ledger: cleanLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args, + }); + const leakyRes = await callAnalyzeSignal({ + store: leakyStore.store, + ledger: leakyLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args, + }); + + expect(cleanRes.isError).toBe(false); + expect(leakyRes.isError).toBe(false); + expect(leakyRes.text).toBe(cleanRes.text); + expect(leakyLedger.rows).toEqual(cleanLedger.rows); + + // Every fundamentalsAsOf call's asOf is strictly before vaultCutoffTs + expect(cleanStore.fundamentalsCalls.length).toBeGreaterThan(0); + for (const call of [...cleanStore.fundamentalsCalls, ...leakyStore.fundamentalsCalls]) { + expect(Date.parse(call.asOf)).toBeLessThan(fixture.vaultCutoffTs); + } + + // Malformed fundamentals table -> sanitized SignalPanelError with zero ledger writes + const badTableStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: () => ({ columns: null, rows: null } as unknown as Table), + }); + const badTableLedger = createFakeTrialLedger(); + const badTableRes = await callAnalyzeSignal({ + store: badTableStore.store, + ledger: badTableLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args, + }); + expect(badTableRes.isError).toBe(true); + expect(badTableRes.text).toBe('SignalPanelError: Invalid signal panel input.'); + expect(badTableLedger.rows).toHaveLength(0); + }); +}); diff --git a/libs/research/test/mcp-copilot-server.test.ts b/libs/research/test/mcp-copilot-server.test.ts index 2bc4ab24..8bd18a11 100644 --- a/libs/research/test/mcp-copilot-server.test.ts +++ b/libs/research/test/mcp-copilot-server.test.ts @@ -217,6 +217,7 @@ interface CopilotStudyFixture { readonly postCutoffDate: string; readonly bars: readonly BarRecord[]; readonly shortsTable: Table; + readonly fundamentalsRows: readonly TableRow[]; readonly eventsTable: Table; readonly symbols: readonly SymbolSearchRow[]; readonly exchangeCalendars: EventStudyExchangeCalendars; @@ -238,8 +239,42 @@ function buildCopilotStudyFixture(): CopilotStudyFixture { const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); const bars: BarRecord[] = []; const shortsRows: TableRow[] = []; + const fundamentalsRows: TableRow[] = []; const eventRows: TableRow[] = []; + const fundamentalReleaseIndices = [0, 22, 44, 64]; + for (let rIdx = 0; rIdx < fundamentalReleaseIndices.length; rIdx += 1) { + const t = fundamentalReleaseIndices[rIdx]!; + const relDate = allDates[t]!; + const effectiveKnownAt = makeUtcMs(relDate, 13); // 08:00 ET pre-close + for (let l = 0; l < listingCount; l += 1) { + const revenue = 250 + ((l * 7 + rIdx * 5) % listingCount) * 40 + rIdx * 15; + const ttmRevenue = revenue * 4 + ((l + rIdx) % 4) * 25; + fundamentalsRows.push({ + listing_id: listingIds[l]!, + effective_known_at: effectiveKnownAt, + known_at_source: 'sec_edgar_filing', + has_estimated_lag: false, + period_end: relDate, + fiscal_period: `Q${(rIdx % 4) + 1}`, + currency: 'USD', + period_known_at: effectiveKnownAt, + revenue, + net_income: Number((revenue * 0.14).toFixed(2)), + operating_cash_flow: Number((revenue * 0.19).toFixed(2)), + total_assets: Number((revenue * 3.8).toFixed(2)), + total_equity: Number((revenue * 1.7).toFixed(2)), + shares_outstanding: 10_000_000, + ttm_revenue: ttmRevenue, + ttm_net_income: Number((ttmRevenue * 0.14).toFixed(2)), + ttm_operating_cash_flow: Number((ttmRevenue * 0.19).toFixed(2)), + ttm_period_end: relDate, + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }); + } + } + const eventDayIndices = [12, 20, 28, 38, 48, 58]; const eventSet = new Set(); for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { @@ -362,6 +397,7 @@ function buildCopilotStudyFixture(): CopilotStudyFixture { columns: [...SHORTS_COLUMNS], rows: shortsRows, }, + fundamentalsRows, eventsTable: { columns: [...EVENTS_COLUMNS], rows: eventRows, @@ -378,6 +414,7 @@ interface FakeMarketDataStoreHandle { readonly store: MarketDataStore; readonly getBarsCalls: () => number; readonly getShortsCalls: () => number; + readonly getFundamentalsCalls: () => number; readonly getEventsCalls: () => number; readonly getUniverseCalls: () => number; } @@ -391,6 +428,7 @@ function createFakeMarketDataStore( const leaky = options?.leakyVaultRows ?? false; let barsCalls = 0; let shortsCalls = 0; + let fundamentalsCalls = 0; let eventsCalls = 0; let universeCalls = 0; @@ -537,8 +575,63 @@ function createFakeMarketDataStore( async crossSection() { throw new MarketDataStoreNotImplementedError('crossSection'); }, - async fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + async fundamentalsAsOf(q): Promise
{ + fundamentalsCalls += 1; + const idSet = new Set(q.listingIds); + const asOfMs = parseBoundMs(q.asOf, true); + const allowEstimatedLag = q.allowEstimatedLag ?? false; + const latestByListing = new Map(); + + for (const row of fixture.fundamentalsRows) { + const listingId = row.listing_id as number; + const knownAt = row.effective_known_at as number; + if (!idSet.has(listingId) || knownAt > asOfMs) { + continue; + } + const prev = latestByListing.get(listingId); + if (prev === undefined || knownAt > (prev.effective_known_at as number)) { + latestByListing.set(listingId, row); + } + } + + const rows: TableRow[] = []; + for (const lid of [...latestByListing.keys()].sort((a, b) => a - b)) { + const row = latestByListing.get(lid)!; + if (!allowEstimatedLag && row.has_estimated_lag === true) { + continue; + } + rows.push(row); + } + + if (leaky) { + rows.push({ + listing_id: fixture.listingIds[0]!, + effective_known_at: fixture.vaultCutoffTs, + known_at_source: 'sec_edgar_filing', + has_estimated_lag: false, + period_end: fixture.vaultCutoffDate, + fiscal_period: 'Q4', + currency: 'USD', + period_known_at: fixture.vaultCutoffTs, + revenue: 999_999, + ttm_revenue: 999_999, + }); + } + + return { + columns: [ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + ...q.fields, + ], + rows, + }; }, async macroAsOf() { throw new MarketDataStoreNotImplementedError('macroAsOf'); @@ -552,6 +645,7 @@ function createFakeMarketDataStore( store, getBarsCalls: () => barsCalls, getShortsCalls: () => shortsCalls, + getFundamentalsCalls: () => fundamentalsCalls, getEventsCalls: () => eventsCalls, getUniverseCalls: () => universeCalls, }; @@ -763,13 +857,14 @@ describe('createResearchCopilotMcpServer', () => { } }); - test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal -> event_study -> read_knowledge -> file_finding in one stdio session', async () => { + test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal (shorts + fundamentals) -> event_study -> read_knowledge -> file_finding in one stdio session', async () => { const fixture = buildCopilotStudyFixture(); - const { serverOptions, ledger, findings } = buildComposedServerOptions(fixture); + const { serverOptions, storeHandle, ledger, findings } = buildComposedServerOptions(fixture); const server = createResearchCopilotMcpServer(serverOptions); const sink = createMemoryOutput(); - let signalTrialRef = ''; + let shortsTrialRef = ''; + let fundamentalsTrialRef = ''; async function* requestStream(): AsyncGenerator { yield `${JSON.stringify({ @@ -839,6 +934,25 @@ describe('createResearchCopilotMcpServer', () => { jsonrpc: '2.0', id: 6, method: 'tools/call', + params: { + name: 'analyze_signal', + arguments: { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: fixture.lastPreCutoffDate, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + adjustment: 'raw', + }, + }, + })}\n`; + + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 7, + method: 'tools/call', params: { name: 'event_study', arguments: { @@ -858,7 +972,7 @@ describe('createResearchCopilotMcpServer', () => { yield `${JSON.stringify({ jsonrpc: '2.0', - id: 7, + id: 8, method: 'tools/call', params: { name: 'read_knowledge', @@ -866,28 +980,36 @@ describe('createResearchCopilotMcpServer', () => { }, })}\n`; - // Decode the earlier analyze_signal response written by runStdioServer before - // constructing the file_finding call so the trialRef is dynamically linked. - expect(sink.lines.length).toBeGreaterThanOrEqual(5); - const signalResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope; - const signalPayload = decodeToolJson(signalResp); - expect(signalPayload.status).toBe('ok'); - if (signalPayload.status !== 'ok') { - throw new Error('Expected analyze_signal status to be ok.'); + // Decode both earlier analyze_signal responses written by runStdioServer before + // constructing the file_finding call so both trialRefs are dynamically linked. + expect(sink.lines.length).toBeGreaterThanOrEqual(6); + const shortsResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope; + const shortsPayload = decodeToolJson(shortsResp); + expect(shortsPayload.status).toBe('ok'); + if (shortsPayload.status !== 'ok') { + throw new Error('Expected shorts analyze_signal status to be ok.'); } - signalTrialRef = String(signalPayload.trial.trialId); + shortsTrialRef = String(shortsPayload.trial.trialId); + + const fundamentalsResp = JSON.parse(sink.lines[5]!) as JsonRpcResponseEnvelope; + const fundamentalsPayload = decodeToolJson(fundamentalsResp); + expect(fundamentalsPayload.status).toBe('ok'); + if (fundamentalsPayload.status !== 'ok') { + throw new Error('Expected fundamentals analyze_signal status to be ok.'); + } + fundamentalsTrialRef = String(fundamentalsPayload.trial.trialId); yield `${JSON.stringify({ jsonrpc: '2.0', - id: 8, + id: 9, method: 'tools/call', params: { name: 'file_finding', arguments: { kind: 'finding', - title: 'Short-interest net_change study on synthetic US_EQ panel', + title: 'Short-interest and fundamentals signal studies on synthetic US_EQ panel', summary: `Dataset ${FIXTURE_DATASET_ID}, raw close-to-close returns, zero modeled costs, pre-Vault window ${fixture.firstDate}..${fixture.lastPreCutoffDate}.`, - trialRefs: [signalTrialRef], + trialRefs: [shortsTrialRef, fundamentalsTrialRef], evidenceRefs: [FIXTURE_DATASET_ID], idempotencyKey: 'copilot-e2e-finding-1', }, @@ -899,10 +1021,10 @@ describe('createResearchCopilotMcpServer', () => { const rawOut = sink.text(); expect(rawOut.endsWith('\n')).toBe(true); - expect(sink.lines).toHaveLength(8); + expect(sink.lines).toHaveLength(9); const responses = sink.lines.map(line => JSON.parse(line) as JsonRpcResponseEnvelope); - expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); + expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); for (const resp of responses) { expect(resp.error).toBeUndefined(); } @@ -933,16 +1055,34 @@ describe('createResearchCopilotMcpServer', () => { expect(queryPayload.truncated).toBe(true); expect(queryPayload.rows.every(r => r.ts < fixture.vaultCutoffTs)).toBe(true); - // 5. analyze_signal - const signalPayload = decodeToolJson(responses[4]!); - expect(signalPayload.status).toBe('ok'); - if (signalPayload.status !== 'ok') { - throw new Error('Expected analyze_signal status to be ok.'); + // 5. analyze_signal (shorts) + const shortsSignalPayload = decodeToolJson(responses[4]!); + expect(shortsSignalPayload.status).toBe('ok'); + if (shortsSignalPayload.status !== 'ok') { + throw new Error('Expected shorts analyze_signal status to be ok.'); } - expect(String(signalPayload.trial.trialId)).toBe(signalTrialRef); + expect(shortsSignalPayload.signal).toEqual({ source: 'shorts', field: 'net_change' }); + expect(String(shortsSignalPayload.trial.trialId)).toBe(shortsTrialRef); - // 6. event_study - const eventPayload = decodeToolJson(responses[5]!); + // 6. analyze_signal (fundamentals) + const fundamentalsSignalPayload = decodeToolJson(responses[5]!); + expect(fundamentalsSignalPayload.status).toBe('ok'); + if (fundamentalsSignalPayload.status !== 'ok') { + throw new Error('Expected fundamentals analyze_signal status to be ok.'); + } + expect(fundamentalsSignalPayload.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: false, + }); + expect(String(fundamentalsSignalPayload.trial.trialId)).toBe(fundamentalsTrialRef); + expect(fundamentalsSignalPayload.trial.expressionHash).not.toBe( + shortsSignalPayload.trial.expressionHash + ); + expect(storeHandle.getFundamentalsCalls()).toBeGreaterThan(0); + + // 7. event_study + const eventPayload = decodeToolJson(responses[6]!); expect(eventPayload.status).toBe('ok'); if (eventPayload.status !== 'ok') { throw new Error('Expected event_study status to be ok.'); @@ -950,27 +1090,29 @@ describe('createResearchCopilotMcpServer', () => { expect(eventPayload.benchmark).toBe('equal_weight'); expect(eventPayload.study.hasBenchmark).toBe(true); - // 7. read_knowledge - const knowledgePayload = decodeToolJson(responses[6]!); + // 8. read_knowledge + const knowledgePayload = decodeToolJson(responses[7]!); expect(knowledgePayload.rowCount).toBe(1); expect(knowledgePayload.rows[0]?.id).toBe('card-dsr-01'); - // 8. file_finding - const findingPayload = decodeToolJson(responses[7]!); + // 9. file_finding + const findingPayload = decodeToolJson(responses[8]!); expect(findingPayload).toEqual({ id: FIXED_FINDING_ID, createdAt: FIXED_NOW_ISO, created: true, }); - // Verify trial_ledger recorded both stages under AGENT_PRINCIPAL and matches responses. - expect(ledger.rows).toHaveLength(2); - expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'event_study']); + // Verify trial_ledger recorded both signal_ic trials (distinct hashes) and event_study under AGENT_PRINCIPAL. + expect(ledger.rows).toHaveLength(3); + expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'signal_ic', 'event_study']); expect(ledger.rows.every(r => r.principal_id === AGENT_PRINCIPAL)).toBe(true); - expect(ledger.rows[0]?.trial_id).toBe(String(signalPayload.trial.trialId)); - expect(ledger.rows[1]?.trial_id).toBe(String(eventPayload.trial.trialId)); + expect(ledger.rows[0]?.trial_id).toBe(String(shortsSignalPayload.trial.trialId)); + expect(ledger.rows[1]?.trial_id).toBe(String(fundamentalsSignalPayload.trial.trialId)); + expect(ledger.rows[2]?.trial_id).toBe(String(eventPayload.trial.trialId)); + expect(ledger.rows[0]?.expression_hash).not.toBe(ledger.rows[1]?.expression_hash); - // Verify FindingWritePort recorded exactly one pending_review finding referencing signal trial. + // Verify FindingWritePort recorded exactly one pending_review finding referencing both signal trials. expect(findings.appendCalls).toHaveLength(1); expect(findings.stored).toHaveLength(1); expect(findings.stored[0]).toMatchObject({ @@ -978,7 +1120,7 @@ describe('createResearchCopilotMcpServer', () => { createdAt: findingPayload.createdAt, kind: 'finding', status: 'pending_review', - trialRefs: [signalTrialRef], + trialRefs: [shortsTrialRef, fundamentalsTrialRef], evidenceRefs: [FIXTURE_DATASET_ID], }); }); From bec64c5ec6f6c37e7e9baa134f8800171e72f2dc Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:30:22 -0500 Subject: [PATCH 09/15] =?UTF-8?q?T-149:=20M2.1h=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`analyze=5Fsignal`:=20add=20a=20Vault-fenced=20`fundamental?= =?UTF-8?q?s`=20signal=20source=20(point-in-time=20`fundamentalsAsOf`=20mo?= =?UTF-8?q?nth-end=20snapshots=20=E2=86=92=20`SignalObservation`s)=20+=20e?= =?UTF-8?q?xtend=20the=20headless=20stdio=20end-to-end=20test=20to=20run?= =?UTF-8?q?=20a=20fundamental=20AND=20a=20shorts=20study=20(pure,=20inject?= =?UTF-8?q?ed=20ports,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/analyze-signal.ts | 162 ++++++++++- libs/research/test/mcp-analyze-signal.test.ts | 259 ++++++++++++++++++ 2 files changed, 418 insertions(+), 3 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index 8a803e12..ef4ca71c 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -579,6 +579,69 @@ function resolveSnapshotAsOf( }; } +function buildBarTimestampsByListing(bars: readonly BarRecord[]): Map { + const byListing = new Map(); + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i]; + if ( + typeof bar !== 'object' || + bar === null || + typeof bar.listingId !== 'number' || + !Number.isSafeInteger(bar.listingId) || + typeof bar.ts !== 'number' || + !Number.isFinite(bar.ts) + ) { + continue; + } + let list = byListing.get(bar.listingId); + if (list === undefined) { + list = []; + byListing.set(bar.listingId, list); + } + list.push(bar.ts); + } + for (const [lid, list] of byListing) { + list.sort((a, b) => a - b); + let write = 0; + for (let i = 0; i < list.length; i += 1) { + const ts = list[i] as number; + if (write === 0 || list[write - 1] !== ts) { + list[write] = ts; + write += 1; + } + } + list.length = write; + byListing.set(lid, list); + } + return byListing; +} + +function findLatestBarBefore( + sortedTs: readonly number[] | undefined, + upperExclusiveMs: number, + lowerExclusiveMs: number +): number | null { + if (sortedTs === undefined || sortedTs.length === 0) { + return null; + } + let lo = 0; + let hi = sortedTs.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if ((sortedTs[mid] as number) < upperExclusiveMs) { + lo = mid + 1; + } else { + hi = mid; + } + } + const idx = lo - 1; + if (idx < 0) { + return null; + } + const candidate = sortedTs[idx] as number; + return candidate > lowerExclusiveMs ? candidate : null; +} + function appendEligibleFundamentalsObservations(params: { readonly table: Table; readonly field: FundamentalsPitValueField; @@ -588,7 +651,7 @@ function appendEligibleFundamentalsObservations(params: { readonly vaultCutoffTs: number; readonly seenKeys: Set; readonly out: SignalObservation[]; -}): void { +}): Map { const { table, field, @@ -612,6 +675,8 @@ function appendEligibleFundamentalsObservations(params: { ); } + const latestKnownAtByListing = new Map(); + for (let i = 0; i < table.rows.length; i += 1) { const row = table.rows[i]; if (typeof row !== 'object' || row === null) { @@ -640,12 +705,22 @@ function appendEligibleFundamentalsObservations(params: { } const rawValue = row[field]; - if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { + const isFiniteValue = typeof rawValue === 'number' && Number.isFinite(rawValue); + if (!isFiniteValue && rawValue !== null) { continue; } const normalizedListingId = listingId === 0 ? 0 : listingId; const normalizedKnownAt = knownAt === 0 ? 0 : knownAt; + const prevLatest = latestKnownAtByListing.get(normalizedListingId); + if (prevLatest === undefined || normalizedKnownAt > prevLatest) { + latestKnownAtByListing.set(normalizedListingId, normalizedKnownAt); + } + + if (!isFiniteValue) { + continue; + } + const normalizedValue = rawValue === 0 ? 0 : rawValue; const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; if (seenKeys.has(dedupeKey)) { @@ -658,6 +733,8 @@ function appendEligibleFundamentalsObservations(params: { value: normalizedValue, }); } + + return latestKnownAtByListing; } function buildCanonicalStudyExpression(params: { @@ -940,6 +1017,9 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT signals = []; const seenKeys = new Set(); + const barTimestampsByListing = buildBarTimestampsByListing(eligibleBars); + let windowFloorMs = Number.NEGATIVE_INFINITY; + for (const snapshotDate of snapshotDates) { const snapshot = resolveSnapshotAsOf( snapshotDate, @@ -952,7 +1032,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT asOf: snapshot.asOf, allowEstimatedLag: input.signal.allowEstimatedLag, }); - appendEligibleFundamentalsObservations({ + const latestKnownByListing = appendEligibleFundamentalsObservations({ table: rawTable, field: input.signal.field, listingIdSet, @@ -962,6 +1042,82 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT seenKeys, out: signals, }); + + // Backfill vintages superseded earlier within this month (or prior + // to the first eligible bar for the initial month) by stepping to + // the latest uncovered eligible bar strictly before each returned + // vintage. Listings sharing a target bar timestamp are batched. + const pendingByBarTs = new Map(); + const enqueueBackfill = ( + knownByListing: ReadonlyMap, + upperBoundExclusiveMs?: number + ): void => { + for (const [lid, knownAt] of knownByListing) { + const upperExclusive = + upperBoundExclusiveMs !== undefined + ? Math.min(knownAt, upperBoundExclusiveMs) + : knownAt; + const prevBarTs = findLatestBarBefore( + barTimestampsByListing.get(lid), + upperExclusive, + windowFloorMs + ); + if (prevBarTs !== null) { + let bucket = pendingByBarTs.get(prevBarTs); + if (bucket === undefined) { + bucket = []; + pendingByBarTs.set(prevBarTs, bucket); + } + bucket.push(lid); + } + } + }; + + enqueueBackfill(latestKnownByListing); + + while (pendingByBarTs.size > 0) { + // Pop the highest bar timestamp first so earlier buckets merge + // newly discovered listings landing on the same session. + let nextBarTs = Number.NEGATIVE_INFINITY; + for (const ts of pendingByBarTs.keys()) { + if (ts > nextBarTs) { + nextBarTs = ts; + } + } + const batchListingIds = sortAndDedupeListingIds(pendingByBarTs.get(nextBarTs) ?? []); + pendingByBarTs.delete(nextBarTs); + if (batchListingIds.length === 0) { + continue; + } + + const batchAsOfMs = Math.min(nextBarTs, fenced.asOfMs); + const batchAsOf = + batchAsOfMs === fenced.asOfMs + ? fenced.canonicalAsOf + : formatUtcIsoWithMicros(batchAsOfMs, 0); + const batchListingIdSet = new Set(batchListingIds); + + const backfillTable = await store.fundamentalsAsOf({ + listingIds: batchListingIds, + fields: [input.signal.field], + asOf: batchAsOf, + allowEstimatedLag: input.signal.allowEstimatedLag, + }); + const backfillKnownByListing = appendEligibleFundamentalsObservations({ + table: backfillTable, + field: input.signal.field, + listingIdSet: batchListingIdSet, + snapshotAsOfMs: batchAsOfMs, + fencedAsOfMs: fenced.asOfMs, + vaultCutoffTs, + seenKeys, + out: signals, + }); + + enqueueBackfill(backfillKnownByListing, nextBarTs); + } + + windowFloorMs = snapshot.asOfMs; } } diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index 40c52efd..8176615e 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -2537,6 +2537,265 @@ describe('MCP analyze_signal tool — fundamentals source', () => { expect(futureLedger.rows).toEqual(mcpLedger.rows); }); + test('same-month restatement replay retains earlier intra-month vintage through the day before the amendment', async () => { + // Regression fixture for intra-month superseded vintages: + // - Dataset ID: `synthetic:mcp-analyze-signal-same-month-restatement:seed-20261204:v1` + // - 6 listings across 2023-03-01..2023-05-12 (53 sessions), Vault cutoff 2023-05-15T00:00:00Z + // - March 10: initial Q1 release (listings 0..4 only; listing 5 has NO prior release before April 5) + // - April 5: Q2 release for all 6 listings (strictly ascending ttm_revenue across listings) + // - April 18: Q1 restatement (SAME month as Q2!) keeping Q2 as latest period while reversing + // ttm_revenue cross-sectional ordering. + // Under latest-only month-end reads, the April 30 snapshot returns only the April 18 vintage + // and erases April 5 from April 5..17 (falling back to March for listings 0..4 and dropping + // listing 5 completely). With intra-month backfill, April 5..17 uses the original April 5 Q2 + // values and April 18+ uses the restated values. + const listingIds = [81_001, 81_002, 81_003, 81_004, 81_005, 81_006]; + const allDates = makeBusinessDates('2023-03-01', 53); + const vaultCutoffDate = '2023-05-15'; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const marKnownAt = makeUtcMs('2023-03-10', 13); + const aprQ2KnownAt = makeUtcMs('2023-04-05', 13); + const aprRestatedKnownAt = makeUtcMs('2023-04-18', 13); + + const rand = createSeededRng(20261204); + const bars: BarRecord[] = []; + const prices = new Float64Array(listingIds.length).fill(40); + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingIds.length; l += 1) { + const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 30_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + const pitRows: FundamentalsPitFixtureRow[] = []; + const expectedAllVintagesObs: SignalObservation[] = []; + const brokenMonthEndOnlyObs: SignalObservation[] = []; + + for (let l = 0; l < listingIds.length; l += 1) { + const lid = listingIds[l]!; + // March ordering: alternating/scrambled; April 5 Q2: strictly ascending; April 18 restated: strictly descending + const marVal = 200 + ((l * 3) % listingIds.length) * 25; + const aprQ2Val = 100 + l * 40; + const aprRestatedVal = 400 - l * 45; + + if (l < 5) { + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: marKnownAt, + periodEnd: '2022-12-31', + fiscalPeriod: 'Q1', + revenue: marVal / 4, + ttmRevenue: marVal, + }) + ); + expectedAllVintagesObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + brokenMonthEndOnlyObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + } + + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprQ2KnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprQ2Val / 4, + ttmRevenue: aprQ2Val, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprRestatedKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprQ2Val / 4, + ttmRevenue: aprRestatedVal, + }) + ); + + expectedAllVintagesObs.push( + { listingId: lid, knownAt: aprQ2KnownAt, value: aprQ2Val }, + { listingId: lid, knownAt: aprRestatedKnownAt, value: aprRestatedVal } + ); + // Month-end-only baseline misses the April 5 vintage completely + brokenMonthEndOnlyObs.push({ listingId: lid, knownAt: aprRestatedKnownAt, value: aprRestatedVal }); + } + + // 1. Direct baseline with all eligible vintages (including April 5 Q2) + const directBuilt = buildForwardReturnPanel({ + bars, + signals: expectedAllVintagesObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const directLedger = createFakeTrialLedger(); + const directStudy = await analyzeSignal(directLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_same_month_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3 }, + universe: listingIds, + horizon: '3d', + }, + panel: directBuilt.panel, + vaultCutoffDate, + }); + expect(directStudy.status).toBe('ok'); + if (directStudy.status !== 'ok') { + return; + } + + // 2. Broken month-end-only counterfactual (omits April 5 Q2) + const brokenBuilt = buildForwardReturnPanel({ + bars, + signals: brokenMonthEndOnlyObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const brokenLedger = createFakeTrialLedger(); + const brokenStudy = await analyzeSignal(brokenLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'broken_month_end_only_counterfactual', + params: { field: 'ttm_revenue', horizonSessions: 3 }, + universe: listingIds, + horizon: '3d', + }, + panel: brokenBuilt.panel, + vaultCutoffDate, + }); + expect(brokenStudy.status).toBe('ok'); + + // 3. MCP handler over multi-month window (March..May) + const mcpStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const mcpLedger = createFakeTrialLedger(); + const mcpRes = await callAnalyzeSignal({ + store: mcpStore.store, + ledger: mcpLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(mcpRes.isError).toBe(false); + const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; + expect(mcpPayload.status).toBe('ok'); + if (mcpPayload.status !== 'ok') { + return; + } + + // Exact parity with the full-vintage direct baseline across all dates (including April 5..17) + expect(mcpPayload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); + expect(mcpPayload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); + expect(mcpLedger.rows[0]?.daily_series).toEqual(directLedger.rows[0]?.daily_series); + + // Specifically verify April 5..17 dated points match direct baseline and differ from month-end-only + const aprilPreAmendmentDates = mcpPayload.analysis.ledgerSeries.points + .filter(p => p.date >= '2023-04-05' && p.date <= '2023-04-17') + .map(p => p.date); + expect(aprilPreAmendmentDates.length).toBeGreaterThan(0); + expect(aprilPreAmendmentDates[0]).toBe('2023-04-05'); + expect(aprilPreAmendmentDates[aprilPreAmendmentDates.length - 1]).toBe('2023-04-17'); + + const mcpByDate = new Map(mcpPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])); + const brokenByDate = new Map( + brokenStudy.analysis.dates.map((d, idx) => [d, brokenStudy.analysis.rankIcSeries[idx]!]) + ); + let aprilDiffCount = 0; + for (const d of aprilPreAmendmentDates) { + if (mcpByDate.get(d) !== brokenByDate.get(d)) { + aprilDiffCount += 1; + } + } + expect(aprilDiffCount).toBeGreaterThan(0); + + // Every fundamentalsAsOf call (month-end + backfill) stays strictly below Vault cutoff and forwards allowEstimatedLag + for (const call of mcpStore.fundamentalsCalls) { + expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); + expect(call.allowEstimatedLag).toBe(false); + } + + // 4. Single-month window starting in April (2023-04-03..2023-04-28): + // must retain March prior (for Apr 3..4), April 5 Q2 (for Apr 5..17), and April 18 restatement (Apr 18..28). + const aprilOnlyBars = bars.filter(b => b.ts >= makeUtcMs('2023-04-03', 0) && b.ts <= makeUtcMs('2023-04-28', 23)); + const aprilDirectBuilt = buildForwardReturnPanel({ + bars: aprilOnlyBars, + signals: expectedAllVintagesObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const aprilDirectLedger = createFakeTrialLedger(); + const aprilDirectStudy = await analyzeSignal(aprilDirectLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_april_only_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3 }, + universe: listingIds, + horizon: '3d', + }, + panel: aprilDirectBuilt.panel, + vaultCutoffDate, + }); + expect(aprilDirectStudy.status).toBe('ok'); + + const aprilMcpStore = createFakeStore({ + bars: aprilOnlyBars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const aprilMcpLedger = createFakeTrialLedger(); + const aprilMcpRes = await callAnalyzeSignal({ + store: aprilMcpStore.store, + ledger: aprilMcpLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: '2023-04-03', + to: '2023-04-28', + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(aprilMcpRes.isError).toBe(false); + const aprilMcpPayload = JSON.parse(aprilMcpRes.text) as AnalyzeSignalResultPayload; + expect(aprilMcpPayload.status).toBe('ok'); + if (aprilMcpPayload.status === 'ok' && aprilDirectStudy.status === 'ok') { + expect(aprilMcpPayload.analysis.rankIc).toEqual(aprilDirectStudy.analysis.rankIc); + expect(aprilMcpLedger.rows[0]?.daily_series).toEqual(aprilDirectLedger.rows[0]?.daily_series); + expect(aprilMcpPayload.trial.sampleStart).toBe('2023-04-03'); + } + }); + test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { const fixture = buildFundamentalsStudyFixture(); const from = fixture.allDates[0]!; From 5fc2f7476072aaa81cf8e3ff27808645300c09e3 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:39:37 -0500 Subject: [PATCH 10/15] =?UTF-8?q?T-149:=20M2.1h=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`analyze=5Fsignal`:=20add=20a=20Vault-fenced=20`fundamental?= =?UTF-8?q?s`=20signal=20source=20(point-in-time=20`fundamentalsAsOf`=20mo?= =?UTF-8?q?nth-end=20snapshots=20=E2=86=92=20`SignalObservation`s)=20+=20e?= =?UTF-8?q?xtend=20the=20headless=20stdio=20end-to-end=20test=20to=20run?= =?UTF-8?q?=20a=20fundamental=20AND=20a=20shorts=20study=20(pure,=20inject?= =?UTF-8?q?ed=20ports,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/analyze-signal.ts | 41 +- libs/research/test/mcp-analyze-signal.test.ts | 368 +++++++++++++++++- 2 files changed, 392 insertions(+), 17 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index ef4ca71c..eaa43c40 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -1002,6 +1002,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT ); signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); } else { + const { field: fundamentalsField, allowEstimatedLag } = input.signal; const snapshotDates = deriveMonthlySnapshotDates(eligibleBars); if (snapshotDates.length > ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS) { return { @@ -1028,13 +1029,13 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT ); const rawTable = await store.fundamentalsAsOf({ listingIds, - fields: [input.signal.field], + fields: [fundamentalsField], asOf: snapshot.asOf, - allowEstimatedLag: input.signal.allowEstimatedLag, + allowEstimatedLag, }); const latestKnownByListing = appendEligibleFundamentalsObservations({ table: rawTable, - field: input.signal.field, + field: fundamentalsField, listingIdSet, snapshotAsOfMs: snapshot.asOfMs, fencedAsOfMs: fenced.asOfMs, @@ -1046,17 +1047,27 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT // Backfill vintages superseded earlier within this month (or prior // to the first eligible bar for the initial month) by stepping to // the latest uncovered eligible bar strictly before each returned - // vintage. Listings sharing a target bar timestamp are batched. + // vintage. When `allowEstimatedLag` is false, DuckDB omits listings + // whose latest vintage uses estimated publication lag, so treat + // omitted listings as unresolved intervals and probe earlier + // eligible closes in the month. Listings sharing a target bar + // timestamp are batched. const pendingByBarTs = new Map(); const enqueueBackfill = ( + queriedListingIds: readonly number[], knownByListing: ReadonlyMap, - upperBoundExclusiveMs?: number + upperBoundExclusiveMs: number ): void => { - for (const [lid, knownAt] of knownByListing) { - const upperExclusive = - upperBoundExclusiveMs !== undefined - ? Math.min(knownAt, upperBoundExclusiveMs) - : knownAt; + for (const lid of queriedListingIds) { + const knownAt = knownByListing.get(lid); + let upperExclusive: number; + if (knownAt !== undefined) { + upperExclusive = Math.min(knownAt, upperBoundExclusiveMs); + } else if (!allowEstimatedLag) { + upperExclusive = upperBoundExclusiveMs; + } else { + continue; + } const prevBarTs = findLatestBarBefore( barTimestampsByListing.get(lid), upperExclusive, @@ -1073,7 +1084,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT } }; - enqueueBackfill(latestKnownByListing); + enqueueBackfill(listingIds, latestKnownByListing, snapshot.asOfMs); while (pendingByBarTs.size > 0) { // Pop the highest bar timestamp first so earlier buckets merge @@ -1099,13 +1110,13 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT const backfillTable = await store.fundamentalsAsOf({ listingIds: batchListingIds, - fields: [input.signal.field], + fields: [fundamentalsField], asOf: batchAsOf, - allowEstimatedLag: input.signal.allowEstimatedLag, + allowEstimatedLag, }); const backfillKnownByListing = appendEligibleFundamentalsObservations({ table: backfillTable, - field: input.signal.field, + field: fundamentalsField, listingIdSet: batchListingIdSet, snapshotAsOfMs: batchAsOfMs, fencedAsOfMs: fenced.asOfMs, @@ -1114,7 +1125,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT out: signals, }); - enqueueBackfill(backfillKnownByListing, nextBarTs); + enqueueBackfill(batchListingIds, backfillKnownByListing, nextBarTs); } windowFloorMs = snapshot.asOfMs; diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index 8176615e..41ee7c95 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -2189,9 +2189,17 @@ describe('MCP analyze_signal tool — fundamentals source', () => { } const cutoffTs = makeUtcMs('2023-04-01', 0); + const preWindowKnownAt = makeUtcMs('2022-12-15', 13); const storeOrder = createFakeStore({ bars, - fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + fundamentalsResolver: q => ({ + columns: ['listing_id', 'effective_known_at', 'revenue'], + rows: q.listingIds.map(lid => ({ + listing_id: lid, + effective_known_at: preWindowKnownAt, + revenue: 100, + })), + }), }); const ledgerOrder = createFakeTrialLedger(); @@ -2273,9 +2281,17 @@ describe('MCP analyze_signal tool — fundamentals source', () => { } const capCutoffTs = makeUtcMs('2025-01-01', 0); + const capPreWindowKnownAt = makeUtcMs('2009-12-15', 13); const exactCapStore = createFakeStore({ bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS), - fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + fundamentalsResolver: q => ({ + columns: ['listing_id', 'effective_known_at', 'revenue'], + rows: q.listingIds.map(lid => ({ + listing_id: lid, + effective_known_at: capPreWindowKnownAt, + revenue: 100, + })), + }), }); const exactCapLedger = createFakeTrialLedger(); const exactCapRes = await callAnalyzeSignal({ @@ -2796,6 +2812,354 @@ describe('MCP analyze_signal tool — fundamentals source', () => { } }); + test('estimated-lag omission backfill recovers earlier verified intra-month vintages when allowEstimatedLag is false', async () => { + // Regression fixture for DuckDB estimated-lag omission under allowEstimatedLag: false: + // - Dataset ID: `synthetic:mcp-analyze-signal-estimated-lag-omission:seed-20261205:v1` + // - 6 listings across 2023-03-01..2023-05-12 (53 sessions), Vault cutoff 2023-05-15T00:00:00Z + // - March 10: verified Q1 release (listings 0..4 only; listing 5 has no March prior) + // - April 5: verified Q2 release (`has_estimated_lag: false`) for all 6 listings + // - April 18: estimated-lag update (`has_estimated_lag: true`) for all 6 listings, so + // DuckDB's `fundamentalsAsOf(..., allowEstimatedLag: false)` omits listings 1..5 + // at April month-end and omits listing 0 at intermediate backfill probes. + // - April 25: verified update (`has_estimated_lag: false`) for listing 0 only (exercises + // sandwiched omission during backfill after a later verified release). + const listingIds = [82_001, 82_002, 82_003, 82_004, 82_005, 82_006]; + const allDates = makeBusinessDates('2023-03-01', 53); + const vaultCutoffDate = '2023-05-15'; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const marKnownAt = makeUtcMs('2023-03-10', 13); + const aprVerifiedKnownAt = makeUtcMs('2023-04-05', 13); + const aprEstimatedLagKnownAt = makeUtcMs('2023-04-18', 13); + const aprLateVerifiedKnownAt = makeUtcMs('2023-04-25', 13); + + const rand = createSeededRng(20261205); + const bars: BarRecord[] = []; + const prices = new Float64Array(listingIds.length).fill(45); + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingIds.length; l += 1) { + const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 30_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + const pitRows: FundamentalsPitFixtureRow[] = []; + const expectedVerifiedObs: SignalObservation[] = []; + const expectedAllowLagObs: SignalObservation[] = []; + const brokenOmittedAprilObs: SignalObservation[] = []; + + for (let l = 0; l < listingIds.length; l += 1) { + const lid = listingIds[l]!; + const marVal = 200 + ((l * 3) % listingIds.length) * 25; + const aprVerifiedVal = 100 + l * 40; + const aprEstimatedVal = 400 - l * 45; + const aprLateVerifiedVal = 150; + + if (l < 5) { + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: marKnownAt, + periodEnd: '2022-12-31', + fiscalPeriod: 'Q1', + revenue: marVal / 4, + ttmRevenue: marVal, + hasEstimatedLag: false, + }) + ); + expectedVerifiedObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + expectedAllowLagObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + brokenOmittedAprilObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + } + + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprVerifiedKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprVerifiedVal / 4, + ttmRevenue: aprVerifiedVal, + hasEstimatedLag: false, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprEstimatedLagKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprEstimatedVal / 4, + ttmRevenue: aprEstimatedVal, + hasEstimatedLag: true, + }) + ); + + expectedVerifiedObs.push({ + listingId: lid, + knownAt: aprVerifiedKnownAt, + value: aprVerifiedVal, + }); + expectedAllowLagObs.push( + { listingId: lid, knownAt: aprVerifiedKnownAt, value: aprVerifiedVal }, + { listingId: lid, knownAt: aprEstimatedLagKnownAt, value: aprEstimatedVal } + ); + + if (l === 0) { + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprLateVerifiedKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprLateVerifiedVal / 4, + ttmRevenue: aprLateVerifiedVal, + hasEstimatedLag: false, + }) + ); + expectedVerifiedObs.push({ + listingId: lid, + knownAt: aprLateVerifiedKnownAt, + value: aprLateVerifiedVal, + }); + expectedAllowLagObs.push({ + listingId: lid, + knownAt: aprLateVerifiedKnownAt, + value: aprLateVerifiedVal, + }); + brokenOmittedAprilObs.push({ + listingId: lid, + knownAt: aprLateVerifiedKnownAt, + value: aprLateVerifiedVal, + }); + } + } + + // 1. Direct verified-only baseline (includes April 5 verified release; excludes April 18 estimated lag) + const directVerifiedBuilt = buildForwardReturnPanel({ + bars, + signals: expectedVerifiedObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const directVerifiedLedger = createFakeTrialLedger(); + const directVerifiedStudy = await analyzeSignal(directVerifiedLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_estimated_lag_omission_verified_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, + universe: listingIds, + horizon: '3d', + }, + panel: directVerifiedBuilt.panel, + vaultCutoffDate, + }); + expect(directVerifiedStudy.status).toBe('ok'); + if (directVerifiedStudy.status !== 'ok') { + return; + } + + // 2. Broken counterfactual without omission backfill (loses April 5 for all omitted listings) + const brokenBuilt = buildForwardReturnPanel({ + bars, + signals: brokenOmittedAprilObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const brokenLedger = createFakeTrialLedger(); + const brokenStudy = await analyzeSignal(brokenLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'broken_estimated_lag_omission_counterfactual', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, + universe: listingIds, + horizon: '3d', + }, + panel: brokenBuilt.panel, + vaultCutoffDate, + }); + expect(brokenStudy.status).toBe('ok'); + + // 3. MCP handler with allowEstimatedLag: false (default) over March..May + const mcpStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const mcpLedger = createFakeTrialLedger(); + const mcpRes = await callAnalyzeSignal({ + store: mcpStore.store, + ledger: mcpLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(mcpRes.isError).toBe(false); + const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; + expect(mcpPayload.status).toBe('ok'); + if (mcpPayload.status !== 'ok') { + return; + } + + // Exact parity with the verified-only direct baseline across all dates (including April 5..17) + expect(mcpPayload.analysis.rankIc).toEqual(directVerifiedStudy.analysis.rankIc); + expect(mcpPayload.analysis.pearsonIc).toEqual(directVerifiedStudy.analysis.pearsonIc); + expect(mcpLedger.rows[0]?.daily_series).toEqual(directVerifiedLedger.rows[0]?.daily_series); + + const aprilPreEstimatedDates = mcpPayload.analysis.ledgerSeries.points + .filter(p => p.date >= '2023-04-05' && p.date <= '2023-04-17') + .map(p => p.date); + expect(aprilPreEstimatedDates[0]).toBe('2023-04-05'); + expect(aprilPreEstimatedDates[aprilPreEstimatedDates.length - 1]).toBe('2023-04-17'); + + const mcpByDate = new Map(mcpPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])); + const brokenByDate = new Map( + brokenStudy.analysis.dates.map((d, idx) => [d, brokenStudy.analysis.rankIcSeries[idx]!]) + ); + let aprilDiffCount = 0; + for (const d of aprilPreEstimatedDates) { + if (mcpByDate.get(d) !== brokenByDate.get(d)) { + aprilDiffCount += 1; + } + } + expect(aprilDiffCount).toBeGreaterThan(0); + + // Every fundamentalsAsOf call stays strictly below Vault cutoff and forwards allowEstimatedLag: false + for (const call of mcpStore.fundamentalsCalls) { + expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); + expect(call.allowEstimatedLag).toBe(false); + } + + // 4. Single-month April-only window (2023-04-03..2023-04-28) with allowEstimatedLag: false + const aprilOnlyBars = bars.filter( + b => b.ts >= makeUtcMs('2023-04-03', 0) && b.ts <= makeUtcMs('2023-04-28', 23) + ); + const aprilDirectBuilt = buildForwardReturnPanel({ + bars: aprilOnlyBars, + signals: expectedVerifiedObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const aprilDirectLedger = createFakeTrialLedger(); + const aprilDirectStudy = await analyzeSignal(aprilDirectLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_estimated_lag_april_only_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, + universe: listingIds, + horizon: '3d', + }, + panel: aprilDirectBuilt.panel, + vaultCutoffDate, + }); + expect(aprilDirectStudy.status).toBe('ok'); + + const aprilMcpStore = createFakeStore({ + bars: aprilOnlyBars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const aprilMcpLedger = createFakeTrialLedger(); + const aprilMcpRes = await callAnalyzeSignal({ + store: aprilMcpStore.store, + ledger: aprilMcpLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: '2023-04-03', + to: '2023-04-28', + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(aprilMcpRes.isError).toBe(false); + const aprilMcpPayload = JSON.parse(aprilMcpRes.text) as AnalyzeSignalResultPayload; + expect(aprilMcpPayload.status).toBe('ok'); + if (aprilMcpPayload.status === 'ok' && aprilDirectStudy.status === 'ok') { + expect(aprilMcpPayload.analysis.rankIc).toEqual(aprilDirectStudy.analysis.rankIc); + expect(aprilMcpLedger.rows[0]?.daily_series).toEqual(aprilDirectLedger.rows[0]?.daily_series); + } + + // 5. With allowEstimatedLag: true, April 18 estimated-lag update is included alongside April 5 + const allowLagDirectBuilt = buildForwardReturnPanel({ + bars, + signals: expectedAllowLagObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const allowLagDirectLedger = createFakeTrialLedger(); + const allowLagDirectStudy = await analyzeSignal(allowLagDirectLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_estimated_lag_allowed_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: true }, + universe: listingIds, + horizon: '3d', + }, + panel: allowLagDirectBuilt.panel, + vaultCutoffDate, + }); + expect(allowLagDirectStudy.status).toBe('ok'); + + const allowLagStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const allowLagLedger = createFakeTrialLedger(); + const allowLagRes = await callAnalyzeSignal({ + store: allowLagStore.store, + ledger: allowLagLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(allowLagRes.isError).toBe(false); + const allowLagPayload = JSON.parse(allowLagRes.text) as AnalyzeSignalResultPayload; + expect(allowLagPayload.status).toBe('ok'); + if (allowLagPayload.status === 'ok' && allowLagDirectStudy.status === 'ok') { + expect(allowLagPayload.analysis.rankIc).toEqual(allowLagDirectStudy.analysis.rankIc); + expect(allowLagLedger.rows[0]?.daily_series).toEqual( + allowLagDirectLedger.rows[0]?.daily_series + ); + expect(allowLagLedger.rows[0]?.daily_series).not.toEqual(mcpLedger.rows[0]?.daily_series); + } + expect(allowLagStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); + }); + test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { const fixture = buildFundamentalsStudyFixture(); const from = fixture.allDates[0]!; From e5b97c232470576d17f3fb8e66bbc4a5b1a44753 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:48:26 -0500 Subject: [PATCH 11/15] =?UTF-8?q?T-149:=20M2.1h=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`analyze=5Fsignal`:=20add=20a=20Vault-fenced=20`fundamental?= =?UTF-8?q?s`=20signal=20source=20(point-in-time=20`fundamentalsAsOf`=20mo?= =?UTF-8?q?nth-end=20snapshots=20=E2=86=92=20`SignalObservation`s)=20+=20e?= =?UTF-8?q?xtend=20the=20headless=20stdio=20end-to-end=20test=20to=20run?= =?UTF-8?q?=20a=20fundamental=20AND=20a=20shorts=20study=20(pure,=20inject?= =?UTF-8?q?ed=20ports,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/analyze-signal.ts | 27 ++--- libs/research/test/mcp-analyze-signal.test.ts | 112 ++++++++++++++++++ 2 files changed, 121 insertions(+), 18 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index eaa43c40..0103f10a 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -705,8 +705,7 @@ function appendEligibleFundamentalsObservations(params: { } const rawValue = row[field]; - const isFiniteValue = typeof rawValue === 'number' && Number.isFinite(rawValue); - if (!isFiniteValue && rawValue !== null) { + if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { continue; } @@ -717,10 +716,6 @@ function appendEligibleFundamentalsObservations(params: { latestKnownAtByListing.set(normalizedListingId, normalizedKnownAt); } - if (!isFiniteValue) { - continue; - } - const normalizedValue = rawValue === 0 ? 0 : rawValue; const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; if (seenKeys.has(dedupeKey)) { @@ -1047,10 +1042,10 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT // Backfill vintages superseded earlier within this month (or prior // to the first eligible bar for the initial month) by stepping to // the latest uncovered eligible bar strictly before each returned - // vintage. When `allowEstimatedLag` is false, DuckDB omits listings - // whose latest vintage uses estimated publication lag, so treat - // omitted listings as unresolved intervals and probe earlier - // eligible closes in the month. Listings sharing a target bar + // vintage. Under either lag setting, a requested listing with no + // valid observation (omitted by DuckDB or carrying a null/non-finite + // field) is treated as an unresolved interval so earlier eligible + // closes within the month are probed. Listings sharing a target bar // timestamp are batched. const pendingByBarTs = new Map(); const enqueueBackfill = ( @@ -1060,14 +1055,10 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT ): void => { for (const lid of queriedListingIds) { const knownAt = knownByListing.get(lid); - let upperExclusive: number; - if (knownAt !== undefined) { - upperExclusive = Math.min(knownAt, upperBoundExclusiveMs); - } else if (!allowEstimatedLag) { - upperExclusive = upperBoundExclusiveMs; - } else { - continue; - } + const upperExclusive = + knownAt !== undefined + ? Math.min(knownAt, upperBoundExclusiveMs) + : upperBoundExclusiveMs; const prevBarTs = findLatestBarBefore( barTimestampsByListing.get(lid), upperExclusive, diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index 41ee7c95..e871fdeb 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -3158,6 +3158,118 @@ describe('MCP analyze_signal tool — fundamentals source', () => { expect(allowLagLedger.rows[0]?.daily_series).not.toEqual(mcpLedger.rows[0]?.daily_series); } expect(allowLagStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); + + // 6. Stale March null row for an omitted listing must not suppress April omission backfill; + // exact payload and ledger rows must match the clean run. + const staleNullKnownAt = makeUtcMs('2023-03-20', 13); + const staleNullStore = createFakeStore({ + bars, + fundamentalsResolver: q => { + const cleanTable = queryFundamentalsFixtureRows(pitRows, q); + const returnedIds = new Set(cleanTable.rows.map(r => r.listing_id)); + const injected: TableRow[] = []; + for (const omittedTarget of [listingIds[1]!, listingIds[5]!]) { + if (q.listingIds.includes(omittedTarget) && !returnedIds.has(omittedTarget)) { + injected.push({ + listing_id: omittedTarget, + effective_known_at: staleNullKnownAt, + known_at_source: 'sec_edgar_filing', + has_estimated_lag: false, + period_end: '2022-12-31', + fiscal_period: 'Q1', + currency: 'USD', + period_known_at: staleNullKnownAt, + ttm_revenue: null, + ttm_period_end: null, + ttm_currency: null, + ttm_has_estimated_lag: false, + }); + } + } + return { + columns: cleanTable.columns, + rows: [...cleanTable.rows, ...injected], + }; + }, + }); + const staleNullLedger = createFakeTrialLedger(); + const staleNullRes = await callAnalyzeSignal({ + store: staleNullStore.store, + ledger: staleNullLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(staleNullRes.isError).toBe(false); + expect(staleNullRes.text).toBe(mcpRes.text); + expect(staleNullLedger.rows).toEqual(mcpLedger.rows); + for (const call of staleNullStore.fundamentalsCalls) { + expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); + expect(call.allowEstimatedLag).toBe(false); + } + + // 7. Genuinely null latest field with allowEstimatedLag: true must still probe earlier + // eligible closes and recover the valid April 5 release. + const nullLatestPitRows: FundamentalsPitFixtureRow[] = pitRows.map(row => + row.effective_known_at === aprEstimatedLagKnownAt ? { ...row, ttm_revenue: null } : row + ); + const nullLatestAllowLagStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(nullLatestPitRows, q), + }); + const nullLatestAllowLagLedger = createFakeTrialLedger(); + const nullLatestAllowLagRes = await callAnalyzeSignal({ + store: nullLatestAllowLagStore.store, + ledger: nullLatestAllowLagLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(nullLatestAllowLagRes.isError).toBe(false); + const nullLatestAllowLagPayload = JSON.parse( + nullLatestAllowLagRes.text + ) as AnalyzeSignalResultPayload; + expect(nullLatestAllowLagPayload.status).toBe('ok'); + if (nullLatestAllowLagPayload.status === 'ok') { + expect(nullLatestAllowLagPayload.analysis.rankIc).toEqual( + directVerifiedStudy.analysis.rankIc + ); + expect(nullLatestAllowLagPayload.analysis.pearsonIc).toEqual( + directVerifiedStudy.analysis.pearsonIc + ); + expect(nullLatestAllowLagLedger.rows[0]?.daily_series).toEqual( + directVerifiedLedger.rows[0]?.daily_series + ); + const recoveredByDate = new Map( + nullLatestAllowLagPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value]) + ); + let recoveredAprilDiffCount = 0; + for (const d of aprilPreEstimatedDates) { + if (recoveredByDate.get(d) !== brokenByDate.get(d)) { + recoveredAprilDiffCount += 1; + } + } + expect(recoveredAprilDiffCount).toBeGreaterThan(0); + } + expect(nullLatestAllowLagStore.fundamentalsCalls.length).toBeGreaterThan(0); + for (const call of nullLatestAllowLagStore.fundamentalsCalls) { + expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); + expect(call.allowEstimatedLag).toBe(true); + } }); test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { From 29b25e3b8e3156c7983f4302b33a94761149bc67 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:01:05 -0500 Subject: [PATCH 12/15] T-149: tests --- ...ze-signal-fundamentals-real-duckdb.test.ts | 522 ++++++++++++++++++ 1 file changed, 522 insertions(+) create mode 100644 libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts diff --git a/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts b/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts new file mode 100644 index 00000000..9cff62f1 --- /dev/null +++ b/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts @@ -0,0 +1,522 @@ +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 type { MarketDataStore } from '@stock-bot/research/market-data-store'; +import type { FundamentalsAsOfQuery } from '@stock-bot/research/market-data-store-duckdb'; +import { createAnalyzeSignalTool, createMcpServer } from '@stock-bot/research/mcp'; +import { type SignalObservation, buildForwardReturnPanel, collectBars } from '@stock-bot/research/signal-panel'; +import { analyzeSignal } from '@stock-bot/research/signal-study'; +import type { TrialLedgerExecutor } from '@stock-bot/research/trial-ledger'; +import { createNodeDuckDbExecutor, openDuckDbMarketDataStore } from '../src/index'; + +// QA end-to-end evidence for T-149: MCP `analyze_signal` (source = fundamentals) +// driven against the REAL DuckDB `fundamentalsAsOf` over Hive Parquet files. +// - Dataset ID: `synthetic:qa-analyze-signal-fundamentals-real-duckdb:seed-20261206:v1` +// - Tool version: `mcp:analyze_signal:v1`; adjustment `raw`; horizon 3 sessions; modeled costs 0 +// - Pre-Vault window 2023-03-01..2023-05-12; Vault cutoff 2023-05-15T00:00:00.000Z +// - Bars: 6 listings (101..106), 20:00 UTC closes; 5 post-cutoff bars must be fenced out. +// - Fundamentals (ttm_revenue), all 13:00 UTC: +// 2023-03-10 verified (101..105), 2023-04-05 verified Q2 (all), +// 2023-04-18 same-month restatement (101..103, verified), +// 2023-04-18 estimated-lag update (104) -> omitted by DuckDB under default lag, +// 2023-04-20 verified row with NULL ttm_revenue (105) -> must not displace 2023-04-05. +// - Baseline: direct `buildForwardReturnPanel` + `analyzeSignal` over independently listed +// expected observations. + +const VAULT_CUTOFF_TS = Date.UTC(2023, 4, 15); +const VAULT_CUTOFF_DATE = '2023-05-15'; +const PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const LISTING_IDS = [101, 102, 103, 104, 105, 106] as const; +const HORIZON = 3; +// Listing with bars but no fundamentals rows at all (sparse coverage probe). +const UNCOVERED_LISTING_ID = 107; +const BAR_LISTING_IDS = [...LISTING_IDS, UNCOVERED_LISTING_ID] as const; + +const tempDirs: string[] = []; + +afterEach(async () => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir !== undefined) { + await rm(dir, { recursive: true, force: true }); + } + } +}); + +function createSeededRng(seed: number): () => number { + let s = seed >>> 0; + return () => { + s = (s + 0x6d2b79f5) >>> 0; + let t = s; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function businessDates(start: string, count: number): string[] { + const out: string[] = []; + const d = new Date(`${start}T00:00:00Z`); + while (out.length < count) { + const dow = d.getUTCDay(); + if (dow !== 0 && dow !== 6) { + out.push(d.toISOString().slice(0, 10)); + } + d.setUTCDate(d.getUTCDate() + 1); + } + return out; +} + +function ms(date: string, hour: number): number { + return Date.parse(`${date}T${String(hour).padStart(2, '0')}:00:00.000Z`); +} + +interface PitRow { + readonly listingId: number; + readonly knownAt: string; // YYYY-MM-DD + readonly hour?: number; // UTC hour, default 13 + readonly ttm: number | null; + readonly estimated?: boolean; +} + +const BASE_PIT_ROWS: readonly PitRow[] = [ + ...[101, 102, 103, 104, 105].map((lid, l) => ({ + listingId: lid, + knownAt: '2023-03-10', + ttm: 200 + ((l * 3) % 5) * 25, + })), + ...LISTING_IDS.map((lid, l) => ({ listingId: lid, knownAt: '2023-04-05', ttm: 100 + l * 40 })), + ...[101, 102, 103].map((lid, l) => ({ listingId: lid, knownAt: '2023-04-18', ttm: 400 - l * 90 })), + { listingId: 104, knownAt: '2023-04-18', ttm: 999, estimated: true }, + { listingId: 105, knownAt: '2023-04-20', ttm: null }, +]; + +function pitRowSql(r: PitRow): string { + const est = r.estimated === true ? 'TRUE' : 'FALSE'; + const ttm = r.ttm === null ? 'NULL::DOUBLE' : `${r.ttm}::DOUBLE`; + const ttmMeta = + r.ttm === null ? 'NULL::DATE, NULL::VARCHAR' : `DATE '2023-03-31', 'USD'::VARCHAR`; + const ts = `${r.knownAt} ${String(r.hour ?? 13).padStart(2, '0')}:00:00+00`; + return `(${r.listingId}::INTEGER, TIMESTAMPTZ '${ts}', 'filing_date'::VARCHAR, ${est}::BOOLEAN, + DATE '2023-03-31', 'Q1'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${ts}', + 1.0::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, + ${ttmMeta}, ${ttm}, NULL::DOUBLE, NULL::DOUBLE, ${est}::BOOLEAN)`; +} + +async function writeCurated( + curatedRoot: string, + pitPartitions: Readonly> +): Promise { + const rand = createSeededRng(20261206); + const dates = businessDates('2023-03-01', 58); // 53 pre-cutoff + 5 Vault sessions + const prices = BAR_LISTING_IDS.map(() => 40); + const barValues: string[] = []; + for (const date of dates) { + for (let l = 0; l < BAR_LISTING_IDS.length; l += 1) { + const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(6)); + const ts = `TIMESTAMPTZ '${date} 20:00:00+00'`; + barValues.push( + `(${BAR_LISTING_IDS[l]}::INTEGER, DATE '${date}', ${ts}, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, 50000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, ${ts})` + ); + } + } + + await mkdir(join(curatedRoot, 'bars_1d', 'year=2023'), { recursive: true }); + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES ${barValues.join(', ')}) + AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) + ) TO '${join(curatedRoot, 'bars_1d', 'year=2023', 'part.parquet')}' (FORMAT PARQUET) + `); + for (const [year, rows] of Object.entries(pitPartitions)) { + const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`); + await mkdir(dir, { recursive: true }); + await writer.run(` + COPY ( + SELECT * FROM (VALUES ${rows.map(pitRowSql).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(); + } +} + +interface LedgerRow { + readonly trial_id: string; + readonly created_at: Date; + readonly principal_id: string; + readonly campaign_id: string | null; + readonly stage: string; + readonly universe_market: string; + readonly horizon_bucket: string; + readonly hypothesis_id: string | null; + readonly expression_hash: string; + readonly sample_start: string; + readonly sample_end: string; + readonly n_obs: number; + readonly sharpe_unann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly daily_series: number[]; +} + +// Deterministic in-memory trial_ledger port (fixed created_at, sequential ids). +function createLedger(): { executor: TrialLedgerExecutor; rows: LedgerRow[] } { + const rows: LedgerRow[] = []; + let nextId = 1; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + const p = params ?? []; + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + const id = nextId++; + const row: LedgerRow = { + trial_id: String(id), + created_at: new Date(Date.UTC(2024, 0, 1, 0, 0, id)), + principal_id: p[0] as string, + campaign_id: (p[1] as string | null) ?? null, + stage: p[2] as string, + universe_market: p[3] as string, + horizon_bucket: p[4] as string, + hypothesis_id: (p[5] as string | null) ?? null, + expression_hash: p[6] as string, + sample_start: p[7] as string, + sample_end: p[8] as string, + n_obs: p[9] as number, + sharpe_unann: p[10] as number, + skewness: p[11] as number, + kurtosis: p[12] as number, + daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)), + }; + rows.push(row); + return { + rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row], + rowCount: 1, + }; + } + if (trimmed.startsWith('SELECT')) { + if (text.includes('WHERE trial_id = $1::bigint')) { + const matched = rows.filter(r => r.trial_id === String(p[0])); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const matched = rows.filter( + r => r.universe_market === p[0] && r.horizon_bucket === p[1] + ); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + } + return { rows: [], rowCount: 0 }; + }, + }; + return { executor, rows }; +} + +async function openStore( + pitPartitions: Readonly> +): Promise<{ + store: MarketDataStore; + calls: FundamentalsAsOfQuery[]; + close: () => Promise; +}> { + const root = await mkdtemp(join(tmpdir(), 'stockbot-qa-as-fnd-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(duckTempDir, { recursive: true }); + await writeCurated(curatedRoot, pitPartitions); + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs: VAULT_CUTOFF_TS, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '1GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + const calls: FundamentalsAsOfQuery[] = []; + const inner = opened.store; + const store: MarketDataStore = { + ...inner, + bars: q => inner.bars(q), + shortsAsOf: q => inner.shortsAsOf(q), + universe: q => inner.universe(q), + fundamentalsAsOf: q => { + calls.push(q); + return inner.fundamentalsAsOf(q); + }, + }; + return { store, calls, close: () => opened.close() }; +} + +async function runTool( + store: MarketDataStore, + ledger: TrialLedgerExecutor, + allowEstimatedLag?: boolean, + listingIds: readonly number[] = LISTING_IDS +): Promise<{ isError: boolean; text: string }> { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createAnalyzeSignalTool({ + store, + ledger, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + principalId: PRINCIPAL, + }), + ], + }); + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'qa-1', + method: 'tools/call', + params: { + name: 'analyze_signal', + arguments: { + listingIds: [...listingIds], + from: '2023-03-01', + to: '2023-05-19', // straddles the Vault cutoff; must be clamped + signal: { + source: 'fundamentals', + field: 'ttm_revenue', + ...(allowEstimatedLag === undefined ? {} : { allowEstimatedLag }), + }, + horizonSessions: HORIZON, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }, + }) + ); + const parsed = JSON.parse(raw as string) as { + result: { isError?: boolean; content: { text: string }[] }; + }; + return { isError: parsed.result.isError === true, text: parsed.result.content[0]?.text ?? '' }; +} + +function expectedObservations( + includeEstimated: boolean, + rows: readonly PitRow[] = BASE_PIT_ROWS +): SignalObservation[] { + const out: SignalObservation[] = []; + for (const r of rows) { + if (r.ttm === null || (r.estimated === true && !includeEstimated)) { + continue; + } + out.push({ listingId: r.listingId, knownAt: ms(r.knownAt, r.hour ?? 13), value: r.ttm }); + } + return out; +} + +async function directBaseline( + store: MarketDataStore, + signals: SignalObservation[], + listingIds: readonly number[] = LISTING_IDS +): Promise<{ rankIc: unknown; series: number[]; sampleStart: string; sampleEnd: string }> { + const bars = await collectBars(store.bars({ + listingIds: [...listingIds], + from: '2023-03-01', + to: '2023-05-12', + timeframe: '1d', + adjustment: 'raw', + })); + const built = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: HORIZON, + vaultCutoffDate: VAULT_CUTOFF_DATE, + }); + const ledger = createLedger(); + const study = await analyzeSignal(ledger.executor, { + principalId: PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'qa_direct_baseline', + params: { field: 'ttm_revenue' }, + universe: [...listingIds], + horizon: `${HORIZON}d`, + }, + panel: built.panel, + vaultCutoffDate: VAULT_CUTOFF_DATE, + }); + if (study.status !== 'ok') { + throw new Error(`baseline study not ok: ${study.status}`); + } + return { + rankIc: study.analysis.rankIc, + series: ledger.rows[0]!.daily_series, + sampleStart: study.trial.sampleStart, + sampleEnd: study.trial.sampleEnd, + }; +} + +interface OkPayload { + status: 'ok'; + signal: unknown; + analysis: { rankIc: unknown }; + trial: { sampleStart: string; sampleEnd: string; expressionHash: string }; +} + +describe('analyze_signal fundamentals over real DuckDB fundamentalsAsOf (QA)', () => { + test('default lag: same-month restatement, estimated-lag omission and null-field rows replay exactly like the verified-only baseline', async () => { + const s = await openStore({ '2023': BASE_PIT_ROWS }); + try { + const ledger = createLedger(); + const res = await runTool(s.store, ledger.executor); + expect(res.isError).toBe(false); + const payload = JSON.parse(res.text) as OkPayload; + expect(payload.status).toBe('ok'); + expect(payload.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: false, + }); + + const baseline = await directBaseline(s.store, expectedObservations(false)); + expect(payload.analysis.rankIc).toEqual(baseline.rankIc); + expect(ledger.rows).toHaveLength(1); + expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); + expect(payload.trial.sampleStart).toBe(baseline.sampleStart); + expect(payload.trial.sampleEnd).toBe(baseline.sampleEnd); + expect(payload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); + + // Every real-store read is strictly pre-Vault and forwards the lag flag verbatim. + expect(s.calls.length).toBeGreaterThan(0); + for (const call of s.calls) { + expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS); + expect(call.allowEstimatedLag).toBe(false); + expect(call.fields).toEqual(['ttm_revenue']); + } + // Fan-out bound: month-end snapshots (3) + at most one probe per eligible session (53). + expect(s.calls.length).toBeLessThanOrEqual(3 + 53); + } finally { + await s.close(); + } + }); + + test('allowEstimatedLag true includes the estimated update and matches its own baseline', async () => { + const s = await openStore({ '2023': BASE_PIT_ROWS }); + try { + const ledger = createLedger(); + const res = await runTool(s.store, ledger.executor, true); + const payload = JSON.parse(res.text) as OkPayload; + expect(payload.status).toBe('ok'); + const baseline = await directBaseline(s.store, expectedObservations(true)); + expect(payload.analysis.rankIc).toEqual(baseline.rankIc); + expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); + expect(s.calls.every(c => c.allowEstimatedLag === true)).toBe(true); + + const defaultLedger = createLedger(); + const defaultRes = await runTool(s.store, defaultLedger.executor); + const defaultPayload = JSON.parse(defaultRes.text) as OkPayload; + expect(defaultPayload.trial.expressionHash).not.toBe(payload.trial.expressionHash); + expect(defaultLedger.rows[0]!.daily_series).not.toEqual(ledger.rows[0]!.daily_series); + } finally { + await s.close(); + } + }); + + test('appending Vault-window and post-cutoff revisions in another Parquet partition leaves payload and ledger rows byte-identical', async () => { + const clean = await openStore({ '2023': BASE_PIT_ROWS }); + const poisoned = await openStore({ + '2023': BASE_PIT_ROWS, + '2099': [ + // Exactly at the Vault cutoff, inside the Vault, and long after. + ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-15', ttm: 5_000 + lid })), + ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-17', ttm: 7_000 - lid })), + ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2024-01-02', ttm: 9_000 + lid })), + ], + }); + try { + const cleanLedger = createLedger(); + const poisonedLedger = createLedger(); + const cleanRes = await runTool(clean.store, cleanLedger.executor); + const poisonedRes = await runTool(poisoned.store, poisonedLedger.executor); + expect(cleanRes.isError).toBe(false); + expect(poisonedRes.text).toBe(cleanRes.text); + expect(poisonedLedger.rows).toEqual(cleanLedger.rows); + expect(poisoned.calls.map(c => c.asOf)).toEqual(clean.calls.map(c => c.asOf)); + } finally { + await clean.close(); + await poisoned.close(); + } + }); + + test('a release stamped exactly at a bar close and superseded next morning is replayed at that close', async () => { + // 106 files at 2023-04-12 20:00:00Z (== bar close ts) and restates at 2023-04-13 13:00Z. + // A month-end-only read would only see the 04-13 vintage; the 04-12 close must use 50. + const rows: readonly PitRow[] = [ + ...BASE_PIT_ROWS, + { listingId: 106, knownAt: '2023-04-12', hour: 20, ttm: 50 }, + { listingId: 106, knownAt: '2023-04-13', ttm: 900 }, + ]; + const s = await openStore({ '2023': rows }); + try { + const ledger = createLedger(); + const res = await runTool(s.store, ledger.executor); + const payload = JSON.parse(res.text) as OkPayload; + expect(payload.status).toBe('ok'); + const baseline = await directBaseline(s.store, expectedObservations(false, rows)); + expect(payload.analysis.rankIc).toEqual(baseline.rankIc); + expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); + // Probe at the exact close timestamp is issued (store compares effective_known_at <= asOf). + expect(s.calls.some(c => Date.parse(c.asOf) === ms('2023-04-12', 20))).toBe(true); + } finally { + await s.close(); + } + }); + + test('sparse coverage: a listing with bars but no fundamentals stays bounded and does not change the study', async () => { + // Measurement for the reviewer's non-blocking fan-out note. The uncovered listing is + // probed at each eligible session, so calls grow with sessions, not with listings. + const covered = await openStore({ '2023': BASE_PIT_ROWS }); + const sparse = await openStore({ '2023': BASE_PIT_ROWS }); + try { + const coveredLedger = createLedger(); + const sparseLedger = createLedger(); + const coveredRes = await runTool(covered.store, coveredLedger.executor); + const sparseRes = await runTool(sparse.store, sparseLedger.executor, undefined, [ + ...LISTING_IDS, + UNCOVERED_LISTING_ID, + ]); + const coveredPayload = JSON.parse(coveredRes.text) as OkPayload; + const sparsePayload = JSON.parse(sparseRes.text) as OkPayload; + expect(coveredPayload.status).toBe('ok'); + expect(sparsePayload.status).toBe('ok'); + + // No signal for 107 -> same cross-sectional series as the covered-only study. + const baseline = await directBaseline(sparse.store, expectedObservations(false), [ + ...LISTING_IDS, + UNCOVERED_LISTING_ID, + ]); + expect(sparseLedger.rows[0]!.daily_series).toEqual(baseline.series); + + // 53 eligible sessions over 3 UTC months: <= 3 month-end snapshots + 53 probes. + expect(sparse.calls.length).toBeLessThanOrEqual(3 + 53); + expect(sparse.calls.length).toBeGreaterThan(covered.calls.length); + // Each session timestamp is probed at most once. + const asOfs = sparse.calls.map(c => c.asOf); + expect(new Set(asOfs).size).toBe(asOfs.length); + for (const call of sparse.calls) { + expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS); + } + } finally { + await covered.close(); + await sparse.close(); + } + }); +}); From 5e5b0d1d40f99a54d81ccce4d2577708d5d539a3 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:14:04 -0500 Subject: [PATCH 13/15] =?UTF-8?q?T-152:=20M2.3j=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20`qmIntraday`=20=E2=86=92=20`bars=5F1m`=20curat?= =?UTF-8?q?ion=20stage=20(raw=20bars,=20no=20split=20un-adjustment=20?= =?UTF-8?q?=E2=86=92=20`provider=5Fmapping`=20=E2=86=92=20`Bar1mRow`?= =?UTF-8?q?=20=E2=86=92=20`IlpShardedWriter`)=20with=20tests=20(no=20new?= =?UTF-8?q?=20crates,=20no=20CLI/bench=20changes,=20no=20live=20Mongo/Ques?= =?UTF-8?q?tDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/bars_1m.rs | 3 + tools/curate-etl/src/bson_stream.rs | 63 ++ tools/curate-etl/src/bson_stream_tests.rs | 190 +++++- tools/curate-etl/src/curate_bars_1m.rs | 78 ++- tools/curate-etl/src/curate_qm_bars_1m.rs | 206 ++++++ .../curate-etl/src/curate_qm_bars_1m_tests.rs | 605 ++++++++++++++++++ tools/curate-etl/src/lib.rs | 21 +- 7 files changed, 1127 insertions(+), 39 deletions(-) create mode 100644 tools/curate-etl/src/curate_qm_bars_1m.rs create mode 100644 tools/curate-etl/src/curate_qm_bars_1m_tests.rs diff --git a/tools/curate-etl/src/bars_1m.rs b/tools/curate-etl/src/bars_1m.rs index d4d603cd..88d2ad9d 100644 --- a/tools/curate-etl/src/bars_1m.rs +++ b/tools/curate-etl/src/bars_1m.rs @@ -32,6 +32,9 @@ use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable}; /// Canonical provenance label written to [`Bar1mRow::source`] for un-adjusted `eodIntraday1M` bars. pub const BARS_1M_SOURCE_EOD: &str = "eod_unadj"; +/// Canonical provenance label written to [`Bar1mRow::source`] for raw `qmIntraday` bars. +pub const BARS_1M_SOURCE_QM: &str = "qm_raw"; + /// Regular Trading Hours start minute in Eastern Time (`09:30 ET` = `570`). pub const RTH_START_MINUTE_ET: u16 = 9 * 60 + 30; diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs index df36a1bf..be7c201a 100644 --- a/tools/curate-etl/src/bson_stream.rs +++ b/tools/curate-etl/src/bson_stream.rs @@ -40,6 +40,9 @@ use crate::bson_qm_events::{ BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames, RawQmEarning, RawQmFiling, }; +use crate::bson_qm_intraday::{ + decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, RawQmIntradayBar, +}; use crate::bson_qm_prices::{ decode_qm_price_buffer, BsonQmPriceDecodeStats, BsonQmPriceError, RawQmPrice, }; @@ -613,6 +616,66 @@ where decode_eod_intraday_chunks(&mut chunk_reader, on_bar, on_error) } +#[inline] +fn rebase_qm_intraday_error(base: u64, err: BsonQmIntradayError) -> BsonQmIntradayError { + match err { + BsonQmIntradayError::CorruptBson { offset, detail } => BsonQmIntradayError::CorruptBson { + offset: rebase_offset(base, offset), + detail, + }, + other => other, + } +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_intraday_buffer`], +/// accumulating [`BsonQmIntradayDecodeStats`] and rebasing per-document error offsets to +/// absolute stream byte offsets. +pub fn decode_qm_intraday_chunks( + reader: &mut RawBsonChunkReader, + mut on_bar: F, + mut on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmIntradayBar<'a>), + E: FnMut(u64, BsonQmIntradayError), +{ + let mut total = BsonQmIntradayDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_qm_intraday_buffer( + chunk.bytes, + &mut on_bar, + |local_offset, err| { + let abs_offset = base + local_offset as u64; + on_error(abs_offset, rebase_qm_intraday_error(base, err)); + }, + ); + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `qmIntraday` [`std::io::Read`] source through +/// [`decode_qm_intraday_buffer`] with bounded memory. +/// +/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset +/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`. +pub fn decode_qm_intraday_stream( + reader: R, + options: BsonStreamOptions, + on_bar: F, + on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmIntradayBar<'a>), + E: FnMut(u64, BsonQmIntradayError), +{ + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_qm_intraday_chunks(&mut chunk_reader, on_bar, on_error) +} + /// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_price_buffer`], /// accumulating [`BsonEodDecodeStats`] and rebasing per-document error offsets to absolute stream /// byte offsets. diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs index 5e05e142..1ca61802 100644 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -13,12 +13,15 @@ use crate::bson_eod_prices::{ use crate::bson_qm_actions::{ decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, }; +use crate::bson_qm_intraday::{ + decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, +}; use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError}; use crate::bson_stream::{ decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_stream, - decode_qm_dividend_stream, decode_qm_price_stream, decode_qm_split_stream, BsonStreamError, - BsonStreamOptions, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, - MIN_BSON_DOC_BYTES, + decode_qm_dividend_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream, + decode_qm_price_stream, decode_qm_split_stream, BsonStreamError, BsonStreamOptions, + RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, }; #[derive(Debug, Clone, Copy)] @@ -2278,3 +2281,184 @@ fn decode_eod_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() { } if offset == trunc_offset )); } + +#[test] +fn decode_qm_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() { + let make_doc = |code: &str, ts_ms: i64, open: f64, close: f64, vol: f64| -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), DateTime::from_millis(ts_ms)); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), open.max(close) + 0.5); + doc.append(cstr!("low"), open.min(close) - 0.5); + doc.append(cstr!("close"), close); + doc.append(cstr!("sharevolume"), vol); + // Include adjusted fields that must be validated and ignored. + doc.append(cstr!("adjustedopen"), open / 10.0); + doc.append(cstr!("adjustedclose"), close / 10.0); + doc.append(cstr!("avolume"), vol * 10.0); + doc.into_bytes() + }; + + // Empty input returns zeroed stats with zero callbacks. + { + let mut empty_rows = 0usize; + let mut empty_errs = 0usize; + let stats = decode_qm_intraday_stream( + Cursor::new(Vec::::new()), + BsonStreamOptions::default(), + |_| empty_rows += 1, + |_, _| empty_errs += 1, + ) + .unwrap(); + assert_eq!(stats, BsonQmIntradayDecodeStats::default()); + assert_eq!(empty_rows, 0); + assert_eq!(empty_errs, 0); + } + + let mut fixture = Vec::new(); + fixture.extend_from_slice(&make_doc("NVDA", 1_717_767_000_000, 1200.0, 1205.0, 1_000.0)); + fixture.extend_from_slice(&make_doc("AAPL", 1_717_767_060_000, 195.0, 195.25, 0.0)); + + // Semantic error: invalid timestamp (negative DateTime millis). + let bad_ts_offset = fixture.len() as u64; + fixture.extend_from_slice(&make_doc("NVDA", -60_000, 1200.0, 1205.0, 100.0)); + + // Valid length-framed doc with corrupt trailing terminator -> CorruptBson with embedded offset. + let mut corrupt_bytes = make_doc("MSFT", 1_717_767_120_000, 420.0, 421.0, 500.0); + *corrupt_bytes.last_mut().unwrap() = 0xEE; + let corrupt_offset = fixture.len() as u64; + fixture.extend_from_slice(&corrupt_bytes); + + fixture.extend_from_slice(&make_doc("SHOP:CA", 1_717_767_180_000, 88.0, 88.4, 2_500.0)); + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_qm_intraday_buffer( + &fixture, + |b| { + expected_rows.push(( + b.qm_search_code.to_owned(), + b.ts, + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + b.volume.to_bits(), + )) + }, + |off, err| expected_errs.push((off as u64, err)), + ); + assert_eq!(expected_stats.docs_seen, 5); + assert_eq!(expected_stats.rows_decoded, 3); + assert_eq!(expected_stats.rejected_invalid_timestamp, 1); + assert_eq!(expected_stats.rejected_corrupt_document, 1); + assert_eq!(expected_stats.rejected_total(), 2); + + // Exercise decode_qm_intraday_stream across small capacities and short reads splitting + // length prefixes and document bodies. + for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (512, 13)] { + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: 4096, + }; + let mut got_rows = Vec::new(); + let mut got_errs = Vec::new(); + let got_stats = decode_qm_intraday_stream( + FixedStepReader::new(&fixture, step), + opts, + |b| { + got_rows.push(( + b.qm_search_code.to_owned(), + b.ts, + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + b.volume.to_bits(), + )) + }, + |off, err| got_errs.push((off, err)), + ) + .unwrap(); + + assert_eq!(got_stats, expected_stats); + assert_eq!(got_rows, expected_rows); + assert_eq!(got_errs, expected_errs); + assert_eq!(got_errs[0].0, bad_ts_offset); + assert!(matches!( + got_errs[1], + (off, BsonQmIntradayError::CorruptBson { offset, .. }) + if off == corrupt_offset && offset as u64 == corrupt_offset + )); + } + + // Exercise decode_qm_intraday_chunks directly with random read sizes and EINTR interrupts. + let opts = BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes: 4096, + }; + let mut chunk_reader = + RawBsonChunkReader::with_options(RandomInterruptReader::new(&fixture, 0x152, true), opts) + .unwrap(); + let mut chunk_rows = Vec::new(); + let mut chunk_errs = Vec::new(); + let chunk_stats = decode_qm_intraday_chunks( + &mut chunk_reader, + |b| { + chunk_rows.push(( + b.qm_search_code.to_owned(), + b.ts, + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + b.volume.to_bits(), + )) + }, + |off, err| chunk_errs.push((off, err)), + ) + .unwrap(); + assert_eq!(chunk_stats, expected_stats); + assert_eq!(chunk_rows, expected_rows); + assert_eq!(chunk_errs, expected_errs); + + // Truncated trailing document must deliver the complete prefix first and then return + // BsonStreamError::TruncatedDocument at the exact tail offset. + let mut truncated = fixture.clone(); + let trunc_offset = truncated.len() as u64; + truncated.extend_from_slice(&120_i32.to_le_bytes()); + truncated.extend_from_slice(&[0x02, b'a', 0x00]); + let mut prefix_rows = Vec::new(); + let mut prefix_errs = Vec::new(); + let err = decode_qm_intraday_stream( + FixedStepReader::new(&truncated, 5), + BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes: 4096, + }, + |b| { + prefix_rows.push(( + b.qm_search_code.to_owned(), + b.ts, + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + b.volume.to_bits(), + )) + }, + |off, e| prefix_errs.push((off, e)), + ) + .unwrap_err(); + assert_eq!(prefix_rows, expected_rows); + assert_eq!(prefix_errs, expected_errs); + assert!(matches!( + err, + BsonStreamError::TruncatedDocument { + offset, + remaining: 7, + declared_len: Some(120), + } if offset == trunc_offset + )); +} diff --git a/tools/curate-etl/src/curate_bars_1m.rs b/tools/curate-etl/src/curate_bars_1m.rs index 7ca5af9e..849ebbc7 100644 --- a/tools/curate-etl/src/curate_bars_1m.rs +++ b/tools/curate-etl/src/curate_bars_1m.rs @@ -25,8 +25,9 @@ use std::io::{self, Write}; use crate::bars::Bar1dRow; use crate::bars_1m::{ - build_bars_1m, check_session_closes_against_bars_1d, Bar1mRow, Bars1mError, Bars1mStats, - EodIntradayBar, IntradaySession, SessionCloseCheck, SessionCloseCutoffPolicy, + build_bars_1m, check_session_closes_against_bars_1d, Bar1mRow, Bars1mBuild, Bars1mError, + Bars1mStats, EodIntradayBar, IntradaySession, SessionCloseCheck, SessionCloseCutoffPolicy, + BARS_1M_SOURCE_EOD, }; use crate::bson_eod_intraday::BsonEodIntradayDecodeStats; use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; @@ -184,35 +185,18 @@ fn bar_1m_values_bit_eq(a: &Bar1mRow, b: &Bar1mRow) -> bool { && a.session == b.session } -/// Pure `bars_1m` curation stage: un-adjusts source-keyed `eodIntraday1M` bars via -/// [`build_bars_1m`], resolves `(mapping_source, source_id, session_date) -> listing_id` through -/// `provider_mapping` using each bar's Eastern Time `session_date`, and emits [`Bar1mRow`] -/// rows sorted and unique by `(listing_id, ts)`. -/// -/// - Rejects empty or whitespace-only `mapping_source` with [`CurateBars1mError::EmptyMappingSource`]. -/// Non-blank `mapping_source` values are looked up verbatim. -/// - Rows whose `(mapping_source, source_id, session_date)` is not covered by any range in -/// `provider_mapping` are counted in [`CurateBars1mStats::dropped_unmapped`]. -/// - After re-sorting in place by `(listing_id, ts)`, cross-`source_id` collisions on the same -/// `(listing_id, ts)` collapse to one row when OHLCV (bitwise) and `session` match -/// (`listing_collision_collapsed += g - 1`), and drop the entire group otherwise -/// (`listing_collision_dropped += g`). -pub fn curate_bars_1m( - bars: B, - splits: &SplitTable, +/// Maps source-keyed [`Bars1mBuild`] rows to permanent `listing_id: i32` keys via +/// `provider_mapping` on each bar's Eastern Time `session_date`, stamps `source`, re-sorts in +/// place by `(listing_id, ts)`, and compacts cross-`source_id` collisions. +pub(crate) fn map_bars_1m( + built: Bars1mBuild, provider_mapping: &ProviderMappingTable, mapping_source: &str, -) -> Result + source: &'static str, +) -> CurateBars1mOutput where - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, + K: Eq + AsRef, { - if mapping_source.trim().is_empty() { - return Err(CurateBars1mError::EmptyMappingSource); - } - - let built = build_bars_1m(bars, splits); - let mut stats = CurateBars1mStats { builder: built.stats, rows_in: built.rows.len(), @@ -254,7 +238,7 @@ where close: bar.close, volume: bar.volume, session: bar.session, - source: bar.source, + source, }); } } @@ -319,7 +303,43 @@ where rows.truncate(write_idx); stats.rows_out = rows.len(); - Ok(CurateBars1mOutput { rows, stats }) + CurateBars1mOutput { rows, stats } +} + +/// Pure `bars_1m` curation stage: un-adjusts source-keyed `eodIntraday1M` bars via +/// [`build_bars_1m`], resolves `(mapping_source, source_id, session_date) -> listing_id` through +/// `provider_mapping` using each bar's Eastern Time `session_date`, and emits [`Bar1mRow`] +/// rows sorted and unique by `(listing_id, ts)`. +/// +/// - Rejects empty or whitespace-only `mapping_source` with [`CurateBars1mError::EmptyMappingSource`]. +/// Non-blank `mapping_source` values are looked up verbatim. +/// - Rows whose `(mapping_source, source_id, session_date)` is not covered by any range in +/// `provider_mapping` are counted in [`CurateBars1mStats::dropped_unmapped`]. +/// - After re-sorting in place by `(listing_id, ts)`, cross-`source_id` collisions on the same +/// `(listing_id, ts)` collapse to one row when OHLCV (bitwise) and `session` match +/// (`listing_collision_collapsed += g - 1`), and drop the entire group otherwise +/// (`listing_collision_dropped += g`). +pub fn curate_bars_1m( + bars: B, + splits: &SplitTable, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, +) -> Result +where + K: Ord + Eq + Hash + Clone + AsRef, + B: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CurateBars1mError::EmptyMappingSource); + } + + let built = build_bars_1m(bars, splits); + Ok(map_bars_1m( + built, + provider_mapping, + mapping_source, + BARS_1M_SOURCE_EOD, + )) } /// Thin wrapper running [`check_session_closes_against_bars_1d`] over `listing_id`-keyed curated diff --git a/tools/curate-etl/src/curate_qm_bars_1m.rs b/tools/curate-etl/src/curate_qm_bars_1m.rs new file mode 100644 index 00000000..19fb6e0c --- /dev/null +++ b/tools/curate-etl/src/curate_qm_bars_1m.rs @@ -0,0 +1,206 @@ +//! Pure, in-memory `bars_1m` curation stage for raw QuoteMedia `qmIntraday` bars (`M2.3j`), +//! joining [`crate::bars_1m::build_bars_1m`], [`crate::provider_mapping::ProviderMappingTable`], +//! [`crate::ilp::IlpShardedWriter`], and [`crate::bson_stream::decode_qm_intraday_stream`]. +//! +//! # Contract & Point-in-Time Rules +//! - Uses [`EodIntradayBar`] as the existing source-keyed carrier for canonical raw QuoteMedia +//! OHLCV and `qmSearchCode`. +//! - **No split un-adjustment:** `qmIntraday` raw fields (`open`, `high`, `low`, `close`, +//! `sharevolume`) are already un-adjusted (`design/DATA-CONTRACTS.md` §1). This stage takes no +//! [`SplitTable`] and invokes [`build_bars_1m`] with an internal empty [`SplitTable`] so valid +//! OHLCV values pass through bit-identical while reusing Eastern Time session tagging, OHLCV +//! validation, and same-key deduplication. +//! - **Signed-zero volume normalization:** [`crate::bson_qm_intraday::decode_qm_intraday_doc`] +//! normalizes `-0.0` `sharevolume` to `+0.0` during BSON decode, and [`build_bars_1m`] applies +//! the same `-0.0 -> +0.0` normalization for direct in-memory inputs. +//! - Resolves each built row's `(mapping_source, qmSearchCode, session_date)` to a permanent +//! `listing_id: i32` on its Eastern Time `session_date`, stamps [`BARS_1M_SOURCE_QM`] +//! (`"qm_raw"`), re-sorts in place by `(listing_id, ts)`, and compacts cross-`source_id` +//! collisions using the same bitwise-equality / conflict-drop rule as [`crate::curate_bars_1m`]. +//! - Writes sorted `Bar1mRow` rows into a caller-owned [`IlpShardedWriter`] without calling +//! [`IlpShardedWriter::finish`], allowing multiple chunks to stream through one writer. + +use std::error::Error; +use std::fmt; +use std::hash::Hash; +use std::io::{self, Write}; + +use crate::bars_1m::{build_bars_1m, EodIntradayBar, BARS_1M_SOURCE_QM}; +use crate::bson_qm_intraday::BsonQmIntradayDecodeStats; +use crate::bson_stream::{decode_qm_intraday_stream, BsonStreamError, BsonStreamOptions}; +use crate::curate_bars_1m::{ + map_bars_1m, CurateBars1mError, CurateBars1mOutput, CurateBars1mWriteError, + CurateBars1mWriteReport, +}; +use crate::ilp::IlpShardedWriter; +use crate::provider_mapping::ProviderMappingTable; +use crate::split::SplitTable; + +/// Combined decode and write summary returned by [`curate_and_write_qm_bars_1m_from_bson`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateQmBars1mBsonReport { + pub decode_stats: BsonQmIntradayDecodeStats, + pub write_report: CurateBars1mWriteReport, +} + +/// Typed error returned by [`curate_and_write_qm_bars_1m_from_bson`]. +#[derive(Debug)] +pub enum CurateQmBars1mBsonError { + Stream(BsonStreamError), + Write(CurateBars1mWriteError), +} + +impl fmt::Display for CurateQmBars1mBsonError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Stream(err) => write!(f, "qmIntraday bars_1m BSON stream failed: {err}"), + Self::Write(err) => write!(f, "{err}"), + } + } +} + +impl Error for CurateQmBars1mBsonError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Stream(err) => Some(err), + Self::Write(err) => Some(err), + } + } +} + +impl From for CurateQmBars1mBsonError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From for CurateQmBars1mBsonError { + fn from(err: CurateBars1mWriteError) -> Self { + Self::Write(err) + } +} + +/// Pure `qmIntraday` -> `bars_1m` curation stage: validates, session-tags, and deduplicates +/// already-raw QuoteMedia 1-minute bars via [`build_bars_1m`] with an internal empty +/// [`SplitTable`] (no split un-adjustment), resolves +/// `(mapping_source, qmSearchCode, session_date) -> listing_id` on each bar's Eastern Time +/// `session_date`, stamps [`BARS_1M_SOURCE_QM`], and emits [`crate::bars_1m::Bar1mRow`] rows +/// sorted and unique by `(listing_id, ts)`. +/// +/// - Rejects empty or whitespace-only `mapping_source` with [`CurateBars1mError::EmptyMappingSource`] +/// before consuming `bars`. Non-blank `mapping_source` values are looked up verbatim. +/// - Accepts no [`SplitTable`]: raw `qmIntraday` OHLCV passes through bit-identical (aside from +/// `-0.0 -> +0.0` volume normalization). +/// - Shares [`CurateBars1mOutput`], [`crate::curate_bars_1m::CurateBars1mStats`], and +/// [`CurateBars1mError`] with [`crate::curate_bars_1m::curate_bars_1m`]. +pub fn curate_qm_bars_1m( + bars: B, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, +) -> Result +where + K: Ord + Eq + Hash + Clone + AsRef, + B: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CurateBars1mError::EmptyMappingSource); + } + + let empty_splits = SplitTable::::default(); + let built = build_bars_1m(bars, &empty_splits); + Ok(map_bars_1m( + built, + provider_mapping, + mapping_source, + BARS_1M_SOURCE_QM, + )) +} + +/// Runs [`curate_qm_bars_1m`] and streams every curated row in `(listing_id, ts)` order into the +/// caller-owned [`IlpShardedWriter`] using `known_at_micros`. +/// +/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple +/// chunks through a single writer before flushing and collecting aggregate +/// [`crate::ilp::IlpWriteStats`]. +pub fn curate_and_write_qm_bars_1m( + bars: B, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, + writer: &mut IlpShardedWriter, + known_at_micros: i64, +) -> Result +where + W: Write + Send, + K: Ord + Eq + Hash + Clone + AsRef, + B: IntoIterator>, +{ + let curated = curate_qm_bars_1m(bars, provider_mapping, mapping_source)?; + let mut rows_written = 0usize; + for row in &curated.rows { + writer.write_bar_1m(row, known_at_micros)?; + rows_written += 1; + } + + Ok(CurateBars1mWriteReport { + curate_stats: curated.stats, + rows_written, + }) +} + +/// Decodes a concatenated raw BSON `qmIntraday` stream via [`decode_qm_intraday_stream`], +/// converts each valid document via +/// [`crate::bson_qm_intraday::RawQmIntradayBar::into_eod_intraday_bar`], and runs +/// [`curate_and_write_qm_bars_1m`] against the caller-owned [`IlpShardedWriter`]. +/// +/// - Rejects empty or whitespace-only `mapping_source` before reading `reader` or writing to +/// `writer`. +/// - Per-document semantic decode errors are counted and skipped in [`BsonQmIntradayDecodeStats`]; +/// fatal stream framing or I/O errors abort before any row from this call is written to `writer`. +/// +/// # Memory note +/// This helper buffers all decoded [`EodIntradayBar`] rows for a single call in memory +/// before curating and writing. Bounded chunking by listing or calendar month is handled by +/// higher-level runner stages. +pub fn curate_and_write_qm_bars_1m_from_bson( + reader: R, + options: BsonStreamOptions, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, + writer: &mut IlpShardedWriter, + known_at_micros: i64, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + if mapping_source.trim().is_empty() { + return Err(CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource).into()); + } + + let mut bars: Vec> = Vec::new(); + let decode_stats = decode_qm_intraday_stream( + reader, + options, + |raw| { + bars.push(raw.into_eod_intraday_bar(|code, _| code.to_owned())); + }, + |_offset, _err| {}, + )?; + + let write_report = curate_and_write_qm_bars_1m( + bars, + provider_mapping, + mapping_source, + writer, + known_at_micros, + )?; + + Ok(CurateQmBars1mBsonReport { + decode_stats, + write_report, + }) +} + +#[cfg(test)] +#[path = "curate_qm_bars_1m_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_qm_bars_1m_tests.rs b/tools/curate-etl/src/curate_qm_bars_1m_tests.rs new file mode 100644 index 00000000..1812141c --- /dev/null +++ b/tools/curate-etl/src/curate_qm_bars_1m_tests.rs @@ -0,0 +1,605 @@ +use std::error::Error; +use std::io::{self, Cursor, Read}; + +use bson::raw::{cstr, RawDocumentBuf}; +use bson::DateTime; + +use super::*; +use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM}; +use crate::bson_qm_intraday::decode_qm_intraday_bytes; +use crate::curate_bars_1m::curate_bars_1m; +use crate::ilp::{encode_bar_1m, shard_for_listing_id, IlpWriterOptions, TABLE_BARS_1M}; +use crate::provider_mapping::ProviderMappingRow; +use crate::shorts::et_to_utc_micros; +use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn et_ts(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { + et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp") +} + +fn bar_1m( + key: &str, + ts: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> EodIntradayBar { + EodIntradayBar { + key: key.to_string(), + ts, + open, + high, + low, + close, + volume, + } +} + +fn map_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +#[allow(clippy::too_many_arguments)] +fn make_qm_bson_doc( + code: &str, + ts_micros: i64, + open: f64, + high: f64, + low: f64, + close: f64, + sharevolume: f64, +) -> RawDocumentBuf { + assert_eq!(ts_micros % 1_000, 0, "qm timestamp must be millisecond-aligned"); + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), DateTime::from_millis(ts_micros / 1_000)); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("sharevolume"), sharevolume); + doc +} + +fn assert_conservation_and_order(out: &CurateBars1mOutput) { + let s = &out.stats; + assert_eq!( + s.rows_in, s.builder.rows_out, + "rows_in != builder.rows_out: {s:?}" + ); + assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); + assert_eq!( + s.rows_in, + s.rows_out + + s.dropped_unmapped + + s.listing_collision_collapsed + + s.listing_collision_dropped, + "curate_qm_bars_1m conservation invariant failed: {s:?}" + ); + assert_eq!( + s.rows_out, + s.pre_rows_out + s.rth_rows_out + s.post_rows_out, + "session breakdown != rows_out: {s:?}" + ); + + for pair in out.rows.windows(2) { + assert!( + (pair[0].key, pair[0].ts) < (pair[1].key, pair[1].ts), + "rows not strictly sorted and unique by (listing_id, ts): {:?} vs {:?}", + (pair[0].key, pair[0].ts), + (pair[1].key, pair[1].ts) + ); + } +} + +fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool { + !needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle) +} + +#[test] +fn raw_qm_passthrough_preserves_ohlcv_bits_across_future_split_unlike_eod_control() { + let pre_day = day(2024, 6, 7); + let ex_date = day(2024, 6, 10); + let nvda_listing_id = 77_001; + let pre_ts = et_ts(2024, 6, 7, 15, 59); + + // Pre-split NVDA raw values vs 10:1 retroactively split-adjusted values. + let raw_open = 1205.0_f64; + let raw_high = 1210.0_f64; + let raw_low = 1204.0_f64; + let raw_close = 1208.88_f64; + let raw_vol = 41_239.0_f64; + + let mut qm_doc = make_qm_bson_doc( + "NVDA", + pre_ts, + raw_open, + raw_high, + raw_low, + raw_close, + raw_vol, + ); + // Distinct adjusted fields in the same BSON document must be ignored. + qm_doc.append(cstr!("adjustedopen"), 120.50_f64); + qm_doc.append(cstr!("adjustedhigh"), 121.00_f64); + qm_doc.append(cstr!("adjustedlow"), 120.40_f64); + qm_doc.append(cstr!("adjustedclose"), 120.888_f64); + qm_doc.append(cstr!("avolume"), 412_390.0_f64); + + let decoded = decode_qm_intraday_bytes(qm_doc.as_bytes()).unwrap(); + let qm_bar = decoded.into_eod_intraday_bar(|code, _| code.to_owned()); + + let splits = SplitTable::from_events([( + "NVDA".to_string(), + SplitEvent { + ex_date, + ratio: 10.0, + }, + )]) + .unwrap(); + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(2020, 1, 1), + None, + nvda_listing_id, + )]) + .unwrap(); + + // Control: EOD stage with the 10:1 split DOES scale OHLCV (and stamps BARS_1M_SOURCE_EOD). + let eod_control = curate_bars_1m([qm_bar.clone()], &splits, &mapping, "qm").unwrap(); + assert_eq!(eod_control.rows.len(), 1); + let eod_row = &eod_control.rows[0]; + assert_eq!(eod_row.source, BARS_1M_SOURCE_EOD); + assert_ne!(eod_row.open.to_bits(), qm_bar.open.to_bits()); + assert_ne!(eod_row.high.to_bits(), qm_bar.high.to_bits()); + assert_ne!(eod_row.low.to_bits(), qm_bar.low.to_bits()); + assert_ne!(eod_row.close.to_bits(), qm_bar.close.to_bits()); + assert_ne!(eod_row.volume.to_bits(), qm_bar.volume.to_bits()); + + // QuoteMedia stage accepts no SplitTable and preserves all five OHLCV fields bit-identically. + let qm_out = curate_qm_bars_1m([qm_bar.clone()], &mapping, "qm").unwrap(); + assert_conservation_and_order(&qm_out); + assert_eq!(qm_out.rows.len(), 1); + let row = &qm_out.rows[0]; + assert_eq!(row.key, nvda_listing_id); + assert_eq!(row.ts, pre_ts); + assert_eq!(row.session_date, pre_day); + assert_eq!(row.session, IntradaySession::Rth); + assert_eq!(row.source, BARS_1M_SOURCE_QM); + assert_ne!(row.source, BARS_1M_SOURCE_EOD); + assert_eq!(row.open.to_bits(), raw_open.to_bits()); + assert_eq!(row.high.to_bits(), raw_high.to_bits()); + assert_eq!(row.low.to_bits(), raw_low.to_bits()); + assert_eq!(row.close.to_bits(), raw_close.to_bits()); + assert_eq!(row.volume.to_bits(), raw_vol.to_bits()); +} + +#[test] +fn mapping_uses_eastern_time_session_date_boundaries_gaps_and_is_shuffle_invariant() { + // 2024-06-10 20:30 ET (EDT = UTC-4) is 2024-06-11 00:30 UTC (next UTC calendar day). + // Mapping ends inclusively on 2024-06-10, so ET session_date resolves while UTC date would drop. + let d_start = day(2024, 6, 10); + let d_gap = day(2024, 6, 11); + let d_resume = day(2024, 6, 12); + + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "ACME:CA", d_start, Some(d_start), 101), + map_row("qm", "ACME:CA", d_resume, None, 202), + map_row("qm", "BETA", d_start, Some(d_resume), 303), + ]) + .unwrap(); + + // PRE on inclusive valid_from (2024-06-10 08:00 ET) -> listing 101 + let b_pre = bar_1m("ACME:CA", et_ts(2024, 6, 10, 8, 0), 10.0, 10.2, 9.9, 10.1, 100.0); + // POST on inclusive valid_to whose UTC date is 2024-06-11 -> listing 101 + let b_post_utc_next = bar_1m("ACME:CA", et_ts(2024, 6, 10, 20, 30), 10.1, 10.3, 10.0, 10.2, 50.0); + // Date inside gap (2024-06-11) -> dropped_unmapped + let b_gap = bar_1m("ACME:CA", et_ts(2024, 6, 11, 10, 0), 10.5, 10.6, 10.4, 10.5, 200.0); + // RTH on inclusive second range valid_from (2024-06-12) -> listing 202 + let b_resumed = bar_1m("ACME:CA", et_ts(2024, 6, 12, 10, 0), 11.0, 11.2, 10.9, 11.1, 300.0); + // RTH for BETA on 2024-06-11 -> listing 303 + let b_beta = bar_1m("BETA", et_ts(2024, 6, 11, 14, 15), 25.0, 25.5, 24.8, 25.2, 400.0); + // Unknown qmSearchCode -> dropped_unmapped + let b_unknown = bar_1m("UNKNOWN", et_ts(2024, 6, 10, 10, 0), 5.0, 5.1, 4.9, 5.0, 10.0); + + let ordered = vec![ + b_pre.clone(), + b_post_utc_next.clone(), + b_gap.clone(), + b_resumed.clone(), + b_beta.clone(), + b_unknown.clone(), + ]; + let shuffled = vec![ + b_unknown, + b_resumed, + b_post_utc_next, + b_beta, + b_gap, + b_pre, + ]; + + let out_ordered = curate_qm_bars_1m(ordered, &mapping, "qm").unwrap(); + let out_shuffled = curate_qm_bars_1m(shuffled, &mapping, "qm").unwrap(); + + assert_conservation_and_order(&out_ordered); + assert_conservation_and_order(&out_shuffled); + assert_eq!(out_ordered, out_shuffled); + + assert_eq!(out_ordered.stats.rows_in, 6); + assert_eq!(out_ordered.stats.rows_out, 4); + assert_eq!(out_ordered.stats.dropped_unmapped, 2); + assert_eq!(out_ordered.stats.listings_out, 3); + assert_eq!(out_ordered.stats.pre_rows_out, 1); + assert_eq!(out_ordered.stats.rth_rows_out, 2); + assert_eq!(out_ordered.stats.post_rows_out, 1); + + // Verify exact ET session_date and listing assignment on the UTC-next-day POST bar. + let post_row = out_ordered + .rows + .iter() + .find(|r| r.session == IntradaySession::Post) + .expect("POST row present"); + assert_eq!(post_row.key, 101); + assert_eq!(post_row.session_date, d_start); + assert_ne!(post_row.session_date, d_gap); + assert!(out_ordered.rows.iter().all(|r| r.source == BARS_1M_SOURCE_QM)); +} + +#[test] +fn same_code_duplicates_and_cross_code_alias_collisions_enforce_conservation() { + let listing_id = 505; + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "OLD:CA", day(2024, 1, 1), None, listing_id), + map_row("qm", "NEW:CA", day(2024, 1, 1), None, listing_id), + map_row("qm", "ALT:CA", day(2024, 1, 1), None, listing_id), + ]) + .unwrap(); + + let ts_same_dup = et_ts(2024, 6, 10, 9, 30); + let ts_alias_ok = et_ts(2024, 6, 10, 9, 31); + let ts_alias_conflict = et_ts(2024, 6, 10, 9, 32); + let ts_unique_post = et_ts(2024, 6, 10, 16, 5); + + let bars = vec![ + // Same-code exact duplicate -> collapsed in builder (duplicate_collapsed = 1). + bar_1m("OLD:CA", ts_same_dup, 10.0, 10.5, 9.8, 10.2, 100.0), + bar_1m("OLD:CA", ts_same_dup, 10.0, 10.5, 9.8, 10.2, 100.0), + // Three distinct qmSearchCodes with bit-identical OHLCV -> group of 3 collapses by g-1 = 2. + bar_1m("OLD:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), + bar_1m("NEW:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), + bar_1m("ALT:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), + // Two distinct qmSearchCodes with conflicting close -> entire group of g = 2 dropped. + bar_1m("OLD:CA", ts_alias_conflict, 10.4, 10.8, 10.3, 10.5, 300.0), + bar_1m("NEW:CA", ts_alias_conflict, 10.4, 10.8, 10.3, 10.6, 300.0), + // Clean POST row. + bar_1m("NEW:CA", ts_unique_post, 10.6, 10.7, 10.5, 10.65, 0.0), + ]; + + let out = curate_qm_bars_1m(bars, &mapping, "qm").unwrap(); + assert_conservation_and_order(&out); + + assert_eq!(out.stats.builder.bars_in, 8); + assert_eq!(out.stats.builder.duplicate_collapsed, 1); + assert_eq!(out.stats.builder.rows_out, 7); + assert_eq!(out.stats.rows_in, 7); + assert_eq!(out.stats.listing_collision_collapsed, 2); + assert_eq!(out.stats.listing_collision_dropped, 2); + assert_eq!(out.stats.dropped_unmapped, 0); + assert_eq!(out.stats.rows_out, 3); + assert_eq!(out.stats.listings_out, 1); + assert_eq!(out.stats.pre_rows_out, 0); + assert_eq!(out.stats.rth_rows_out, 2); + assert_eq!(out.stats.post_rows_out, 1); + + let emitted_ts: Vec = out.rows.iter().map(|r| r.ts).collect(); + assert_eq!(emitted_ts, vec![ts_same_dup, ts_alias_ok, ts_unique_post]); + assert!(out.rows.iter().all(|r| r.source == BARS_1M_SOURCE_QM)); +} + +#[test] +fn bson_to_ilp_streams_multi_chunk_writes_qm_raw_and_supports_writer_reuse() { + let known_at = 1_718_050_123_456_000_i64; + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "NVDA", day(2020, 1, 1), None, 101), + map_row("qm", "SHOP:CA", day(2020, 1, 1), None, 202), + ]) + .unwrap(); + + let ts1 = et_ts(2024, 6, 7, 15, 59); + let ts2 = et_ts(2024, 6, 10, 9, 30); + let ts3 = et_ts(2024, 6, 10, 16, 10); + + let doc1 = make_qm_bson_doc("NVDA", ts1, 1205.0, 1210.0, 1204.0, 1208.88, 41_239.0); + // Semantically invalid doc: missing required field `close`. + let mut bad_doc = RawDocumentBuf::new(); + bad_doc.append(cstr!("qmSearchCode"), "NVDA"); + bad_doc.append(cstr!("timestamp"), DateTime::from_millis(ts2 / 1_000)); + bad_doc.append(cstr!("open"), 120.0_f64); + bad_doc.append(cstr!("high"), 121.0_f64); + bad_doc.append(cstr!("low"), 119.5_f64); + bad_doc.append(cstr!("sharevolume"), 1_000.0_f64); + let doc2 = make_qm_bson_doc("SHOP:CA", ts2, 88.0, 89.0, 87.5, 88.4, 2_500.0); + + let mut chunk1_bytes = Vec::new(); + chunk1_bytes.extend_from_slice(doc1.as_bytes()); + chunk1_bytes.extend_from_slice(bad_doc.as_bytes()); + chunk1_bytes.extend_from_slice(doc2.as_bytes()); + + let doc3 = make_qm_bson_doc("NVDA", ts3, 121.0, 121.5, 120.8, 121.2, 5_000.0); + let chunk2_bytes = doc3.as_bytes().to_vec(); + + // Force multi-chunk streaming with a tiny chunk capacity smaller than two documents. + let stream_opts = BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 4096, + }; + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let mut s2 = Vec::new(); + let mut s3 = Vec::new(); + let (rep1, rep2, ilp_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1, &mut s2, &mut s3], + IlpWriterOptions::default(), + ) + .unwrap(); + let rep1 = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&chunk1_bytes), + stream_opts, + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap(); + // Reuse the same open writer for a second call. + let rep2 = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&chunk2_bytes), + stream_opts, + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap(); + let stats = writer.finish().unwrap(); + (rep1, rep2, stats) + }; + + assert_eq!(rep1.decode_stats.docs_seen, 3); + assert_eq!(rep1.decode_stats.rows_decoded, 2); + assert_eq!(rep1.decode_stats.rejected_missing_field, 1); + assert_eq!( + rep1.decode_stats.docs_seen, + rep1.decode_stats.rows_decoded + rep1.decode_stats.rejected_total() + ); + assert_eq!(rep1.write_report.rows_written, 2); + assert_eq!( + rep1.write_report.rows_written, + rep1.write_report.curate_stats.rows_out + ); + + assert_eq!(rep2.decode_stats.docs_seen, 1); + assert_eq!(rep2.decode_stats.rows_decoded, 1); + assert_eq!(rep2.write_report.rows_written, 1); + assert_eq!( + ilp_stats.rows, + rep1.write_report.rows_written + rep2.write_report.rows_written + ); + assert_eq!(ilp_stats.rows, 3); + + // Build expected exact ILP lines for each emitted row and verify per-shard routing, + // `source=qm_raw`, exact `known_at`, and per-shard ordering. + let expected_row1 = Bar1mRow { + key: 101, + ts: ts1, + session_date: day(2024, 6, 7), + open: 1205.0, + high: 1210.0, + low: 1204.0, + close: 1208.88, + volume: 41_239.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_QM, + }; + let expected_row2 = Bar1mRow { + key: 202, + ts: ts2, + session_date: day(2024, 6, 10), + open: 88.0, + high: 89.0, + low: 87.5, + close: 88.4, + volume: 2_500.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_QM, + }; + let expected_row3 = Bar1mRow { + key: 101, + ts: ts3, + session_date: day(2024, 6, 10), + open: 121.0, + high: 121.5, + low: 120.8, + close: 121.2, + volume: 5_000.0, + session: IntradaySession::Post, + source: BARS_1M_SOURCE_QM, + }; + + let mut expected_shards = vec![Vec::::new(); 4]; + for row in [&expected_row1, &expected_row2, &expected_row3] { + let shard = shard_for_listing_id(row.key, 4); + encode_bar_1m(&mut expected_shards[shard], row, known_at).unwrap(); + } + + let actual_shards = [&s0, &s1, &s2, &s3]; + for (idx, (actual, expected)) in actual_shards.iter().zip(&expected_shards).enumerate() { + assert_eq!(*actual, expected, "shard {idx} ILP bytes mismatch"); + } + + let all_bytes: Vec = actual_shards.iter().flat_map(|s| s.iter().copied()).collect(); + assert!(contains_subslice(&all_bytes, TABLE_BARS_1M.as_bytes())); + assert!(contains_subslice( + &all_bytes, + format!("source={BARS_1M_SOURCE_QM}").as_bytes() + )); + assert!(!contains_subslice( + &all_bytes, + format!("source={BARS_1M_SOURCE_EOD}").as_bytes() + )); + assert!(contains_subslice( + &all_bytes, + format!("known_at={known_at}t").as_bytes() + )); +} + +struct CountingReader { + inner: R, + reads: usize, +} + +impl Read for CountingReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.reads += 1; + self.inner.read(buf) + } +} + +#[test] +fn truncated_stream_and_blank_mapping_source_fail_closed_with_zero_writes() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(2020, 1, 1), + None, + 101, + )]) + .unwrap(); + let known_at = 1_718_050_000_000_000_i64; + + let doc1 = make_qm_bson_doc( + "NVDA", + et_ts(2024, 6, 7, 15, 59), + 1205.0, + 1210.0, + 1204.0, + 1208.88, + 41_239.0, + ); + let doc2 = make_qm_bson_doc( + "NVDA", + et_ts(2024, 6, 10, 15, 59), + 121.0, + 121.5, + 120.8, + 121.2, + 5_000.0, + ); + + // Truncated tail after a valid document with max_batch_rows = 1 must write zero bytes. + let mut truncated_bytes = Vec::new(); + truncated_bytes.extend_from_slice(doc1.as_bytes()); + let doc2_bytes = doc2.as_bytes(); + truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let (err, trunc_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&truncated_bytes), + BsonStreamOptions::default(), + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap_err(); + let stats = writer.finish().unwrap(); + (err, stats) + }; + assert!(matches!( + err, + CurateQmBars1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) + )); + assert!(err.source().is_some()); + assert_eq!(trunc_stats.rows, 0); + assert!(s0.is_empty()); + assert!(s1.is_empty()); + + // Blank mapping_source on pure stage returns EmptyMappingSource. + let pure_err = curate_qm_bars_1m( + [bar_1m("NVDA", et_ts(2024, 6, 7, 15, 59), 10.0, 11.0, 9.0, 10.5, 100.0)], + &mapping, + " \t", + ) + .unwrap_err(); + assert_eq!(pure_err, CurateBars1mError::EmptyMappingSource); + + // Blank mapping_source on BSON stage rejects before any read or write. + let mut counting_reader = CountingReader { + inner: Cursor::new(doc1.as_bytes()), + reads: 0, + }; + let mut sink = Vec::new(); + let (blank_err, blank_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut sink], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_qm_bars_1m_from_bson( + &mut counting_reader, + BsonStreamOptions::default(), + &mapping, + " \n\t ", + &mut writer, + known_at, + ) + .unwrap_err(); + let stats = writer.finish().unwrap(); + (err, stats) + }; + assert!(matches!( + blank_err, + CurateQmBars1mBsonError::Write(CurateBars1mWriteError::Curate( + CurateBars1mError::EmptyMappingSource + )) + )); + assert!(blank_err.source().is_some()); + assert_eq!(counting_reader.reads, 0); + assert_eq!(blank_stats.rows, 0); + assert!(sink.is_empty()); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index cee11fe3..5d412354 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -46,7 +46,7 @@ pub use bars_1m::{ build_bars_1m, check_session_closes, check_session_closes_against_bars_1d, Bar1mRow, Bars1mBuild, Bars1mError, Bars1mStats, DailySessionClose, EodIntradayBar, IntradaySession, SessionCloseCheck, SessionCloseCutoffPolicy, SessionCloseMismatchSample, SessionCloseStats, - BARS_1M_SOURCE_EOD, RTH_END_MINUTE_ET, RTH_START_MINUTE_ET, + BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM, RTH_END_MINUTE_ET, RTH_START_MINUTE_ET, }; pub use bson_ceo_shorts::{ decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc, @@ -81,12 +81,13 @@ pub use bson_qm_prices::{ }; pub use bson_stream::{ decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_intraday_chunks, - decode_eod_intraday_stream, decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream, - decode_qm_earnings_chunks, decode_qm_earnings_stream, decode_qm_filings_chunks, - decode_qm_filings_stream, decode_qm_price_chunks, decode_qm_price_stream, - decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks, - decode_te_market_data_stream, BsonCeoShortsStreamError, BsonQmEventsStreamError, - BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, + decode_eod_intraday_stream, decode_eod_price_chunks, decode_eod_price_stream, + decode_qm_dividend_chunks, decode_qm_dividend_stream, decode_qm_earnings_chunks, + decode_qm_earnings_stream, decode_qm_filings_chunks, decode_qm_filings_stream, + decode_qm_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_chunks, + decode_qm_price_stream, decode_qm_split_chunks, decode_qm_split_stream, + decode_te_market_data_chunks, decode_te_market_data_stream, BsonCeoShortsStreamError, + BsonQmEventsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, }; pub use bson_te_market_data::{ @@ -243,6 +244,12 @@ pub use curate_bars_1m::{ CurateBars1mOutput, CurateBars1mStats, CurateBars1mWriteError, CurateBars1mWriteReport, }; +pub mod curate_qm_bars_1m; +pub use curate_qm_bars_1m::{ + curate_and_write_qm_bars_1m, curate_and_write_qm_bars_1m_from_bson, curate_qm_bars_1m, + CurateQmBars1mBsonError, CurateQmBars1mBsonReport, +}; + pub mod run_curate_bars; pub use run_curate_bars::{ default_curate_bars_threads, format_curate_bars_report, load_listing_currencies_tsv, From a8cebf060516ebee84279b1e0d343a42124d1033 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:20:59 -0500 Subject: [PATCH 14/15] T-152: tests --- .../curate-etl/src/curate_qm_bars_1m_tests.rs | 218 ++++++++++++++++++ 1 file changed, 218 insertions(+) diff --git a/tools/curate-etl/src/curate_qm_bars_1m_tests.rs b/tools/curate-etl/src/curate_qm_bars_1m_tests.rs index 1812141c..22a3eff9 100644 --- a/tools/curate-etl/src/curate_qm_bars_1m_tests.rs +++ b/tools/curate-etl/src/curate_qm_bars_1m_tests.rs @@ -603,3 +603,221 @@ fn truncated_stream_and_blank_mapping_source_fail_closed_with_zero_writes() { assert_eq!(blank_stats.rows, 0); assert!(sink.is_empty()); } + +// --------------------------------------------------------------------------------------------- +// QA (T-152) additional coverage. +// --------------------------------------------------------------------------------------------- + +#[test] +fn qa_bson_to_ilp_reorders_reverse_ts_rows_within_one_shard_and_reuses_writer() { + // Two valid bars for the same listing in REVERSE timestamp order in one BSON call: the shard + // must receive them ascending by ts. A single shard makes every row share one sink. + let known_at = 1_718_100_000_000_000_i64; + let mapping = + ProviderMappingTable::from_rows([map_row("qm", "NVDA", day(2020, 1, 1), None, 101)]) + .unwrap(); + let ts_early = et_ts(2024, 6, 10, 9, 30); + let ts_late = et_ts(2024, 6, 10, 9, 45); + let ts_next = et_ts(2024, 6, 11, 9, 30); + + let late = make_qm_bson_doc("NVDA", ts_late, 121.0, 122.0, 120.5, 121.5, 900.0); + let early = make_qm_bson_doc("NVDA", ts_early, 120.0, 120.9, 119.8, 120.6, 700.0); + let mut call1 = Vec::new(); + call1.extend_from_slice(late.as_bytes()); + call1.extend_from_slice(early.as_bytes()); + let call2 = make_qm_bson_doc("NVDA", ts_next, 123.0, 123.5, 122.5, 123.1, 1_100.0) + .as_bytes() + .to_vec(); + + let opts = BsonStreamOptions { + chunk_capacity_bytes: 48, + max_doc_bytes: 4096, + }; + let mut sink = Vec::new(); + let (rep1, rep2, stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut sink], + IlpWriterOptions { + max_batch_bytes: 1 << 16, + max_batch_rows: 1, + }, + ) + .unwrap(); + let rep1 = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&call1), + opts, + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap(); + let rep2 = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&call2), + opts, + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap(); + (rep1, rep2, writer.finish().unwrap()) + }; + assert_eq!(rep1.write_report.rows_written, 2); + assert_eq!(rep2.write_report.rows_written, 1); + assert_eq!(stats.rows, 3); + + let row = |ts: i64, o: f64, h: f64, l: f64, c: f64, v: f64, date: i32| Bar1mRow { + key: 101, + ts, + session_date: date, + open: o, + high: h, + low: l, + close: c, + volume: v, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_QM, + }; + let mut expected = Vec::new(); + for r in [ + row(ts_early, 120.0, 120.9, 119.8, 120.6, 700.0, day(2024, 6, 10)), + row(ts_late, 121.0, 122.0, 120.5, 121.5, 900.0, day(2024, 6, 10)), + row(ts_next, 123.0, 123.5, 122.5, 123.1, 1_100.0, day(2024, 6, 11)), + ] { + encode_bar_1m(&mut expected, &r, known_at).unwrap(); + } + assert_eq!(sink, expected, "shard must receive rows ascending by ts across calls"); +} + +#[test] +fn qa_invalid_ohlcv_and_out_of_range_dates_are_accounted_and_volume_neg_zero_normalized() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "ACME", + day(2024, 6, 10), + Some(day(2024, 6, 10)), + 9, + )]) + .unwrap(); + let bars = vec![ + // Valid, -0.0 volume -> +0.0. + bar_1m("ACME", et_ts(2024, 6, 10, 10, 0), 10.0, 10.5, 9.5, 10.2, -0.0), + // high < low -> builder drops (inconsistent). + bar_1m("ACME", et_ts(2024, 6, 10, 10, 1), 10.0, 9.0, 9.5, 10.2, 1.0), + // NaN close -> builder drops. + bar_1m("ACME", et_ts(2024, 6, 10, 10, 2), 10.0, 10.5, 9.5, f64::NAN, 1.0), + // Negative volume -> builder drops. + bar_1m("ACME", et_ts(2024, 6, 10, 10, 3), 10.0, 10.5, 9.5, 10.2, -5.0), + // Day before valid_from and day after valid_to -> dropped_unmapped. + bar_1m("ACME", et_ts(2024, 6, 7, 10, 0), 10.0, 10.5, 9.5, 10.2, 1.0), + bar_1m("ACME", et_ts(2024, 6, 11, 10, 0), 10.0, 10.5, 9.5, 10.2, 1.0), + ]; + let out = curate_qm_bars_1m(bars, &mapping, "qm").unwrap(); + assert_conservation_and_order(&out); + let b = &out.stats.builder; + assert_eq!(b.bars_in, 6); + assert_eq!( + b.dropped_invalid_ohlc + b.dropped_inconsistent_ohlc + b.dropped_invalid_volume, + 3, + "{b:?}" + ); + assert_eq!(out.stats.rows_in, 3); + assert_eq!(out.stats.dropped_unmapped, 2); + assert_eq!(out.rows.len(), 1); + assert_eq!(out.rows[0].volume.to_bits(), 0.0_f64.to_bits()); + assert_eq!(out.rows[0].source, BARS_1M_SOURCE_QM); +} + +#[test] +fn qa_mapping_source_is_namespace_scoped_and_matched_verbatim() { + // Same code under a different provider namespace (`eod`) must not resolve for `qm`. + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "NVDA", day(2020, 1, 1), None, 1), + map_row("qm", "NVDA", day(2020, 1, 1), None, 2), + ]) + .unwrap(); + let bars = || [bar_1m("NVDA", et_ts(2024, 6, 10, 10, 0), 1.0, 1.0, 1.0, 1.0, 1.0)]; + let qm = curate_qm_bars_1m(bars(), &mapping, "qm").unwrap(); + assert_eq!(qm.rows.len(), 1); + assert_eq!(qm.rows[0].key, 2); + // Padded namespace is non-blank and looked up verbatim -> nothing matches. + let padded = curate_qm_bars_1m(bars(), &mapping, " qm").unwrap(); + assert_conservation_and_order(&padded); + assert_eq!(padded.rows.len(), 0); + assert_eq!(padded.stats.dropped_unmapped, 1); +} + +#[test] +fn qa_curate_and_write_blank_namespace_and_multichunk_truncation_write_nothing() { + let mapping = + ProviderMappingTable::from_rows([map_row("qm", "NVDA", day(2020, 1, 1), None, 101)]) + .unwrap(); + let known_at = 1_718_000_000_000_000_i64; + + // In-memory write path: blank namespace -> Curate error, zero bytes. + let mut sink = Vec::new(); + { + let mut writer = IlpShardedWriter::new( + vec![&mut sink], + IlpWriterOptions { + max_batch_bytes: 1, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_qm_bars_1m( + [bar_1m("NVDA", et_ts(2024, 6, 10, 10, 0), 1.0, 1.0, 1.0, 1.0, 1.0)], + &mapping, + "", + &mut writer, + known_at, + ) + .unwrap_err(); + assert!(matches!( + err, + CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource) + )); + assert_eq!(writer.finish().unwrap().rows, 0); + } + assert!(sink.is_empty()); + + // Many valid docs streamed across many small chunks, then a truncated tail: zero bytes. + let mut bytes = Vec::new(); + for m in 0..20u8 { + let doc = make_qm_bson_doc("NVDA", et_ts(2024, 6, 10, 10, m), 1.0, 1.0, 1.0, 1.0, 1.0); + bytes.extend_from_slice(doc.as_bytes()); + } + bytes.extend_from_slice(&200_i32.to_le_bytes()); + bytes.extend_from_slice(&[0x02, b'x']); + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1], + IlpWriterOptions { + max_batch_bytes: 1, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&bytes), + BsonStreamOptions { + chunk_capacity_bytes: 40, + max_doc_bytes: 4096, + }, + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap_err(); + assert!(matches!( + err, + CurateQmBars1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) + )); + assert_eq!(writer.finish().unwrap().rows, 0); + } + assert!(s0.is_empty() && s1.is_empty()); +} From 42d82469a4998ea3f3f9b77d1fd353b33adf80f2 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 01:36:18 -0500 Subject: [PATCH 15/15] =?UTF-8?q?T-156:=20M2.2e=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20Zstd=20Parquet=20writer=20for=20`fundamentals=5Fpit/y?= =?UTF-8?q?ear=3DYYYY/part.parquet`=20(`FundamentalsSnapshot`=20?= =?UTF-8?q?=E2=86=92=20flat=20row=20matching=20the=20DuckDB=20`fundamental?= =?UTF-8?q?sAsOf`=20reader=20columns)=20with=20tests=20(no=20new=20crates,?= =?UTF-8?q?=20no=20CLI/bench=20changes,=20no=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/lib.rs | 5 + tools/curate-etl/src/parquet_fundamentals.rs | 1508 ++++++++++++++++ .../src/parquet_fundamentals_tests.rs | 1537 +++++++++++++++++ 3 files changed, 3050 insertions(+) create mode 100644 tools/curate-etl/src/parquet_fundamentals.rs create mode 100644 tools/curate-etl/src/parquet_fundamentals_tests.rs diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 5d412354..fb59f375 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -25,6 +25,7 @@ pub mod parquet_adj; pub mod parquet_bars; pub mod parquet_corporate_actions; pub mod parquet_events; +pub mod parquet_fundamentals; pub mod parquet_fx; mod parquet_publish; pub mod parquet_shorts; @@ -162,6 +163,10 @@ pub use parquet_events::{ events_parquet_schema, write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, ParquetEventsError, }; +pub use parquet_fundamentals::{ + fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitParquetRow, + FundamentalsPitWriteOptions, FundamentalsPitWriteStats, ParquetFundamentalsError, +}; pub use parquet_fx::{ fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, ParquetFxError, diff --git a/tools/curate-etl/src/parquet_fundamentals.rs b/tools/curate-etl/src/parquet_fundamentals.rs new file mode 100644 index 00000000..f833350d --- /dev/null +++ b/tools/curate-etl/src/parquet_fundamentals.rs @@ -0,0 +1,1508 @@ +//! Streaming, atomic, year-partitioned Zstd Parquet writer for `fundamentals_pit`. +//! +//! Writes `/fundamentals_pit/year=YYYY/part.parquet` files matching the 20-column +//! contract schema read by `planFundamentalsAsOfQuery` in +//! `libs/research/src/market-data-store-duckdb.ts`: +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `effective_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 3. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 4. `has_estimated_lag` (`BOOLEAN`, `REQUIRED`) +//! 5. `period_end` (`INT32`, `REQUIRED`, `DATE`) +//! 6. `fiscal_period` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 7. `currency` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 8. `period_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 9. `revenue` (`DOUBLE`, `OPTIONAL`) +//! 10. `net_income` (`DOUBLE`, `OPTIONAL`) +//! 11. `operating_cash_flow` (`DOUBLE`, `OPTIONAL`) +//! 12. `total_assets` (`DOUBLE`, `OPTIONAL`) +//! 13. `total_equity` (`DOUBLE`, `OPTIONAL`) +//! 14. `shares_outstanding` (`DOUBLE`, `OPTIONAL`) +//! 15. `ttm_revenue` (`DOUBLE`, `OPTIONAL`) +//! 16. `ttm_net_income` (`DOUBLE`, `OPTIONAL`) +//! 17. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`) +//! 18. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`) +//! 19. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) +//! 20. `ttm_has_estimated_lag` (`BOOLEAN`, `OPTIONAL`) + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::collections::BTreeMap; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use parquet::basic::{ + Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel, +}; +use parquet::column::writer::ColumnWriter; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::{SerializedFileWriter, SerializedRowGroupWriter}; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::events::partition_year_utc; +use crate::fundamentals::FundamentalsSnapshot; +pub use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; +use crate::parquet_publish::{ + create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, + rollback_published, write_i32_col, write_i64_col, write_interned_str_col, + write_optional_f64_col, write_optional_i32_col, write_optional_interned_str_col, + DatasetFileLock, PublishIoError, PublishedPartition, StagingFileGuard, StringInterner, + DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, +}; +pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; +use crate::shorts::epoch_days_to_ymd; + +/// Single flat `fundamentals_pit` row keyed by `(listing_id, effective_known_at_micros)`. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsPitParquetRow { + pub listing_id: i32, + pub effective_known_at_micros: i64, + pub known_at_source: Cow<'static, str>, + pub has_estimated_lag: bool, + pub period_end: i32, + pub fiscal_period: Cow<'static, str>, + pub currency: Cow<'static, str>, + pub period_known_at_micros: i64, + pub revenue: Option, + pub net_income: Option, + pub operating_cash_flow: Option, + pub total_assets: Option, + pub total_equity: Option, + pub shares_outstanding: Option, + pub ttm_revenue: Option, + pub ttm_net_income: Option, + pub ttm_operating_cash_flow: Option, + pub ttm_period_end: Option, + pub ttm_currency: Option>, + pub ttm_has_estimated_lag: Option, +} + +impl TryFrom<&FundamentalsSnapshot> for FundamentalsPitParquetRow { + type Error = ParquetFundamentalsError; + + fn try_from(snapshot: &FundamentalsSnapshot) -> Result { + let latest = snapshot.periods.first().ok_or( + ParquetFundamentalsError::EmptySnapshotPeriods { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + }, + )?; + + let ( + ttm_revenue, + ttm_net_income, + ttm_operating_cash_flow, + ttm_period_end, + ttm_currency, + ttm_has_estimated_lag, + ) = match &snapshot.ttm { + Some(ttm) => ( + ttm.flows.revenue, + ttm.flows.net_income, + ttm.flows.operating_cash_flow, + Some(ttm.ending_period_end), + Some(Cow::Owned(ttm.currency.clone())), + Some(ttm.has_estimated_lag), + ), + None => (None, None, None, None, None, None), + }; + + Ok(Self { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + known_at_source: Cow::Borrowed(snapshot.known_at_source), + has_estimated_lag: snapshot.has_estimated_lag, + period_end: latest.period_end, + fiscal_period: Cow::Borrowed(latest.fiscal_period.as_str()), + currency: Cow::Owned(latest.currency.clone()), + period_known_at_micros: latest.known_at_utc_micros, + revenue: latest.fields.revenue, + net_income: latest.fields.net_income, + operating_cash_flow: latest.fields.operating_cash_flow, + total_assets: latest.fields.total_assets, + total_equity: latest.fields.total_equity, + shares_outstanding: latest.fields.shares_outstanding, + ttm_revenue, + ttm_net_income, + ttm_operating_cash_flow, + ttm_period_end, + ttm_currency, + ttm_has_estimated_lag, + }) + } +} + +impl TryFrom> for FundamentalsPitParquetRow { + type Error = ParquetFundamentalsError; + + fn try_from(snapshot: FundamentalsSnapshot) -> Result { + let mut periods = snapshot.periods.into_iter(); + let latest = periods.next().ok_or( + ParquetFundamentalsError::EmptySnapshotPeriods { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + }, + )?; + + let ( + ttm_revenue, + ttm_net_income, + ttm_operating_cash_flow, + ttm_period_end, + ttm_currency, + ttm_has_estimated_lag, + ) = match snapshot.ttm { + Some(ttm) => ( + ttm.flows.revenue, + ttm.flows.net_income, + ttm.flows.operating_cash_flow, + Some(ttm.ending_period_end), + Some(Cow::Owned(ttm.currency)), + Some(ttm.has_estimated_lag), + ), + None => (None, None, None, None, None, None), + }; + + Ok(Self { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + known_at_source: Cow::Borrowed(snapshot.known_at_source), + has_estimated_lag: snapshot.has_estimated_lag, + period_end: latest.period_end, + fiscal_period: Cow::Borrowed(latest.fiscal_period.as_str()), + currency: Cow::Owned(latest.currency), + period_known_at_micros: latest.known_at_utc_micros, + revenue: latest.fields.revenue, + net_income: latest.fields.net_income, + operating_cash_flow: latest.fields.operating_cash_flow, + total_assets: latest.fields.total_assets, + total_equity: latest.fields.total_equity, + shares_outstanding: latest.fields.shares_outstanding, + ttm_revenue, + ttm_net_income, + ttm_operating_cash_flow, + ttm_period_end, + ttm_currency, + ttm_has_estimated_lag, + }) + } +} + +/// Configuration for [`write_fundamentals_pit_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FundamentalsPitWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for FundamentalsPitWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_fundamentals_pit_dataset`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FundamentalsPitWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub rows_by_year: BTreeMap, +} + +/// Typed error returned by [`FundamentalsPitParquetRow::try_from`] and +/// [`write_fundamentals_pit_dataset`]. +#[derive(Debug)] +pub enum ParquetFundamentalsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + EmptySnapshotPeriods { + listing_id: i32, + effective_known_at_micros: i64, + }, + UnsortedInput { + row_index: usize, + prev_listing_id: i32, + prev_effective_known_at_micros: i64, + listing_id: i32, + effective_known_at_micros: i64, + }, + DuplicateRow { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + PartitionYearOutOfRange { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + year: i32, + min_year: i32, + max_year: i32, + }, + PeriodEndOutOfRange { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + period_end: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + TtmPeriodEndOutOfRange { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + ttm_period_end: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + PeriodKnownAtAfterEffectiveKnownAt { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + period_known_at_micros: i64, + }, + EmptyKnownAtSource { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + EmptyFiscalPeriod { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + EmptyCurrency { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + EmptyTtmCurrency { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + InconsistentTtmMetadata { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + NonFiniteValue { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + field: &'static str, + value: f64, + }, + LockTimeout { + path: PathBuf, + waited: Duration, + }, + RollbackFailed { + cause: Box, + failures: Vec, + }, + Io { + path: PathBuf, + source: io::Error, + }, + Parquet { + path: PathBuf, + source: ParquetError, + }, +} + +impl fmt::Display for ParquetFundamentalsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidRowGroupRows => { + write!(f, "invalid row_group_rows: must be greater than 0") + } + Self::InvalidZstdLevel { level } => { + write!(f, "invalid Zstd compression level: {level}") + } + Self::EmptySnapshotPeriods { + listing_id, + effective_known_at_micros, + } => write!( + f, + "snapshot for (listing_id={listing_id}, effective_known_at={effective_known_at_micros}) has no visible periods" + ), + Self::UnsortedInput { + row_index, + prev_listing_id, + prev_effective_known_at_micros, + listing_id, + effective_known_at_micros, + } => write!( + f, + "unsorted input at row {row_index}: ({listing_id}, {effective_known_at_micros}) follows ({prev_listing_id}, {prev_effective_known_at_micros})" + ), + Self::DuplicateRow { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "duplicate fundamentals_pit row at row {row_index}: (listing_id={listing_id}, effective_known_at={effective_known_at_micros})" + ), + Self::PartitionYearOutOfRange { + row_index, + listing_id, + effective_known_at_micros, + year, + min_year, + max_year, + } => write!( + f, + "partition year {year} (effective_known_at {effective_known_at_micros}) at row {row_index} for listing_id {listing_id} is outside allowed range {min_year}..={max_year}" + ), + Self::PeriodEndOutOfRange { + row_index, + listing_id, + effective_known_at_micros, + period_end, + year, + min_year, + max_year, + } => write!( + f, + "period_end {period_end} (year {year}) at row {row_index} for ({listing_id}, {effective_known_at_micros}) is outside allowed range {min_year}..={max_year}" + ), + Self::TtmPeriodEndOutOfRange { + row_index, + listing_id, + effective_known_at_micros, + ttm_period_end, + year, + min_year, + max_year, + } => write!( + f, + "ttm_period_end {ttm_period_end} (year {year}) at row {row_index} for ({listing_id}, {effective_known_at_micros}) is outside allowed range {min_year}..={max_year}" + ), + Self::PeriodKnownAtAfterEffectiveKnownAt { + row_index, + listing_id, + effective_known_at_micros, + period_known_at_micros, + } => write!( + f, + "period_known_at {period_known_at_micros} is after effective_known_at {effective_known_at_micros} at row {row_index} for listing_id {listing_id}" + ), + Self::EmptyKnownAtSource { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty known_at_source at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" + ), + Self::EmptyFiscalPeriod { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty fiscal_period at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" + ), + Self::EmptyCurrency { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" + ), + Self::EmptyTtmCurrency { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty ttm_currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty when present" + ), + Self::InconsistentTtmMetadata { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "inconsistent TTM columns at row {row_index} for ({listing_id}, {effective_known_at_micros}): ttm_period_end, ttm_currency, and ttm_has_estimated_lag must all be Some or all be None, and TTM flow values require TTM metadata" + ), + Self::NonFiniteValue { + row_index, + listing_id, + effective_known_at_micros, + field, + value, + } => write!( + f, + "non-finite value {value} in field '{field}' at row {row_index} for ({listing_id}, {effective_known_at_micros})" + ), + Self::LockTimeout { path, waited } => write!( + f, + "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", + waited.as_millis(), + path.display() + ), + Self::RollbackFailed { cause, failures } => { + write!( + f, + "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", + failures.len() + )?; + for failure in failures { + write!(f, " [{failure}]")?; + } + Ok(()) + } + Self::Io { path, source } => { + write!(f, "I/O error at '{}': {source}", path.display()) + } + Self::Parquet { path, source } => { + write!(f, "Parquet error at '{}': {source}", path.display()) + } + } + } +} + +impl Error for ParquetFundamentalsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::Io { source, .. } => Some(source), + Self::Parquet { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for ParquetFundamentalsError { + fn from(err: PublishIoError) -> Self { + match err { + PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, + PublishIoError::Io { path, source } => Self::Io { path, source }, + } + } +} + +/// Builds the exact 20-column Parquet schema for `fundamentals_pit` matching +/// `FUNDAMENTALS_BASE_SCHEMA`, `FUNDAMENTALS_PIT_VALUE_FIELDS`, and +/// `FUNDAMENTALS_TTM_META_SCHEMA` in `libs/research/src/market-data-store-duckdb.ts`. +pub fn fundamentals_pit_parquet_schema() -> Result { + let fields: Vec = vec![ + Arc::new( + Type::primitive_type_builder("listing_id", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("effective_known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("has_estimated_lag", PhysicalType::BOOLEAN) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("period_end", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("fiscal_period", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("period_known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("revenue", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("net_income", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("operating_cash_flow", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("total_assets", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("total_equity", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("shares_outstanding", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_revenue", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_net_income", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_operating_cash_flow", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_has_estimated_lag", PhysicalType::BOOLEAN) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("fundamentals_pit") + .with_fields(fields) + .build()?, + )) +} + +fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { + Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(zstd_level)) + .set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true) + .set_column_dictionary_enabled(ColumnPath::from("fiscal_period"), true) + .set_column_dictionary_enabled(ColumnPath::from("currency"), true) + .set_column_dictionary_enabled(ColumnPath::from("ttm_currency"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn compare_row_keys(a: &FundamentalsPitParquetRow, b: &FundamentalsPitParquetRow) -> Ordering { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.effective_known_at_micros.cmp(&b.effective_known_at_micros)) +} + +#[inline] +fn check_opt_finite( + row: &FundamentalsPitParquetRow, + row_index: usize, + field: &'static str, + value: Option, +) -> Result<(), ParquetFundamentalsError> { + if let Some(v) = value { + if !v.is_finite() { + return Err(ParquetFundamentalsError::NonFiniteValue { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + field, + value: v, + }); + } + } + Ok(()) +} + +fn validate_row( + row: &FundamentalsPitParquetRow, + row_index: usize, +) -> Result { + let year = partition_year_utc(row.effective_known_at_micros); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { + return Err(ParquetFundamentalsError::PartitionYearOutOfRange { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + + let (period_year, _, _) = epoch_days_to_ymd(row.period_end); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&period_year) { + return Err(ParquetFundamentalsError::PeriodEndOutOfRange { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + period_end: row.period_end, + year: period_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + + if row.period_known_at_micros > row.effective_known_at_micros { + return Err( + ParquetFundamentalsError::PeriodKnownAtAfterEffectiveKnownAt { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + period_known_at_micros: row.period_known_at_micros, + }, + ); + } + + if row.known_at_source.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyKnownAtSource { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + if row.fiscal_period.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyFiscalPeriod { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + if row.currency.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyCurrency { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + + check_opt_finite(row, row_index, "revenue", row.revenue)?; + check_opt_finite(row, row_index, "net_income", row.net_income)?; + check_opt_finite( + row, + row_index, + "operating_cash_flow", + row.operating_cash_flow, + )?; + check_opt_finite(row, row_index, "total_assets", row.total_assets)?; + check_opt_finite(row, row_index, "total_equity", row.total_equity)?; + check_opt_finite(row, row_index, "shares_outstanding", row.shares_outstanding)?; + check_opt_finite(row, row_index, "ttm_revenue", row.ttm_revenue)?; + check_opt_finite(row, row_index, "ttm_net_income", row.ttm_net_income)?; + check_opt_finite( + row, + row_index, + "ttm_operating_cash_flow", + row.ttm_operating_cash_flow, + )?; + + let has_ttm_period_end = row.ttm_period_end.is_some(); + let has_ttm_currency = row.ttm_currency.is_some(); + let has_ttm_lag = row.ttm_has_estimated_lag.is_some(); + let all_ttm_meta = has_ttm_period_end && has_ttm_currency && has_ttm_lag; + let no_ttm_meta = !has_ttm_period_end && !has_ttm_currency && !has_ttm_lag; + let has_any_ttm_flow = row.ttm_revenue.is_some() + || row.ttm_net_income.is_some() + || row.ttm_operating_cash_flow.is_some(); + + if (!all_ttm_meta && !no_ttm_meta) || (no_ttm_meta && has_any_ttm_flow) { + return Err(ParquetFundamentalsError::InconsistentTtmMetadata { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + + if let Some(ttm_end) = row.ttm_period_end { + let (ttm_year, _, _) = epoch_days_to_ymd(ttm_end); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&ttm_year) { + return Err(ParquetFundamentalsError::TtmPeriodEndOutOfRange { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + ttm_period_end: ttm_end, + year: ttm_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + } + if let Some(ttm_ccy) = row.ttm_currency.as_deref() { + if ttm_ccy.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyTtmCurrency { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + } + + Ok(year) +} + +fn write_bool_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[bool], +) -> Result<(), ParquetError> { + let mut col = match rg_writer.next_column()? { + Some(col) => col, + None => { + return Err(ParquetError::General( + "unexpected end of Parquet schema columns".to_string(), + )); + } + }; + match col.untyped() { + ColumnWriter::BoolColumnWriter(typed) => { + typed.write_batch(values, None, None)?; + } + _ => { + return Err(ParquetError::General( + "expected BOOLEAN column writer".to_string(), + )); + } + } + col.close() +} + +fn write_optional_bool_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[bool], + def_levels: &[i16], +) -> Result<(), ParquetError> { + let mut col = match rg_writer.next_column()? { + Some(col) => col, + None => { + return Err(ParquetError::General( + "unexpected end of Parquet schema columns".to_string(), + )); + } + }; + match col.untyped() { + ColumnWriter::BoolColumnWriter(typed) => { + typed.write_batch(values, Some(def_levels), None)?; + } + _ => { + return Err(ParquetError::General( + "expected BOOLEAN column writer".to_string(), + )); + } + } + col.close() +} + +#[derive(Default)] +struct OptionalF64Column { + values: Vec, + def_levels: Vec, +} + +impl OptionalF64Column { + #[inline] + fn push(&mut self, value: Option) { + match value { + Some(v) => { + self.values.push(v); + self.def_levels.push(1); + } + None => { + self.def_levels.push(0); + } + } + } + + fn clear(&mut self) { + self.values.clear(); + self.def_levels.clear(); + } +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + effective_known_at_micros: Vec, + known_at_source_ids: Vec, + known_at_source_interner: StringInterner, + has_estimated_lag: Vec, + period_end: Vec, + fiscal_period_ids: Vec, + fiscal_period_interner: StringInterner, + currency_ids: Vec, + currency_interner: StringInterner, + period_known_at_micros: Vec, + revenue: OptionalF64Column, + net_income: OptionalF64Column, + operating_cash_flow: OptionalF64Column, + total_assets: OptionalF64Column, + total_equity: OptionalF64Column, + shares_outstanding: OptionalF64Column, + ttm_revenue: OptionalF64Column, + ttm_net_income: OptionalF64Column, + ttm_operating_cash_flow: OptionalF64Column, + ttm_period_end_values: Vec, + ttm_period_end_defs: Vec, + ttm_currency_ids: Vec, + ttm_currency_defs: Vec, + ttm_currency_interner: StringInterner, + ttm_has_estimated_lag_values: Vec, + ttm_has_estimated_lag_defs: Vec, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &FundamentalsPitParquetRow) { + self.listing_id.push(row.listing_id); + self.effective_known_at_micros + .push(row.effective_known_at_micros); + let kas_id = self + .known_at_source_interner + .intern(row.known_at_source.as_ref()); + self.known_at_source_ids.push(kas_id); + self.has_estimated_lag.push(row.has_estimated_lag); + self.period_end.push(row.period_end); + let fp_id = self + .fiscal_period_interner + .intern(row.fiscal_period.as_ref()); + self.fiscal_period_ids.push(fp_id); + let ccy_id = self.currency_interner.intern(row.currency.as_ref()); + self.currency_ids.push(ccy_id); + self.period_known_at_micros + .push(row.period_known_at_micros); + + self.revenue.push(row.revenue); + self.net_income.push(row.net_income); + self.operating_cash_flow.push(row.operating_cash_flow); + self.total_assets.push(row.total_assets); + self.total_equity.push(row.total_equity); + self.shares_outstanding.push(row.shares_outstanding); + self.ttm_revenue.push(row.ttm_revenue); + self.ttm_net_income.push(row.ttm_net_income); + self.ttm_operating_cash_flow + .push(row.ttm_operating_cash_flow); + + match row.ttm_period_end { + Some(day) => { + self.ttm_period_end_values.push(day); + self.ttm_period_end_defs.push(1); + } + None => { + self.ttm_period_end_defs.push(0); + } + } + match row.ttm_currency.as_deref() { + Some(ccy) => { + let id = self.ttm_currency_interner.intern(ccy); + self.ttm_currency_ids.push(id); + self.ttm_currency_defs.push(1); + } + None => { + self.ttm_currency_defs.push(0); + } + } + match row.ttm_has_estimated_lag { + Some(flag) => { + self.ttm_has_estimated_lag_values.push(flag); + self.ttm_has_estimated_lag_defs.push(1); + } + None => { + self.ttm_has_estimated_lag_defs.push(0); + } + } + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.effective_known_at_micros.clear(); + self.known_at_source_ids.clear(); + self.known_at_source_interner.clear(); + self.has_estimated_lag.clear(); + self.period_end.clear(); + self.fiscal_period_ids.clear(); + self.fiscal_period_interner.clear(); + self.currency_ids.clear(); + self.currency_interner.clear(); + self.period_known_at_micros.clear(); + self.revenue.clear(); + self.net_income.clear(); + self.operating_cash_flow.clear(); + self.total_assets.clear(); + self.total_equity.clear(); + self.shares_outstanding.clear(); + self.ttm_revenue.clear(); + self.ttm_net_income.clear(); + self.ttm_operating_cash_flow.clear(); + self.ttm_period_end_values.clear(); + self.ttm_period_end_defs.clear(); + self.ttm_currency_ids.clear(); + self.ttm_currency_defs.clear(); + self.ttm_currency_interner.clear(); + self.ttm_has_estimated_lag_values.clear(); + self.ttm_has_estimated_lag_defs.clear(); + } +} + +struct PartitionWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl PartitionWriter { + fn open( + dataset_dir: &Path, + year: i32, + run_id: &str, + schema: &TypePtr, + props: &WriterPropertiesPtr, + staging_guards: &mut BTreeMap, + ) -> Result { + let year_dir = dataset_dir.join(format!("year={year:04}")); + fs::create_dir_all(&year_dir).map_err(|source| ParquetFundamentalsError::Io { + path: year_dir.clone(), + source, + })?; + + let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; + staging_guards.insert(year, StagingFileGuard::new(tmp_path.clone())); + let final_path = year_dir.join("part.parquet"); + + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetFundamentalsError::Parquet { + path: tmp_path.clone(), + source, + }, + )?; + + Ok(Self { + tmp_path, + final_path, + writer, + buf: RowGroupBuffer::default(), + rows_written: 0, + row_groups_written: 0, + }) + } + + fn flush_row_group( + &mut self, + scratch: &mut Vec, + ) -> Result<(), ParquetFundamentalsError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetFundamentalsError::Parquet { + path: self.tmp_path.clone(), + source, + }; + + let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; + + // 1. listing_id (INT32, REQUIRED) + write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; + // 2. effective_known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.effective_known_at_micros).map_err(map_pq)?; + // 3. known_at_source (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.known_at_source_ids, + &self.buf.known_at_source_interner, + scratch, + ) + .map_err(map_pq)?; + // 4. has_estimated_lag (BOOLEAN, REQUIRED) + write_bool_col(&mut rg_writer, &self.buf.has_estimated_lag).map_err(map_pq)?; + // 5. period_end (INT32, REQUIRED, DATE) + write_i32_col(&mut rg_writer, &self.buf.period_end).map_err(map_pq)?; + // 6. fiscal_period (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.fiscal_period_ids, + &self.buf.fiscal_period_interner, + scratch, + ) + .map_err(map_pq)?; + // 7. currency (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.currency_ids, + &self.buf.currency_interner, + scratch, + ) + .map_err(map_pq)?; + // 8. period_known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.period_known_at_micros).map_err(map_pq)?; + // 9. revenue (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.revenue.values, + &self.buf.revenue.def_levels, + ) + .map_err(map_pq)?; + // 10. net_income (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.net_income.values, + &self.buf.net_income.def_levels, + ) + .map_err(map_pq)?; + // 11. operating_cash_flow (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.operating_cash_flow.values, + &self.buf.operating_cash_flow.def_levels, + ) + .map_err(map_pq)?; + // 12. total_assets (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.total_assets.values, + &self.buf.total_assets.def_levels, + ) + .map_err(map_pq)?; + // 13. total_equity (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.total_equity.values, + &self.buf.total_equity.def_levels, + ) + .map_err(map_pq)?; + // 14. shares_outstanding (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.shares_outstanding.values, + &self.buf.shares_outstanding.def_levels, + ) + .map_err(map_pq)?; + // 15. ttm_revenue (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_revenue.values, + &self.buf.ttm_revenue.def_levels, + ) + .map_err(map_pq)?; + // 16. ttm_net_income (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_net_income.values, + &self.buf.ttm_net_income.def_levels, + ) + .map_err(map_pq)?; + // 17. ttm_operating_cash_flow (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_operating_cash_flow.values, + &self.buf.ttm_operating_cash_flow.def_levels, + ) + .map_err(map_pq)?; + // 18. ttm_period_end (INT32, OPTIONAL, DATE) + write_optional_i32_col( + &mut rg_writer, + &self.buf.ttm_period_end_values, + &self.buf.ttm_period_end_defs, + ) + .map_err(map_pq)?; + // 19. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING) + write_optional_interned_str_col( + &mut rg_writer, + &self.buf.ttm_currency_ids, + &self.buf.ttm_currency_defs, + &self.buf.ttm_currency_interner, + scratch, + ) + .map_err(map_pq)?; + // 20. ttm_has_estimated_lag (BOOLEAN, OPTIONAL) + write_optional_bool_col( + &mut rg_writer, + &self.buf.ttm_has_estimated_lag_values, + &self.buf.ttm_has_estimated_lag_defs, + ) + .map_err(map_pq)?; + + rg_writer.close().map_err(map_pq)?; + + self.rows_written += row_count; + self.row_groups_written += 1; + self.buf.clear(); + Ok(()) + } + + fn finish_and_sync( + mut self, + scratch: &mut Vec, + ) -> Result { + self.flush_row_group(scratch)?; + + let mut buf_writer = + self.writer + .into_inner() + .map_err(|source| ParquetFundamentalsError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer + .flush() + .map_err(|source| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all() + .map_err(|source| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedPartitionFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedPartitionFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +fn finish_with_rollback( + cause: ParquetFundamentalsError, + published: &[PublishedPartition], + extra_failure: Option, +) -> ParquetFundamentalsError { + let mut failures = Vec::new(); + if let Some(failure) = extra_failure { + failures.push(failure); + } + failures.extend(rollback_published(published)); + if failures.is_empty() { + cause + } else { + ParquetFundamentalsError::RollbackFailed { + cause: Box::new(cause), + failures, + } + } +} + +/// Streams strictly ascending `fundamentals_pit` rows into year-partitioned Zstd Parquet files at +/// `/fundamentals_pit/year=YYYY/part.parquet`, partitioned by the UTC year of +/// `effective_known_at`. +/// +/// # Sort Order & Validation +/// Input rows must be strictly ascending and unique by `(listing_id, effective_known_at_micros)`. +/// Out-of-order rows, duplicates, non-finite numeric fields, out-of-range dates/years, +/// `period_known_at_micros > effective_known_at_micros`, empty required strings, or inconsistent +/// TTM metadata return typed [`ParquetFundamentalsError`] variants with nothing published. Empty +/// input returns `Ok(FundamentalsPitWriteStats::default())` without creating +/// `/fundamentals_pit` or touching pre-existing partitions. +pub fn write_fundamentals_pit_dataset( + out_dir: P, + rows: I, + options: FundamentalsPitWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_fundamentals_pit_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _, _| {}, + ) +} + +fn write_fundamentals_pit_dataset_with_hooks( + out_dir: P, + rows: I, + options: FundamentalsPitWriteOptions, + lock_timeout: Duration, + on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(i32, &Path, Option<&Path>), +{ + write_fundamentals_pit_dataset_with_lock_and_backup_hooks( + out_dir, + rows, + options, + lock_timeout, + || {}, + on_after_backup, + ) +} + +fn write_fundamentals_pit_dataset_with_lock_and_backup_hooks( + out_dir: P, + rows: I, + options: FundamentalsPitWriteOptions, + lock_timeout: Duration, + mut on_lock_contended: G, + mut on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + G: FnMut(), + F: FnMut(i32, &Path, Option<&Path>), +{ + if options.row_group_rows == 0 { + return Err(ParquetFundamentalsError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetFundamentalsError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(FundamentalsPitWriteStats::default()); + }; + validate_row(first_item.borrow(), 0)?; + + let out_dir = out_dir.as_ref(); + let dataset_dir = out_dir.join("fundamentals_pit"); + let schema = + fundamentals_pit_parquet_schema().map_err(|source| ParquetFundamentalsError::Parquet { + path: dataset_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&dataset_dir).map_err(|source| ParquetFundamentalsError::Io { + path: dataset_dir.clone(), + source, + })?; + + let dataset_mu = dataset_mutex(&dataset_dir); + let _in_process_guard = match dataset_mu.try_lock() { + Ok(guard) => guard, + Err(std::sync::TryLockError::Poisoned(err)) => err.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + on_lock_contended(); + dataset_mu.lock().unwrap_or_else(|err| err.into_inner()) + } + }; + let _file_lock = DatasetFileLock::acquire_with_timeout(&dataset_dir, lock_timeout)?; + + let run_id = next_run_id(); + // Declared before `writers` so reverse drop order closes file handles before unlinking `.tmp`. + let mut staging_guards: BTreeMap = BTreeMap::new(); + let mut writers: BTreeMap = BTreeMap::new(); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let synced_files: Vec<(i32, SyncedPartitionFile)> = { + let mut prev_item: Option = None; + + for (row_index, item) in std::iter::once(first_item).chain(row_iter).enumerate() { + let row = item.borrow(); + if let Some(prev) = prev_item.as_ref() { + let prev_row = prev.borrow(); + match compare_row_keys(row, prev_row) { + Ordering::Equal => { + return Err(ParquetFundamentalsError::DuplicateRow { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + Ordering::Less => { + return Err(ParquetFundamentalsError::UnsortedInput { + row_index, + prev_listing_id: prev_row.listing_id, + prev_effective_known_at_micros: prev_row.effective_known_at_micros, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + Ordering::Greater => {} + } + } + let year = validate_row(row, row_index)?; + + let pw = match writers.entry(year) { + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::btree_map::Entry::Vacant(entry) => { + let opened = PartitionWriter::open( + &dataset_dir, + year, + &run_id, + &schema, + &props, + &mut staging_guards, + )?; + entry.insert(opened) + } + }; + + pw.buf.push(row); + if pw.buf.len() == options.row_group_rows { + pw.flush_row_group(&mut scratch)?; + } + prev_item = Some(item); + } + + let mut synced = Vec::with_capacity(writers.len()); + let drained: Vec<(i32, PartitionWriter)> = + std::mem::take(&mut writers).into_iter().collect(); + for (year, pw) in drained { + let file = pw.finish_and_sync(&mut scratch)?; + synced.push((year, file)); + } + synced + }; + + let mut stats = FundamentalsPitWriteStats::default(); + let mut published: Vec = Vec::with_capacity(synced_files.len()); + for (year, file) in synced_files { + let backup_path = match fs::symlink_metadata(&file.final_path) { + Ok(meta) if !meta.is_dir() => { + match create_backup_preserving_live(&file.final_path, &run_id) { + Ok(bak) => Some(bak), + Err(err) => { + return Err(finish_with_rollback(err.into(), &published, None)); + } + } + } + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + let err = ParquetFundamentalsError::Io { + path: file.final_path, + source, + }; + return Err(finish_with_rollback(err, &published, None)); + } + }; + + on_after_backup(year, &file.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { + let extra_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: file.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let err = ParquetFundamentalsError::Io { + path: file.final_path, + source, + }; + return Err(finish_with_rollback(err, &published, extra_failure)); + } + + if let Some(guard) = staging_guards.get_mut(&year) { + guard.disarm(); + } + + published.push(PublishedPartition { + final_path: file.final_path, + backup_path, + }); + stats.rows_written += file.rows_written; + stats.files_written += 1; + stats.row_groups_written += file.row_groups_written; + stats.bytes_written += file.bytes; + stats.rows_by_year.insert(year, file.rows_written); + } + + for part in &published { + if let Some(bak) = &part.backup_path { + let _ = fs::remove_file(bak); + } + } + + Ok(stats) +} + +#[cfg(test)] +#[path = "parquet_fundamentals_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/parquet_fundamentals_tests.rs b/tools/curate-etl/src/parquet_fundamentals_tests.rs new file mode 100644 index 00000000..eedf655e --- /dev/null +++ b/tools/curate-etl/src/parquet_fundamentals_tests.rs @@ -0,0 +1,1537 @@ +//! Schema, round-trip, PIT restatement replay, partitioning, validation, and atomic-rollback +//! tests for `parquet_fundamentals`. + +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::basic::{ + Compression, ConvertedType, LogicalType, Repetition, TimeUnit, Type as PhysicalType, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, + write_fundamentals_pit_dataset_with_hooks, FundamentalsPitParquetRow, + FundamentalsPitWriteOptions, FundamentalsPitWriteStats, ParquetFundamentalsError, + DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, +}; +use crate::events::{ + partition_year_utc, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::fundamentals::{ + build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, + FundamentalsFields, FundamentalsPeriodSlot, FundamentalsSnapshot, StatutoryLagVenue, +}; +use crate::parquet_publish::DEFAULT_LOCK_TIMEOUT; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-fundamentals-test-{label}-{pid}-{seq}" + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(year: i32, month: u32, day: u32) -> i32 { + ymd_to_epoch_days(year, month, day).expect("valid test date") +} + +fn utc_micros( + year: i32, + month: u32, + day_of_month: u32, + hour: u8, + minute: u8, + second: u8, + micro: i64, +) -> i64 { + let epoch_day = day(year, month, day_of_month); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000_000 + micro +} + +fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + fn walk(dir: &Path) { + for entry in fs::read_dir(dir).expect("read_dir") { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(&path); + } else { + let name = path + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or_default(); + assert!( + !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", + "unexpected transient file left behind: {}", + path.display() + ); + } + } + } + walk(dir); +} + +fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_rows = meta.row_group(rg_idx).num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_i32_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i32 records"); + assert!(n > 0, "unexpected short read in INT32 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + + let read_opt_i32_col = |col_idx: usize| -> Vec> { + let mut vals = Vec::new(); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read optional i32 records"); + assert!(n > 0, "unexpected short read in opt INT32 column {col_idx}"); + read += n; + } + } + _ => panic!("expected optional INT32 column at index {col_idx}"), + } + let mut val_iter = vals.into_iter(); + defs.into_iter() + .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .collect() + }; + + let read_i64_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i64 records"); + assert!(n > 0, "unexpected short read in INT64 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + + let read_bool_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read bool records"); + assert!(n > 0, "unexpected short read in BOOLEAN column {col_idx}"); + read += n; + } + } + _ => panic!("expected BOOLEAN column at index {col_idx}"), + } + vals + }; + + let read_opt_bool_col = |col_idx: usize| -> Vec> { + let mut vals = Vec::new(); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read optional bool records"); + assert!(n > 0, "unexpected short read in opt BOOLEAN column {col_idx}"); + read += n; + } + } + _ => panic!("expected optional BOOLEAN column at index {col_idx}"), + } + let mut val_iter = vals.into_iter(); + defs.into_iter() + .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .collect() + }; + + let read_opt_f64_col = |col_idx: usize| -> Vec> { + let mut vals = Vec::new(); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read optional f64 records"); + assert!(n > 0, "unexpected short read in DOUBLE column {col_idx}"); + read += n; + } + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + let mut val_iter = vals.into_iter(); + defs.into_iter() + .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .collect() + }; + + let read_str_col = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read byte_array records"); + assert!(n > 0, "unexpected short read in BYTE_ARRAY column {col_idx}"); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + raw.iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) + .collect() + }; + + let read_opt_str_col = |col_idx: usize| -> Vec> { + let mut raw = Vec::new(); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut raw) + .expect("read optional byte_array records"); + assert!( + n > 0, + "unexpected short read in opt BYTE_ARRAY column {col_idx}" + ); + read += n; + } + } + _ => panic!("expected optional BYTE_ARRAY column at index {col_idx}"), + } + let mut val_iter = raw.into_iter().map(|b| { + std::str::from_utf8(b.data()) + .expect("valid utf8") + .to_string() + }); + defs.into_iter() + .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .collect() + }; + + // Positional 20-column decode matching fundamentals_pit_parquet_schema(). + let listing_ids = read_i32_col(0); + let effective_known_at = read_i64_col(1); + let known_at_source = read_str_col(2); + let has_estimated_lag = read_bool_col(3); + let period_end = read_i32_col(4); + let fiscal_period = read_str_col(5); + let currency = read_str_col(6); + let period_known_at = read_i64_col(7); + let revenue = read_opt_f64_col(8); + let net_income = read_opt_f64_col(9); + let operating_cash_flow = read_opt_f64_col(10); + let total_assets = read_opt_f64_col(11); + let total_equity = read_opt_f64_col(12); + let shares_outstanding = read_opt_f64_col(13); + let ttm_revenue = read_opt_f64_col(14); + let ttm_net_income = read_opt_f64_col(15); + let ttm_operating_cash_flow = read_opt_f64_col(16); + let ttm_period_end = read_opt_i32_col(17); + let ttm_currency = read_opt_str_col(18); + let ttm_has_estimated_lag = read_opt_bool_col(19); + + for i in 0..rg_rows { + out.push(FundamentalsPitParquetRow { + listing_id: listing_ids[i], + effective_known_at_micros: effective_known_at[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + has_estimated_lag: has_estimated_lag[i], + period_end: period_end[i], + fiscal_period: Cow::Owned(fiscal_period[i].clone()), + currency: Cow::Owned(currency[i].clone()), + period_known_at_micros: period_known_at[i], + revenue: revenue[i], + net_income: net_income[i], + operating_cash_flow: operating_cash_flow[i], + total_assets: total_assets[i], + total_equity: total_equity[i], + shares_outstanding: shares_outstanding[i], + ttm_revenue: ttm_revenue[i], + ttm_net_income: ttm_net_income[i], + ttm_operating_cash_flow: ttm_operating_cash_flow[i], + ttm_period_end: ttm_period_end[i], + ttm_currency: ttm_currency[i].clone().map(Cow::Owned), + ttm_has_estimated_lag: ttm_has_estimated_lag[i], + }); + } + } + + out +} + +fn assert_row_matches_snapshot_bit_for_bit( + actual: &FundamentalsPitParquetRow, + snapshot: &FundamentalsSnapshot, +) { + let latest = snapshot + .periods + .first() + .expect("snapshot must have at least one period"); + assert_eq!(actual.listing_id, snapshot.key); + assert_eq!( + actual.effective_known_at_micros, + snapshot.effective_known_at_utc_micros + ); + assert_eq!(actual.known_at_source.as_ref(), snapshot.known_at_source); + assert_eq!(actual.has_estimated_lag, snapshot.has_estimated_lag); + assert_eq!(actual.period_end, latest.period_end); + assert_eq!(actual.fiscal_period.as_ref(), latest.fiscal_period.as_str()); + assert_eq!(actual.currency.as_ref(), latest.currency.as_str()); + assert_eq!(actual.period_known_at_micros, latest.known_at_utc_micros); + + assert_eq!( + actual.revenue.map(f64::to_bits), + latest.fields.revenue.map(f64::to_bits) + ); + assert_eq!( + actual.net_income.map(f64::to_bits), + latest.fields.net_income.map(f64::to_bits) + ); + assert_eq!( + actual.operating_cash_flow.map(f64::to_bits), + latest.fields.operating_cash_flow.map(f64::to_bits) + ); + assert_eq!( + actual.total_assets.map(f64::to_bits), + latest.fields.total_assets.map(f64::to_bits) + ); + assert_eq!( + actual.total_equity.map(f64::to_bits), + latest.fields.total_equity.map(f64::to_bits) + ); + assert_eq!( + actual.shares_outstanding.map(f64::to_bits), + latest.fields.shares_outstanding.map(f64::to_bits) + ); + + match &snapshot.ttm { + Some(ttm) => { + assert_eq!( + actual.ttm_revenue.map(f64::to_bits), + ttm.flows.revenue.map(f64::to_bits) + ); + assert_eq!( + actual.ttm_net_income.map(f64::to_bits), + ttm.flows.net_income.map(f64::to_bits) + ); + assert_eq!( + actual.ttm_operating_cash_flow.map(f64::to_bits), + ttm.flows.operating_cash_flow.map(f64::to_bits) + ); + assert_eq!(actual.ttm_period_end, Some(ttm.ending_period_end)); + assert_eq!(actual.ttm_currency.as_deref(), Some(ttm.currency.as_str())); + assert_eq!(actual.ttm_has_estimated_lag, Some(ttm.has_estimated_lag)); + } + None => { + assert_eq!(actual.ttm_revenue, None); + assert_eq!(actual.ttm_net_income, None); + assert_eq!(actual.ttm_operating_cash_flow, None); + assert_eq!(actual.ttm_period_end, None); + assert_eq!(actual.ttm_currency, None); + assert_eq!(actual.ttm_has_estimated_lag, None); + } + } +} + +fn assert_row_bit_eq(a: &FundamentalsPitParquetRow, b: &FundamentalsPitParquetRow) { + assert_eq!(a.listing_id, b.listing_id); + assert_eq!(a.effective_known_at_micros, b.effective_known_at_micros); + assert_eq!(a.known_at_source, b.known_at_source); + assert_eq!(a.has_estimated_lag, b.has_estimated_lag); + assert_eq!(a.period_end, b.period_end); + assert_eq!(a.fiscal_period, b.fiscal_period); + assert_eq!(a.currency, b.currency); + assert_eq!(a.period_known_at_micros, b.period_known_at_micros); + assert_eq!(a.revenue.map(f64::to_bits), b.revenue.map(f64::to_bits)); + assert_eq!( + a.net_income.map(f64::to_bits), + b.net_income.map(f64::to_bits) + ); + assert_eq!( + a.operating_cash_flow.map(f64::to_bits), + b.operating_cash_flow.map(f64::to_bits) + ); + assert_eq!( + a.total_assets.map(f64::to_bits), + b.total_assets.map(f64::to_bits) + ); + assert_eq!( + a.total_equity.map(f64::to_bits), + b.total_equity.map(f64::to_bits) + ); + assert_eq!( + a.shares_outstanding.map(f64::to_bits), + b.shares_outstanding.map(f64::to_bits) + ); + assert_eq!( + a.ttm_revenue.map(f64::to_bits), + b.ttm_revenue.map(f64::to_bits) + ); + assert_eq!( + a.ttm_net_income.map(f64::to_bits), + b.ttm_net_income.map(f64::to_bits) + ); + assert_eq!( + a.ttm_operating_cash_flow.map(f64::to_bits), + b.ttm_operating_cash_flow.map(f64::to_bits) + ); + assert_eq!(a.ttm_period_end, b.ttm_period_end); + assert_eq!(a.ttm_currency, b.ttm_currency); + assert_eq!(a.ttm_has_estimated_lag, b.ttm_has_estimated_lag); +} + +fn sample_row(listing_id: i32, effective_known_at_micros: i64) -> FundamentalsPitParquetRow { + FundamentalsPitParquetRow { + listing_id, + effective_known_at_micros, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + has_estimated_lag: false, + period_end: day(2024, 3, 31), + fiscal_period: Cow::Borrowed("Q"), + currency: Cow::Borrowed("USD"), + period_known_at_micros: effective_known_at_micros, + revenue: Some(100.0), + net_income: Some(15.0), + operating_cash_flow: Some(22.0), + total_assets: Some(500.0), + total_equity: Some(250.0), + shares_outstanding: Some(10_000_000.0), + ttm_revenue: Some(400.0), + ttm_net_income: Some(60.0), + ttm_operating_cash_flow: Some(88.0), + ttm_period_end: Some(day(2024, 3, 31)), + ttm_currency: Some(Cow::Borrowed("USD")), + ttm_has_estimated_lag: Some(false), + } +} + +#[test] +fn schema_matches_contract_columns_types_nullability_and_order() { + let schema = fundamentals_pit_parquet_schema().expect("build schema"); + assert_eq!(schema.name(), "fundamentals_pit"); + + let fields = schema.get_fields(); + assert_eq!(fields.len(), 20); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 20] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "effective_known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "known_at_source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "has_estimated_lag", + PhysicalType::BOOLEAN, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "period_end", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "fiscal_period", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "currency", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "period_known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "revenue", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "net_income", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "operating_cash_flow", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "total_assets", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "total_equity", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "shares_outstanding", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_revenue", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_net_income", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_operating_cash_flow", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_period_end", + PhysicalType::INT32, + Repetition::OPTIONAL, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "ttm_currency", + PhysicalType::BYTE_ARRAY, + Repetition::OPTIONAL, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "ttm_has_estimated_lag", + PhysicalType::BOOLEAN, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + let field = &fields[idx]; + assert_eq!(field.name(), name, "column {idx} name"); + assert_eq!(field.get_physical_type(), phys, "column {idx} physical type"); + assert_eq!( + field.get_basic_info().repetition(), + rep, + "column {idx} repetition" + ); + assert_eq!( + field.get_basic_info().logical_type_ref().cloned(), + logical, + "column {idx} logical type" + ); + assert_eq!( + field.get_basic_info().converted_type(), + converted, + "column {idx} converted type" + ); + } +} + +#[test] +fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero() { + let tmp = TempDirGuard::new("builder-roundtrip"); + + let venues = BTreeMap::from([ + (10_i32, StatutoryLagVenue::UsTsx), + (20_i32, StatutoryLagVenue::TsxvCse), + ]); + + let observations = vec![ + // Listing 10: 4 consecutive quarters (Q2 2023 .. Q1 2024), with distinct flow values + // and a missing operating_cash_flow in Q4 2023 so TTM operating_cash_flow is None while + // ttm_revenue and ttm_net_income are populated. + FinancialObservation { + key: 10_i32, + period_end: day(2023, 6, 30), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2023, 8, 2)), + fields: FundamentalsFields { + revenue: Some(101.25), + net_income: Some(11.5), + operating_cash_flow: Some(19.75), + total_assets: Some(1_000.0), + total_equity: Some(400.0), + shares_outstanding: Some(50_000_000.0), + }, + }, + FinancialObservation { + key: 10_i32, + period_end: day(2023, 9, 30), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2023, 11, 3)), + fields: FundamentalsFields { + revenue: Some(110.5), + net_income: Some(12.25), + operating_cash_flow: Some(21.0), + total_assets: None, + total_equity: Some(415.0), + shares_outstanding: Some(50_100_000.0), + }, + }, + FinancialObservation { + key: 10_i32, + period_end: day(2023, 12, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 2, 14)), + fields: FundamentalsFields { + revenue: Some(125.0), + net_income: Some(14.0), + operating_cash_flow: None, + total_assets: Some(1_120.0), + total_equity: None, + shares_outstanding: Some(50_200_000.0), + }, + }, + FinancialObservation { + key: 10_i32, + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 5, 1)), + fields: FundamentalsFields { + revenue: Some(130.75), + net_income: Some(16.5), + operating_cash_flow: Some(24.25), + total_assets: Some(1_150.0), + total_equity: Some(440.0), + shares_outstanding: None, + }, + }, + // Listing 20: unlinked observation -> statutory_lag_estimate (+60d for TSXV/CSE), ttm == None. + FinancialObservation { + key: 20_i32, + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "CAD".to_string(), + report_date: None, + fields: FundamentalsFields { + revenue: Some(-0.0), + net_income: Some(-3.5), + operating_cash_flow: None, + total_assets: Some(25.0), + total_equity: Some(12.5), + shares_outstanding: Some(8_000_000.0), + }, + }, + ]; + + let filings = vec![ + QmFiling { + key: 10_i32, + timefiled: "2023-08-02T16:10:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-10-2023Q2".to_string()), + url: None, + }, + QmFiling { + key: 10_i32, + timefiled: "2023-11-03T16:05:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-10-2023Q3".to_string()), + url: None, + }, + QmFiling { + key: 10_i32, + timefiled: "2024-02-14T16:15:00 EST".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-10-2023Q4".to_string()), + url: None, + }, + QmFiling { + key: 10_i32, + timefiled: "2024-05-01T16:20:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-10-2024Q1".to_string()), + url: None, + }, + ]; + + let built = build_fundamentals_rows(observations, filings, &venues); + let mut snapshots = build_fundamentals_snapshots(&built.rows, 4).expect("build snapshots"); + assert_eq!(snapshots.len(), 5); + + // Append a direct snapshot carrying signed negative zero (-0.0) in a statement field so we + // verify the Parquet writer preserves exact IEEE-754 bit patterns without altering them. + snapshots.push(FundamentalsSnapshot { + key: 30_i32, + effective_known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0), + known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG, + has_estimated_lag: true, + periods: vec![FundamentalsPeriodSlot { + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "CAD".to_string(), + known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0), + known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG, + has_estimated_lag: true, + fields: FundamentalsFields { + revenue: Some(-0.0_f64), + net_income: Some(0.0_f64), + operating_cash_flow: None, + total_assets: Some(10.0), + total_equity: None, + shares_outstanding: Some(1_000_000.0), + }, + }], + ttm: None, + }); + + let rows_from_ref: Vec = snapshots + .iter() + .map(FundamentalsPitParquetRow::try_from) + .collect::>() + .expect("convert snapshots by ref"); + let rows_from_owned: Vec = snapshots + .clone() + .into_iter() + .map(FundamentalsPitParquetRow::try_from) + .collect::>() + .expect("convert snapshots owned"); + assert_eq!(rows_from_ref.len(), rows_from_owned.len()); + for (a, b) in rows_from_ref.iter().zip(rows_from_owned.iter()) { + assert_row_bit_eq(a, b); + } + + let opts = FundamentalsPitWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }; + let stats = write_fundamentals_pit_dataset(tmp.path(), &rows_from_ref, opts) + .expect("write fundamentals_pit"); + + let expected_by_year = BTreeMap::from([(2023, 2), (2024, 4)]); + assert_eq!(stats.rows_written, 6); + assert_eq!(stats.files_written, 2); + assert_eq!(stats.row_groups_written, 3); + assert_eq!(stats.rows_by_year, expected_by_year); + + let expected_schema = fundamentals_pit_parquet_schema().unwrap(); + let mut total_bytes = 0u64; + for (&year, &expected_count) in &expected_by_year { + let path = tmp + .path() + .join(format!("fundamentals_pit/year={year:04}/part.parquet")); + assert!(path.is_file(), "missing {}", path.display()); + total_bytes += fs::metadata(&path).unwrap().len(); + + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref()); + assert_eq!(meta.file_metadata().num_rows() as usize, expected_count); + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "year {year} column {} must be ZSTD", + col.column_path() + ); + } + } + + let decoded = read_parquet_rows(&path); + let expected_snapshots: Vec<&FundamentalsSnapshot> = snapshots + .iter() + .filter(|s| partition_year_utc(s.effective_known_at_utc_micros) == year) + .collect(); + assert_eq!(decoded.len(), expected_snapshots.len()); + for (actual_row, snap) in decoded.iter().zip(expected_snapshots.iter()) { + assert_row_matches_snapshot_bit_for_bit(actual_row, snap); + } + + if year == 2024 { + // Verify signed negative zero (-0.0) survived bit-for-bit on listing 30. + let signed_zero_row = decoded + .iter() + .find(|r| r.listing_id == 30) + .expect("listing 30 row"); + assert_eq!( + signed_zero_row.revenue.map(f64::to_bits), + Some((-0.0_f64).to_bits()) + ); + assert_ne!( + signed_zero_row.revenue.map(f64::to_bits), + Some(0.0_f64.to_bits()) + ); + assert_eq!( + signed_zero_row.net_income.map(f64::to_bits), + Some(0.0_f64.to_bits()) + ); + + // Verify listing 10 Q1 2024 snapshot has TTM revenue & net_income populated, + // TTM operating_cash_flow None, and distinct flow values. + let ttm_row = decoded + .iter() + .find(|r| r.listing_id == 10 && r.period_end == day(2024, 3, 31)) + .expect("listing 10 Q1 2024 row"); + assert_eq!(ttm_row.ttm_revenue, Some(467.5)); + assert_eq!(ttm_row.ttm_net_income, Some(54.25)); + assert_eq!(ttm_row.ttm_operating_cash_flow, None); + assert_eq!(ttm_row.ttm_period_end, Some(day(2024, 3, 31))); + assert_eq!(ttm_row.ttm_currency.as_deref(), Some("USD")); + assert_eq!(ttm_row.ttm_has_estimated_lag, Some(false)); + } + } + assert_eq!(stats.bytes_written, total_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +#[test] +fn restated_q1_after_q2_preserves_earlier_snapshots_and_keeps_q2_as_latest_period() { + let venues = BTreeMap::from([(42_i32, StatutoryLagVenue::UsTsx)]); + + let base_observations = vec![ + FinancialObservation { + key: 42_i32, + period_end: day(2023, 6, 30), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2023, 8, 1)), + fields: FundamentalsFields { + revenue: Some(100.0), + net_income: Some(10.0), + operating_cash_flow: Some(15.0), + total_assets: Some(900.0), + total_equity: Some(400.0), + shares_outstanding: Some(10_000_000.0), + }, + }, + FinancialObservation { + key: 42_i32, + period_end: day(2023, 9, 30), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2023, 11, 1)), + fields: FundamentalsFields { + revenue: Some(110.0), + net_income: Some(11.0), + operating_cash_flow: Some(16.0), + total_assets: Some(920.0), + total_equity: Some(410.0), + shares_outstanding: Some(10_000_000.0), + }, + }, + FinancialObservation { + key: 42_i32, + period_end: day(2023, 12, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 2, 1)), + fields: FundamentalsFields { + revenue: Some(120.0), + net_income: Some(12.0), + operating_cash_flow: Some(17.0), + total_assets: Some(950.0), + total_equity: Some(420.0), + shares_outstanding: Some(10_000_000.0), + }, + }, + // Q1 2024 original filing on 2024-05-01 + FinancialObservation { + key: 42_i32, + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 5, 1)), + fields: FundamentalsFields { + revenue: Some(130.0), + net_income: Some(13.0), + operating_cash_flow: Some(18.0), + total_assets: Some(980.0), + total_equity: Some(430.0), + shares_outstanding: Some(10_000_000.0), + }, + }, + // Q2 2024 filing on 2024-08-01 + FinancialObservation { + key: 42_i32, + period_end: day(2024, 6, 30), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 8, 1)), + fields: FundamentalsFields { + revenue: Some(140.0), + net_income: Some(14.0), + operating_cash_flow: Some(19.0), + total_assets: Some(1_010.0), + total_equity: Some(445.0), + shares_outstanding: Some(10_000_000.0), + }, + }, + ]; + + let base_filings = vec![ + QmFiling { + key: 42_i32, + timefiled: "2023-08-01T16:10:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-Q2-2023".to_string()), + url: None, + }, + QmFiling { + key: 42_i32, + timefiled: "2023-11-01T16:10:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-Q3-2023".to_string()), + url: None, + }, + QmFiling { + key: 42_i32, + timefiled: "2024-02-01T16:10:00 EST".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-Q4-2023".to_string()), + url: None, + }, + QmFiling { + key: 42_i32, + timefiled: "2024-05-01T16:10:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-Q1-2024".to_string()), + url: None, + }, + QmFiling { + key: 42_i32, + timefiled: "2024-08-01T16:10:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-Q2-2024".to_string()), + url: None, + }, + ]; + + // Baseline run (pre-amendment) + let tmp_base = TempDirGuard::new("restatement-base"); + let base_built = build_fundamentals_rows( + base_observations.clone(), + base_filings.clone(), + &venues, + ); + let base_snaps = build_fundamentals_snapshots(&base_built.rows, 4).expect("build base snaps"); + let base_rows: Vec = base_snaps + .iter() + .map(FundamentalsPitParquetRow::try_from) + .collect::>() + .unwrap(); + write_fundamentals_pit_dataset( + tmp_base.path(), + &base_rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("write baseline"); + + let mut base_decoded = read_parquet_rows( + &tmp_base + .path() + .join("fundamentals_pit/year=2023/part.parquet"), + ); + base_decoded.extend(read_parquet_rows( + &tmp_base + .path() + .join("fundamentals_pit/year=2024/part.parquet"), + )); + assert_eq!(base_decoded.len(), 5); + + // Amended run: append Q1 2024 restatement filed on 2024-09-15 (after Q2's 2024-08-01 filing) + let mut amended_observations = base_observations; + amended_observations.push(FinancialObservation { + key: 42_i32, + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 9, 15)), + fields: FundamentalsFields { + revenue: Some(125.0), // restated -5.0 + net_income: Some(9.0), // restated -4.0 + operating_cash_flow: None, // carried forward from Q1 original (18.0) + total_assets: Some(975.0), + total_equity: Some(426.0), + shares_outstanding: Some(10_000_000.0), + }, + }); + let mut amended_filings = base_filings; + amended_filings.push(QmFiling { + key: 42_i32, + timefiled: "2024-09-15T16:30:00 EDT".to_string(), + form_type: "10-Q/A".to_string(), + filing_id: Some("F-Q1-2024-A".to_string()), + url: None, + }); + + let tmp_amended = TempDirGuard::new("restatement-amended"); + let amended_built = build_fundamentals_rows(amended_observations, amended_filings, &venues); + let amended_snaps = + build_fundamentals_snapshots(&amended_built.rows, 4).expect("build amended snaps"); + let amended_rows: Vec = amended_snaps + .iter() + .map(FundamentalsPitParquetRow::try_from) + .collect::>() + .unwrap(); + write_fundamentals_pit_dataset( + tmp_amended.path(), + &amended_rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("write amended"); + + let mut amended_decoded = read_parquet_rows( + &tmp_amended + .path() + .join("fundamentals_pit/year=2023/part.parquet"), + ); + amended_decoded.extend(read_parquet_rows( + &tmp_amended + .path() + .join("fundamentals_pit/year=2024/part.parquet"), + )); + assert_eq!(amended_decoded.len(), 6); + + // Every earlier snapshot (including Q2 on 2024-08-01) must remain bit-for-bit identical. + for i in 0..5 { + assert_row_bit_eq(&amended_decoded[i], &base_decoded[i]); + } + + let q2_row = &amended_decoded[4]; + let restatement_row = &amended_decoded[5]; + // Restatement appears as its own later effective_known_at row (2024-09-15 16:30 EDT = 20:30 UTC). + assert_eq!( + restatement_row.effective_known_at_micros, + utc_micros(2024, 9, 15, 20, 30, 0, 0) + ); + assert!(restatement_row.effective_known_at_micros > q2_row.effective_known_at_micros); + + // Q2 remains the latest period_end and period_known_at — restated Q1 never replaces Q2. + assert_eq!(restatement_row.period_end, day(2024, 6, 30)); + assert_eq!(restatement_row.period_known_at_micros, q2_row.period_known_at_micros); + assert_eq!(restatement_row.revenue, q2_row.revenue); + assert_eq!(restatement_row.net_income, q2_row.net_income); + assert_eq!( + restatement_row.operating_cash_flow, + q2_row.operating_cash_flow + ); + + // TTM flows reflect the restated Q1 (Q3 2023 + Q4 2023 + Q1 2024 restated + Q2 2024): + // baseline Q2 TTM: rev = 110+120+130+140 = 500, ni = 11+12+13+14 = 50, ocf = 16+17+18+19 = 70 + assert_eq!(q2_row.ttm_revenue, Some(500.0)); + assert_eq!(q2_row.ttm_net_income, Some(50.0)); + assert_eq!(q2_row.ttm_operating_cash_flow, Some(70.0)); + // after Q1 restatement: rev = 495, ni = 46, ocf unchanged = 70 + assert_eq!(restatement_row.ttm_revenue, Some(495.0)); + assert_eq!(restatement_row.ttm_net_income, Some(46.0)); + assert_eq!(restatement_row.ttm_operating_cash_flow, Some(70.0)); + assert_eq!(restatement_row.ttm_period_end, Some(day(2024, 6, 30))); +} + +#[test] +fn partitions_by_effective_known_at_utc_year_with_boundary_and_stats() { + let tmp_a = TempDirGuard::new("partition-boundary-a"); + let tmp_b = TempDirGuard::new("partition-boundary-b"); + + let rows = vec![ + sample_row(1, utc_micros(2023, 5, 1, 12, 0, 0, 0)), + sample_row(1, utc_micros(2023, 12, 31, 23, 59, 59, 999_999)), + sample_row(1, utc_micros(2024, 1, 1, 0, 0, 0, 0)), + sample_row(2, utc_micros(2023, 11, 15, 21, 5, 0, 0)), + sample_row(2, utc_micros(2024, 2, 10, 14, 0, 0, 0)), + ]; + + let opts = FundamentalsPitWriteOptions::default(); + let stats_a = write_fundamentals_pit_dataset(tmp_a.path(), &rows, opts).unwrap(); + let stats_b = write_fundamentals_pit_dataset(tmp_b.path(), &rows, opts).unwrap(); + assert_eq!(stats_a, stats_b); + + let expected_by_year = BTreeMap::from([(2023, 3), (2024, 2)]); + assert_eq!(stats_a.rows_written, 5); + assert_eq!(stats_a.files_written, 2); + assert_eq!(stats_a.row_groups_written, 2); + assert_eq!(stats_a.rows_by_year, expected_by_year); + + let dataset_dir = tmp_a.path().join("fundamentals_pit"); + let mut year_dirs: Vec = fs::read_dir(&dataset_dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + year_dirs.sort(); + assert_eq!(year_dirs, vec!["year=2023", "year=2024"]); + + let mut total_bytes = 0u64; + for year in [2023, 2024] { + let pa = tmp_a + .path() + .join(format!("fundamentals_pit/year={year:04}/part.parquet")); + let pb = tmp_b + .path() + .join(format!("fundamentals_pit/year={year:04}/part.parquet")); + assert!(pa.is_file()); + let bytes_a = fs::read(&pa).unwrap(); + let bytes_b = fs::read(&pb).unwrap(); + assert_eq!( + bytes_a, bytes_b, + "year {year} output must be deterministic across runs" + ); + total_bytes += bytes_a.len() as u64; + + let decoded = read_parquet_rows(&pa); + assert_eq!(decoded.len(), expected_by_year[&year]); + for pair in decoded.windows(2) { + let k0 = (pair[0].listing_id, pair[0].effective_known_at_micros); + let k1 = (pair[1].listing_id, pair[1].effective_known_at_micros); + assert!(k0 < k1, "keys must be strictly increasing: {k0:?} vs {k1:?}"); + } + for row in &decoded { + assert_eq!(partition_year_utc(row.effective_known_at_micros), year); + } + } + assert_eq!(stats_a.bytes_written, total_bytes); + assert_no_transient_files(&dataset_dir); +} + +#[test] +fn empty_input_creates_no_directory_and_preserves_existing_dataset() { + let tmp_fresh = TempDirGuard::new("empty-fresh"); + let stats = write_fundamentals_pit_dataset( + tmp_fresh.path(), + std::iter::empty::(), + FundamentalsPitWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats, FundamentalsPitWriteStats::default()); + assert!(!tmp_fresh.path().join("fundamentals_pit").exists()); + + let tmp_existing = TempDirGuard::new("empty-existing"); + let seed = vec![sample_row(1, utc_micros(2024, 5, 1, 20, 0, 0, 0))]; + write_fundamentals_pit_dataset( + tmp_existing.path(), + &seed, + FundamentalsPitWriteOptions::default(), + ) + .unwrap(); + let part = tmp_existing + .path() + .join("fundamentals_pit/year=2024/part.parquet"); + let before = fs::read(&part).unwrap(); + + let stats2 = write_fundamentals_pit_dataset( + tmp_existing.path(), + std::iter::empty::(), + FundamentalsPitWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats2, FundamentalsPitWriteStats::default()); + assert_eq!(fs::read(&part).unwrap(), before); +} + +#[test] +fn rejects_empty_snapshot_periods() { + let empty_snapshot = FundamentalsSnapshot:: { + key: 7, + effective_known_at_utc_micros: utc_micros(2024, 5, 1, 20, 0, 0, 0), + known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, + has_estimated_lag: false, + periods: Vec::new(), + ttm: None, + }; + + let err_ref = FundamentalsPitParquetRow::try_from(&empty_snapshot).unwrap_err(); + assert!(matches!( + err_ref, + ParquetFundamentalsError::EmptySnapshotPeriods { + listing_id: 7, + .. + } + )); + + let err_owned = FundamentalsPitParquetRow::try_from(empty_snapshot).unwrap_err(); + assert!(matches!( + err_owned, + ParquetFundamentalsError::EmptySnapshotPeriods { + listing_id: 7, + .. + } + )); +} + +#[test] +fn rejects_duplicate_and_unsorted_keys_without_leaving_partial_output() { + let ts1 = utc_micros(2023, 8, 1, 20, 0, 0, 0); + let ts2 = utc_micros(2024, 5, 1, 20, 0, 0, 0); + + // Duplicate (listing_id, effective_known_at) + let tmp_dup = TempDirGuard::new("reject-dup"); + let dup_rows = vec![sample_row(1, ts1), sample_row(1, ts1)]; + let err = write_fundamentals_pit_dataset( + tmp_dup.path(), + &dup_rows, + FundamentalsPitWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetFundamentalsError::DuplicateRow { + row_index: 1, + listing_id: 1, + .. + } + )); + assert!(!tmp_dup + .path() + .join("fundamentals_pit/year=2023/part.parquet") + .exists()); + assert_no_transient_files(&tmp_dup.path().join("fundamentals_pit")); + + // Unsorted keys (later row has smaller effective_known_at for same listing) + let tmp_unsorted = TempDirGuard::new("reject-unsorted"); + let unsorted_rows = vec![sample_row(1, ts2), sample_row(1, ts1)]; + let err = write_fundamentals_pit_dataset( + tmp_unsorted.path(), + &unsorted_rows, + FundamentalsPitWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetFundamentalsError::UnsortedInput { + row_index: 1, + prev_listing_id: 1, + listing_id: 1, + .. + } + )); + assert!(!tmp_unsorted + .path() + .join("fundamentals_pit/year=2024/part.parquet") + .exists()); + assert_no_transient_files(&tmp_unsorted.path().join("fundamentals_pit")); +} + +#[test] +fn rejects_non_finite_statement_and_ttm_values_without_leaving_partial_output() { + let ts_2023 = utc_micros(2023, 8, 1, 20, 0, 0, 0); + let ts_2024 = utc_micros(2024, 5, 1, 20, 0, 0, 0); + + type RowMutator = fn(&mut FundamentalsPitParquetRow); + let cases: [(&str, RowMutator); 4] = [ + ("revenue", |r| r.revenue = Some(f64::NAN)), + ("total_assets", |r| r.total_assets = Some(f64::INFINITY)), + ("ttm_revenue", |r| r.ttm_revenue = Some(f64::NEG_INFINITY)), + ("ttm_operating_cash_flow", |r| { + r.ttm_operating_cash_flow = Some(f64::NAN) + }), + ]; + + for (expected_field, mutate) in cases { + let tmp = TempDirGuard::new(&format!("reject-nonfinite-{expected_field}")); + let good = sample_row(1, ts_2023); + let mut bad = sample_row(1, ts_2024); + mutate(&mut bad); + + let err = write_fundamentals_pit_dataset( + tmp.path(), + &[good, bad], + FundamentalsPitWriteOptions::default(), + ) + .unwrap_err(); + match err { + ParquetFundamentalsError::NonFiniteValue { + row_index: 1, + field, + .. + } => assert_eq!(field, expected_field), + other => panic!("expected NonFiniteValue({expected_field}), got {other:?}"), + } + assert!(!tmp + .path() + .join("fundamentals_pit/year=2023/part.parquet") + .exists()); + assert!(!tmp + .path() + .join("fundamentals_pit/year=2024/part.parquet") + .exists()); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + } +} + +#[test] +fn rejects_invalid_options_dates_strings_and_inconsistent_ttm_metadata() { + let tmp = TempDirGuard::new("reject-validation"); + let ts = utc_micros(2024, 5, 1, 20, 0, 0, 0); + + // row_group_rows == 0 + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[sample_row(1, ts)], + FundamentalsPitWriteOptions { + row_group_rows: 0, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ), + Err(ParquetFundamentalsError::InvalidRowGroupRows) + )); + + // Invalid Zstd level + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[sample_row(1, ts)], + FundamentalsPitWriteOptions { + row_group_rows: 10, + zstd_level: 999, + }, + ), + Err(ParquetFundamentalsError::InvalidZstdLevel { level: 999 }) + )); + + // Partition year out of range + let mut bad_year = sample_row(1, utc_micros(MIN_PARQUET_YEAR - 1, 6, 1, 0, 0, 0, 0)); + bad_year.period_known_at_micros = bad_year.effective_known_at_micros; + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[bad_year], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::PartitionYearOutOfRange { .. }) + )); + + // period_end out of range + let mut bad_period = sample_row(1, ts); + bad_period.period_end = day(MAX_PARQUET_YEAR + 1, 1, 1); + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[bad_period], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::PeriodEndOutOfRange { .. }) + )); + + // period_known_at > effective_known_at + let mut future_period_known = sample_row(1, ts); + future_period_known.period_known_at_micros = ts + 1; + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[future_period_known], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::PeriodKnownAtAfterEffectiveKnownAt { .. }) + )); + + // Empty required strings + let mut empty_source = sample_row(1, ts); + empty_source.known_at_source = Cow::Borrowed(" "); + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[empty_source], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::EmptyKnownAtSource { .. }) + )); + + // Partial TTM metadata (ttm_currency missing while ttm_period_end present) + let mut partial_ttm = sample_row(1, ts); + partial_ttm.ttm_currency = None; + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[partial_ttm], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::InconsistentTtmMetadata { .. }) + )); + + // TTM flow present while all TTM metadata is None + let mut orphan_ttm_flow = sample_row(1, ts); + orphan_ttm_flow.ttm_period_end = None; + orphan_ttm_flow.ttm_currency = None; + orphan_ttm_flow.ttm_has_estimated_lag = None; + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[orphan_ttm_flow], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::InconsistentTtmMetadata { .. }) + )); + + assert!(!tmp.path().join("fundamentals_pit").exists()); +} + +#[test] +fn failed_later_year_publish_rolls_back_and_preserves_existing_partitions_byte_for_byte() { + let tmp = TempDirGuard::new("rollback-existing"); + + // Seed an existing 2023 partition. + let initial_rows = vec![sample_row(1, utc_micros(2023, 8, 1, 20, 0, 0, 0))]; + write_fundamentals_pit_dataset( + tmp.path(), + &initial_rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("seed initial 2023 partition"); + + let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); + let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + let original_2023_bytes = fs::read(&part_2023).unwrap(); + + // Attempt a 2-year write (2023 update + 2024 new) where publishing 2024 fails because a + // directory occupies `year=2024/part.parquet` right before rename. + let mut updated_2023 = sample_row(1, utc_micros(2023, 8, 1, 20, 0, 0, 0)); + updated_2023.revenue = Some(999.0); + let new_2024 = sample_row(1, utc_micros(2024, 5, 1, 20, 0, 0, 0)); + + let err = write_fundamentals_pit_dataset_with_hooks( + tmp.path(), + &[updated_2023, new_2024], + FundamentalsPitWriteOptions::default(), + DEFAULT_LOCK_TIMEOUT, + |year, final_path, _bak| { + if year == 2024 { + fs::create_dir_all(final_path).expect("inject directory conflict at 2024 target"); + } + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetFundamentalsError::Io { .. })); + + // 2023 must be restored byte-for-byte; 2024 must not contain a published file. + assert_eq!(fs::read(&part_2023).unwrap(), original_2023_bytes); + assert!(part_2024.is_dir(), "injected blocker dir remains untouched"); + fs::remove_dir(&part_2024).unwrap(); + assert!(!part_2024.exists()); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +}