From 57b398694fdcec209c1321d5f0310be13f63a5dc Mon Sep 17 00:00:00 2001 From: Studio Date: Sun, 29 Nov 2026 07:22:40 -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 | 35 + libs/research/package.json | 1 + .../benchmark-market-data-store-duckdb.ts | 172 +++ libs/research/src/index.ts | 1 + libs/research/src/market-data-store-duckdb.ts | 851 +++++++++++ .../test/market-data-store-duckdb.test.ts | 1346 +++++++++++++++++ 6 files changed, 2406 insertions(+) create mode 100644 libs/research/scripts/benchmark-market-data-store-duckdb.ts create mode 100644 libs/research/src/market-data-store-duckdb.ts create mode 100644 libs/research/test/market-data-store-duckdb.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index 8f0d6452..a263252c 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -74,3 +74,38 @@ Fixed-seed (`20260402`) end-to-end `analyzeSignal` benchmark covering `5,040` bu - **Command:** `bun run libs/research/scripts/benchmark-signal-study.ts` - **Observed (Bun 1.2.16):** `elapsedMs = 1691.13 ms`, `rowsPerSec = 8,940,793 rows/s` (`2,980 dates/s`, `nObs = 5040`, `meanRankIc = 0.057294`, `recencyGatePassed = true`) + +## DuckDB Curated Parquet Query Planner & `MarketDataStore` Adapter + +Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-store-duckdb` (`libs/research/src/market-data-store-duckdb.ts`). The module is dependency-free and browser-safe; DuckDB execution is injected via `DuckDbExecutor` (`{ run(sql), query(sql, params) }`) so parameter values are always bound separately from SQL text. + +### 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. + +### Mandatory Vault, PIT & 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 (`*`, `?`, `[`, `]`). +- 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` 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`): + +- **`'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. + +### 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: + +- **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`) diff --git a/libs/research/package.json b/libs/research/package.json index dd8dd698..9c2f57a9 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -11,6 +11,7 @@ "./dataset-contracts": "./src/dataset-contracts.ts", "./datasets": "./src/datasets.ts", "./market-data-store": "./src/market-data-store.ts", + "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", "./results": "./src/results.ts", "./signal-study": "./src/signal-study.ts", "./strategy-api": "./src/strategy-api.ts", diff --git a/libs/research/scripts/benchmark-market-data-store-duckdb.ts b/libs/research/scripts/benchmark-market-data-store-duckdb.ts new file mode 100644 index 00000000..c3f60ae5 --- /dev/null +++ b/libs/research/scripts/benchmark-market-data-store-duckdb.ts @@ -0,0 +1,172 @@ +import { + BARS_ADJUSTMENTS, + type BarsQuery, + type DuckDbPlanContext, + EVENT_KINDS, + type EventsQuery, + type FxQuery, + type PlannedDuckDbQuery, + type ShortsAsOfQuery, + planBars1dQuery, + planEventsQuery, + planFx1dQuery, + planShortsAsOfQuery, +} from '../src/market-data-store-duckdb'; + +const SEED = 20261129; +const QUERY_COUNT = 120_000; +const CURATED_ROOT = '/mnt/data/stockbot/curated'; +const VAULT_CUTOFF_TS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); + +const CTX: DuckDbPlanContext = { + curatedRoot: CURATED_ROOT, + vaultCutoffTs: VAULT_CUTOFF_TS, +}; + +function createMulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +type WorkloadItem = + | { readonly kind: 'bars'; readonly q: BarsQuery } + | { readonly kind: 'events'; readonly q: EventsQuery } + | { readonly kind: 'shorts'; readonly q: ShortsAsOfQuery } + | { readonly kind: 'fx'; readonly q: FxQuery }; + +const rng = createMulberry32(SEED); +const startBaseMs = Date.UTC(2016, 0, 1, 0, 0, 0, 0); +const preCutoffSpanMs = VAULT_CUTOFF_TS - startBaseMs - 86_400_000; +const postCutoffSpanMs = 180 * 86_400_000; + +function randomDateOrIso(epochMs: number): string { + const iso = new Date(epochMs).toISOString(); + return rng() < 0.5 ? iso.slice(0, 10) : iso; +} + +function randomListingIds(): number[] { + const count = 1 + Math.floor(rng() * 4); + const ids: number[] = new Array(count); + for (let i = 0; i < count; i += 1) { + ids[i] = 1 + Math.floor(rng() * 50_000); + } + return ids; +} + +const workload: WorkloadItem[] = new Array(QUERY_COUNT); +for (let i = 0; i < QUERY_COUNT; i += 1) { + const fromMs = startBaseMs + Math.floor(rng() * preCutoffSpanMs); + const toMs = fromMs + Math.floor(rng() * (VAULT_CUTOFF_TS - fromMs + postCutoffSpanMs)); + const asOfMs = + rng() < 0.35 + ? undefined + : startBaseMs + Math.floor(rng() * (VAULT_CUTOFF_TS - startBaseMs + postCutoffSpanMs)); + + const from = randomDateOrIso(fromMs); + const to = randomDateOrIso(toMs); + const asOf = asOfMs === undefined ? undefined : randomDateOrIso(asOfMs); + + const slot = i % 7; + if (slot < 3) { + const adjustment = BARS_ADJUSTMENTS[slot] ?? 'raw'; + workload[i] = { + kind: 'bars', + q: { + listingIds: randomListingIds(), + timeframe: '1d', + from, + to, + adjustment, + asOf, + }, + }; + } else if (slot === 3 || slot === 4) { + const kindA = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'filing'; + const kindB = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'earnings'; + workload[i] = { + kind: 'events', + q: { + kinds: slot === 3 ? [kindA] : [kindA, kindB], + listingIds: slot === 3 ? randomListingIds() : undefined, + from, + to, + asOf, + }, + }; + } else if (slot === 5) { + workload[i] = { + kind: 'shorts', + q: { + listingIds: randomListingIds(), + from, + to, + asOf, + }, + }; + } else { + workload[i] = { + kind: 'fx', + q: { + pair: 'USD.CAD', + timeframe: '1d', + from, + to, + }, + }; + } +} + +function mixFnv1a(hash: number, value: number): number { + let h = (hash ^ (value >>> 0)) >>> 0; + h = Math.imul(h, 0x01000193) >>> 0; + return h; +} + +let checksum = 0x811c9dc5; +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; + } + 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)); + +console.log( + JSON.stringify( + { + seed: SEED, + queries: QUERY_COUNT, + totalParams, + elapsedMs: Number(elapsedMs.toFixed(2)), + queriesPerSec, + checksum: checksum.toString(16).padStart(8, '0'), + }, + null, + 2 + ) +); diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index fd3691a2..927bd71e 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -1,5 +1,6 @@ // The default entrypoint is browser safe; server validation is an explicit subpath. export * from './dataset-contracts'; export * from './market-data-store'; +export * from './market-data-store-duckdb'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/market-data-store-duckdb.ts b/libs/research/src/market-data-store-duckdb.ts new file mode 100644 index 00000000..1a676746 --- /dev/null +++ b/libs/research/src/market-data-store-duckdb.ts @@ -0,0 +1,851 @@ +/** + * Pure, dependency-free DuckDB SQL query planner and injected-executor + * `MarketDataStore` adapter for curated daily Parquet datasets + * (`design/DATA-CONTRACTS.md` §3.A & §4). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero DuckDB driver + * dependency, zero bare `process` access. SQL execution is injected via + * {@link DuckDbExecutor}, mirroring `TrialLedgerExecutor` in `./trial-ledger`. + * + * Curated Parquet layout under `curatedRoot` (`design/DATA-CONTRACTS.md` §3.A): + * - `/bars_1d/year=*\/part.parquet` (`hive_partitioning = true`) + * - `/adj_factors/part.parquet` + * - `/events/year=*\/part.parquet` (`hive_partitioning = true`) + * - `/shorts/part.parquet` + * - `/fx_1d/part.parquet` + * + * `bars` (`timeframe: '1d'`) adjustment formulas (`tools/curate-etl/README.md`): + * - `bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share + * `volume`. + * - `adj_factors` stores per-`(listing_id, ex_date)` cumulative back-adjustment + * 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`): + * - `'split'`: + * - `price_adj = price_raw / COALESCE(a.cum_split_factor, 1.0)` for + * `open`, `high`, `low`, `close`, and `vwap` (preserving `NULL` `vwap`). + * - `volume_adj = volume_raw * COALESCE(a.cum_split_factor, 1.0)`. + * - `'total'`: + * - `price_adj = price_raw / COALESCE(a.cum_total_factor, 1.0)` for + * `open`, `high`, `low`, `close`, and `vwap` (preserving `NULL` `vwap`). + * - `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. + */ + +import { + type BarBatch, + type BarRecord, + type EventKind, + type FencedTimeRange, + type MarketDataStore, + MarketDataStoreValidationError, + type Table, + type TableCell, + type TableRow, + applyVaultFence, + resolveDuckDbConnectionBudget, +} from './market-data-store'; + +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; + +export const EVENT_KINDS = ['filing', 'earnings', 'ceo_post', 'corporate_action'] as const; +const EVENT_KIND_SET: ReadonlySet = new Set(EVENT_KINDS); + +export const FX_PAIR_MAP = { + 'USD.CAD': 'USDCAD', +} as const; + +export const BARS_ADJUSTMENTS = ['raw', 'split', 'total'] as const; +const BARS_ADJUSTMENT_SET: ReadonlySet = new Set(BARS_ADJUSTMENTS); + +export const EVENTS_COLUMNS = [ + 'listing_id', + 'ts', + 'known_at', + 'known_at_source', + 'kind', + 'subtype', + 'payload_json', +] as const; + +export const SHORTS_COLUMNS = [ + 'listing_id', + 'report_date', + 'known_at', + 'shares_short', + 'net_change', + 'pct_float', + 'source', +] as const; + +export const FX_1D_COLUMNS = [ + 'pair', + 'session_date', + 'ts', + 'open', + 'high', + 'low', + 'close', + 'source', + 'known_at', +] as const; + +/** Scalar parameter value bound separately from SQL text. */ +export type DuckDbParam = string | number | boolean | null; + +/** + * Injected DuckDB SQL executor interface. Parameter values are always passed + * separately from SQL text via `params`. + */ +export interface DuckDbExecutor { + run(sql: string): Promise; + query(sql: string, params: readonly DuckDbParam[]): Promise; +} + +/** Pure output of a DuckDB query planner. */ +export interface PlannedDuckDbQuery { + readonly sql: string; + readonly params: readonly DuckDbParam[]; + readonly fenced: FencedTimeRange; +} + +/** Context required to plan fenced DuckDB queries against curated Parquet. */ +export interface DuckDbPlanContext { + readonly curatedRoot: string; + readonly vaultCutoffTs: number; + readonly vaultOperatorAuthorized?: boolean; +} + +/** Configuration for {@link createDuckDbMarketDataStore}. */ +export interface DuckDbMarketDataStoreOptions extends DuckDbPlanContext { + readonly executor: DuckDbExecutor; + readonly env?: Readonly>; + readonly barBatchSize?: number; +} + +export type BarsQuery = Parameters[0]; +export type EventsQuery = Parameters[0]; +export type ShortsAsOfQuery = Parameters[0]; +export type FxQuery = Parameters[0]; + +/** + * Thrown when a `MarketDataStore` method or timeframe is outside the curated + * daily DuckDB Parquet adapter slice. + */ +export class MarketDataStoreNotImplementedError extends Error { + override readonly name = 'MarketDataStoreNotImplementedError'; + readonly method: keyof MarketDataStore; + readonly detail?: string; + + constructor(method: keyof MarketDataStore, detail?: string) { + super( + detail !== undefined + ? `MarketDataStore.${method} is not implemented by the DuckDB daily Parquet adapter: ${detail}` + : `MarketDataStore.${method} is not implemented by the DuckDB daily Parquet adapter.` + ); + this.method = method; + this.detail = detail; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +function isPlainRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function hasForbiddenCuratedRootChar(value: string): boolean { + for (let i = 0; i < value.length; i += 1) { + const code = value.charCodeAt(i); + // Reject ASCII control chars (0x00..0x1f, 0x7f), SQL quote/separator (', ;), + // and DuckDB read_parquet glob metacharacters (*, ?, [, ]). + if ( + code <= 0x1f || + code === 0x7f || + code === 0x27 || + code === 0x3b || + code === 0x2a || + code === 0x3f || + code === 0x5b || + code === 0x5d + ) { + return true; + } + } + return false; +} + +/** + * Strictly validates `curatedRoot` as an absolute POSIX path with no control + * characters, single quotes, semicolons, or glob metacharacters, normalizing + * trailing slashes (except `'/'`). + */ +export function validateCuratedRoot(raw: string): string { + if ( + typeof raw !== 'string' || + raw.length === 0 || + !raw.startsWith('/') || + hasForbiddenCuratedRootChar(raw) + ) { + throw new MarketDataStoreValidationError( + `Invalid curatedRoot "${String(raw)}". Expected a non-empty absolute POSIX path without quotes, semicolons, control characters, or glob characters (*, ?, [, ]).`, + 'curatedRoot' + ); + } + + let end = raw.length; + while (end > 1 && raw.charCodeAt(end - 1) === 0x2f) { + end -= 1; + } + return end === raw.length ? raw : raw.slice(0, end); +} + +function joinCuratedPath(normalizedRoot: string, relativePath: string): string { + return normalizedRoot === '/' ? `/${relativePath}` : `${normalizedRoot}/${relativePath}`; +} + +function validateListingIds(raw: readonly number[], field = 'listingIds'): number[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + `Expected a non-empty array of INT32 listing IDs for "${field}".`, + field + ); + } + + if (raw.length === 1) { + const id = raw[0]; + if ( + typeof id !== 'number' || + !Number.isSafeInteger(id) || + id < INT32_MIN || + id > INT32_MAX + ) { + throw new MarketDataStoreValidationError( + `Invalid INT32 listing ID at ${field}[0]: ${String(id)}.`, + field + ); + } + return [id === 0 ? 0 : id]; + } + + const seen = new Set(); + const normalized: number[] = []; + for (let i = 0; i < raw.length; i += 1) { + const id = raw[i]; + if ( + typeof id !== 'number' || + !Number.isSafeInteger(id) || + id < INT32_MIN || + id > INT32_MAX + ) { + throw new MarketDataStoreValidationError( + `Invalid INT32 listing ID at ${field}[${i}]: ${String(id)}.`, + field + ); + } + const clean = id === 0 ? 0 : id; + if (!seen.has(clean)) { + seen.add(clean); + normalized.push(clean); + } + } + return normalized; +} + +function validateEventKinds(raw: readonly EventKind[], field = 'kinds'): EventKind[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + `Expected a non-empty array of EventKind values for "${field}".`, + field + ); + } + + if (raw.length === 1) { + const kind = raw[0]; + if (typeof kind !== 'string' || !EVENT_KIND_SET.has(kind)) { + throw new MarketDataStoreValidationError( + `Unknown EventKind "${String(kind)}". Expected one of: ${EVENT_KINDS.join(', ')}.`, + field + ); + } + return [kind as EventKind]; + } + + const seen = new Set(); + const normalized: EventKind[] = []; + for (let i = 0; i < raw.length; i += 1) { + const kind = raw[i]; + if (typeof kind !== 'string' || !EVENT_KIND_SET.has(kind)) { + throw new MarketDataStoreValidationError( + `Unknown EventKind "${String(kind)}". Expected one of: ${EVENT_KINDS.join(', ')}.`, + field + ); + } + if (!seen.has(kind)) { + seen.add(kind); + normalized.push(kind as EventKind); + } + } + return normalized; +} + +function validateAdjustment(raw: unknown): (typeof BARS_ADJUSTMENTS)[number] { + if (typeof raw !== 'string' || !BARS_ADJUSTMENT_SET.has(raw)) { + throw new MarketDataStoreValidationError( + `Invalid adjustment "${String(raw)}". Expected one of: ${BARS_ADJUSTMENTS.join(', ')}.`, + 'adjustment' + ); + } + return raw as (typeof BARS_ADJUSTMENTS)[number]; +} + +function validateFxPair(raw: unknown): (typeof FX_PAIR_MAP)[keyof typeof FX_PAIR_MAP] { + if (typeof raw === 'string' && Object.prototype.hasOwnProperty.call(FX_PAIR_MAP, raw)) { + return FX_PAIR_MAP[raw as keyof typeof FX_PAIR_MAP]; + } + throw new MarketDataStoreValidationError( + `Unsupported FX pair "${String(raw)}". Expected 'USD.CAD'.`, + 'pair' + ); +} + +function validateContext(ctx: DuckDbPlanContext): string { + if (!isPlainRecord(ctx)) { + throw new MarketDataStoreValidationError('Expected a DuckDbPlanContext object.', 'context'); + } + return validateCuratedRoot(ctx.curatedRoot); +} + +function buildPlaceholders(count: number): string { + if (count === 1) { + return '?'; + } + if (count === 2) { + return '?, ?'; + } + if (count === 3) { + return '?, ?, ?'; + } + let out = '?'; + for (let i = 1; i < count; i += 1) { + out += ', ?'; + } + return out; +} + +function formatUtcIso(epochMs: number): string { + return new Date(epochMs).toISOString(); +} + +function formatUtcDate(epochMs: number): string { + return new Date(epochMs).toISOString().slice(0, 10); +} + +/** + * 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. + */ +export function planBars1dQuery(q: BarsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { + const curatedRoot = validateContext(ctx); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); + } + + const timeframe: unknown = q.timeframe; + if (timeframe === '1m' || timeframe === '5m' || timeframe === '1h') { + throw new MarketDataStoreNotImplementedError( + 'bars', + `Timeframe '${timeframe}' is outside the daily Parquet slice.` + ); + } + if (timeframe !== '1d') { + throw new MarketDataStoreValidationError( + `Invalid bars timeframe "${String(timeframe)}". Expected '1d'.`, + 'timeframe' + ); + } + + const adjustment = validateAdjustment(q.adjustment); + const listingIds = validateListingIds(q.listingIds); + const fenced = applyVaultFence( + { + from: q.from, + to: q.to, + asOf: q.asOf, + scope: q.scope, + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + vaultOperatorAuthorized: ctx.vaultOperatorAuthorized, + } + ); + + const fromIso = formatUtcIso(fenced.fromMs); + const toIso = formatUtcIso(fenced.toMs); + const asOfIso = formatUtcIso(fenced.asOfMs); + const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet'); + const listingPlaceholders = buildPlaceholders(listingIds.length); + + if (adjustment === 'raw') { + const sql = + 'SELECT b.listing_id, epoch_ms(b.ts) AS ts, b.open, b.high, b.low, b.close, b.volume, b.vwap, epoch_ms(b.known_at) AS known_at ' + + `FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` + + `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'; + const params: DuckDbParam[] = [...listingIds, fromIso, toIso, asOfIso]; + return { sql, params, fenced }; + } + + const adjPath = joinCuratedPath(curatedRoot, 'adj_factors/part.parquet'); + const priceDivisor = + adjustment === 'split' + ? 'COALESCE(a.cum_split_factor, 1.0)' + : 'COALESCE(a.cum_total_factor, 1.0)'; + const adjSelectCols = + adjustment === 'split' + ? 'listing_id, ex_date, cum_split_factor' + : 'listing_id, ex_date, cum_split_factor, cum_total_factor'; + + const sql = + 'SELECT b.listing_id, epoch_ms(b.ts) AS ts, ' + + `b.open / ${priceDivisor} AS open, ` + + `b.high / ${priceDivisor} AS high, ` + + `b.low / ${priceDivisor} AS low, ` + + `b.close / ${priceDivisor} AS close, ` + + 'b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume, ' + + `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 ` + + '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'; + + const params: DuckDbParam[] = [...listingIds, asOfIso, ...listingIds, fromIso, toIso, asOfIso]; + return { sql, params, fenced }; +} + +/** + * Plans a fenced DuckDB SQL query for point-in-time curated events (`events`). + */ +export function planEventsQuery(q: EventsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { + const curatedRoot = validateContext(ctx); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected an events query object.', 'query'); + } + + const kinds = validateEventKinds(q.kinds); + const listingIds = + q.listingIds !== undefined ? validateListingIds(q.listingIds) : undefined; + const fenced = applyVaultFence( + { + from: q.from, + to: q.to, + asOf: q.asOf, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + } + ); + + const fromIso = formatUtcIso(fenced.fromMs); + const toIso = formatUtcIso(fenced.toMs); + const asOfIso = formatUtcIso(fenced.asOfMs); + const eventsPath = joinCuratedPath(curatedRoot, 'events/year=*/part.parquet'); + const kindPlaceholders = buildPlaceholders(kinds.length); + + if (listingIds !== undefined) { + const listingPlaceholders = buildPlaceholders(listingIds.length); + const sql = + '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'; + const params: DuckDbParam[] = [...kinds, ...listingIds, fromIso, toIso, asOfIso]; + return { sql, params, fenced }; + } + + const sql = + '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'; + const params: DuckDbParam[] = [...kinds, fromIso, toIso, asOfIso]; + return { sql, params, fenced }; +} + +/** + * Plans a fenced DuckDB SQL query for point-in-time curated short interest (`shorts`). + */ +export function planShortsAsOfQuery( + q: ShortsAsOfQuery, + ctx: DuckDbPlanContext +): PlannedDuckDbQuery { + const curatedRoot = validateContext(ctx); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a shortsAsOf query object.', 'query'); + } + + const listingIds = validateListingIds(q.listingIds); + const fenced = applyVaultFence( + { + from: q.from, + to: q.to, + asOf: q.asOf, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + } + ); + + const fromDate = formatUtcDate(fenced.fromMs); + const toDate = formatUtcDate(fenced.toMs); + const asOfIso = formatUtcIso(fenced.asOfMs); + const shortsPath = joinCuratedPath(curatedRoot, 'shorts/part.parquet'); + const listingPlaceholders = buildPlaceholders(listingIds.length); + + const sql = + 'SELECT s.listing_id, CAST(s.report_date AS VARCHAR) AS report_date, epoch_ms(s.known_at) AS known_at, s.shares_short, s.net_change, s.pct_float, s.source ' + + `FROM read_parquet('${shortsPath}') AS s ` + + `WHERE s.listing_id IN (${listingPlaceholders}) AND s.report_date >= ? AND s.report_date <= ? AND s.known_at <= ? ` + + 'ORDER BY s.listing_id ASC, s.report_date ASC'; + const params: DuckDbParam[] = [...listingIds, fromDate, toDate, asOfIso]; + return { sql, params, fenced }; +} + +/** + * 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`. + */ +export function planFx1dQuery(q: FxQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { + const curatedRoot = validateContext(ctx); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected an fx query object.', 'query'); + } + + const timeframe: unknown = q.timeframe; + if (timeframe === '1m') { + throw new MarketDataStoreNotImplementedError( + 'fx', + "Timeframe '1m' is outside the daily Parquet slice." + ); + } + if (timeframe !== '1d') { + throw new MarketDataStoreValidationError( + `Invalid fx timeframe "${String(timeframe)}". Expected '1d'.`, + 'timeframe' + ); + } + + const storedPair = validateFxPair(q.pair); + const fenced = applyVaultFence( + { + from: q.from, + to: q.to, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + } + ); + + const fromIso = formatUtcIso(fenced.fromMs); + const toIso = formatUtcIso(fenced.toMs); + const asOfIso = formatUtcIso(fenced.asOfMs); + const fxPath = joinCuratedPath(curatedRoot, 'fx_1d/part.parquet'); + + const sql = + 'SELECT f.pair, CAST(f.session_date AS VARCHAR) AS session_date, epoch_ms(f.ts) AS ts, f.open, f.high, f.low, f.close, f.source, epoch_ms(f.known_at) AS known_at ' + + `FROM read_parquet('${fxPath}') AS f ` + + 'WHERE f.pair = ? AND f.ts >= ? AND f.ts <= ? AND f.known_at <= ? ' + + 'ORDER BY f.session_date ASC'; + const params: DuckDbParam[] = [storedPair, fromIso, toIso, asOfIso]; + return { sql, params, fenced }; +} + +function readRequiredInt32(row: Record, key: string, rowIndex: number): number { + const val = row[key]; + if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) { + throw new MarketDataStoreValidationError( + `Invalid INT32 column "${key}" in result row ${rowIndex}: ${String(val)}.`, + key + ); + } + return val === 0 ? 0 : val; +} + +function readRequiredSafeInt(row: Record, key: string, rowIndex: number): number { + const val = row[key]; + if (typeof val !== 'number' || !Number.isSafeInteger(val)) { + throw new MarketDataStoreValidationError( + `Invalid integer timestamp column "${key}" in result row ${rowIndex}: ${String(val)}.`, + key + ); + } + return val === 0 ? 0 : val; +} + +function readRequiredFiniteNumber( + row: Record, + key: string, + rowIndex: number +): number { + const val = row[key]; + if (typeof val !== 'number' || !Number.isFinite(val)) { + throw new MarketDataStoreValidationError( + `Invalid numeric column "${key}" in result row ${rowIndex}: ${String(val)}.`, + key + ); + } + return val === 0 ? 0 : val; +} + +function readNullableFiniteNumber( + row: Record, + key: string, + rowIndex: number +): number | null { + const val = row[key]; + if (val === null || val === undefined) { + return null; + } + if (typeof val !== 'number' || !Number.isFinite(val)) { + throw new MarketDataStoreValidationError( + `Invalid nullable numeric column "${key}" in result row ${rowIndex}: ${String(val)}.`, + key + ); + } + return val === 0 ? 0 : val; +} + +function mapBarRows(rows: readonly TableRow[]): BarRecord[] { + if (!Array.isArray(rows)) { + throw new MarketDataStoreValidationError('Executor returned a non-array bars result.', 'rows'); + } + const out: BarRecord[] = new Array(rows.length); + for (let i = 0; i < rows.length; i += 1) { + const raw = rows[i]; + if (!isPlainRecord(raw)) { + throw new MarketDataStoreValidationError( + `Executor returned a non-object bar row at index ${i}.`, + 'rows' + ); + } + out[i] = { + listingId: readRequiredInt32(raw, 'listing_id', i), + ts: readRequiredSafeInt(raw, 'ts', i), + open: readRequiredFiniteNumber(raw, 'open', i), + high: readRequiredFiniteNumber(raw, 'high', i), + low: readRequiredFiniteNumber(raw, 'low', i), + close: readRequiredFiniteNumber(raw, 'close', i), + volume: readRequiredFiniteNumber(raw, 'volume', i), + vwap: readNullableFiniteNumber(raw, 'vwap', i), + knownAt: readRequiredSafeInt(raw, 'known_at', i), + }; + } + return out; +} + +function isValidTableCell(value: unknown): value is TableCell { + if (value === null || typeof value === 'string' || typeof value === 'boolean') { + return true; + } + return typeof value === 'number' && Number.isFinite(value); +} + +function mapTableRows(columns: readonly string[], rows: readonly TableRow[]): Table { + if (!Array.isArray(rows)) { + throw new MarketDataStoreValidationError('Executor returned a non-array table result.', 'rows'); + } + const mappedRows: TableRow[] = new Array(rows.length); + for (let i = 0; i < rows.length; i += 1) { + const raw = rows[i]; + if (!isPlainRecord(raw)) { + throw new MarketDataStoreValidationError( + `Executor returned a non-object table row at index ${i}.`, + 'rows' + ); + } + const cleanRow: Record = {}; + for (const col of columns) { + if (!Object.prototype.hasOwnProperty.call(raw, col)) { + throw new MarketDataStoreValidationError( + `Missing expected column "${col}" in result row ${i}.`, + col + ); + } + 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; + } + mappedRows[i] = cleanRow; + } + return { + columns: [...columns], + rows: mappedRows, + }; +} + +/** + * Creates a `MarketDataStore` backed by an injected {@link DuckDbExecutor} + * 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. + */ +export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOptions): MarketDataStore { + if (!isPlainRecord(options)) { + throw new MarketDataStoreValidationError( + 'Expected a DuckDbMarketDataStoreOptions object.', + 'options' + ); + } + + const executor: unknown = options.executor; + if ( + !isPlainRecord(executor) || + typeof executor.run !== 'function' || + typeof executor.query !== 'function' + ) { + throw new MarketDataStoreValidationError( + 'Expected `executor` with `run(sql)` and `query(sql, params)` methods.', + 'executor' + ); + } + const typedExecutor = executor as unknown as DuckDbExecutor; + + const curatedRoot = validateCuratedRoot(options.curatedRoot); + + const vaultCutoffTs = options.vaultCutoffTs; + if ( + typeof vaultCutoffTs !== 'number' || + !Number.isSafeInteger(vaultCutoffTs) || + Math.abs(vaultCutoffTs) > MAX_ECMASCRIPT_EPOCH_MS || + vaultCutoffTs <= -MAX_ECMASCRIPT_EPOCH_MS + ) { + throw new MarketDataStoreValidationError( + `Invalid epoch millisecond timestamp for "vaultCutoffTs": ${String(vaultCutoffTs)}.`, + 'vaultCutoffTs' + ); + } + + const barBatchSize = options.barBatchSize; + if ( + barBatchSize !== undefined && + (typeof barBatchSize !== 'number' || !Number.isSafeInteger(barBatchSize) || barBatchSize < 1) + ) { + throw new MarketDataStoreValidationError( + `Invalid barBatchSize "${String(barBatchSize)}". Expected a positive safe integer.`, + 'barBatchSize' + ); + } + + const budget = resolveDuckDbConnectionBudget(options.env); + const planCtx: DuckDbPlanContext = { + curatedRoot, + vaultCutoffTs: vaultCutoffTs === 0 ? 0 : vaultCutoffTs, + vaultOperatorAuthorized: options.vaultOperatorAuthorized, + }; + + let budgetInitialized = false; + let budgetInitPromise: Promise | null = null; + + function ensureBudgetInitialized(): Promise { + if (budgetInitialized) { + return Promise.resolve(); + } + if (budgetInitPromise === null) { + budgetInitPromise = (async () => { + for (const statement of budget.statements) { + await typedExecutor.run(statement); + } + budgetInitialized = true; + })().catch((err: unknown) => { + budgetInitPromise = null; + throw err; + }); + } + return budgetInitPromise; + } + + return { + async *bars(q: BarsQuery): AsyncIterable { + const planned = planBars1dQuery(q, planCtx); + await ensureBudgetInitialized(); + const rawRows = await typedExecutor.query(planned.sql, planned.params); + const mapped = mapBarRows(rawRows); + if (mapped.length === 0) { + return; + } + if (barBatchSize === undefined || mapped.length <= barBatchSize) { + yield { rows: mapped }; + return; + } + for (let offset = 0; offset < mapped.length; offset += barBatchSize) { + yield { rows: mapped.slice(offset, offset + barBatchSize) }; + } + }, + + async events(q: EventsQuery): Promise { + const planned = planEventsQuery(q, planCtx); + await ensureBudgetInitialized(); + const rawRows = await typedExecutor.query(planned.sql, planned.params); + return mapTableRows(EVENTS_COLUMNS, 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); + }, + + 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); + }, + + crossSection(): Promise
{ + return Promise.reject(new MarketDataStoreNotImplementedError('crossSection')); + }, + + fundamentalsAsOf(): Promise
{ + return Promise.reject(new MarketDataStoreNotImplementedError('fundamentalsAsOf')); + }, + + macroAsOf(): Promise
{ + return Promise.reject(new MarketDataStoreNotImplementedError('macroAsOf')); + }, + + universe(): Promise { + return Promise.reject(new MarketDataStoreNotImplementedError('universe')); + }, + }; +} diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts new file mode 100644 index 00000000..da0df47c --- /dev/null +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -0,0 +1,1346 @@ +import { describe, expect, it } from 'bun:test'; +import { + BARS_ADJUSTMENTS, + type BarBatch, + type DuckDbExecutor, + type DuckDbParam, + type DuckDbPlanContext, + EVENT_KINDS, + EVENTS_COLUMNS, + FX_1D_COLUMNS, + FX_PAIR_MAP, + MarketDataStoreNotImplementedError, + MarketDataStoreValidationError, + SHORTS_COLUMNS, + type TableRow, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, + createDuckDbMarketDataStore, + planBars1dQuery, + planEventsQuery, + planFx1dQuery, + planShortsAsOfQuery, + resolveDuckDbConnectionBudget, + validateCuratedRoot, +} from '@stock-bot/research'; +import { + BARS_ADJUSTMENTS as subpathBarsAdjustments, + EVENT_KINDS as subpathEventKinds, + EVENTS_COLUMNS as subpathEventsColumns, + FX_1D_COLUMNS as subpathFx1dColumns, + FX_PAIR_MAP as subpathFxPairMap, + MarketDataStoreNotImplementedError as SubpathNotImplementedError, + SHORTS_COLUMNS as subpathShortsColumns, + createDuckDbMarketDataStore as subpathCreateDuckDbMarketDataStore, + planBars1dQuery as subpathPlanBars1dQuery, + planEventsQuery as subpathPlanEventsQuery, + planFx1dQuery as subpathPlanFx1dQuery, + planShortsAsOfQuery as subpathPlanShortsAsOfQuery, + validateCuratedRoot as subpathValidateCuratedRoot, +} from '@stock-bot/research/market-data-store-duckdb'; + +const CURATED_ROOT = '/mnt/data/stockbot/curated'; +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 DEFAULT_CTX: DuckDbPlanContext = { + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, +}; + +interface RecordedCall { + readonly kind: 'run' | 'query'; + readonly sql: string; + readonly params?: readonly DuckDbParam[]; +} + +interface RecordingFakeExecutor { + readonly executor: DuckDbExecutor; + readonly calls: RecordedCall[]; + readonly runCalls: string[]; + readonly queryCalls: Array<{ sql: string; params: readonly DuckDbParam[] }>; +} + +function createRecordingExecutor(options?: { + onRun?: (sql: string, callIndex: number) => Promise | void; + onQuery?: ( + sql: string, + params: readonly DuckDbParam[], + callIndex: number + ) => Promise | readonly TableRow[]; +}): RecordingFakeExecutor { + const calls: RecordedCall[] = []; + const runCalls: string[] = []; + const queryCalls: Array<{ sql: string; params: readonly DuckDbParam[] }> = []; + + const executor: DuckDbExecutor = { + async run(sql: string): Promise { + const idx = runCalls.length; + calls.push({ kind: 'run', sql }); + runCalls.push(sql); + if (options?.onRun !== undefined) { + await options.onRun(sql, idx); + } + }, + async query(sql: string, params: readonly DuckDbParam[]): Promise { + const idx = queryCalls.length; + const snapshot = [...params]; + calls.push({ kind: 'query', sql, params: snapshot }); + queryCalls.push({ sql, params: snapshot }); + if (options?.onQuery !== undefined) { + return await options.onQuery(sql, snapshot, idx); + } + return []; + }, + }; + + return { executor, calls, runCalls, queryCalls }; +} + +async function collectBars(iterable: AsyncIterable): Promise { + const batches: BarBatch[] = []; + for await (const batch of iterable) { + batches.push(batch); + } + return batches; +} + +function createMulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +describe('market-data-store-duckdb exports', () => { + it('exposes identical runtime symbols from package root and subpath', () => { + expect(planBars1dQuery).toBe(subpathPlanBars1dQuery); + expect(planEventsQuery).toBe(subpathPlanEventsQuery); + expect(planShortsAsOfQuery).toBe(subpathPlanShortsAsOfQuery); + expect(planFx1dQuery).toBe(subpathPlanFx1dQuery); + expect(createDuckDbMarketDataStore).toBe(subpathCreateDuckDbMarketDataStore); + expect(validateCuratedRoot).toBe(subpathValidateCuratedRoot); + expect(MarketDataStoreNotImplementedError).toBe(SubpathNotImplementedError); + expect(EVENT_KINDS).toBe(subpathEventKinds); + expect(FX_PAIR_MAP).toBe(subpathFxPairMap); + expect(BARS_ADJUSTMENTS).toBe(subpathBarsAdjustments); + expect(EVENTS_COLUMNS).toBe(subpathEventsColumns); + expect(SHORTS_COLUMNS).toBe(subpathShortsColumns); + expect(FX_1D_COLUMNS).toBe(subpathFx1dColumns); + }); +}); + +describe('pure DuckDB query planners — exact SQL and bound parameters', () => { + it('plans bars 1d raw query with hive_partitioning, bound listingIds, and PIT/Vault predicates', () => { + const inputListingIds = [101, 202, 101, -0]; + const planned = planBars1dQuery( + { + listingIds: inputListingIds, + timeframe: '1d', + from: '2024-01-02', + to: '2025-12-31', + adjustment: 'raw', + asOf: '2026-01-15T12:00:00Z', + }, + { curatedRoot: `${CURATED_ROOT}///`, vaultCutoffTs: CUTOFF_MS } + ); + + // Caller array must not be mutated + expect(inputListingIds).toEqual([101, 202, 101, -0]); + expect(Object.is(planned.params[2], 0)).toBe(true); + + expect(planned.sql).toBe( + 'SELECT b.listing_id, epoch_ms(b.ts) AS ts, b.open, b.high, b.low, b.close, b.volume, b.vwap, epoch_ms(b.known_at) AS known_at ' + + `FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b ` + + 'WHERE b.listing_id IN (?, ?, ?) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ' + + 'ORDER BY b.listing_id ASC, b.ts ASC' + ); + expect(planned.params).toEqual([ + 101, + 202, + 0, + '2024-01-02T00:00:00.000Z', + '2025-12-31T23:59:59.999Z', + '2026-01-15T12:00:00.000Z', + ]); + expect(planned.fenced.scope).toBe('vault_fenced'); + expect(planned.fenced.clampedTo).toBe(false); + 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', () => { + const planned = planBars1dQuery( + { + listingIds: [42, 77], + timeframe: '1d', + from: '2023-01-01', + to: '2025-06-30', + adjustment: 'split', + asOf: '2025-07-01', + }, + DEFAULT_CTX + ); + + expect(planned.sql).toBe( + 'SELECT b.listing_id, epoch_ms(b.ts) AS ts, ' + + 'b.open / COALESCE(a.cum_split_factor, 1.0) AS open, ' + + 'b.high / COALESCE(a.cum_split_factor, 1.0) AS high, ' + + 'b.low / COALESCE(a.cum_split_factor, 1.0) AS low, ' + + 'b.close / COALESCE(a.cum_split_factor, 1.0) AS close, ' + + 'b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume, ' + + '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 ` + + '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' + ); + expect(planned.params).toEqual([ + 42, + 77, + '2025-07-01T23:59:59.999Z', + 42, + 77, + '2023-01-01T00:00:00.000Z', + '2025-06-30T23:59:59.999Z', + '2025-07-01T23:59:59.999Z', + ]); + }); + + it('plans bars 1d total query dividing prices by cum_total_factor and multiplying volume by cum_split_factor', () => { + const planned = planBars1dQuery( + { + listingIds: [7], + timeframe: '1d', + from: '2020-01-01', + to: '2025-01-01', + adjustment: 'total', + }, + { curatedRoot: '/', vaultCutoffTs: CUTOFF_MS } + ); + + expect(planned.sql).toBe( + 'SELECT b.listing_id, epoch_ms(b.ts) AS ts, ' + + 'b.open / COALESCE(a.cum_total_factor, 1.0) AS open, ' + + 'b.high / COALESCE(a.cum_total_factor, 1.0) AS high, ' + + 'b.low / COALESCE(a.cum_total_factor, 1.0) AS low, ' + + 'b.close / COALESCE(a.cum_total_factor, 1.0) AS close, ' + + 'b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume, ' + + 'b.vwap / COALESCE(a.cum_total_factor, 1.0) AS vwap, ' + + 'epoch_ms(b.known_at) AS known_at ' + + "FROM read_parquet('/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b " + + "ASOF LEFT JOIN (SELECT listing_id, ex_date, cum_split_factor, cum_total_factor FROM read_parquet('/adj_factors/part.parquet') 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' + ); + expect(planned.params).toEqual([ + 7, + MAX_ALLOWED_ISO, + 7, + '2020-01-01T00:00:00.000Z', + '2025-01-01T23:59:59.999Z', + MAX_ALLOWED_ISO, + ]); + }); + + it('plans events query with and without listingIds and deduplicates kinds without mutating input', () => { + const kinds: Array<'filing' | 'earnings'> = ['filing', 'earnings', 'filing']; + const withListings = planEventsQuery( + { + kinds, + listingIds: [10, 20], + from: '2025-01-01', + to: '2025-03-31', + asOf: '2025-04-01T00:00:00Z', + }, + DEFAULT_CTX + ); + + expect(kinds).toEqual(['filing', 'earnings', 'filing']); + expect(withListings.sql).toBe( + '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' + ); + expect(withListings.params).toEqual([ + 'filing', + 'earnings', + 10, + 20, + '2025-01-01T00:00:00.000Z', + '2025-03-31T23:59:59.999Z', + '2025-04-01T00:00:00.000Z', + ]); + + const withoutListings = planEventsQuery( + { + kinds: ['corporate_action'], + from: '2025-01-01', + to: '2025-03-31', + }, + DEFAULT_CTX + ); + expect(withoutListings.sql).toBe( + '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' + ); + expect(withoutListings.params).toEqual([ + 'corporate_action', + '2025-01-01T00:00:00.000Z', + '2025-03-31T23:59:59.999Z', + MAX_ALLOWED_ISO, + ]); + }); + + it('plans shortsAsOf query binding UTC YYYY-MM-DD report_date bounds and 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 + }, + DEFAULT_CTX + ); + + expect(planned.sql).toBe( + 'SELECT s.listing_id, CAST(s.report_date AS VARCHAR) AS report_date, epoch_ms(s.known_at) AS known_at, s.shares_short, s.net_change, s.pct_float, s.source ' + + `FROM read_parquet('${CURATED_ROOT}/shorts/part.parquet') AS s ` + + 'WHERE s.listing_id IN (?, ?) AND s.report_date >= ? AND s.report_date <= ? AND s.known_at <= ? ' + + 'ORDER BY s.listing_id ASC, s.report_date ASC' + ); + expect(planned.params).toEqual([ + 500, + 600, + '2024-06-01', + MAX_ALLOWED_DATE, + MAX_ALLOWED_ISO, + ]); + 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', () => { + const planned = planFx1dQuery( + { + pair: 'USD.CAD', + timeframe: '1d', + from: '2022-01-01', + to: '2026-10-01', // clamped + }, + DEFAULT_CTX + ); + + expect(planned.sql).toBe( + 'SELECT f.pair, CAST(f.session_date AS VARCHAR) AS session_date, epoch_ms(f.ts) AS ts, f.open, f.high, f.low, f.close, f.source, epoch_ms(f.known_at) AS known_at ' + + `FROM read_parquet('${CURATED_ROOT}/fx_1d/part.parquet') AS f ` + + 'WHERE f.pair = ? AND f.ts >= ? AND f.ts <= ? AND f.known_at <= ? ' + + 'ORDER BY f.session_date ASC' + ); + expect(planned.params).toEqual([ + 'USDCAD', + '2022-01-01T00:00:00.000Z', + MAX_ALLOWED_ISO, + MAX_ALLOWED_ISO, + ]); + expect(planned.fenced.scope).toBe('vault_fenced'); + expect(planned.fenced.clampedTo).toBe(true); + expect(planned.fenced.asOfMs).toBe(CUTOFF_MS - 1); + }); +}); + +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); + const baseMs = Date.UTC(2015, 0, 1, 0, 0, 0, 0); + const preCutoffSpanMs = CUTOFF_MS - baseMs - 86_400_000; + const postCutoffSpanMs = 365 * 86_400_000; + + for (let i = 0; i < 400; i += 1) { + const fromMs = baseMs + Math.floor(rng() * preCutoffSpanMs); + const toMs = fromMs + Math.floor(rng() * (CUTOFF_MS - fromMs + postCutoffSpanMs)); + const asOfMs = + rng() < 0.35 + ? undefined + : baseMs + Math.floor(rng() * (CUTOFF_MS - baseMs + postCutoffSpanMs)); + + const fromStr = + rng() < 0.5 ? new Date(fromMs).toISOString().slice(0, 10) : new Date(fromMs).toISOString(); + const toStr = + rng() < 0.5 ? new Date(toMs).toISOString().slice(0, 10) : new Date(toMs).toISOString(); + const asOfStr = + asOfMs === undefined + ? undefined + : rng() < 0.5 + ? new Date(asOfMs).toISOString().slice(0, 10) + : new Date(asOfMs).toISOString(); + + const kindIdx = i % 4; + let planned; + if (kindIdx === 0) { + const adj = BARS_ADJUSTMENTS[i % 3]!; + planned = planBars1dQuery( + { + listingIds: [1 + Math.floor(rng() * 100_000)], + timeframe: '1d', + from: fromStr, + to: toStr, + adjustment: adj, + asOf: asOfStr, + }, + DEFAULT_CTX + ); + 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); + if (adj !== 'raw') { + // adj_factors subquery known_at <= ? + const adjAsOf = planned.params[1] as string; + expect(Date.parse(adjAsOf)).toBeLessThan(CUTOFF_MS); + } + } else if (kindIdx === 1) { + planned = planEventsQuery( + { + kinds: [EVENT_KINDS[i % EVENT_KINDS.length]!], + listingIds: rng() < 0.5 ? [1 + Math.floor(rng() * 100_000)] : undefined, + from: fromStr, + to: toStr, + asOf: asOfStr, + }, + DEFAULT_CTX + ); + expect(planned.sql).toContain('e.known_at <= ?'); + 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); + } else if (kindIdx === 2) { + planned = planShortsAsOfQuery( + { + listingIds: [1 + Math.floor(rng() * 100_000)], + from: fromStr, + to: toStr, + asOf: asOfStr, + }, + DEFAULT_CTX + ); + expect(planned.sql).toContain('s.known_at <= ?'); + expect(planned.sql).toContain('s.report_date <= ?'); + 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); + } else { + planned = planFx1dQuery( + { + pair: 'USD.CAD', + timeframe: '1d', + from: fromStr, + to: toStr, + }, + DEFAULT_CTX + ); + expect(planned.sql).toContain('f.known_at <= ?'); + 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(planned.fenced.toMs).toBeLessThan(CUTOFF_MS); + expect(planned.fenced.asOfMs).toBeLessThan(CUTOFF_MS); + } + }); + + it('produces identical SQL and bound params under TZ=UTC and TZ=America/Toronto', () => { + const previousTz = process.env.TZ; + try { + const runAll = () => ({ + bars: planBars1dQuery( + { + listingIds: [101], + timeframe: '1d', + from: '2025-03-08', + to: '2025-11-02', + adjustment: 'total', + asOf: '2025-11-03T01:30:00-05:00', + }, + DEFAULT_CTX + ), + events: planEventsQuery( + { + kinds: ['filing', 'earnings'], + from: '2025-03-08', + to: '2025-11-02', + }, + DEFAULT_CTX + ), + shorts: planShortsAsOfQuery( + { + listingIds: [101], + from: '2025-03-08', + to: '2025-11-02', + }, + DEFAULT_CTX + ), + fx: planFx1dQuery( + { + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-03-08', + to: '2025-11-02', + }, + DEFAULT_CTX + ), + }); + + process.env.TZ = 'UTC'; + const utcResult = runAll(); + process.env.TZ = 'America/Toronto'; + const torontoResult = runAll(); + + expect(torontoResult).toEqual(utcResult); + } finally { + if (previousTz === undefined) { + delete process.env.TZ; + } else { + process.env.TZ = previousTz; + } + } + }); +}); + +describe('Vault fence enforcement with zero executor calls', () => { + it('throws VaultHoldoutFenceError when from >= vaultCutoffTs across all 4 endpoints with 0 executor calls', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + + await expect( + collectBars( + store.bars({ + listingIds: [1], + timeframe: '1d', + from: '2026-05-28', + to: '2026-06-01', + adjustment: 'raw', + }) + ) + ).rejects.toThrow(VaultHoldoutFenceError); + + await expect( + store.events({ + kinds: ['filing'], + from: '2026-05-28T00:00:00Z', + to: '2026-06-01', + }) + ).rejects.toThrow(VaultHoldoutFenceError); + + await expect( + store.shortsAsOf({ + listingIds: [1], + from: '2026-05-29', + to: '2026-06-01', + }) + ).rejects.toThrow(VaultHoldoutFenceError); + + await expect( + store.fx({ + pair: 'USD.CAD', + timeframe: '1d', + from: '2026-05-28', + to: '2026-06-01', + }) + ).rejects.toThrow(VaultHoldoutFenceError); + + expect(fake.calls).toHaveLength(0); + }); + + it('throws VaultScopeNotAuthorizedError for unauthorized vault_evaluation_only with 0 executor calls', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + + await expect( + collectBars( + store.bars({ + listingIds: [1], + timeframe: '1d', + from: '2026-06-01', + to: '2026-07-01', + adjustment: 'raw', + scope: 'vault_evaluation_only', + }) + ) + ).rejects.toThrow(VaultScopeNotAuthorizedError); + + expect(fake.calls).toHaveLength(0); + }); + + it('permits unclamped bars query when vault_evaluation_only is explicitly authorized', () => { + const planned = planBars1dQuery( + { + listingIds: [1], + timeframe: '1d', + from: '2026-06-01', + to: '2026-07-01', + adjustment: 'raw', + scope: 'vault_evaluation_only', + }, + { + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + vaultOperatorAuthorized: true, + } + ); + + expect(planned.fenced.scope).toBe('vault_evaluation_only'); + expect(planned.fenced.clampedTo).toBe(false); + expect(planned.params).toEqual([ + 1, + '2026-06-01T00:00:00.000Z', + '2026-07-01T23:59:59.999Z', + '2026-07-01T23:59:59.999Z', + ]); + }); + + it('keeps events, shortsAsOf, and fx vault_fenced even when vaultOperatorAuthorized is true', () => { + const authCtx: DuckDbPlanContext = { + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + vaultOperatorAuthorized: true, + }; + + expect(() => + planEventsQuery({ kinds: ['filing'], from: '2026-06-01', to: '2026-07-01' }, authCtx) + ).toThrow(VaultHoldoutFenceError); + expect(() => + planShortsAsOfQuery({ listingIds: [1], from: '2026-06-01', to: '2026-07-01' }, authCtx) + ).toThrow(VaultHoldoutFenceError); + expect(() => + planFx1dQuery({ pair: 'USD.CAD', timeframe: '1d', from: '2026-06-01', to: '2026-07-01' }, authCtx) + ).toThrow(VaultHoldoutFenceError); + }); +}); + +describe('SQL injection & strict boundary validation', () => { + it('rejects malicious or malformed curatedRoot values with MarketDataStoreValidationError', () => { + const badRoots = [ + '', + 'relative/path', + '/data/curated; DROP TABLE x', + "/data/curated' OR '1'='1", + '/data/curated\n/evil', + '/data/curated\r/evil', + '/data/curated\0/evil', + '/data/curated\x7f/evil', + '/data/curated/*', + '/data/curated/?', + '/data/curated/[a-z]', + '/data/curated/]', + ]; + + for (const root of badRoots) { + expect(() => validateCuratedRoot(root)).toThrow(MarketDataStoreValidationError); + expect(() => + planFx1dQuery( + { pair: 'USD.CAD', timeframe: '1d', from: '2025-01-01', to: '2025-02-01' }, + { curatedRoot: root, vaultCutoffTs: CUTOFF_MS } + ) + ).toThrow(MarketDataStoreValidationError); + } + }); + + it('rejects non-INT32, non-integer, non-number, or empty listingIds with zero executor calls', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + + const badListingIdInputs: unknown[] = [ + [], + [1.5], + [Number.NaN], + [Number.POSITIVE_INFINITY], + [Number.NEGATIVE_INFINITY], + [2_147_483_648], + [-2_147_483_649], + ['101' as unknown as number], + ]; + + for (const badIds of badListingIdInputs) { + await expect( + collectBars( + store.bars({ + listingIds: badIds as number[], + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + adjustment: 'raw', + }) + ) + ).rejects.toThrow(MarketDataStoreValidationError); + + await expect( + store.shortsAsOf({ + listingIds: badIds as number[], + from: '2025-01-01', + to: '2025-02-01', + }) + ).rejects.toThrow(MarketDataStoreValidationError); + } + + expect(fake.calls).toHaveLength(0); + }); + + it('rejects unknown/empty kinds, unsupported pair, invalid adjustment, and unknown timeframe with zero executor calls', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + + await expect( + store.events({ + kinds: [], + from: '2025-01-01', + to: '2025-02-01', + }) + ).rejects.toThrow(MarketDataStoreValidationError); + + await expect( + store.events({ + kinds: ["filing' OR '1'='1" as unknown as 'filing'], + from: '2025-01-01', + to: '2025-02-01', + }) + ).rejects.toThrow(MarketDataStoreValidationError); + + await expect( + store.fx({ + pair: 'EUR.USD' as unknown as 'USD.CAD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + }) + ).rejects.toThrow(MarketDataStoreValidationError); + + await expect( + store.fx({ + pair: 'USD.CAD', + timeframe: '2d' as unknown as '1d', + from: '2025-01-01', + to: '2025-02-01', + }) + ).rejects.toThrow(MarketDataStoreValidationError); + + await expect( + collectBars( + store.bars({ + listingIds: [1], + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + adjustment: 'dividend' as unknown as 'raw', + }) + ) + ).rejects.toThrow(MarketDataStoreValidationError); + + await expect( + collectBars( + store.bars({ + listingIds: [1], + timeframe: '2d' as unknown as '1d', + from: '2025-01-01', + to: '2025-02-01', + adjustment: 'raw', + }) + ) + ).rejects.toThrow(MarketDataStoreValidationError); + + expect(fake.calls).toHaveLength(0); + }); + + it('never embeds caller-supplied values other than validated curatedRoot in SQL text', () => { + const sentinelId = 987654321; + const barsPlan = planBars1dQuery( + { + listingIds: [sentinelId], + timeframe: '1d', + from: '2024-03-14', + to: '2025-09-22', + adjustment: 'total', + asOf: '2025-10-05T15:45:00Z', + }, + DEFAULT_CTX + ); + expect(barsPlan.sql).not.toContain(String(sentinelId)); + expect(barsPlan.sql).not.toContain('2024-03-14'); + expect(barsPlan.sql).not.toContain('2025-09-22'); + expect(barsPlan.sql).not.toContain('2025-10-05'); + + const eventsPlan = planEventsQuery( + { + kinds: ['ceo_post'], + listingIds: [sentinelId], + from: '2024-03-14', + to: '2025-09-22', + }, + DEFAULT_CTX + ); + expect(eventsPlan.sql).not.toContain('ceo_post'); + expect(eventsPlan.sql).not.toContain(String(sentinelId)); + expect(eventsPlan.sql).not.toContain('2024-03-14'); + + const fxPlan = planFx1dQuery( + { + pair: 'USD.CAD', + timeframe: '1d', + from: '2024-03-14', + to: '2025-09-22', + }, + DEFAULT_CTX + ); + expect(fxPlan.sql).not.toContain('USD.CAD'); + expect(fxPlan.sql).not.toContain('USDCAD'); + expect(fxPlan.sql).not.toContain('2024-03-14'); + }); +}); + +describe('createDuckDbMarketDataStore adapter behavior', () => { + it('validates options eagerly at construction', () => { + const fake = createRecordingExecutor(); + + expect(() => + createDuckDbMarketDataStore({ + executor: {} as unknown as DuckDbExecutor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: 'relative', + vaultCutoffTs: CUTOFF_MS, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: Number.NaN, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + barBatchSize: 0, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: { STOCKBOT_DUCKDB_THREADS: '0' }, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(fake.calls).toHaveLength(0); + }); + + it('runs the three budget SET statements sequentially, once, and strictly before the first query (including concurrent first calls)', async () => { + const env = { + STOCKBOT_DUCKDB_MEMORY_LIMIT: '4GB', + STOCKBOT_DUCKDB_THREADS: '2', + STOCKBOT_DUCKDB_TEMP_DIRECTORY: '/tmp/duckdb-test', + }; + const expectedStatements = resolveDuckDbConnectionBudget(env).statements; + + const fake = createRecordingExecutor({ + async onRun() { + await Promise.resolve(); + }, + async onQuery() { + return []; + }, + }); + + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env, + }); + + // Zero calls before first query + expect(fake.calls).toHaveLength(0); + + await Promise.all([ + collectBars( + store.bars({ + listingIds: [1], + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + adjustment: 'raw', + }) + ), + store.events({ + kinds: ['filing'], + from: '2025-01-01', + to: '2025-02-01', + }), + store.shortsAsOf({ + listingIds: [1], + from: '2025-01-01', + to: '2025-02-01', + }), + store.fx({ + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + }), + ]); + + expect(fake.runCalls).toEqual(expectedStatements); + expect(fake.queryCalls).toHaveLength(4); + expect(fake.calls.slice(0, 3).map(c => c.kind)).toEqual(['run', 'run', 'run']); + expect(fake.calls.slice(3).map(c => c.kind)).toEqual(['query', 'query', 'query', 'query']); + + // Subsequent call does not re-run SET statements + await store.fx({ + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + }); + expect(fake.runCalls).toHaveLength(3); + expect(fake.queryCalls).toHaveLength(5); + }); + + it('retries budget initialization cleanly if an initial executor.run call rejects', async () => { + let failOnce = true; + const fake = createRecordingExecutor({ + async onRun(_sql, callIndex) { + if (failOnce && callIndex === 1) { + failOnce = false; + throw new Error('transient DuckDB SET failure'); + } + }, + onQuery: () => [], + }); + + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + + await expect( + store.fx({ + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + }) + ).rejects.toThrow('transient DuckDB SET failure'); + expect(fake.queryCalls).toHaveLength(0); + + // Second attempt retries all 3 SET statements and executes the query + const table = await store.fx({ + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + }); + expect(table).toEqual({ columns: [...FX_1D_COLUMNS], rows: [] }); + expect(fake.runCalls).toHaveLength(5); // 2 from failed attempt + 3 from retry + expect(fake.queryCalls).toHaveLength(1); + }); + + it('maps BarBatch rows with nullable vwap, empty results, and barBatchSize chunking', async () => { + const sampleRows: TableRow[] = [ + { + listing_id: 101, + ts: Date.UTC(2025, 0, 2, 21, 0, 0), + open: 10, + high: 12, + low: 9.5, + close: 11.25, + volume: 1000, + vwap: 10.8, + known_at: Date.UTC(2025, 0, 2, 22, 0, 0), + }, + { + listing_id: 101, + ts: Date.UTC(2025, 0, 3, 21, 0, 0), + open: 11.25, + high: 11.5, + low: 10.9, + close: 11.1, + volume: 0, + vwap: null, + known_at: Date.UTC(2025, 0, 3, 22, 0, 0), + }, + { + listing_id: 202, + ts: Date.UTC(2025, 0, 2, 21, 0, 0), + open: 50, + high: 52, + low: 49, + close: 51, + volume: 500, + vwap: null, + known_at: Date.UTC(2025, 0, 2, 22, 0, 0), + }, + ]; + + const fake = createRecordingExecutor({ + onQuery: (_sql, _params, idx) => (idx === 0 ? sampleRows : []), + }); + + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + barBatchSize: 2, + }); + + const batches = await collectBars( + store.bars({ + listingIds: [101, 202], + timeframe: '1d', + from: '2025-01-01', + to: '2025-01-10', + adjustment: 'raw', + }) + ); + expect(batches).toHaveLength(2); + expect(batches[0]!.rows).toEqual([ + { + listingId: 101, + ts: Date.UTC(2025, 0, 2, 21, 0, 0), + open: 10, + high: 12, + low: 9.5, + close: 11.25, + volume: 1000, + vwap: 10.8, + knownAt: Date.UTC(2025, 0, 2, 22, 0, 0), + }, + { + listingId: 101, + ts: Date.UTC(2025, 0, 3, 21, 0, 0), + open: 11.25, + high: 11.5, + low: 10.9, + close: 11.1, + volume: 0, + vwap: null, + knownAt: Date.UTC(2025, 0, 3, 22, 0, 0), + }, + ]); + expect(batches[1]!.rows).toHaveLength(1); + expect(batches[1]!.rows[0]!.listingId).toBe(202); + + // Empty result yields 0 batches + const emptyBatches = await collectBars( + store.bars({ + listingIds: [101], + timeframe: '1d', + from: '2025-01-01', + to: '2025-01-10', + adjustment: 'raw', + }) + ); + expect(emptyBatches).toEqual([]); + }); + + it('maps Table rows for events, shortsAsOf, and fx and strips unexpected extra columns', async () => { + const fake = createRecordingExecutor({ + onQuery: (sql) => { + if (sql.includes('/events/')) { + return [ + { + listing_id: 10, + 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: '{"form":"10-K"}', + extra_ignored: 'should-not-appear', + }, + ]; + } + if (sql.includes('/shorts/')) { + return [ + { + listing_id: 10, + report_date: '2025-01-15', + known_at: 1_737_500_000_000, + shares_short: 125_000, + net_change: null, + pct_float: 0.045, + source: 'ceo_shorts', + }, + ]; + } + return [ + { + pair: 'USDCAD', + session_date: '2025-01-15', + ts: 1_736_985_600_000, + open: 1.43, + high: 1.44, + low: 1.425, + close: 1.435, + source: 'eod_cad_forex', + known_at: 1_736_985_600_000, + }, + ]; + }, + }); + + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + + const events = await store.events({ + kinds: ['filing'], + from: '2023-01-01', + to: '2025-02-01', + }); + expect(events.columns).toEqual([...EVENTS_COLUMNS]); + expect(events.rows).toEqual([ + { + listing_id: 10, + 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: '{"form":"10-K"}', + }, + ]); + + const shorts = await store.shortsAsOf({ + listingIds: [10], + from: '2025-01-01', + to: '2025-02-01', + }); + expect(shorts.columns).toEqual([...SHORTS_COLUMNS]); + expect(shorts.rows[0]!.net_change).toBeNull(); + + const fx = await store.fx({ + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + }); + expect(fx.columns).toEqual([...FX_1D_COLUMNS]); + expect(fx.rows[0]!.pair).toBe('USDCAD'); + }); + + it('rejects malformed driver rows with MarketDataStoreValidationError and propagates executor errors', async () => { + const malformedFake = createRecordingExecutor({ + onQuery: (sql) => { + if (sql.includes('/bars_1d/')) { + return [{ listing_id: 101, ts: 1000, open: Number.NaN, high: 1, low: 1, close: 1, volume: 1, vwap: null, known_at: 1000 }]; + } + return [{ pair: 'USDCAD' }]; // missing columns + }, + }); + + const malformedStore = createDuckDbMarketDataStore({ + executor: malformedFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + + await expect( + collectBars( + malformedStore.bars({ + listingIds: [101], + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + adjustment: 'raw', + }) + ) + ).rejects.toThrow(MarketDataStoreValidationError); + + await expect( + malformedStore.fx({ + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-02-01', + }) + ).rejects.toThrow(MarketDataStoreValidationError); + + const failingFake = createRecordingExecutor({ + onQuery: async () => { + throw new Error('parquet file missing'); + }, + }); + const failingStore = createDuckDbMarketDataStore({ + executor: failingFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + + await expect( + failingStore.events({ + kinds: ['filing'], + from: '2025-01-01', + to: '2025-02-01', + }) + ).rejects.toThrow('parquet file missing'); + }); + + it('rejects all out-of-slice methods and timeframes with MarketDataStoreNotImplementedError and 0 executor calls', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + + const cases: Array<{ method: string; run: () => Promise }> = [ + { + method: 'bars', + run: () => + collectBars( + store.bars({ + listingIds: [1], + timeframe: '1m', + from: '2025-01-01', + to: '2025-02-01', + adjustment: 'raw', + }) + ), + }, + { + method: 'bars', + run: () => + collectBars( + store.bars({ + listingIds: [1], + timeframe: '5m', + from: '2025-01-01', + to: '2025-02-01', + adjustment: 'raw', + }) + ), + }, + { + method: 'bars', + run: () => + collectBars( + store.bars({ + listingIds: [1], + timeframe: '1h', + from: '2025-01-01', + to: '2025-02-01', + adjustment: 'raw', + }) + ), + }, + { + method: 'fx', + run: () => + store.fx({ + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-01-01', + to: '2025-02-01', + }), + }, + { + method: 'crossSection', + run: () => + store.crossSection({ + features: ['ret_20d'], + date: '2025-01-15', + universe: 'US_EQ', + }), + }, + { + method: 'fundamentalsAsOf', + run: () => + store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue'], + asOf: '2025-01-15', + }), + }, + { + method: 'macroAsOf', + run: () => + store.macroAsOf({ + countries: ['US'], + indicators: ['CPI'], + from: '2025-01-01', + to: '2025-02-01', + }), + }, + { + method: 'universe', + run: () => store.universe({ ref: 'US_EQ', date: '2025-01-15' }), + }, + ]; + + for (const c of cases) { + let caught: unknown; + try { + await c.run(); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreNotImplementedError); + expect((caught as MarketDataStoreNotImplementedError).method).toBe(c.method); + } + + expect(fake.calls).toHaveLength(0); + }); +});