From 1d4717c48e99f498b6dcf53fecb545a585ba6778 Mon Sep 17 00:00:00 2001 From: Studio Date: Sun, 29 Nov 2026 07:40:21 -0500 Subject: [PATCH] =?UTF-8?q?T-119:=20M1.3e=20=E2=80=94=20`@stock-bot/resear?= =?UTF-8?q?ch`:=20DuckDB=20SQL=20planner=20+=20injected-executor=20`Market?= =?UTF-8?q?DataStore`=20adapter=20for=20curated=20daily=20Parquet=20(`bars?= =?UTF-8?q?`=201d,=20`events`,=20`shortsAsOf`,=20`fx`=201d)=20with=20manda?= =?UTF-8?q?tory=20Vault=20/=20`known=5Fat`=20predicates,=20tests=20and=20l?= =?UTF-8?q?ocal=20benchmark=20(no=20new=20dependencies)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 36 +- .../benchmark-market-data-store-duckdb.ts | 129 ++- libs/research/src/market-data-store-duckdb.ts | 940 ++++++++++++++++-- .../test/market-data-store-duckdb.test.ts | 765 +++++++++++++- 4 files changed, 1718 insertions(+), 152 deletions(-) diff --git a/libs/research/README.md b/libs/research/README.md index a263252c..731e57e9 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -81,31 +81,33 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-st ### API -- **`planBars1dQuery(q, ctx)`** — Plans a fenced query over `/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) for `timeframe: '1d'` and `adjustment: 'raw' | 'split' | 'total'`. Rejects `'1m' | '5m' | '1h'` with `MarketDataStoreNotImplementedError`. -- **`planEventsQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `/events/year=*/part.parquet` (`hive_partitioning = true`) filtered by allow-listed `kinds` and optional `listingIds`. -- **`planShortsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `/shorts/part.parquet`, binding UTC `YYYY-MM-DD` `report_date` bounds and ISO-8601 `known_at <= ?`. -- **`planFx1dQuery(q, ctx)`** — Plans a `'vault_fenced'` query (with default `asOf = vaultCutoffTs - 1`) over `/fx_1d/part.parquet` for `timeframe: '1d'`, mapping `'USD.CAD'` to the stored bound parameter `'USDCAD'`. Rejects `'1m'` with `MarketDataStoreNotImplementedError`. -- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, 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), maps validated rows into `BarBatch` / `Table`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `fundamentalsAsOf`, `macroAsOf`, `universe`) with `MarketDataStoreNotImplementedError` and zero executor calls. +- **`planBars1dQuery(q, ctx)`** — Plans a fenced query over `/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) for `timeframe: '1d'` and `adjustment: 'raw' | 'split' | 'total'`. Rejects `'1m' | '5m' | '1h'` with `MarketDataStoreNotImplementedError`. For `'split'` and `'total'`, requires a verified `point_in_time_fenced` `ctx.adjFactorsSnapshot` matching the query's effective `asOf` and Vault fence, and binds `read_parquet(...)` directly to `ctx.adjFactorsSnapshot.path`. +- **`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 <= ?`. +- **`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`. +- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, adjFactorsPath?, 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), verifies `parquet_kv_metadata` on the exact `adj_factors` file before every `'split'` / `'total'` `bars` query, validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `fundamentalsAsOf`, `macroAsOf`, `universe`) with `MarketDataStoreNotImplementedError` and zero executor calls. -### Mandatory Vault, PIT & Boundary Validation Rules +### Mandatory Vault, PIT, Microsecond & Boundary Validation Rules -- Every planner delegates unconditionally to `applyVaultFence`, binding `ts`/`report_date` bounds and `known_at <= ?` in UTC (`TZ`-invariant). Under `'vault_fenced'`, `from >= vaultCutoffTs` throws `VaultHoldoutFenceError` and `to`/`asOf` clamp to `vaultCutoffTs - 1`; `'vault_evaluation_only'` requires `vaultOperatorAuthorized === true` (only on `bars`; `events`, `shortsAsOf`, and `fx` are always `'vault_fenced'`). -- `curatedRoot` is the only value embedded in SQL text and must be an absolute POSIX path free of control characters (`<= 0x1f`, `0x7f`), `'`, `;`, and glob metacharacters (`*`, `?`, `[`, `]`). +- Every planner delegates unconditionally to `applyVaultFence`, binding `ts`/`report_date` bounds and `known_at <= ?` in UTC (`TZ`-invariant). Under `'vault_fenced'`, `from >= vaultCutoffTs` throws `VaultHoldoutFenceError` and `to`/`asOf` clamp strictly below `vaultCutoffTs`; `'vault_evaluation_only'` requires `vaultOperatorAuthorized === true` (only on `bars`; `events`, `shortsAsOf`, and `fx` are always `'vault_fenced'`). +- **Microsecond upper-bound precision:** Curated Parquet `ts` and `known_at` columns store UTC microseconds (`curate_fx_1d` stamps `23:59:59.999999Z`). Date-only `YYYY-MM-DD` upper bounds (`to`, `asOf`) and default or clamped Vault upper bounds expand to the last included Parquet microsecond (`.999999Z` / `vaultCutoffTs * 1000 - 1`), while explicit time-of-day bounds preserve their caller-specified precision. Under `'vault_fenced'`, every planned upper bound remains strictly `< vaultCutoffTs`. +- `curatedRoot` (and optional `adjFactorsPath`) are the only values embedded in SQL text and must be absolute POSIX paths free of control characters (`<= 0x1f`, `0x7f`), `'`, `;`, and glob metacharacters (`*`, `?`, `[`, `]`). - All caller values (`listingIds` as `INT32` safe integers, allow-listed `kinds`, `'USD.CAD' -> 'USDCAD'`, and UTC date/timestamp bounds) are validated upfront and passed strictly as bound `?` parameters. -### `bars` 1d Adjustment Formulas & `asOf` Anchoring Caveat +### `bars` 1d Adjustment Formulas & Verified Fenced `adj_factors` Requirement -`bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share `volume`. For `'split'` and `'total'`, `bars_1d` is joined via `ASOF LEFT JOIN` against `/adj_factors/part.parquet` (filtered to `listing_id IN (...) AND known_at <= ?`) on `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (matching the first `adj_factors` row with `ex_date > session_date` per `tools/curate-etl/README.md`): +`bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share `volume`. Because `adj_factors` stores right-to-left cumulative suffix products (`cum_split_factor`, `cum_total_factor`), slicing a retrospective `adj_factors` file with `known_at <= asOf` would still embed future or held-out Vault splits/dividends into earlier cumulative factors. -- **`'raw'`**: OHLC, `vwap`, and `volume` are returned unadjusted. -- **`'split'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_split_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`. -- **`'total'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_total_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`. - -> **Point-in-time `asOf` anchoring caveat:** `tools/curate-etl` writes full-horizon curation-time suffix products into `cum_split_factor` and `cum_total_factor`. Filtering `adj_factors` by `known_at <= asOf` excludes post-`asOf` corporate-action rows (so bars on/after the last visible `ex_date` fall back to `1.0`), while earlier surviving rows still carry the curation-time suffix product (introducing a scale jump across the last visible `ex_date` if an excluded future split or dividend exists). Full historical re-anchoring to `asOf` requires a separate `curate-etl` schema/query enhancement. +- **`'raw'`**: OHLC, `vwap`, and `volume` are returned unadjusted (`adj_factors` is not read). +- **`'split'` / `'total'`**: Require a verified `point_in_time_fenced` `adj_factors` Parquet artifact (published by `curate_and_write_adj_factors_as_of` with `stock_bot.adj_factors.*` footer metadata) whose effective inclusive microsecond fence matches the query's effective `asOf` and Vault cutoff. Retrospective, unverified, or mismatched-fence files are rejected with `AdjFactorsSnapshotError` before any `bars` query runs, and `read_parquet(...)` is bound directly to the verified file path. +- Against the verified `adj_factors` file, `bars_1d` is joined via `ASOF LEFT JOIN` (filtered to `listing_id IN (...) AND known_at <= ?`) on `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (matching the first `adj_factors` row with `ex_date > session_date` per `tools/curate-etl/README.md`): + - **`'split'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_split_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`. + - **`'total'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_total_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`. ### Local Query-Planner Benchmark -Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across `bars` 1d (`raw`/`split`/`total`), `events` (with and without `listingIds`), `shortsAsOf`, and `fx` 1d with no database dependency: +Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across `bars` 1d (`raw`/`split`/`total`), `events` (with and without `listingIds`), `shortsAsOf`, and `fx` 1d with no database dependency (full SQL text and ordered parameter values are verified against the pinned checksum outside the timed section): - **Command:** `bun run libs/research/scripts/benchmark-market-data-store-duckdb.ts` -- **Observed (Bun 1.2.16):** `elapsedMs = 178.15 ms`, `queriesPerSec = 673,600 queries/s` (`120,000` queries, `758,061` bound params, deterministic checksum `0d85763b`) +- **Observed (Bun 1.2.16):** `elapsedMs = 218.55 ms`, `queriesPerSec = 549,073 queries/s` (`120,000` queries, `758,061` bound params, pinned checksum `8606c98c`) diff --git a/libs/research/scripts/benchmark-market-data-store-duckdb.ts b/libs/research/scripts/benchmark-market-data-store-duckdb.ts index c3f60ae5..ac75fc95 100644 --- a/libs/research/scripts/benchmark-market-data-store-duckdb.ts +++ b/libs/research/scripts/benchmark-market-data-store-duckdb.ts @@ -1,6 +1,8 @@ import { + type AdjFactorsSnapshotMetadata, BARS_ADJUSTMENTS, type BarsQuery, + type DuckDbParam, type DuckDbPlanContext, EVENT_KINDS, type EventsQuery, @@ -12,13 +14,17 @@ import { planFx1dQuery, planShortsAsOfQuery, } from '../src/market-data-store-duckdb'; +import { applyVaultFence } from '../src/market-data-store'; const SEED = 20261129; const QUERY_COUNT = 120_000; const CURATED_ROOT = '/mnt/data/stockbot/curated'; +const ADJ_PATH = `${CURATED_ROOT}/adj_factors/part.parquet`; const VAULT_CUTOFF_TS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); +const VAULT_CUTOFF_MICROS = VAULT_CUTOFF_TS * 1000; +const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; -const CTX: DuckDbPlanContext = { +const BASE_CTX: DuckDbPlanContext = { curatedRoot: CURATED_ROOT, vaultCutoffTs: VAULT_CUTOFF_TS, }; @@ -34,7 +40,7 @@ function createMulberry32(seed: number): () => number { } type WorkloadItem = - | { readonly kind: 'bars'; readonly q: BarsQuery } + | { readonly kind: 'bars'; readonly q: BarsQuery; readonly ctx: DuckDbPlanContext } | { readonly kind: 'events'; readonly q: EventsQuery } | { readonly kind: 'shorts'; readonly q: ShortsAsOfQuery } | { readonly kind: 'fx'; readonly q: FxQuery }; @@ -58,6 +64,30 @@ function randomListingIds(): number[] { return ids; } +function buildVerifiedSnapshotForBarsQuery( + from: string, + to: string, + asOf: string | undefined +): AdjFactorsSnapshotMetadata { + const fenced = applyVaultFence( + { from, to, asOf, scope: 'vault_fenced' }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ); + const subMs = fenced.clampedAsOf || asOf === undefined || DATE_ONLY_RE.test(asOf) ? 999 : 0; + const effectiveAsOfMicros = fenced.asOfMs * 1000 + subMs; + return { + path: ADJ_PATH, + formatVersion: 1, + snapshotKind: 'point_in_time_fenced', + fence: { + asOfMicros: effectiveAsOfMicros, + vaultCutoffMicros: VAULT_CUTOFF_MICROS, + }, + rowsWritten: 1000, + snapshotChecksum: '0x024ec73a1afe7e6b', + }; +} + const workload: WorkloadItem[] = new Array(QUERY_COUNT); for (let i = 0; i < QUERY_COUNT; i += 1) { const fromMs = startBaseMs + Math.floor(rng() * preCutoffSpanMs); @@ -74,6 +104,13 @@ for (let i = 0; i < QUERY_COUNT; i += 1) { const slot = i % 7; if (slot < 3) { const adjustment = BARS_ADJUSTMENTS[slot] ?? 'raw'; + const ctx: DuckDbPlanContext = + adjustment === 'raw' + ? BASE_CTX + : { + ...BASE_CTX, + adjFactorsSnapshot: buildVerifiedSnapshotForBarsQuery(from, to, asOf), + }; workload[i] = { kind: 'bars', q: { @@ -84,6 +121,7 @@ for (let i = 0; i < QUERY_COUNT; i += 1) { adjustment, asOf, }, + ctx, }; } else if (slot === 3 || slot === 4) { const kindA = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'filing'; @@ -121,41 +159,78 @@ for (let i = 0; i < QUERY_COUNT; i += 1) { } } -function mixFnv1a(hash: number, value: number): number { - let h = (hash ^ (value >>> 0)) >>> 0; - h = Math.imul(h, 0x01000193) >>> 0; +function planWorkloadItem(item: WorkloadItem): PlannedDuckDbQuery { + switch (item.kind) { + case 'bars': + return planBars1dQuery(item.q, item.ctx); + case 'events': + return planEventsQuery(item.q, BASE_CTX); + case 'shorts': + return planShortsAsOfQuery(item.q, BASE_CTX); + case 'fx': + return planFx1dQuery(item.q, BASE_CTX); + } +} + +function fnv1aByte(hash: number, byte: number): number { + return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0; +} + +function fnv1aString(hash: number, str: string): number { + let h = fnv1aByte(hash, str.length & 0xff); + h = fnv1aByte(h, (str.length >>> 8) & 0xff); + for (let i = 0; i < str.length; i += 1) { + const code = str.charCodeAt(i); + h = fnv1aByte(h, code & 0xff); + if (code > 0xff) { + h = fnv1aByte(h, (code >>> 8) & 0xff); + } + } return h; } -let checksum = 0x811c9dc5; -let totalParams = 0; +function fnv1aParam(hash: number, param: DuckDbParam): number { + if (param === null) { + return fnv1aByte(hash, 0x00); + } + if (typeof param === 'string') { + return fnv1aString(fnv1aByte(hash, 0x01), param); + } + if (typeof param === 'number') { + return fnv1aString(fnv1aByte(hash, 0x02), String(param)); + } + return fnv1aByte(fnv1aByte(hash, 0x03), param ? 1 : 0); +} +// Timed section: pure query planning only (no checksum hashing overhead). +let totalParams = 0; const started = performance.now(); for (const item of workload) { - let planned: PlannedDuckDbQuery; - switch (item.kind) { - case 'bars': - planned = planBars1dQuery(item.q, CTX); - break; - case 'events': - planned = planEventsQuery(item.q, CTX); - break; - case 'shorts': - planned = planShortsAsOfQuery(item.q, CTX); - break; - case 'fx': - planned = planFx1dQuery(item.q, CTX); - break; - } + const planned = planWorkloadItem(item); totalParams += planned.params.length; - checksum = mixFnv1a(checksum, planned.sql.length); - checksum = mixFnv1a(checksum, planned.params.length); - checksum = mixFnv1a(checksum, Math.trunc(planned.fenced.toMs / 1000)); - checksum = mixFnv1a(checksum, Math.trunc(planned.fenced.asOfMs / 1000)); } const elapsedMs = performance.now() - started; const queriesPerSec = Math.round(QUERY_COUNT / (elapsedMs / 1000)); +// Untimed verification pass: hash full SQL text and ordered parameter values for all queries. +let checksum = 0x811c9dc5; +for (const item of workload) { + const planned = planWorkloadItem(item); + checksum = fnv1aString(checksum, planned.sql); + checksum = fnv1aByte(checksum, planned.params.length); + for (const param of planned.params) { + checksum = fnv1aParam(checksum, param); + } +} +const checksumHex = checksum.toString(16).padStart(8, '0'); + +const EXPECTED_CHECKSUM = '8606c98c'; +if (checksumHex !== EXPECTED_CHECKSUM) { + throw new Error( + `Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.` + ); +} + console.log( JSON.stringify( { @@ -164,7 +239,7 @@ console.log( totalParams, elapsedMs: Number(elapsedMs.toFixed(2)), queriesPerSec, - checksum: checksum.toString(16).padStart(8, '0'), + checksum: checksumHex, }, null, 2 diff --git a/libs/research/src/market-data-store-duckdb.ts b/libs/research/src/market-data-store-duckdb.ts index 1a676746..258779b9 100644 --- a/libs/research/src/market-data-store-duckdb.ts +++ b/libs/research/src/market-data-store-duckdb.ts @@ -9,7 +9,8 @@ * * Curated Parquet layout under `curatedRoot` (`design/DATA-CONTRACTS.md` §3.A): * - `/bars_1d/year=*\/part.parquet` (`hive_partitioning = true`) - * - `/adj_factors/part.parquet` + * - `/adj_factors/part.parquet` (point-in-time fenced snapshot with + * `stock_bot.adj_factors.*` Parquet footer metadata) * - `/events/year=*\/part.parquet` (`hive_partitioning = true`) * - `/shorts/part.parquet` * - `/fx_1d/part.parquet` @@ -21,11 +22,21 @@ * divisors (`cum_split_factor`, `cum_total_factor`) and `known_at`. * - For `'raw'`, `open`, `high`, `low`, `close`, `volume`, and `vwap` are * projected directly from `bars_1d`. - * - For `'split'` and `'total'`, `bars_1d` is joined via `ASOF LEFT JOIN` - * against `adj_factors` filtered to `listing_id IN (...) AND known_at <= ?` - * on `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (selecting - * the first `adj_factors` row with `ex_date > session_date` and - * `known_at <= asOf`): + * - For `'split'` and `'total'`, because `cum_split_factor` and + * `cum_total_factor` are right-to-left suffix products, slicing a + * retrospective `adj_factors` file with `known_at <= asOf` would still leak + * future or held-out Vault splits/dividends into earlier cumulative factors. + * Therefore, `'split'` and `'total'` queries REQUIRE a verified + * `point_in_time_fenced` `adj_factors` snapshot artifact (parsed from + * Parquet footer `stock_bot.adj_factors.*` metadata) whose effective + * inclusive fence matches the query's effective `asOf` and Vault cutoff. + * Verification is bound directly to the exact `.parquet` file path embedded + * in `read_parquet(...)`; retrospective, unverified, or mismatched-fence + * artifacts are rejected with {@link AdjFactorsSnapshotError}. + * - Against the verified `adj_factors` file, `bars_1d` is joined via + * `ASOF LEFT JOIN` filtered to `listing_id IN (...) AND known_at <= ?` on + * `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (selecting the + * first `adj_factors` row with `ex_date > session_date`): * - `'split'`: * - `price_adj = price_raw / COALESCE(a.cum_split_factor, 1.0)` for * `open`, `high`, `low`, `close`, and `vwap` (preserving `NULL` `vwap`). @@ -36,15 +47,15 @@ * - `volume_adj = volume_raw * COALESCE(a.cum_split_factor, 1.0)` (share * volume scales only by splits, not cash dividends). * - * Point-in-time suffix-product `asOf` anchoring caveat: - * - `tools/curate-etl` writes full-horizon curation-time suffix products into - * `cum_split_factor` and `cum_total_factor`. Filtering `adj_factors` by - * `known_at <= asOf` excludes post-`asOf` corporate-action rows, so bars on - * or after the last visible `ex_date` fall back to `1.0`, while earlier - * surviving rows still carry the curation-time suffix product (introducing a - * scale jump across the last visible `ex_date` whenever an excluded future - * split or dividend exists). Full historical re-anchoring to `asOf` requires - * a separate `curate-etl` schema/query enhancement. + * Microsecond upper-bound semantics: + * - Curated Parquet `ts` and `known_at` columns are stored as + * `TIMESTAMP(MICROS, isAdjustedToUTC=true)` (for example, `curate_fx_1d` + * stamps `ts = known_at = 23:59:59.999999Z`). + * - Date-only `YYYY-MM-DD` upper bounds (`to`, `asOf`) and default or clamped + * Vault upper bounds expand to the last included Parquet microsecond + * (`.999999Z` / `vaultCutoffTs * 1000 - 1`), while explicit time-of-day + * bounds preserve their caller-specified precision. Under `'vault_fenced'`, + * every planned upper bound remains strictly `< vaultCutoffTs`. */ import { @@ -64,6 +75,21 @@ import { const INT32_MIN = -2_147_483_648; const INT32_MAX = 2_147_483_647; const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; +const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; +const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/; +const STRICT_INT_RE = /^-?\d+$/; +const STRICT_UINT_RE = /^\d+$/; +const SNAPSHOT_CHECKSUM_RE = /^0x[0-9a-f]{16}$/; + +export const ADJ_SNAPSHOT_FORMAT_VERSION = 1; +export const ADJ_SNAPSHOT_KV_PREFIX = 'stock_bot.adj_factors.'; + +const KV_FORMAT_VERSION = `${ADJ_SNAPSHOT_KV_PREFIX}format_version`; +const KV_SNAPSHOT_KIND = `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_kind`; +const KV_AS_OF_MICROS = `${ADJ_SNAPSHOT_KV_PREFIX}as_of_micros`; +const KV_VAULT_CUTOFF_MICROS = `${ADJ_SNAPSHOT_KV_PREFIX}vault_cutoff_micros`; +const KV_ROWS_WRITTEN = `${ADJ_SNAPSHOT_KV_PREFIX}rows_written`; +const KV_SNAPSHOT_CHECKSUM = `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_checksum`; export const EVENT_KINDS = ['filing', 'earnings', 'ceo_post', 'corporate_action'] as const; const EVENT_KIND_SET: ReadonlySet = new Set(EVENT_KINDS); @@ -107,6 +133,46 @@ export const FX_1D_COLUMNS = [ 'known_at', ] as const; +type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string'; + +interface TableColumnSpec { + readonly name: string; + readonly kind: ColumnScalarKind; + readonly nullable: boolean; +} + +const EVENTS_SCHEMA: readonly TableColumnSpec[] = [ + { name: 'listing_id', kind: 'int32', nullable: false }, + { name: 'ts', kind: 'safe_int', nullable: false }, + { name: 'known_at', kind: 'safe_int', nullable: false }, + { name: 'known_at_source', kind: 'string', nullable: false }, + { name: 'kind', kind: 'string', nullable: false }, + { name: 'subtype', kind: 'string', nullable: false }, + { name: 'payload_json', kind: 'string', nullable: false }, +]; + +const SHORTS_SCHEMA: readonly TableColumnSpec[] = [ + { name: 'listing_id', kind: 'int32', nullable: false }, + { name: 'report_date', kind: 'string', nullable: false }, + { name: 'known_at', kind: 'safe_int', nullable: false }, + { name: 'shares_short', kind: 'number', nullable: false }, + { name: 'net_change', kind: 'number', nullable: true }, + { name: 'pct_float', kind: 'number', nullable: true }, + { name: 'source', kind: 'string', nullable: false }, +]; + +const FX_1D_SCHEMA: readonly TableColumnSpec[] = [ + { name: 'pair', kind: 'string', nullable: false }, + { name: 'session_date', kind: 'string', nullable: false }, + { name: 'ts', kind: 'safe_int', nullable: false }, + { name: 'open', kind: 'number', nullable: false }, + { name: 'high', kind: 'number', nullable: false }, + { name: 'low', kind: 'number', nullable: false }, + { name: 'close', kind: 'number', nullable: false }, + { name: 'source', kind: 'string', nullable: false }, + { name: 'known_at', kind: 'safe_int', nullable: false }, +]; + /** Scalar parameter value bound separately from SQL text. */ export type DuckDbParam = string | number | boolean | null; @@ -126,18 +192,91 @@ export interface PlannedDuckDbQuery { readonly fenced: FencedTimeRange; } +/** Snapshot classification written by `tools/curate-etl` into `adj_factors/part.parquet`. */ +export type AdjFactorsSnapshotKind = 'retrospective' | 'point_in_time_fenced'; + +/** Point-in-time and Vault fence embedded in `adj_factors/part.parquet` footer metadata. */ +export interface AdjFactorsPointInTimeFence { + readonly asOfMicros: number | null; + readonly vaultCutoffMicros: number | null; +} + +/** + * Verified `adj_factors` Parquet footer metadata parsed via + * {@link parseAdjFactorsSnapshotMetadata}, bound to a concrete `.parquet` file + * path. + */ +export interface AdjFactorsSnapshotMetadata { + readonly path: string; + readonly formatVersion: number; + readonly snapshotKind: AdjFactorsSnapshotKind; + readonly fence: AdjFactorsPointInTimeFence; + readonly rowsWritten: number; + readonly snapshotChecksum: string; +} + +/** Pure output of {@link planAdjFactorsMetadataQuery}. */ +export interface PlannedAdjFactorsMetadataQuery { + readonly path: string; + readonly sql: string; + readonly params: readonly DuckDbParam[]; +} + +export type AdjFactorsSnapshotErrorCode = + | 'missing_snapshot' + | 'missing_metadata' + | 'invalid_metadata' + | 'unsupported_version' + | 'retrospective_rejected' + | 'incompatible_fence' + | 'path_mismatch'; + +/** + * Thrown when an adjusted `bars` (`'split'` or `'total'`) query lacks a + * verified `point_in_time_fenced` `adj_factors` snapshot artifact matching the + * query's effective `asOf` and Vault fence, or when Parquet footer metadata is + * missing, retrospective, malformed, or mismatched. + */ +export class AdjFactorsSnapshotError extends Error { + override readonly name = 'AdjFactorsSnapshotError'; + readonly code: AdjFactorsSnapshotErrorCode; + readonly path?: string; + + constructor(code: AdjFactorsSnapshotErrorCode, message: string, path?: string) { + super(message); + this.code = code; + this.path = path; + Object.setPrototypeOf(this, new.target.prototype); + } +} + /** Context required to plan fenced DuckDB queries against curated Parquet. */ export interface DuckDbPlanContext { readonly curatedRoot: string; readonly vaultCutoffTs: number; readonly vaultOperatorAuthorized?: boolean; + /** + * Verified `adj_factors` snapshot metadata bound to the `.parquet` file to + * be read. Required for `'split'` and `'total'` `bars` queries; rejected if + * retrospective or mismatched for the query's effective `asOf` / Vault fence. + */ + readonly adjFactorsSnapshot?: AdjFactorsSnapshotMetadata; } /** Configuration for {@link createDuckDbMarketDataStore}. */ -export interface DuckDbMarketDataStoreOptions extends DuckDbPlanContext { +export interface DuckDbMarketDataStoreOptions + extends Omit { readonly executor: DuckDbExecutor; readonly env?: Readonly>; readonly barBatchSize?: number; + /** + * Optional absolute POSIX `.parquet` path for `adj_factors` reads in + * `'split'` / `'total'` `bars` queries. Defaults to + * `/adj_factors/part.parquet`. The adapter always reads and + * verifies `parquet_kv_metadata` on this exact file before issuing an + * adjusted `bars` query. + */ + readonly adjFactorsPath?: string; } export type BarsQuery = Parameters[0]; @@ -216,6 +355,26 @@ export function validateCuratedRoot(raw: string): string { return end === raw.length ? raw : raw.slice(0, end); } +/** + * Strictly validates a concrete Parquet file path (absolute POSIX `.parquet` + * path with no control characters, quotes, semicolons, or glob metacharacters). + */ +export function validateParquetFilePath(raw: string, field = 'adjFactorsPath'): string { + if ( + typeof raw !== 'string' || + raw.length === 0 || + !raw.startsWith('/') || + !raw.endsWith('.parquet') || + hasForbiddenCuratedRootChar(raw) + ) { + throw new MarketDataStoreValidationError( + `Invalid Parquet file path "${String(raw)}" for "${field}". Expected an absolute POSIX .parquet path without quotes, semicolons, control characters, or glob characters (*, ?, [, ]).`, + field + ); + } + return raw; +} + function joinCuratedPath(normalizedRoot: string, relativePath: string): string { return normalizedRoot === '/' ? `/${relativePath}` : `${normalizedRoot}/${relativePath}`; } @@ -349,19 +508,536 @@ function buildPlaceholders(count: number): string { return out; } -function formatUtcIso(epochMs: number): string { - return new Date(epochMs).toISOString(); +function extractExplicitSubMsMicros(raw: string): number { + const match = ISO_FRACTIONAL_RE.exec(raw); + if (match === null) { + return 0; + } + const frac = match[1] ?? ''; + if (frac.length <= 3) { + return 0; + } + const microDigits = frac.slice(3, 6).padEnd(3, '0'); + return Number(microDigits); +} + +function resolveFromSubMsMicros(rawFrom: string): number { + if (DATE_ONLY_RE.test(rawFrom)) { + return 0; + } + return extractExplicitSubMsMicros(rawFrom); +} + +function resolveToSubMsMicros(rawTo: string, fenced: FencedTimeRange): number { + if (fenced.clampedTo || DATE_ONLY_RE.test(rawTo)) { + return 999; + } + return extractExplicitSubMsMicros(rawTo); +} + +function resolveAsOfSubMsMicros( + rawAsOf: string | undefined, + rawTo: string, + fenced: FencedTimeRange +): number { + if (fenced.clampedAsOf) { + return 999; + } + if (rawAsOf === undefined) { + if (fenced.scope === 'vault_fenced') { + return 999; + } + return resolveToSubMsMicros(rawTo, fenced); + } + if (DATE_ONLY_RE.test(rawAsOf)) { + return 999; + } + return extractExplicitSubMsMicros(rawAsOf); +} + +function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { + const isoMs = new Date(epochMs).toISOString(); + if (subMsMicros === 0) { + return isoMs; + } + const extra = String(subMsMicros).padStart(3, '0'); + return `${isoMs.slice(0, -1)}${extra}Z`; } function formatUtcDate(epochMs: number): string { return new Date(epochMs).toISOString().slice(0, 10); } +function toEpochMicros(epochMs: number, subMsMicros: number, field: string): number { + const micros = epochMs * 1000 + subMsMicros; + if (!Number.isSafeInteger(micros)) { + throw new MarketDataStoreValidationError( + `Timestamp for "${field}" exceeds safe microsecond integer precision.`, + field + ); + } + return micros === 0 ? 0 : micros; +} + +function parseOptionalMicrosKv(value: string, key: string, path: string): number | null { + if (value === 'none') { + return null; + } + if (!STRICT_INT_RE.test(value)) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Invalid microsecond integer value "${value}" for "${key}" in "${path}".`, + path + ); + } + const parsed = Number(value); + if (!Number.isSafeInteger(parsed)) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Out-of-range microsecond integer value "${value}" for "${key}" in "${path}".`, + path + ); + } + return parsed === 0 ? 0 : parsed; +} + /** - * Plans a fenced DuckDB SQL query for daily curated OHLCV bars (`bars_1d`) with - * optional point-in-time `adj_factors` split or total-return adjustment. + * Plans the DuckDB `parquet_kv_metadata` query that reads + * `stock_bot.adj_factors.*` footer metadata from a concrete `adj_factors` + * Parquet file. */ -export function planBars1dQuery(q: BarsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { +export function planAdjFactorsMetadataQuery(adjPath: string): PlannedAdjFactorsMetadataQuery { + const validPath = validateParquetFilePath(adjPath, 'adjFactorsPath'); + const sql = + 'SELECT decode(key) AS key, decode(value) AS value ' + + `FROM parquet_kv_metadata('${validPath}') ` + + 'WHERE decode(key) LIKE ?'; + return { + path: validPath, + sql, + params: [`${ADJ_SNAPSHOT_KV_PREFIX}%`], + }; +} + +/** + * Parses and strictly validates `stock_bot.adj_factors.*` Parquet footer + * key-value metadata rows (matching `tools/curate-etl/src/curate_adj.rs`) + * and binds the resulting metadata object to `adjPath`. + */ +export function parseAdjFactorsSnapshotMetadata( + adjPath: string, + kvRows: readonly TableRow[] +): AdjFactorsSnapshotMetadata { + const validPath = validateParquetFilePath(adjPath, 'adjFactorsPath'); + if (!Array.isArray(kvRows)) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Expected an array of Parquet metadata rows for "${validPath}".`, + validPath + ); + } + + let foundAny = false; + let formatVersion: number | undefined; + let snapshotKindStr: string | undefined; + let asOfMicros: number | null | undefined; + let vaultCutoffMicros: number | null | undefined; + let rowsWritten: number | undefined; + let snapshotChecksum: string | undefined; + + for (let i = 0; i < kvRows.length; i += 1) { + const row = kvRows[i]; + if (!isPlainRecord(row) || typeof row.key !== 'string') { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Malformed Parquet metadata row at index ${i} for "${validPath}".`, + validPath + ); + } + const key = row.key; + if (!key.startsWith(ADJ_SNAPSHOT_KV_PREFIX)) { + continue; + } + foundAny = true; + const rawVal = row.value; + if (typeof rawVal !== 'string') { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Missing or non-string value for metadata key "${key}" in "${validPath}".`, + validPath + ); + } + + switch (key) { + case KV_FORMAT_VERSION: { + if (formatVersion !== undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Duplicate metadata key "${KV_FORMAT_VERSION}" in "${validPath}".`, + validPath + ); + } + if (!STRICT_UINT_RE.test(rawVal)) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Invalid "${KV_FORMAT_VERSION}" value "${rawVal}" in "${validPath}".`, + validPath + ); + } + const parsed = Number(rawVal); + if (!Number.isSafeInteger(parsed)) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Out-of-range "${KV_FORMAT_VERSION}" value "${rawVal}" in "${validPath}".`, + validPath + ); + } + formatVersion = parsed; + break; + } + case KV_SNAPSHOT_KIND: { + if (snapshotKindStr !== undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Duplicate metadata key "${KV_SNAPSHOT_KIND}" in "${validPath}".`, + validPath + ); + } + snapshotKindStr = rawVal; + break; + } + case KV_AS_OF_MICROS: { + if (asOfMicros !== undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Duplicate metadata key "${KV_AS_OF_MICROS}" in "${validPath}".`, + validPath + ); + } + asOfMicros = parseOptionalMicrosKv(rawVal, KV_AS_OF_MICROS, validPath); + break; + } + case KV_VAULT_CUTOFF_MICROS: { + if (vaultCutoffMicros !== undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Duplicate metadata key "${KV_VAULT_CUTOFF_MICROS}" in "${validPath}".`, + validPath + ); + } + vaultCutoffMicros = parseOptionalMicrosKv(rawVal, KV_VAULT_CUTOFF_MICROS, validPath); + break; + } + case KV_ROWS_WRITTEN: { + if (rowsWritten !== undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Duplicate metadata key "${KV_ROWS_WRITTEN}" in "${validPath}".`, + validPath + ); + } + if (!STRICT_UINT_RE.test(rawVal)) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Invalid "${KV_ROWS_WRITTEN}" value "${rawVal}" in "${validPath}".`, + validPath + ); + } + const parsed = Number(rawVal); + if (!Number.isSafeInteger(parsed)) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Out-of-range "${KV_ROWS_WRITTEN}" value "${rawVal}" in "${validPath}".`, + validPath + ); + } + rowsWritten = parsed; + break; + } + case KV_SNAPSHOT_CHECKSUM: { + if (snapshotChecksum !== undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Duplicate metadata key "${KV_SNAPSHOT_CHECKSUM}" in "${validPath}".`, + validPath + ); + } + if (!SNAPSHOT_CHECKSUM_RE.test(rawVal)) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Invalid "${KV_SNAPSHOT_CHECKSUM}" value "${rawVal}" in "${validPath}". Expected 0x followed by 16 lowercase hex digits.`, + validPath + ); + } + snapshotChecksum = rawVal; + break; + } + default: + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Unknown metadata key "${key}" in "${validPath}".`, + validPath + ); + } + } + + if (!foundAny) { + throw new AdjFactorsSnapshotError( + 'missing_metadata', + `Missing "${ADJ_SNAPSHOT_KV_PREFIX}*" metadata in Parquet footer at "${validPath}" (refusing to read unverified adj_factors Parquet).`, + validPath + ); + } + + if (formatVersion === undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Missing "${KV_FORMAT_VERSION}" in "${validPath}".`, + validPath + ); + } + if (formatVersion !== ADJ_SNAPSHOT_FORMAT_VERSION) { + throw new AdjFactorsSnapshotError( + 'unsupported_version', + `Unsupported adj_factors snapshot metadata version ${formatVersion} at "${validPath}" (supported: ${ADJ_SNAPSHOT_FORMAT_VERSION}).`, + validPath + ); + } + if (snapshotKindStr === undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Missing "${KV_SNAPSHOT_KIND}" in "${validPath}".`, + validPath + ); + } + if (asOfMicros === undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Missing "${KV_AS_OF_MICROS}" in "${validPath}".`, + validPath + ); + } + if (vaultCutoffMicros === undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Missing "${KV_VAULT_CUTOFF_MICROS}" in "${validPath}".`, + validPath + ); + } + if (rowsWritten === undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Missing "${KV_ROWS_WRITTEN}" in "${validPath}".`, + validPath + ); + } + if (snapshotChecksum === undefined) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Missing "${KV_SNAPSHOT_CHECKSUM}" in "${validPath}".`, + validPath + ); + } + + let snapshotKind: AdjFactorsSnapshotKind; + if (snapshotKindStr === 'retrospective') { + if (asOfMicros !== null || vaultCutoffMicros !== null) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Retrospective adj_factors snapshot at "${validPath}" must have 'none' for as_of_micros and vault_cutoff_micros.`, + validPath + ); + } + snapshotKind = 'retrospective'; + } else if (snapshotKindStr === 'point_in_time_fenced') { + if (asOfMicros === null && vaultCutoffMicros === null) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Fenced adj_factors snapshot at "${validPath}" must specify at least one of as_of_micros or vault_cutoff_micros.`, + validPath + ); + } + snapshotKind = 'point_in_time_fenced'; + } else { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Unknown "${KV_SNAPSHOT_KIND}" value "${snapshotKindStr}" in "${validPath}".`, + validPath + ); + } + + return { + path: validPath, + formatVersion, + snapshotKind, + fence: { + asOfMicros, + vaultCutoffMicros, + }, + rowsWritten, + snapshotChecksum, + }; +} + +function effectiveSnapshotCeilingMicros(fence: AdjFactorsPointInTimeFence): number { + const asOfCeiling = fence.asOfMicros; + const vaultCeiling = fence.vaultCutoffMicros !== null ? fence.vaultCutoffMicros - 1 : null; + if (asOfCeiling !== null && vaultCeiling !== null) { + return Math.min(asOfCeiling, vaultCeiling); + } + if (asOfCeiling !== null) { + return asOfCeiling; + } + if (vaultCeiling !== null) { + return vaultCeiling; + } + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + 'Fenced adj_factors snapshot must carry at least one non-null fence bound.' + ); +} + +/** + * Verifies that `snapshot` is a well-formed, `point_in_time_fenced` + * `adj_factors` artifact whose effective inclusive microsecond ceiling matches + * the query's effective `asOf` and Vault fence, returning its validated + * `.parquet` path so the SQL planner binds `read_parquet(...)` directly to the + * verified file. + */ +function verifyAdjFactorsSnapshotForQuery( + snapshot: AdjFactorsSnapshotMetadata | undefined, + requiredAsOfMicros: number, + requiredVaultCutoffMicros: number | null +): string { + if (snapshot === undefined) { + throw new AdjFactorsSnapshotError( + 'missing_snapshot', + 'Adjusted bars queries ("split" / "total") require a verified point_in_time_fenced adj_factors snapshot matching the query asOf and Vault fence.' + ); + } + if (!isPlainRecord(snapshot)) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + 'Expected an AdjFactorsSnapshotMetadata object for adjFactorsSnapshot.' + ); + } + + const validPath = validateParquetFilePath(snapshot.path, 'adjFactorsSnapshot.path'); + + if ( + typeof snapshot.formatVersion !== 'number' || + !Number.isSafeInteger(snapshot.formatVersion) + ) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Invalid adj_factors snapshot formatVersion "${String(snapshot.formatVersion)}" at "${validPath}".`, + validPath + ); + } + if (snapshot.formatVersion !== ADJ_SNAPSHOT_FORMAT_VERSION) { + throw new AdjFactorsSnapshotError( + 'unsupported_version', + `Unsupported adj_factors snapshot version ${snapshot.formatVersion} at "${validPath}" (supported: ${ADJ_SNAPSHOT_FORMAT_VERSION}).`, + validPath + ); + } + if ( + typeof snapshot.rowsWritten !== 'number' || + !Number.isSafeInteger(snapshot.rowsWritten) || + snapshot.rowsWritten < 0 + ) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Invalid adj_factors snapshot rowsWritten "${String(snapshot.rowsWritten)}" at "${validPath}".`, + validPath + ); + } + if ( + typeof snapshot.snapshotChecksum !== 'string' || + !SNAPSHOT_CHECKSUM_RE.test(snapshot.snapshotChecksum) + ) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Invalid adj_factors snapshotChecksum "${String(snapshot.snapshotChecksum)}" at "${validPath}".`, + validPath + ); + } + + if (snapshot.snapshotKind === 'retrospective') { + throw new AdjFactorsSnapshotError( + 'retrospective_rejected', + `Refusing retrospective adj_factors snapshot at "${validPath}" for point-in-time adjusted bars query (cumulative factors may embed post-asOf or held-out Vault actions).`, + validPath + ); + } + if (snapshot.snapshotKind !== 'point_in_time_fenced') { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Unknown adj_factors snapshotKind "${String(snapshot.snapshotKind)}" at "${validPath}".`, + validPath + ); + } + + if (!isPlainRecord(snapshot.fence)) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Missing fence object in adj_factors snapshot metadata at "${validPath}".`, + validPath + ); + } + const { asOfMicros, vaultCutoffMicros } = snapshot.fence; + if ( + (asOfMicros !== null && (typeof asOfMicros !== 'number' || !Number.isSafeInteger(asOfMicros))) || + (vaultCutoffMicros !== null && + (typeof vaultCutoffMicros !== 'number' || !Number.isSafeInteger(vaultCutoffMicros))) + ) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Invalid microsecond fence bounds in adj_factors snapshot metadata at "${validPath}".`, + validPath + ); + } + if (asOfMicros === null && vaultCutoffMicros === null) { + throw new AdjFactorsSnapshotError( + 'invalid_metadata', + `Fenced adj_factors snapshot at "${validPath}" has no non-null fence bounds.`, + validPath + ); + } + + const actualCeiling = effectiveSnapshotCeilingMicros(snapshot.fence); + if ( + requiredVaultCutoffMicros !== null && + actualCeiling >= requiredVaultCutoffMicros + ) { + throw new AdjFactorsSnapshotError( + 'incompatible_fence', + `adj_factors snapshot at "${validPath}" admits actions at or past Vault cutoff (${actualCeiling} >= ${requiredVaultCutoffMicros}).`, + validPath + ); + } + if (actualCeiling !== requiredAsOfMicros) { + throw new AdjFactorsSnapshotError( + 'incompatible_fence', + `adj_factors snapshot at "${validPath}" has effective fence ceiling ${actualCeiling} µs, which does not match query effective asOf ${requiredAsOfMicros} µs.`, + validPath + ); + } + + return validPath; +} + +interface ValidatedBarsInputs { + readonly curatedRoot: string; + readonly adjustment: (typeof BARS_ADJUSTMENTS)[number]; + readonly listingIds: number[]; + readonly fenced: FencedTimeRange; + readonly fromSubMs: number; + readonly toSubMs: number; + readonly asOfSubMs: number; +} + +function validateBarsQueryInputs(q: BarsQuery, ctx: DuckDbPlanContext): ValidatedBarsInputs { const curatedRoot = validateContext(ctx); if (!isPlainRecord(q)) { throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); @@ -396,9 +1072,43 @@ export function planBars1dQuery(q: BarsQuery, ctx: DuckDbPlanContext): PlannedDu } ); - const fromIso = formatUtcIso(fenced.fromMs); - const toIso = formatUtcIso(fenced.toMs); - const asOfIso = formatUtcIso(fenced.asOfMs); + const fromSubMs = resolveFromSubMsMicros(q.from); + const toSubMs = resolveToSubMsMicros(q.to, fenced); + const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); + if (fenced.fromMs === fenced.toMs && fromSubMs > toSubMs) { + throw new MarketDataStoreValidationError( + `Query start "${q.from}" must not be after end "${q.to}".`, + 'from' + ); + } + + return { + curatedRoot, + adjustment, + listingIds, + fenced, + fromSubMs, + toSubMs, + asOfSubMs, + }; +} + +/** + * Plans a fenced DuckDB SQL query for daily curated OHLCV bars (`bars_1d`) with + * optional point-in-time `adj_factors` split or total-return adjustment. + * + * For `'split'` and `'total'`, `ctx.adjFactorsSnapshot` must supply verified + * `point_in_time_fenced` Parquet footer metadata matching the query's effective + * `asOf` and Vault fence; `read_parquet(...)` is bound directly to + * `ctx.adjFactorsSnapshot.path`. + */ +export function planBars1dQuery(q: BarsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { + const { curatedRoot, adjustment, listingIds, fenced, fromSubMs, toSubMs, asOfSubMs } = + validateBarsQueryInputs(q, ctx); + + const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); + const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); + const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet'); const listingPlaceholders = buildPlaceholders(listingIds.length); @@ -412,7 +1122,15 @@ export function planBars1dQuery(q: BarsQuery, ctx: DuckDbPlanContext): PlannedDu return { sql, params, fenced }; } - const adjPath = joinCuratedPath(curatedRoot, 'adj_factors/part.parquet'); + const requiredAsOfMicros = toEpochMicros(fenced.asOfMs, asOfSubMs, 'asOf'); + const requiredVaultCutoffMicros = + fenced.scope === 'vault_fenced' ? toEpochMicros(ctx.vaultCutoffTs, 0, 'vaultCutoffTs') : null; + const verifiedAdjPath = verifyAdjFactorsSnapshotForQuery( + ctx.adjFactorsSnapshot, + requiredAsOfMicros, + requiredVaultCutoffMicros + ); + const priceDivisor = adjustment === 'split' ? 'COALESCE(a.cum_split_factor, 1.0)' @@ -432,7 +1150,7 @@ export function planBars1dQuery(q: BarsQuery, ctx: DuckDbPlanContext): PlannedDu `b.vwap / ${priceDivisor} AS vwap, ` + 'epoch_ms(b.known_at) AS known_at ' + `FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` + - `ASOF LEFT JOIN (SELECT ${adjSelectCols} FROM read_parquet('${adjPath}') WHERE listing_id IN (${listingPlaceholders}) AND known_at <= ?) AS a ` + + `ASOF LEFT JOIN (SELECT ${adjSelectCols} FROM read_parquet('${verifiedAdjPath}') WHERE listing_id IN (${listingPlaceholders}) AND known_at <= ?) AS a ` + 'ON b.listing_id = a.listing_id AND b.session_date < a.ex_date ' + `WHERE b.listing_id IN (${listingPlaceholders}) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ` + 'ORDER BY b.listing_id ASC, b.ts ASC'; @@ -443,6 +1161,8 @@ export function planBars1dQuery(q: BarsQuery, ctx: DuckDbPlanContext): PlannedDu /** * Plans a fenced DuckDB SQL query for point-in-time curated events (`events`). + * Preserves the Parquet writer's total sort order: + * `(listing_id, ts, kind, subtype, payload_json, known_at, known_at_source)`. */ export function planEventsQuery(q: EventsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { const curatedRoot = validateContext(ctx); @@ -465,11 +1185,23 @@ export function planEventsQuery(q: EventsQuery, ctx: DuckDbPlanContext): Planned } ); - const fromIso = formatUtcIso(fenced.fromMs); - const toIso = formatUtcIso(fenced.toMs); - const asOfIso = formatUtcIso(fenced.asOfMs); + const fromSubMs = resolveFromSubMsMicros(q.from); + const toSubMs = resolveToSubMsMicros(q.to, fenced); + const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); + if (fenced.fromMs === fenced.toMs && fromSubMs > toSubMs) { + throw new MarketDataStoreValidationError( + `Query start "${q.from}" must not be after end "${q.to}".`, + 'from' + ); + } + + const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); + const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); + const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); const eventsPath = joinCuratedPath(curatedRoot, 'events/year=*/part.parquet'); const kindPlaceholders = buildPlaceholders(kinds.length); + const orderBy = + 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC'; if (listingIds !== undefined) { const listingPlaceholders = buildPlaceholders(listingIds.length); @@ -477,7 +1209,7 @@ export function planEventsQuery(q: EventsQuery, ctx: DuckDbPlanContext): Planned 'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' + `FROM read_parquet('${eventsPath}', hive_partitioning = true) AS e ` + `WHERE e.kind IN (${kindPlaceholders}) AND e.listing_id IN (${listingPlaceholders}) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ` + - 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC'; + orderBy; const params: DuckDbParam[] = [...kinds, ...listingIds, fromIso, toIso, asOfIso]; return { sql, params, fenced }; } @@ -486,7 +1218,7 @@ export function planEventsQuery(q: EventsQuery, ctx: DuckDbPlanContext): Planned 'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' + `FROM read_parquet('${eventsPath}', hive_partitioning = true) AS e ` + `WHERE e.kind IN (${kindPlaceholders}) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ` + - 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC'; + orderBy; const params: DuckDbParam[] = [...kinds, fromIso, toIso, asOfIso]; return { sql, params, fenced }; } @@ -516,9 +1248,10 @@ export function planShortsAsOfQuery( } ); + const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); const fromDate = formatUtcDate(fenced.fromMs); const toDate = formatUtcDate(fenced.toMs); - const asOfIso = formatUtcIso(fenced.asOfMs); + const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); const shortsPath = joinCuratedPath(curatedRoot, 'shorts/part.parquet'); const listingPlaceholders = buildPlaceholders(listingIds.length); @@ -534,7 +1267,10 @@ export function planShortsAsOfQuery( /** * Plans a fenced DuckDB SQL query for daily curated FX bars (`fx_1d`). * `fx` has no `asOf`/`scope` in `MarketDataStore`, so it is always planned - * under `'vault_fenced'` with default `asOf = vaultCutoffTs - 1`. + * under `'vault_fenced'` with default `asOf = vaultCutoffTs * 1000 - 1` µs. + * Date-only `to` and clamped/default Vault upper bounds expand to the last + * included Parquet microsecond (`23:59:59.999999Z`), matching `curate_fx_1d`'s + * `23:59:59.999999Z` session timestamps. */ export function planFx1dQuery(q: FxQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { const curatedRoot = validateContext(ctx); @@ -568,9 +1304,19 @@ export function planFx1dQuery(q: FxQuery, ctx: DuckDbPlanContext): PlannedDuckDb } ); - const fromIso = formatUtcIso(fenced.fromMs); - const toIso = formatUtcIso(fenced.toMs); - const asOfIso = formatUtcIso(fenced.asOfMs); + const fromSubMs = resolveFromSubMsMicros(q.from); + const toSubMs = resolveToSubMsMicros(q.to, fenced); + const asOfSubMs = resolveAsOfSubMsMicros(undefined, q.to, fenced); + if (fenced.fromMs === fenced.toMs && fromSubMs > toSubMs) { + throw new MarketDataStoreValidationError( + `Query start "${q.from}" must not be after end "${q.to}".`, + 'from' + ); + } + + const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); + const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); + const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); const fxPath = joinCuratedPath(curatedRoot, 'fx_1d/part.parquet'); const sql = @@ -665,14 +1411,68 @@ function mapBarRows(rows: readonly TableRow[]): BarRecord[] { return out; } -function isValidTableCell(value: unknown): value is TableCell { - if (value === null || typeof value === 'string' || typeof value === 'boolean') { - return true; +function readValidatedTableCell( + row: Record, + spec: TableColumnSpec, + rowIndex: number +): TableCell { + const val = row[spec.name]; + if (val === null) { + if (spec.nullable) { + return null; + } + throw new MarketDataStoreValidationError( + `Unexpected null for non-nullable column "${spec.name}" in result row ${rowIndex}.`, + spec.name + ); + } + + switch (spec.kind) { + case 'int32': + if ( + typeof val !== 'number' || + !Number.isSafeInteger(val) || + val < INT32_MIN || + val > INT32_MAX + ) { + throw new MarketDataStoreValidationError( + `Expected INT32 for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, + spec.name + ); + } + return val === 0 ? 0 : val; + case 'safe_int': + if (typeof val !== 'number' || !Number.isSafeInteger(val)) { + throw new MarketDataStoreValidationError( + `Expected integer timestamp for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, + spec.name + ); + } + return val === 0 ? 0 : val; + case 'number': + if (typeof val !== 'number' || !Number.isFinite(val)) { + throw new MarketDataStoreValidationError( + `Expected finite number for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, + spec.name + ); + } + return val === 0 ? 0 : val; + case 'string': + if (typeof val !== 'string') { + throw new MarketDataStoreValidationError( + `Expected string for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, + spec.name + ); + } + return val; } - return typeof value === 'number' && Number.isFinite(value); } -function mapTableRows(columns: readonly string[], rows: readonly TableRow[]): Table { +function mapTableRows( + columns: readonly string[], + schema: readonly TableColumnSpec[], + rows: readonly TableRow[] +): Table { if (!Array.isArray(rows)) { throw new MarketDataStoreValidationError('Executor returned a non-array table result.', 'rows'); } @@ -686,21 +1486,14 @@ function mapTableRows(columns: readonly string[], rows: readonly TableRow[]): Ta ); } const cleanRow: Record = {}; - for (const col of columns) { - if (!Object.prototype.hasOwnProperty.call(raw, col)) { + for (const spec of schema) { + if (!Object.prototype.hasOwnProperty.call(raw, spec.name)) { throw new MarketDataStoreValidationError( - `Missing expected column "${col}" in result row ${i}.`, - col + `Missing expected column "${spec.name}" in result row ${i}.`, + spec.name ); } - const cell = raw[col]; - if (!isValidTableCell(cell)) { - throw new MarketDataStoreValidationError( - `Invalid scalar cell value for column "${col}" in result row ${i}: ${String(cell)}.`, - col - ); - } - cleanRow[col] = cell; + cleanRow[spec.name] = readValidatedTableCell(raw, spec, i); } mappedRows[i] = cleanRow; } @@ -715,8 +1508,15 @@ function mapTableRows(columns: readonly string[], rows: readonly TableRow[]): Ta * over curated daily Parquet files. * * The three `resolveDuckDbConnectionBudget(env).statements` are executed - * sequentially, at most once, strictly after the first query plans cleanly and - * strictly before the first `executor.query(...)` call. + * sequentially, at most once, strictly after the first query validates cleanly + * and strictly before the first `executor.query(...)` call. + * + * For `'split'` and `'total'` `bars` queries, the adapter queries + * `parquet_kv_metadata` on the exact `adj_factors` Parquet file it is about to + * read, parses and verifies the `stock_bot.adj_factors.*` footer metadata + * against the query's effective `asOf` and Vault fence, and refuses + * unverified, retrospective, or mismatched-fence artifacts before issuing the + * `bars` data query. */ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOptions): MarketDataStore { if (!isPlainRecord(options)) { @@ -740,6 +1540,10 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption const typedExecutor = executor as unknown as DuckDbExecutor; const curatedRoot = validateCuratedRoot(options.curatedRoot); + const adjFactorsPath = + options.adjFactorsPath !== undefined + ? validateParquetFilePath(options.adjFactorsPath, 'adjFactorsPath') + : joinCuratedPath(curatedRoot, 'adj_factors/part.parquet'); const vaultCutoffTs = options.vaultCutoffTs; if ( @@ -795,8 +1599,24 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption return { async *bars(q: BarsQuery): AsyncIterable { - const planned = planBars1dQuery(q, planCtx); - await ensureBudgetInitialized(); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); + } + + let planned: PlannedDuckDbQuery; + if (q.adjustment === 'split' || q.adjustment === 'total') { + // Validate timeframe, listingIds, adjustment, and Vault fence before any executor call. + validateBarsQueryInputs(q, planCtx); + await ensureBudgetInitialized(); + const metaQuery = planAdjFactorsMetadataQuery(adjFactorsPath); + const kvRows = await typedExecutor.query(metaQuery.sql, metaQuery.params); + const adjFactorsSnapshot = parseAdjFactorsSnapshotMetadata(adjFactorsPath, kvRows); + planned = planBars1dQuery(q, { ...planCtx, adjFactorsSnapshot }); + } else { + planned = planBars1dQuery(q, planCtx); + await ensureBudgetInitialized(); + } + const rawRows = await typedExecutor.query(planned.sql, planned.params); const mapped = mapBarRows(rawRows); if (mapped.length === 0) { @@ -815,21 +1635,21 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption const planned = planEventsQuery(q, planCtx); await ensureBudgetInitialized(); const rawRows = await typedExecutor.query(planned.sql, planned.params); - return mapTableRows(EVENTS_COLUMNS, rawRows); + return mapTableRows(EVENTS_COLUMNS, EVENTS_SCHEMA, rawRows); }, async shortsAsOf(q: ShortsAsOfQuery): Promise { const planned = planShortsAsOfQuery(q, planCtx); await ensureBudgetInitialized(); const rawRows = await typedExecutor.query(planned.sql, planned.params); - return mapTableRows(SHORTS_COLUMNS, rawRows); + return mapTableRows(SHORTS_COLUMNS, SHORTS_SCHEMA, rawRows); }, async fx(q: FxQuery): Promise
{ const planned = planFx1dQuery(q, planCtx); await ensureBudgetInitialized(); const rawRows = await typedExecutor.query(planned.sql, planned.params); - return mapTableRows(FX_1D_COLUMNS, rawRows); + return mapTableRows(FX_1D_COLUMNS, FX_1D_SCHEMA, rawRows); }, crossSection(): Promise
{ diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index da0df47c..a8fec904 100644 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'bun:test'; import { + ADJ_SNAPSHOT_FORMAT_VERSION, + ADJ_SNAPSHOT_KV_PREFIX, + AdjFactorsSnapshotError, + type AdjFactorsSnapshotMetadata, BARS_ADJUSTMENTS, type BarBatch, type DuckDbExecutor, @@ -16,14 +20,20 @@ import { VaultHoldoutFenceError, VaultScopeNotAuthorizedError, createDuckDbMarketDataStore, + parseAdjFactorsSnapshotMetadata, + planAdjFactorsMetadataQuery, planBars1dQuery, planEventsQuery, planFx1dQuery, planShortsAsOfQuery, resolveDuckDbConnectionBudget, validateCuratedRoot, + validateParquetFilePath, } from '@stock-bot/research'; import { + ADJ_SNAPSHOT_FORMAT_VERSION as subpathAdjSnapshotFormatVersion, + ADJ_SNAPSHOT_KV_PREFIX as subpathAdjSnapshotKvPrefix, + AdjFactorsSnapshotError as SubpathAdjFactorsSnapshotError, BARS_ADJUSTMENTS as subpathBarsAdjustments, EVENT_KINDS as subpathEventKinds, EVENTS_COLUMNS as subpathEventsColumns, @@ -32,23 +42,95 @@ import { MarketDataStoreNotImplementedError as SubpathNotImplementedError, SHORTS_COLUMNS as subpathShortsColumns, createDuckDbMarketDataStore as subpathCreateDuckDbMarketDataStore, + parseAdjFactorsSnapshotMetadata as subpathParseAdjFactorsSnapshotMetadata, + planAdjFactorsMetadataQuery as subpathPlanAdjFactorsMetadataQuery, planBars1dQuery as subpathPlanBars1dQuery, planEventsQuery as subpathPlanEventsQuery, planFx1dQuery as subpathPlanFx1dQuery, planShortsAsOfQuery as subpathPlanShortsAsOfQuery, validateCuratedRoot as subpathValidateCuratedRoot, + validateParquetFilePath as subpathValidateParquetFilePath, } from '@stock-bot/research/market-data-store-duckdb'; const CURATED_ROOT = '/mnt/data/stockbot/curated'; +const DEFAULT_ADJ_PATH = `${CURATED_ROOT}/adj_factors/part.parquet`; const CUTOFF_MS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); // 2026-05-28T00:00:00.000Z -const MAX_ALLOWED_ISO = new Date(CUTOFF_MS - 1).toISOString(); // 2026-05-27T23:59:59.999Z -const MAX_ALLOWED_DATE = MAX_ALLOWED_ISO.slice(0, 10); // 2026-05-27 +const CUTOFF_MICROS = CUTOFF_MS * 1000; +const MAX_ALLOWED_ISO_MICROS = '2026-05-27T23:59:59.999999Z'; +const MAX_ALLOWED_DATE = '2026-05-27'; const DEFAULT_CTX: DuckDbPlanContext = { curatedRoot: CURATED_ROOT, vaultCutoffTs: CUTOFF_MS, }; +function makeFencedKvRows(opts: { + snapshotKind?: string; + asOfMicros?: number | null; + vaultCutoffMicros?: number | null; + rowsWritten?: number; + checksum?: string; + formatVersion?: string; +}): TableRow[] { + return [ + { key: 'stock_bot.adj_factors.format_version', value: opts.formatVersion ?? '1' }, + { key: 'stock_bot.adj_factors.snapshot_kind', value: opts.snapshotKind ?? 'point_in_time_fenced' }, + { + key: 'stock_bot.adj_factors.as_of_micros', + value: opts.asOfMicros === undefined || opts.asOfMicros === null ? 'none' : String(opts.asOfMicros), + }, + { + key: 'stock_bot.adj_factors.vault_cutoff_micros', + value: + opts.vaultCutoffMicros === undefined || opts.vaultCutoffMicros === null + ? 'none' + : String(opts.vaultCutoffMicros), + }, + { key: 'stock_bot.adj_factors.rows_written', value: String(opts.rowsWritten ?? 1) }, + { + key: 'stock_bot.adj_factors.snapshot_checksum', + value: opts.checksum ?? '0x024ec73a1afe7e6b', + }, + ]; +} + +function makeFencedSnapshot(opts: { + path?: string; + asOfMicros?: number | null; + vaultCutoffMicros?: number | null; + rowsWritten?: number; +}): AdjFactorsSnapshotMetadata { + return parseAdjFactorsSnapshotMetadata( + opts.path ?? DEFAULT_ADJ_PATH, + makeFencedKvRows({ + asOfMicros: opts.asOfMicros, + vaultCutoffMicros: opts.vaultCutoffMicros, + rowsWritten: opts.rowsWritten, + }) + ); +} + +/** Parses a UTC ISO-8601 timestamp with optional up-to-microsecond fractional digits into epoch µs. */ +function parseIsoToMicros(iso: string): number { + const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/.exec(iso); + if (m === null) { + throw new Error(`Unexpected UTC ISO timestamp: ${iso}`); + } + const frac = (m[7] ?? '').padEnd(6, '0').slice(0, 6); + const ms = Number(frac.slice(0, 3)); + const subMs = Number(frac.slice(3, 6)); + const epochMs = Date.UTC( + Number(m[1]), + Number(m[2]) - 1, + Number(m[3]), + Number(m[4]), + Number(m[5]), + Number(m[6]), + ms + ); + return epochMs * 1000 + subMs; +} + interface RecordedCall { readonly kind: 'run' | 'query'; readonly sql: string; @@ -122,9 +204,15 @@ describe('market-data-store-duckdb exports', () => { expect(planEventsQuery).toBe(subpathPlanEventsQuery); expect(planShortsAsOfQuery).toBe(subpathPlanShortsAsOfQuery); expect(planFx1dQuery).toBe(subpathPlanFx1dQuery); + expect(planAdjFactorsMetadataQuery).toBe(subpathPlanAdjFactorsMetadataQuery); + expect(parseAdjFactorsSnapshotMetadata).toBe(subpathParseAdjFactorsSnapshotMetadata); expect(createDuckDbMarketDataStore).toBe(subpathCreateDuckDbMarketDataStore); expect(validateCuratedRoot).toBe(subpathValidateCuratedRoot); + expect(validateParquetFilePath).toBe(subpathValidateParquetFilePath); expect(MarketDataStoreNotImplementedError).toBe(SubpathNotImplementedError); + expect(AdjFactorsSnapshotError).toBe(SubpathAdjFactorsSnapshotError); + expect(ADJ_SNAPSHOT_FORMAT_VERSION).toBe(subpathAdjSnapshotFormatVersion); + expect(ADJ_SNAPSHOT_KV_PREFIX).toBe(subpathAdjSnapshotKvPrefix); expect(EVENT_KINDS).toBe(subpathEventKinds); expect(FX_PAIR_MAP).toBe(subpathFxPairMap); expect(BARS_ADJUSTMENTS).toBe(subpathBarsAdjustments); @@ -164,7 +252,7 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => 202, 0, '2024-01-02T00:00:00.000Z', - '2025-12-31T23:59:59.999Z', + '2025-12-31T23:59:59.999999Z', '2026-01-15T12:00:00.000Z', ]); expect(planned.fenced.scope).toBe('vault_fenced'); @@ -172,7 +260,13 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => expect(planned.fenced.clampedAsOf).toBe(false); }); - it('plans bars 1d split query with ASOF LEFT JOIN on b.session_date < a.ex_date and cum_split_factor', () => { + it('plans bars 1d split query with verified fenced adj_factors snapshot bound to read_parquet', () => { + const asOfMicros = parseIsoToMicros('2025-07-01T23:59:59.999999Z'); + const snapshot = makeFencedSnapshot({ + path: DEFAULT_ADJ_PATH, + asOfMicros, + vaultCutoffMicros: CUTOFF_MICROS, + }); const planned = planBars1dQuery( { listingIds: [42, 77], @@ -182,7 +276,7 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => adjustment: 'split', asOf: '2025-07-01', }, - DEFAULT_CTX + { ...DEFAULT_CTX, adjFactorsSnapshot: snapshot } ); expect(planned.sql).toBe( @@ -195,7 +289,7 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => 'b.vwap / COALESCE(a.cum_split_factor, 1.0) AS vwap, ' + 'epoch_ms(b.known_at) AS known_at ' + `FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b ` + - `ASOF LEFT JOIN (SELECT listing_id, ex_date, cum_split_factor FROM read_parquet('${CURATED_ROOT}/adj_factors/part.parquet') WHERE listing_id IN (?, ?) AND known_at <= ?) AS a ` + + `ASOF LEFT JOIN (SELECT listing_id, ex_date, cum_split_factor FROM read_parquet('${DEFAULT_ADJ_PATH}') WHERE listing_id IN (?, ?) AND known_at <= ?) AS a ` + 'ON b.listing_id = a.listing_id AND b.session_date < a.ex_date ' + 'WHERE b.listing_id IN (?, ?) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ' + 'ORDER BY b.listing_id ASC, b.ts ASC' @@ -203,16 +297,21 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => expect(planned.params).toEqual([ 42, 77, - '2025-07-01T23:59:59.999Z', + '2025-07-01T23:59:59.999999Z', 42, 77, '2023-01-01T00:00:00.000Z', - '2025-06-30T23:59:59.999Z', - '2025-07-01T23:59:59.999Z', + '2025-06-30T23:59:59.999999Z', + '2025-07-01T23:59:59.999999Z', ]); }); it('plans bars 1d total query dividing prices by cum_total_factor and multiplying volume by cum_split_factor', () => { + const snapshot = makeFencedSnapshot({ + path: '/adj_factors/part.parquet', + asOfMicros: null, + vaultCutoffMicros: CUTOFF_MICROS, + }); const planned = planBars1dQuery( { listingIds: [7], @@ -221,7 +320,7 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => to: '2025-01-01', adjustment: 'total', }, - { curatedRoot: '/', vaultCutoffTs: CUTOFF_MS } + { curatedRoot: '/', vaultCutoffTs: CUTOFF_MS, adjFactorsSnapshot: snapshot } ); expect(planned.sql).toBe( @@ -241,15 +340,15 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => ); expect(planned.params).toEqual([ 7, - MAX_ALLOWED_ISO, + MAX_ALLOWED_ISO_MICROS, 7, '2020-01-01T00:00:00.000Z', - '2025-01-01T23:59:59.999Z', - MAX_ALLOWED_ISO, + '2025-01-01T23:59:59.999999Z', + MAX_ALLOWED_ISO_MICROS, ]); }); - it('plans events query with and without listingIds and deduplicates kinds without mutating input', () => { + it('plans events query with and without listingIds using complete Parquet writer tie-breaker ordering', () => { const kinds: Array<'filing' | 'earnings'> = ['filing', 'earnings', 'filing']; const withListings = planEventsQuery( { @@ -267,7 +366,7 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => 'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' + `FROM read_parquet('${CURATED_ROOT}/events/year=*/part.parquet', hive_partitioning = true) AS e ` + 'WHERE e.kind IN (?, ?) AND e.listing_id IN (?, ?) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ' + - 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC' + 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC' ); expect(withListings.params).toEqual([ 'filing', @@ -275,7 +374,7 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => 10, 20, '2025-01-01T00:00:00.000Z', - '2025-03-31T23:59:59.999Z', + '2025-03-31T23:59:59.999999Z', '2025-04-01T00:00:00.000Z', ]); @@ -291,23 +390,73 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => 'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' + `FROM read_parquet('${CURATED_ROOT}/events/year=*/part.parquet', hive_partitioning = true) AS e ` + 'WHERE e.kind IN (?) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ' + - 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC' + 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC' ); expect(withoutListings.params).toEqual([ 'corporate_action', '2025-01-01T00:00:00.000Z', - '2025-03-31T23:59:59.999Z', - MAX_ALLOWED_ISO, + '2025-03-31T23:59:59.999999Z', + MAX_ALLOWED_ISO_MICROS, ]); }); - it('plans shortsAsOf query binding UTC YYYY-MM-DD report_date bounds and ISO known_at bound', () => { + it('orders two distinct filings sharing (listing_id, ts, kind, subtype) deterministically via payload_json tie-breaker', async () => { + const sameSecondMs = Date.UTC(2025, 2, 10, 21, 5, 0); + const filingA: TableRow = { + listing_id: 10, + ts: sameSecondMs, + known_at: sameSecondMs, + known_at_source: 'filing_timestamp', + kind: 'filing', + subtype: '8-k', + payload_json: '{"accession":"0001","item":"2.02"}', + }; + const filingB: TableRow = { + listing_id: 10, + ts: sameSecondMs, + known_at: sameSecondMs, + known_at_source: 'filing_timestamp', + kind: 'filing', + subtype: '8-k', + payload_json: '{"accession":"0002","item":"7.01"}', + }; + + const fake = createRecordingExecutor({ + onQuery: (sql) => { + // Confirm the SQL query requests the complete writer tie-breaker order. + expect(sql).toContain( + 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC' + ); + // Simulate DuckDB sorting rows by the exact ORDER BY key. + return [filingB, filingA].sort((a, b) => + String(a.payload_json).localeCompare(String(b.payload_json)) + ); + }, + }); + + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + + const result = await store.events({ + kinds: ['filing'], + listingIds: [10], + from: '2025-03-10', + to: '2025-03-10', + }); + expect(result.rows).toEqual([filingA, filingB]); + }); + + it('plans shortsAsOf query binding UTC YYYY-MM-DD report_date bounds and microsecond ISO known_at bound', () => { const planned = planShortsAsOfQuery( { listingIds: [500, 600], from: '2024-06-01', - to: '2026-08-01', // clamped to 2026-05-27T23:59:59.999Z - asOf: '2026-09-01', // clamped to 2026-05-27T23:59:59.999Z + to: '2026-08-01', // clamped to 2026-05-27T23:59:59.999999Z + asOf: '2026-09-01', // clamped to 2026-05-27T23:59:59.999999Z }, DEFAULT_CTX ); @@ -323,13 +472,13 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => 600, '2024-06-01', MAX_ALLOWED_DATE, - MAX_ALLOWED_ISO, + MAX_ALLOWED_ISO_MICROS, ]); expect(planned.fenced.clampedTo).toBe(true); expect(planned.fenced.clampedAsOf).toBe(true); }); - it('plans fx 1d query mapping USD.CAD to bound USDCAD and enforcing vault_fenced default asOf', () => { + it('plans fx 1d query mapping USD.CAD to bound USDCAD and enforcing vault_fenced microsecond default asOf', () => { const planned = planFx1dQuery( { pair: 'USD.CAD', @@ -349,8 +498,8 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => expect(planned.params).toEqual([ 'USDCAD', '2022-01-01T00:00:00.000Z', - MAX_ALLOWED_ISO, - MAX_ALLOWED_ISO, + MAX_ALLOWED_ISO_MICROS, + MAX_ALLOWED_ISO_MICROS, ]); expect(planned.fenced.scope).toBe('vault_fenced'); expect(planned.fenced.clampedTo).toBe(true); @@ -358,6 +507,408 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => }); }); +describe('FX 1d microsecond bounds (curate_fx_1d 23:59:59.999999Z compatibility)', () => { + it('includes a single-day FX session stamped at 23:59:59.999999Z for date-only from=to', () => { + const planned = planFx1dQuery( + { + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-15', + to: '2025-01-15', + }, + DEFAULT_CTX + ); + + expect(planned.params).toEqual([ + 'USDCAD', + '2025-01-15T00:00:00.000Z', + '2025-01-15T23:59:59.999999Z', + MAX_ALLOWED_ISO_MICROS, + ]); + + const writerTsMicros = parseIsoToMicros('2025-01-15T23:59:59.999999Z'); + const boundFromMicros = parseIsoToMicros(planned.params[1] as string); + const boundToMicros = parseIsoToMicros(planned.params[2] as string); + const boundAsOfMicros = parseIsoToMicros(planned.params[3] as string); + + expect(writerTsMicros).toBeGreaterThanOrEqual(boundFromMicros); + expect(writerTsMicros).toBeLessThanOrEqual(boundToMicros); + expect(writerTsMicros).toBeLessThanOrEqual(boundAsOfMicros); + expect(boundToMicros).toBeLessThan(CUTOFF_MICROS); + expect(boundAsOfMicros).toBeLessThan(CUTOFF_MICROS); + }); + + it('includes the last pre-Vault FX session (2026-05-27T23:59:59.999999Z) while excluding the Vault cutoff day', () => { + const planned = planFx1dQuery( + { + pair: 'USD.CAD', + timeframe: '1d', + from: '2026-05-27', + to: '2026-05-27', + }, + DEFAULT_CTX + ); + + expect(planned.params).toEqual([ + 'USDCAD', + '2026-05-27T00:00:00.000Z', + '2026-05-27T23:59:59.999999Z', + '2026-05-27T23:59:59.999999Z', + ]); + + const lastPreVaultMicros = parseIsoToMicros('2026-05-27T23:59:59.999999Z'); + const firstVaultMicros = parseIsoToMicros('2026-05-28T00:00:00.000000Z'); + const boundToMicros = parseIsoToMicros(planned.params[2] as string); + const boundAsOfMicros = parseIsoToMicros(planned.params[3] as string); + + expect(lastPreVaultMicros).toBeLessThanOrEqual(boundToMicros); + expect(lastPreVaultMicros).toBeLessThanOrEqual(boundAsOfMicros); + expect(boundToMicros).toBeLessThan(firstVaultMicros); + expect(boundAsOfMicros).toBeLessThan(firstVaultMicros); + }); + + it('preserves explicit time-of-day upper bounds without expanding to .999999Z', () => { + const explicitSec = planFx1dQuery( + { + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-15T00:00:00Z', + to: '2025-01-15T16:00:00Z', + }, + DEFAULT_CTX + ); + expect(explicitSec.params[2]).toBe('2025-01-15T16:00:00.000Z'); + + const explicitMs = planFx1dQuery( + { + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-15T00:00:00Z', + to: '2025-01-15T23:59:59.999Z', + }, + DEFAULT_CTX + ); + expect(explicitMs.params[2]).toBe('2025-01-15T23:59:59.999Z'); + // Writer's 23:59:59.999999Z is excluded when caller explicitly asks for <= 23:59:59.999Z. + expect(parseIsoToMicros('2025-01-15T23:59:59.999999Z')).toBeGreaterThan( + parseIsoToMicros(explicitMs.params[2] as string) + ); + }); + + it('keeps clamped/default upper bounds strictly before non-midnight Vault cutoffs', () => { + const nonMidnightCutoffMs = Date.UTC(2026, 4, 28, 12, 30, 0, 500); + const planned = planFx1dQuery( + { + pair: 'USD.CAD', + timeframe: '1d', + from: '2026-05-01', + to: '2026-06-01', + }, + { curatedRoot: CURATED_ROOT, vaultCutoffTs: nonMidnightCutoffMs } + ); + expect(planned.params[2]).toBe('2026-05-28T12:30:00.499999Z'); + expect(planned.params[3]).toBe('2026-05-28T12:30:00.499999Z'); + expect(parseIsoToMicros(planned.params[2] as string)).toBe(nonMidnightCutoffMs * 1000 - 1); + }); +}); + +describe('adj_factors snapshot verification & Vault future-split leakage prevention', () => { + it('plans parquet_kv_metadata query bound to the exact adj_factors file path', () => { + const metaQuery = planAdjFactorsMetadataQuery(DEFAULT_ADJ_PATH); + expect(metaQuery).toEqual({ + path: DEFAULT_ADJ_PATH, + sql: + 'SELECT decode(key) AS key, decode(value) AS value ' + + `FROM parquet_kv_metadata('${DEFAULT_ADJ_PATH}') ` + + 'WHERE decode(key) LIKE ?', + params: ['stock_bot.adj_factors.%'], + }); + + expect(() => planAdjFactorsMetadataQuery("'/evil.parquet")).toThrow( + MarketDataStoreValidationError + ); + expect(() => planAdjFactorsMetadataQuery('/data/adj_factors/part.csv')).toThrow( + MarketDataStoreValidationError + ); + }); + + it('parses valid curate-etl footer metadata and rejects missing, malformed, or unsupported metadata', () => { + const asOfMicros = Date.UTC(2018, 2, 14, 12, 0, 0) * 1000; + const parsed = parseAdjFactorsSnapshotMetadata( + DEFAULT_ADJ_PATH, + makeFencedKvRows({ asOfMicros, vaultCutoffMicros: null, rowsWritten: 42 }) + ); + expect(parsed).toEqual({ + path: DEFAULT_ADJ_PATH, + formatVersion: 1, + snapshotKind: 'point_in_time_fenced', + fence: { asOfMicros, vaultCutoffMicros: null }, + rowsWritten: 42, + snapshotChecksum: '0x024ec73a1afe7e6b', + }); + + // Missing metadata + expect(() => parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, [])).toThrow( + AdjFactorsSnapshotError + ); + try { + parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, []); + } catch (err) { + expect((err as AdjFactorsSnapshotError).code).toBe('missing_metadata'); + } + + // Unsupported version + try { + parseAdjFactorsSnapshotMetadata( + DEFAULT_ADJ_PATH, + makeFencedKvRows({ formatVersion: '2', asOfMicros }) + ); + expect.unreachable('should throw unsupported_version'); + } catch (err) { + expect(err).toBeInstanceOf(AdjFactorsSnapshotError); + expect((err as AdjFactorsSnapshotError).code).toBe('unsupported_version'); + } + + // Duplicate key + expect(() => + parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, [ + ...makeFencedKvRows({ asOfMicros }), + { key: 'stock_bot.adj_factors.format_version', value: '1' }, + ]) + ).toThrow(AdjFactorsSnapshotError); + + // Unknown stock_bot.adj_factors.* key + expect(() => + parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, [ + ...makeFencedKvRows({ asOfMicros }), + { key: 'stock_bot.adj_factors.extra', value: '1' }, + ]) + ).toThrow(AdjFactorsSnapshotError); + + // Invalid checksum + expect(() => + parseAdjFactorsSnapshotMetadata( + DEFAULT_ADJ_PATH, + makeFencedKvRows({ asOfMicros, checksum: 'deadbeef' }) + ) + ).toThrow(AdjFactorsSnapshotError); + + // Retrospective with non-none fence + expect(() => + parseAdjFactorsSnapshotMetadata( + DEFAULT_ADJ_PATH, + makeFencedKvRows({ snapshotKind: 'retrospective', asOfMicros }) + ) + ).toThrow(AdjFactorsSnapshotError); + + // Fenced with both bounds none + expect(() => + parseAdjFactorsSnapshotMetadata( + DEFAULT_ADJ_PATH, + makeFencedKvRows({ + snapshotKind: 'point_in_time_fenced', + asOfMicros: null, + vaultCutoffMicros: null, + }) + ) + ).toThrow(AdjFactorsSnapshotError); + }); + + it('rejects retrospective and mismatched-fence snapshots and prevents Vault future-split leakage', async () => { + // Fixture mirroring tools/curate-etl/tests/curate_adj_qa_contract.rs: + // - Listing 42 has a visible 2-for-1 split on 2024-06-10 (pre-Vault) + // - Listing 42 has a held-out 2-for-1 split on 2026-07-15 (inside Vault, after CUTOFF_MS) + // - Raw close on 2024-06-07 (immediately before visible split) is 100.0. + // - Retrospective snapshot has cum_split_factor = 4.0 -> 100 / 4 = 25.0 (LEAK!). + // - Fenced snapshot (vault_cutoff = CUTOFF_MICROS) excludes the 2026-07-15 split before + // compounding, so cum_split_factor = 2.0 -> 100 / 2 = 50.0 (CLEAN!). + const rawPreSplitClose = 100.0; + + // 1. Planner rejects missing adjFactorsSnapshot for split/total + try { + planBars1dQuery( + { + listingIds: [42], + timeframe: '1d', + from: '2024-06-01', + to: '2024-06-15', + adjustment: 'split', + }, + DEFAULT_CTX + ); + expect.unreachable('should throw missing_snapshot'); + } catch (err) { + expect(err).toBeInstanceOf(AdjFactorsSnapshotError); + expect((err as AdjFactorsSnapshotError).code).toBe('missing_snapshot'); + } + + // 2. Adapter rejects retrospective adj_factors snapshot without executing bars query + const retroFake = createRecordingExecutor({ + onQuery: (sql) => { + if (sql.includes('parquet_kv_metadata')) { + return makeFencedKvRows({ + snapshotKind: 'retrospective', + asOfMicros: null, + vaultCutoffMicros: null, + rowsWritten: 2, + }); + } + throw new Error('bars query must never run against retrospective adj_factors'); + }, + }); + const retroStore = createDuckDbMarketDataStore({ + executor: retroFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + + try { + await collectBars( + retroStore.bars({ + listingIds: [42], + timeframe: '1d', + from: '2024-06-01', + to: '2024-06-15', + adjustment: 'split', + }) + ); + expect.unreachable('should reject retrospective snapshot'); + } catch (err) { + expect(err).toBeInstanceOf(AdjFactorsSnapshotError); + expect((err as AdjFactorsSnapshotError).code).toBe('retrospective_rejected'); + } + expect(retroFake.queryCalls).toHaveLength(1); + expect(retroFake.queryCalls[0]!.sql).toContain('parquet_kv_metadata'); + + // 3. Adapter rejects neighbouring fence 1 microsecond off (curate_adj_qa_contract.rs:282) + // and rejects a snapshot fenced past the Vault cutoff (which would embed the 2026-07-15 split). + const laterCutoffMicros = Date.UTC(2026, 7, 1, 0, 0, 0) * 1000; + for (const badFence of [ + { asOfMicros: CUTOFF_MICROS - 2, vaultCutoffMicros: CUTOFF_MICROS }, // 1 µs too early + { asOfMicros: null, vaultCutoffMicros: CUTOFF_MICROS + 1 }, // 1 µs past cutoff + { asOfMicros: null, vaultCutoffMicros: laterCutoffMicros }, // includes Vault split + ]) { + const badFake = createRecordingExecutor({ + onQuery: (sql) => { + if (sql.includes('parquet_kv_metadata')) { + return makeFencedKvRows({ ...badFence, rowsWritten: 2 }); + } + throw new Error('bars query must never run against mismatched fence'); + }, + }); + const badStore = createDuckDbMarketDataStore({ + executor: badFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + + try { + await collectBars( + badStore.bars({ + listingIds: [42], + timeframe: '1d', + from: '2024-06-01', + to: '2024-06-15', + adjustment: 'split', + }) + ); + expect.unreachable('should reject incompatible fence'); + } catch (err) { + expect(err).toBeInstanceOf(AdjFactorsSnapshotError); + expect((err as AdjFactorsSnapshotError).code).toBe('incompatible_fence'); + } + expect(badFake.queryCalls).toHaveLength(1); + } + + // 4. Adapter accepts exact fenced snapshot (vault_cutoff wins over later as_of, matching + // curate_adj_qa_contract.rs:303) bound to custom adjFactorsPath, and adjusts close by 2.0 (not 4.0). + const fencedAdjPath = `${CURATED_ROOT}/adj_factors/vault_2026_05_28/part.parquet`; + const fencedFake = createRecordingExecutor({ + onQuery: (sql) => { + if (sql.includes('parquet_kv_metadata')) { + expect(sql).toContain(`parquet_kv_metadata('${fencedAdjPath}')`); + return makeFencedKvRows({ + asOfMicros: Date.UTC(2026, 9, 1, 0, 0, 0) * 1000, // later as_of; vault_cutoff wins + vaultCutoffMicros: CUTOFF_MICROS, + rowsWritten: 1, // only the visible 2024-06-10 split + }); + } + // Verification is bound to the exact file read in the bars SQL. + expect(sql).toContain(`read_parquet('${fencedAdjPath}')`); + const fencedCumSplitFactor = 2.0; // Vault 2026-07-15 split excluded before compounding + return [ + { + listing_id: 42, + ts: Date.UTC(2024, 5, 7, 20, 0, 0), + open: rawPreSplitClose / fencedCumSplitFactor, + high: rawPreSplitClose / fencedCumSplitFactor, + low: rawPreSplitClose / fencedCumSplitFactor, + close: rawPreSplitClose / fencedCumSplitFactor, + volume: 1000 * fencedCumSplitFactor, + vwap: null, + known_at: Date.UTC(2024, 5, 7, 20, 0, 0), + }, + ]; + }, + }); + const fencedStore = createDuckDbMarketDataStore({ + executor: fencedFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + adjFactorsPath: fencedAdjPath, + env: {}, + }); + + const batches = await collectBars( + fencedStore.bars({ + listingIds: [42], + timeframe: '1d', + from: '2024-06-01', + to: '2024-06-15', + adjustment: 'split', + }) + ); + expect(batches).toHaveLength(1); + expect(batches[0]!.rows[0]!.close).toBe(50.0); + expect(batches[0]!.rows[0]!.volume).toBe(2000); + expect(fencedFake.runCalls).toHaveLength(3); + expect(fencedFake.queryCalls).toHaveLength(2); + expect(fencedFake.calls.slice(0, 3).map(c => c.kind)).toEqual(['run', 'run', 'run']); + }); + + it('rejects retrospective snapshot even under authorized vault_evaluation_only', () => { + const retroSnapshot = parseAdjFactorsSnapshotMetadata( + DEFAULT_ADJ_PATH, + makeFencedKvRows({ snapshotKind: 'retrospective', asOfMicros: null, vaultCutoffMicros: null }) + ); + + try { + planBars1dQuery( + { + listingIds: [42], + timeframe: '1d', + from: '2026-06-01', + to: '2026-07-01', + adjustment: 'split', + scope: 'vault_evaluation_only', + }, + { + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + vaultOperatorAuthorized: true, + adjFactorsSnapshot: retroSnapshot, + } + ); + expect.unreachable('should reject retrospective snapshot under vault_evaluation_only'); + } catch (err) { + expect(err).toBeInstanceOf(AdjFactorsSnapshotError); + expect((err as AdjFactorsSnapshotError).code).toBe('retrospective_rejected'); + } + }); +}); + describe('mandatory Vault & PIT invariants + TZ invariance', () => { it('enforces bound known_at <= ? and upper bounds < vaultCutoffTs across 400 seeded mixed queries', () => { const rng = createMulberry32(20261129); @@ -388,6 +939,23 @@ describe('mandatory Vault & PIT invariants + TZ invariance', () => { let planned; if (kindIdx === 0) { const adj = BARS_ADJUSTMENTS[i % 3]!; + // Compute matching fenced snapshot for split/total + const rawPlan = planBars1dQuery( + { + listingIds: [1], + timeframe: '1d', + from: fromStr, + to: toStr, + adjustment: 'raw', + asOf: asOfStr, + }, + DEFAULT_CTX + ); + const effAsOfMicros = parseIsoToMicros(rawPlan.params[rawPlan.params.length - 1] as string); + const snapshot = makeFencedSnapshot({ + asOfMicros: effAsOfMicros, + vaultCutoffMicros: CUTOFF_MICROS, + }); planned = planBars1dQuery( { listingIds: [1 + Math.floor(rng() * 100_000)], @@ -397,18 +965,17 @@ describe('mandatory Vault & PIT invariants + TZ invariance', () => { adjustment: adj, asOf: asOfStr, }, - DEFAULT_CTX + adj === 'raw' ? DEFAULT_CTX : { ...DEFAULT_CTX, adjFactorsSnapshot: snapshot } ); expect(planned.sql).toContain('known_at <= ?'); expect(planned.sql).toContain('b.ts <= ?'); const boundTo = planned.params[planned.params.length - 2] as string; const boundAsOf = planned.params[planned.params.length - 1] as string; - expect(Date.parse(boundTo)).toBeLessThan(CUTOFF_MS); - expect(Date.parse(boundAsOf)).toBeLessThan(CUTOFF_MS); + expect(parseIsoToMicros(boundTo)).toBeLessThan(CUTOFF_MICROS); + expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS); if (adj !== 'raw') { - // adj_factors subquery known_at <= ? const adjAsOf = planned.params[1] as string; - expect(Date.parse(adjAsOf)).toBeLessThan(CUTOFF_MS); + expect(parseIsoToMicros(adjAsOf)).toBeLessThan(CUTOFF_MICROS); } } else if (kindIdx === 1) { planned = planEventsQuery( @@ -425,8 +992,8 @@ describe('mandatory Vault & PIT invariants + TZ invariance', () => { expect(planned.sql).toContain('e.ts <= ?'); const boundTo = planned.params[planned.params.length - 2] as string; const boundAsOf = planned.params[planned.params.length - 1] as string; - expect(Date.parse(boundTo)).toBeLessThan(CUTOFF_MS); - expect(Date.parse(boundAsOf)).toBeLessThan(CUTOFF_MS); + expect(parseIsoToMicros(boundTo)).toBeLessThan(CUTOFF_MICROS); + expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS); } else if (kindIdx === 2) { planned = planShortsAsOfQuery( { @@ -442,7 +1009,7 @@ describe('mandatory Vault & PIT invariants + TZ invariance', () => { const boundToDate = planned.params[planned.params.length - 2] as string; const boundAsOf = planned.params[planned.params.length - 1] as string; expect(Date.parse(`${boundToDate}T00:00:00.000Z`)).toBeLessThan(CUTOFF_MS); - expect(Date.parse(boundAsOf)).toBeLessThan(CUTOFF_MS); + expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS); } else { planned = planFx1dQuery( { @@ -457,8 +1024,8 @@ describe('mandatory Vault & PIT invariants + TZ invariance', () => { expect(planned.sql).toContain('f.ts <= ?'); const boundTo = planned.params[planned.params.length - 2] as string; const boundAsOf = planned.params[planned.params.length - 1] as string; - expect(Date.parse(boundTo)).toBeLessThan(CUTOFF_MS); - expect(Date.parse(boundAsOf)).toBeLessThan(CUTOFF_MS); + expect(parseIsoToMicros(boundTo)).toBeLessThan(CUTOFF_MICROS); + expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS); } expect(planned.fenced.toMs).toBeLessThan(CUTOFF_MS); expect(planned.fenced.asOfMs).toBeLessThan(CUTOFF_MS); @@ -467,6 +1034,8 @@ describe('mandatory Vault & PIT invariants + TZ invariance', () => { it('produces identical SQL and bound params under TZ=UTC and TZ=America/Toronto', () => { const previousTz = process.env.TZ; + const asOfMicros = Date.UTC(2025, 10, 3, 6, 30, 0) * 1000; // 2025-11-03T01:30:00-05:00 + const snapshot = makeFencedSnapshot({ asOfMicros, vaultCutoffMicros: CUTOFF_MICROS }); try { const runAll = () => ({ bars: planBars1dQuery( @@ -478,7 +1047,7 @@ describe('mandatory Vault & PIT invariants + TZ invariance', () => { adjustment: 'total', asOf: '2025-11-03T01:30:00-05:00', }, - DEFAULT_CTX + { ...DEFAULT_CTX, adjFactorsSnapshot: snapshot } ), events: planEventsQuery( { @@ -524,7 +1093,7 @@ describe('mandatory Vault & PIT invariants + TZ invariance', () => { }); describe('Vault fence enforcement with zero executor calls', () => { - it('throws VaultHoldoutFenceError when from >= vaultCutoffTs across all 4 endpoints with 0 executor calls', async () => { + it('throws VaultHoldoutFenceError when from >= vaultCutoffTs across all 4 endpoints (incl. split bars) with 0 executor calls', async () => { const fake = createRecordingExecutor(); const store = createDuckDbMarketDataStore({ executor: fake.executor, @@ -544,6 +1113,18 @@ describe('Vault fence enforcement with zero executor calls', () => { ) ).rejects.toThrow(VaultHoldoutFenceError); + await expect( + collectBars( + store.bars({ + listingIds: [1], + timeframe: '1d', + from: '2026-05-28', + to: '2026-06-01', + adjustment: 'split', + }) + ) + ).rejects.toThrow(VaultHoldoutFenceError); + await expect( store.events({ kinds: ['filing'], @@ -587,7 +1168,7 @@ describe('Vault fence enforcement with zero executor calls', () => { timeframe: '1d', from: '2026-06-01', to: '2026-07-01', - adjustment: 'raw', + adjustment: 'split', scope: 'vault_evaluation_only', }) ) @@ -618,8 +1199,8 @@ describe('Vault fence enforcement with zero executor calls', () => { expect(planned.params).toEqual([ 1, '2026-06-01T00:00:00.000Z', - '2026-07-01T23:59:59.999Z', - '2026-07-01T23:59:59.999Z', + '2026-07-01T23:59:59.999999Z', + '2026-07-01T23:59:59.999999Z', ]); }); @@ -783,8 +1364,10 @@ describe('SQL injection & strict boundary validation', () => { expect(fake.calls).toHaveLength(0); }); - it('never embeds caller-supplied values other than validated curatedRoot in SQL text', () => { + it('never embeds caller-supplied values other than validated curatedRoot/adjPath in SQL text', () => { const sentinelId = 987654321; + const asOfMicros = Date.UTC(2025, 9, 5, 15, 45, 0) * 1000; + const snapshot = makeFencedSnapshot({ asOfMicros, vaultCutoffMicros: CUTOFF_MICROS }); const barsPlan = planBars1dQuery( { listingIds: [sentinelId], @@ -794,7 +1377,7 @@ describe('SQL injection & strict boundary validation', () => { adjustment: 'total', asOf: '2025-10-05T15:45:00Z', }, - DEFAULT_CTX + { ...DEFAULT_CTX, adjFactorsSnapshot: snapshot } ); expect(barsPlan.sql).not.toContain(String(sentinelId)); expect(barsPlan.sql).not.toContain('2024-03-14'); @@ -849,6 +1432,15 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { }) ).toThrow(MarketDataStoreValidationError); + expect(() => + createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + adjFactorsPath: "/evil'; DROP TABLE x;.parquet", + }) + ).toThrow(MarketDataStoreValidationError); + expect(() => createDuckDbMarketDataStore({ executor: fake.executor, @@ -1114,7 +1706,7 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { known_at: 1_737_500_000_000, shares_short: 125_000, net_change: null, - pct_float: 0.045, + pct_float: null, source: 'ceo_shorts', }, ]; @@ -1123,13 +1715,13 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { { pair: 'USDCAD', session_date: '2025-01-15', - ts: 1_736_985_600_000, + ts: 1_736_985_599_999, open: 1.43, high: 1.44, low: 1.425, close: 1.435, source: 'eod_cad_forex', - known_at: 1_736_985_600_000, + known_at: 1_736_985_599_999, }, ]; }, @@ -1167,6 +1759,7 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { }); expect(shorts.columns).toEqual([...SHORTS_COLUMNS]); expect(shorts.rows[0]!.net_change).toBeNull(); + expect(shorts.rows[0]!.pct_float).toBeNull(); const fx = await store.fx({ pair: 'USD.CAD', @@ -1178,6 +1771,82 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { expect(fx.rows[0]!.pair).toBe('USDCAD'); }); + it('validates per-column scalar types and nullability even when all expected columns are present', async () => { + const cases: Array<{ + label: string; + row: TableRow; + run: (store: ReturnType) => Promise; + }> = [ + { + label: 'fx stringified ts', + row: { + pair: 'USDCAD', + session_date: '2025-01-15', + ts: '2025-01-15T23:59:59.999999Z', // wrong scalar type (string instead of safe_int) + open: 1.43, + high: 1.44, + low: 1.425, + close: 1.435, + source: 'eod_cad_forex', + known_at: 1_736_985_599_999, + }, + run: (s) => s.fx({ pair: 'USD.CAD', timeframe: '1d', from: '2025-01-15', to: '2025-01-15' }), + }, + { + label: 'fx null close', + row: { + pair: 'USDCAD', + session_date: '2025-01-15', + ts: 1_736_985_599_999, + open: 1.43, + high: 1.44, + low: 1.425, + close: null, // forbidden null + source: 'eod_cad_forex', + known_at: 1_736_985_599_999, + }, + run: (s) => s.fx({ pair: 'USD.CAD', timeframe: '1d', from: '2025-01-15', to: '2025-01-15' }), + }, + { + label: 'events stringified listing_id', + row: { + listing_id: '10', // wrong scalar type (string instead of int32) + ts: 1_700_000_000_000, + known_at: 1_700_000_000_000, + known_at_source: 'filing_timestamp', + kind: 'filing', + subtype: '10-k', + payload_json: '{}', + }, + run: (s) => s.events({ kinds: ['filing'], from: '2023-01-01', to: '2025-02-01' }), + }, + { + label: 'shorts null required shares_short', + row: { + listing_id: 10, + report_date: '2025-01-15', + known_at: 1_737_500_000_000, + shares_short: null, // forbidden null + net_change: null, + pct_float: null, + source: 'ceo_shorts', + }, + run: (s) => s.shortsAsOf({ listingIds: [10], from: '2025-01-01', to: '2025-02-01' }), + }, + ]; + + for (const c of cases) { + const fake = createRecordingExecutor({ onQuery: () => [c.row] }); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + await expect(c.run(store)).rejects.toThrow(MarketDataStoreValidationError); + } + }); + it('rejects malformed driver rows with MarketDataStoreValidationError and propagates executor errors', async () => { const malformedFake = createRecordingExecutor({ onQuery: (sql) => { @@ -1269,7 +1938,7 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { timeframe: '5m', from: '2025-01-01', to: '2025-02-01', - adjustment: 'raw', + adjustment: 'split', }) ), }, @@ -1282,7 +1951,7 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { timeframe: '1h', from: '2025-01-01', to: '2025-02-01', - adjustment: 'raw', + adjustment: 'total', }) ), },