diff --git a/libs/research/README.md b/libs/research/README.md index 731e57e9..4fd83b00 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -86,7 +86,7 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-st - **`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. +- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table`, 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, Microsecond & Boundary Validation Rules @@ -100,7 +100,7 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-st `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 (`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. +- **`'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. To prevent TOCTOU races when `curate-etl` atomically replaces `/adj_factors/part.parquet` between footer verification and the factor scan, `createDuckDbMarketDataStore` requires either `pinAdjFactorsArtifact` (binding a stable handle such as `/proc/self/fd/`, `/dev/fd/`, or a private hardlink/copy for both queries and releasing it in `finally`) or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable published path; unpinned mutable paths fail closed with `AdjFactorsSnapshotError('unpinned_mutable_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)`. diff --git a/libs/research/src/market-data-store-duckdb.ts b/libs/research/src/market-data-store-duckdb.ts index 258779b9..75104968 100644 --- a/libs/research/src/market-data-store-duckdb.ts +++ b/libs/research/src/market-data-store-duckdb.ts @@ -30,9 +30,15 @@ * `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}. + * To prevent TOCTOU races when `curate-etl` atomically replaces the mutable + * `/adj_factors/part.parquet` path between footer verification + * and the factor scan, {@link createDuckDbMarketDataStore} pins a single + * artifact version via {@link DuckDbMarketDataStoreOptions.pinAdjFactorsArtifact} + * (stable handle such as `/proc/self/fd/`, `/dev/fd/`, or private + * hardlink/copy) or requires an explicit write-once + * {@link DuckDbMarketDataStoreOptions.immutableAdjFactorsPath} distinct from + * the mutable published path; unpinned mutable paths fail closed 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 @@ -80,6 +86,7 @@ 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}$/; +const FD_HANDLE_PATH_RE = /^\/(?:proc\/self|dev)\/fd\/[1-9]\d*$/; export const ADJ_SNAPSHOT_FORMAT_VERSION = 1; export const ADJ_SNAPSHOT_KV_PREFIX = 'stock_bot.adj_factors.'; @@ -229,7 +236,8 @@ export type AdjFactorsSnapshotErrorCode = | 'unsupported_version' | 'retrospective_rejected' | 'incompatible_fence' - | 'path_mismatch'; + | 'path_mismatch' + | 'unpinned_mutable_path'; /** * Thrown when an adjusted `bars` (`'split'` or `'total'`) query lacks a @@ -263,6 +271,37 @@ export interface DuckDbPlanContext { readonly adjFactorsSnapshot?: AdjFactorsSnapshotMetadata; } +/** + * Handle returned by {@link AdjFactorsArtifactPinner} pinning a single + * `adj_factors` Parquet artifact version (e.g. an open `/proc/self/fd/`, + * `/dev/fd/`, a private hardlink, or a staged copy) across both footer + * verification (`parquet_kv_metadata`) and the `bars` factor scan + * (`read_parquet`). + */ +export interface PinnedAdjFactorsArtifact { + /** + * Stable path referencing the single pinned artifact version (an absolute + * POSIX `.parquet` path distinct from the mutable published path, or a + * `/proc/self/fd/` / `/dev/fd/` handle path). + */ + readonly pinnedPath: string; + /** + * Releases the pinned handle or temporary link/copy once the query finishes + * or fails. Always invoked in a `finally` block. + */ + release(): Promise | void; +} + +/** + * Pins a mutable `adj_factors` Parquet source path to a stable file handle or + * immutable copy before footer verification so concurrent ETL atomic renames + * cannot swap the file between `parquet_kv_metadata(...)` and + * `read_parquet(...)`. + */ +export type AdjFactorsArtifactPinner = ( + sourcePath: string +) => Promise | PinnedAdjFactorsArtifact; + /** Configuration for {@link createDuckDbMarketDataStore}. */ export interface DuckDbMarketDataStoreOptions extends Omit { @@ -270,13 +309,26 @@ export interface DuckDbMarketDataStoreOptions 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. + * Optional absolute POSIX `.parquet` source path for `adj_factors` reads when + * using {@link pinAdjFactorsArtifact}. Defaults to + * `/adj_factors/part.parquet`. Mutually exclusive with + * {@link immutableAdjFactorsPath}. */ readonly adjFactorsPath?: string; + /** + * Optional pinning hook that binds the mutable `adj_factors` source path to a + * stable file handle (`/proc/self/fd/`, `/dev/fd/`) or private + * hardlink/copy `.parquet` path distinct from the mutable path across both + * footer verification and the factor scan. + */ + readonly pinAdjFactorsArtifact?: AdjFactorsArtifactPinner; + /** + * Optional absolute POSIX `.parquet` path to a write-once immutable + * `adj_factors` snapshot artifact (must NOT be the mutable published + * `/adj_factors/part.parquet` path). Mutually exclusive with + * {@link adjFactorsPath}. + */ + readonly immutableAdjFactorsPath?: string; } export type BarsQuery = Parameters[0]; @@ -375,6 +427,45 @@ export function validateParquetFilePath(raw: string, field = 'adjFactorsPath'): return raw; } +/** + * Strictly validates an `adj_factors` artifact path accepted by DuckDB + * `parquet_kv_metadata(...)` and `read_parquet(...)`: either an absolute POSIX + * `.parquet` path or a pinned file-descriptor handle path + * (`/proc/self/fd/` or `/dev/fd/`). + */ +export function validateAdjFactorsArtifactPath(raw: string, field = 'adjFactorsPath'): string { + if ( + typeof raw !== 'string' || + raw.length === 0 || + !raw.startsWith('/') || + hasForbiddenCuratedRootChar(raw) || + (!raw.endsWith('.parquet') && !FD_HANDLE_PATH_RE.test(raw)) + ) { + throw new MarketDataStoreValidationError( + `Invalid adj_factors artifact path "${String(raw)}" for "${field}". Expected an absolute POSIX .parquet path or pinned /proc/self/fd/ (/dev/fd/) handle without quotes, semicolons, control characters, or glob characters (*, ?, [, ]).`, + field + ); + } + return raw; +} + +function canonicalizePosixPath(path: string): string { + const parts = path.split('/'); + const stack: string[] = []; + for (let i = 0; i < parts.length; i += 1) { + const part = parts[i]; + if (part === undefined || part === '' || part === '.') { + continue; + } + if (part === '..') { + stack.pop(); + continue; + } + stack.push(part); + } + return `/${stack.join('/')}`; +} + function joinCuratedPath(normalizedRoot: string, relativePath: string): string { return normalizedRoot === '/' ? `/${relativePath}` : `${normalizedRoot}/${relativePath}`; } @@ -607,7 +698,7 @@ function parseOptionalMicrosKv(value: string, key: string, path: string): number * Parquet file. */ export function planAdjFactorsMetadataQuery(adjPath: string): PlannedAdjFactorsMetadataQuery { - const validPath = validateParquetFilePath(adjPath, 'adjFactorsPath'); + const validPath = validateAdjFactorsArtifactPath(adjPath, 'adjFactorsPath'); const sql = 'SELECT decode(key) AS key, decode(value) AS value ' + `FROM parquet_kv_metadata('${validPath}') ` + @@ -628,7 +719,7 @@ export function parseAdjFactorsSnapshotMetadata( adjPath: string, kvRows: readonly TableRow[] ): AdjFactorsSnapshotMetadata { - const validPath = validateParquetFilePath(adjPath, 'adjFactorsPath'); + const validPath = validateAdjFactorsArtifactPath(adjPath, 'adjFactorsPath'); if (!Array.isArray(kvRows)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', @@ -922,7 +1013,7 @@ function verifyAdjFactorsSnapshotForQuery( ); } - const validPath = validateParquetFilePath(snapshot.path, 'adjFactorsSnapshot.path'); + const validPath = validateAdjFactorsArtifactPath(snapshot.path, 'adjFactorsSnapshot.path'); if ( typeof snapshot.formatVersion !== 'number' || @@ -1511,12 +1602,15 @@ function mapTableRows( * 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. + * For `'split'` and `'total'` `bars` queries, the adapter pins a single + * `adj_factors` artifact version across both `parquet_kv_metadata(...)` footer + * verification and the `read_parquet(...)` factor scan — either via + * {@link DuckDbMarketDataStoreOptions.pinAdjFactorsArtifact} (releasing the + * handle in `finally`) or via an explicit write-once + * {@link DuckDbMarketDataStoreOptions.immutableAdjFactorsPath} distinct from + * the mutable `/adj_factors/part.parquet` path. Unpinned reads of + * a mutable path fail closed with {@link AdjFactorsSnapshotError} + * (`code: 'unpinned_mutable_path'`) and zero executor calls. */ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOptions): MarketDataStore { if (!isPlainRecord(options)) { @@ -1540,10 +1634,44 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption const typedExecutor = executor as unknown as DuckDbExecutor; const curatedRoot = validateCuratedRoot(options.curatedRoot); - const adjFactorsPath = + const defaultMutableAdjPath = joinCuratedPath(curatedRoot, 'adj_factors/part.parquet'); + const canonicalDefaultMutableAdjPath = canonicalizePosixPath(defaultMutableAdjPath); + + if (options.adjFactorsPath !== undefined && options.immutableAdjFactorsPath !== undefined) { + throw new MarketDataStoreValidationError( + 'Options `adjFactorsPath` and `immutableAdjFactorsPath` are mutually exclusive.', + 'immutableAdjFactorsPath' + ); + } + + const adjFactorsSourcePath = options.adjFactorsPath !== undefined ? validateParquetFilePath(options.adjFactorsPath, 'adjFactorsPath') - : joinCuratedPath(curatedRoot, 'adj_factors/part.parquet'); + : defaultMutableAdjPath; + const canonicalSourceAdjPath = canonicalizePosixPath(adjFactorsSourcePath); + + let immutableAdjFactorsPath: string | undefined; + if (options.immutableAdjFactorsPath !== undefined) { + const validatedImmutable = validateParquetFilePath( + options.immutableAdjFactorsPath, + 'immutableAdjFactorsPath' + ); + if (canonicalizePosixPath(validatedImmutable) === canonicalDefaultMutableAdjPath) { + throw new MarketDataStoreValidationError( + `Option \`immutableAdjFactorsPath\` must not point to the mutable published path "${defaultMutableAdjPath}". Use \`pinAdjFactorsArtifact\` to pin the mutable path or provide a write-once snapshot path.`, + 'immutableAdjFactorsPath' + ); + } + immutableAdjFactorsPath = validatedImmutable; + } + + const pinAdjFactorsArtifact = options.pinAdjFactorsArtifact; + if (pinAdjFactorsArtifact !== undefined && typeof pinAdjFactorsArtifact !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `pinAdjFactorsArtifact` to be a function returning a PinnedAdjFactorsArtifact handle.', + 'pinAdjFactorsArtifact' + ); + } const vaultCutoffTs = options.vaultCutoffTs; if ( @@ -1597,27 +1725,75 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption return budgetInitPromise; } + async function executeAdjustedBarsQuery( + q: BarsQuery, + artifactPath: string + ): Promise { + const metaQuery = planAdjFactorsMetadataQuery(artifactPath); + const kvRows = await typedExecutor.query(metaQuery.sql, metaQuery.params); + const adjFactorsSnapshot = parseAdjFactorsSnapshotMetadata(artifactPath, kvRows); + const planned = planBars1dQuery(q, { ...planCtx, adjFactorsSnapshot }); + return typedExecutor.query(planned.sql, planned.params); + } + return { async *bars(q: BarsQuery): AsyncIterable { if (!isPlainRecord(q)) { throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); } - let planned: PlannedDuckDbQuery; + let rawRows: readonly TableRow[]; if (q.adjustment === 'split' || q.adjustment === 'total') { - // Validate timeframe, listingIds, adjustment, and Vault fence before any executor call. + // Validate timeframe, listingIds, adjustment, and Vault fence before any executor/pinner 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 }); + + if (pinAdjFactorsArtifact !== undefined) { + await ensureBudgetInitialized(); + const sourceToPin = immutableAdjFactorsPath ?? adjFactorsSourcePath; + const rawPin: unknown = await pinAdjFactorsArtifact(sourceToPin); + if (!isPlainRecord(rawPin) || typeof rawPin.release !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `pinAdjFactorsArtifact` to return `{ pinnedPath, release() }`.', + 'pinAdjFactorsArtifact' + ); + } + const release = rawPin.release as () => Promise | void; + try { + const pinnedPath = validateAdjFactorsArtifactPath( + rawPin.pinnedPath as string, + 'pinnedPath' + ); + const canonicalPinned = canonicalizePosixPath(pinnedPath); + if ( + canonicalPinned === canonicalSourceAdjPath || + canonicalPinned === canonicalDefaultMutableAdjPath + ) { + throw new AdjFactorsSnapshotError( + 'unpinned_mutable_path', + `\`pinAdjFactorsArtifact\` returned the mutable path "${pinnedPath}" without pinning a distinct handle or immutable snapshot copy.`, + pinnedPath + ); + } + rawRows = await executeAdjustedBarsQuery(q, pinnedPath); + } finally { + await release(); + } + } else if (immutableAdjFactorsPath !== undefined) { + await ensureBudgetInitialized(); + rawRows = await executeAdjustedBarsQuery(q, immutableAdjFactorsPath); + } else { + throw new AdjFactorsSnapshotError( + 'unpinned_mutable_path', + `Refusing to read mutable adj_factors path "${adjFactorsSourcePath}" across separate footer verification and factor scan queries without pinning. Provide \`pinAdjFactorsArtifact\` or \`immutableAdjFactorsPath\`.`, + adjFactorsSourcePath + ); + } } else { - planned = planBars1dQuery(q, planCtx); + const planned = planBars1dQuery(q, planCtx); await ensureBudgetInitialized(); + rawRows = await typedExecutor.query(planned.sql, planned.params); } - const rawRows = await typedExecutor.query(planned.sql, planned.params); const mapped = mapBarRows(rawRows); if (mapped.length === 0) { return; diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index a8fec904..abe5e954 100644 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'bun:test'; import { ADJ_SNAPSHOT_FORMAT_VERSION, ADJ_SNAPSHOT_KV_PREFIX, + type AdjFactorsArtifactPinner, AdjFactorsSnapshotError, type AdjFactorsSnapshotMetadata, BARS_ADJUSTMENTS, @@ -15,6 +16,7 @@ import { FX_PAIR_MAP, MarketDataStoreNotImplementedError, MarketDataStoreValidationError, + type PinnedAdjFactorsArtifact, SHORTS_COLUMNS, type TableRow, VaultHoldoutFenceError, @@ -27,6 +29,7 @@ import { planFx1dQuery, planShortsAsOfQuery, resolveDuckDbConnectionBudget, + validateAdjFactorsArtifactPath, validateCuratedRoot, validateParquetFilePath, } from '@stock-bot/research'; @@ -48,6 +51,7 @@ import { planEventsQuery as subpathPlanEventsQuery, planFx1dQuery as subpathPlanFx1dQuery, planShortsAsOfQuery as subpathPlanShortsAsOfQuery, + validateAdjFactorsArtifactPath as subpathValidateAdjFactorsArtifactPath, validateCuratedRoot as subpathValidateCuratedRoot, validateParquetFilePath as subpathValidateParquetFilePath, } from '@stock-bot/research/market-data-store-duckdb'; @@ -209,6 +213,7 @@ describe('market-data-store-duckdb exports', () => { expect(createDuckDbMarketDataStore).toBe(subpathCreateDuckDbMarketDataStore); expect(validateCuratedRoot).toBe(subpathValidateCuratedRoot); expect(validateParquetFilePath).toBe(subpathValidateParquetFilePath); + expect(validateAdjFactorsArtifactPath).toBe(subpathValidateAdjFactorsArtifactPath); expect(MarketDataStoreNotImplementedError).toBe(SubpathNotImplementedError); expect(AdjFactorsSnapshotError).toBe(SubpathAdjFactorsSnapshotError); expect(ADJ_SNAPSHOT_FORMAT_VERSION).toBe(subpathAdjSnapshotFormatVersion); @@ -743,6 +748,7 @@ describe('adj_factors snapshot verification & Vault future-split leakage prevent } // 2. Adapter rejects retrospective adj_factors snapshot without executing bars query + const retroPath = `${CURATED_ROOT}/adj_factors/snapshots/retro.parquet`; const retroFake = createRecordingExecutor({ onQuery: (sql) => { if (sql.includes('parquet_kv_metadata')) { @@ -760,6 +766,7 @@ describe('adj_factors snapshot verification & Vault future-split leakage prevent executor: retroFake.executor, curatedRoot: CURATED_ROOT, vaultCutoffTs: CUTOFF_MS, + immutableAdjFactorsPath: retroPath, env: {}, }); @@ -784,6 +791,7 @@ describe('adj_factors snapshot verification & Vault future-split leakage prevent // 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; + const badPath = `${CURATED_ROOT}/adj_factors/snapshots/mismatched.parquet`; 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 @@ -801,6 +809,7 @@ describe('adj_factors snapshot verification & Vault future-split leakage prevent executor: badFake.executor, curatedRoot: CURATED_ROOT, vaultCutoffTs: CUTOFF_MS, + immutableAdjFactorsPath: badPath, env: {}, }); @@ -823,7 +832,7 @@ describe('adj_factors snapshot verification & Vault future-split leakage prevent } // 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). + // curate_adj_qa_contract.rs:303) bound to immutableAdjFactorsPath, 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) => { @@ -857,7 +866,7 @@ describe('adj_factors snapshot verification & Vault future-split leakage prevent executor: fencedFake.executor, curatedRoot: CURATED_ROOT, vaultCutoffTs: CUTOFF_MS, - adjFactorsPath: fencedAdjPath, + immutableAdjFactorsPath: fencedAdjPath, env: {}, }); @@ -878,6 +887,288 @@ describe('adj_factors snapshot verification & Vault future-split leakage prevent expect(fencedFake.calls.slice(0, 3).map(c => c.kind)).toEqual(['run', 'run', 'run']); }); + it('pins a single artifact version across footer check and factor scan when ETL atomically replaces part.parquet', async () => { + // Regression for TOCTOU between parquet_kv_metadata and read_parquet: + // Fixture mirrors tools/curate-etl/tests/curate_adj_qa_contract.rs: + // - Listing 42: visible 2-for-1 split (2024-06-10) + held-out Vault 2-for-1 split (2026-07-15) + // - Raw close on 2024-06-07: 100.0 + // - Inode 1 (fenced, vault_cutoff = CUTOFF_MICROS): cum_split_factor = 2.0 -> close = 50.0 + // - Inode 2 (retrospective replacement): cum_split_factor = 4.0 -> close = 25.0 (LEAK!) + interface VirtualAdjInode { + readonly id: number; + readonly kvRows: TableRow[]; + readonly cumSplitFactor: number; + } + + const fencedInode: VirtualAdjInode = { + id: 1, + kvRows: makeFencedKvRows({ + asOfMicros: null, + vaultCutoffMicros: CUTOFF_MICROS, + rowsWritten: 1, + checksum: '0x024ec73a1afe7e6b', + }), + cumSplitFactor: 2.0, + }; + const retrospectiveInode: VirtualAdjInode = { + id: 2, + kvRows: makeFencedKvRows({ + snapshotKind: 'retrospective', + asOfMicros: null, + vaultCutoffMicros: null, + rowsWritten: 2, + checksum: '0x9999999999999999', + }), + cumSplitFactor: 4.0, + }; + + // Simulated POSIX directory entry + open file-descriptor table + const dirEntries = new Map([[DEFAULT_ADJ_PATH, fencedInode]]); + const openFds = new Map(); + let nextFd = 42; + const releasedFds: string[] = []; + + const pinAdjFactorsArtifact: AdjFactorsArtifactPinner = (sourcePath) => { + const inode = dirEntries.get(sourcePath); + if (inode === undefined) { + throw new Error(`ENOENT: ${sourcePath}`); + } + const fdPath = `/proc/self/fd/${nextFd}`; + nextFd += 1; + openFds.set(fdPath, inode); + return { + pinnedPath: fdPath, + release() { + openFds.delete(fdPath); + releasedFds.push(fdPath); + }, + }; + }; + + const resolvePath = (path: string): VirtualAdjInode => { + const inode = openFds.get(path) ?? dirEntries.get(path); + if (inode === undefined) { + throw new Error(`ENOENT: ${path}`); + } + return inode; + }; + + const rawPreSplitClose = 100.0; + let swapped = false; + const fake = createRecordingExecutor({ + onQuery: (sql) => { + const metaMatch = /parquet_kv_metadata\('([^']+)'\)/.exec(sql); + if (metaMatch !== null) { + const path = metaMatch[1]!; + const inode = resolvePath(path); + // Simulate ETL atomically replacing the published path RIGHT BETWEEN + // footer verification and the bars factor scan. + if (!swapped) { + swapped = true; + dirEntries.set(DEFAULT_ADJ_PATH, retrospectiveInode); + } + return inode.kvRows; + } + const readMatches = [...sql.matchAll(/read_parquet\('([^']+)'\)/g)]; + expect(readMatches).toHaveLength(1); + const adjPath = readMatches[0]![1]!; + const inode = resolvePath(adjPath); + return [ + { + listing_id: 42, + ts: Date.UTC(2024, 5, 7, 20, 0, 0), + open: rawPreSplitClose / inode.cumSplitFactor, + high: rawPreSplitClose / inode.cumSplitFactor, + low: rawPreSplitClose / inode.cumSplitFactor, + close: rawPreSplitClose / inode.cumSplitFactor, + volume: 1000 * inode.cumSplitFactor, + vwap: null, + known_at: Date.UTC(2024, 5, 7, 20, 0, 0), + }, + ]; + }, + }); + + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + pinAdjFactorsArtifact, + env: {}, + }); + + // 1. In-flight query pinned Inode 1 before ETL replaced DEFAULT_ADJ_PATH with Inode 2. + // Both parquet_kv_metadata and read_parquet read /proc/self/fd/42 -> Inode 1 -> close = 50.0. + const batches = await collectBars( + store.bars({ + listingIds: [42], + timeframe: '1d', + from: '2024-06-01', + to: '2024-06-15', + adjustment: 'split', + }) + ); + expect(swapped).toBe(true); + expect(batches).toHaveLength(1); + expect(batches[0]!.rows[0]!.close).toBe(50.0); + expect(batches[0]!.rows[0]!.volume).toBe(2000); + expect(fake.queryCalls).toHaveLength(2); + expect(fake.queryCalls[0]!.sql).toContain("parquet_kv_metadata('/proc/self/fd/42')"); + expect(fake.queryCalls[1]!.sql).toContain("read_parquet('/proc/self/fd/42')"); + expect(releasedFds).toEqual(['/proc/self/fd/42']); + expect(openFds.size).toBe(0); + + // 2. Next query opens the newly published retrospective Inode 2 via /proc/self/fd/43, + // fails closed on footer verification without scanning bars, and still releases the fd. + try { + await collectBars( + store.bars({ + listingIds: [42], + timeframe: '1d', + from: '2024-06-01', + to: '2024-06-15', + adjustment: 'split', + }) + ); + expect.unreachable('should fail closed on retrospective replacement'); + } catch (err) { + expect(err).toBeInstanceOf(AdjFactorsSnapshotError); + expect((err as AdjFactorsSnapshotError).code).toBe('retrospective_rejected'); + } + expect(fake.queryCalls).toHaveLength(3); + expect(fake.queryCalls[2]!.sql).toContain("parquet_kv_metadata('/proc/self/fd/43')"); + expect(releasedFds).toEqual(['/proc/self/fd/42', '/proc/self/fd/43']); + expect(openFds.size).toBe(0); + }); + + it('fails closed on unpinned mutable adj_factors paths and buggy no-op pinners', async () => { + // 1. Default mutable path with neither pinAdjFactorsArtifact nor immutableAdjFactorsPath + const unpinnedFake = createRecordingExecutor(); + const unpinnedStore = createDuckDbMarketDataStore({ + executor: unpinnedFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + + try { + await collectBars( + unpinnedStore.bars({ + listingIds: [42], + timeframe: '1d', + from: '2024-06-01', + to: '2024-06-15', + adjustment: 'split', + }) + ); + expect.unreachable('should fail closed on unpinned mutable path'); + } catch (err) { + expect(err).toBeInstanceOf(AdjFactorsSnapshotError); + expect((err as AdjFactorsSnapshotError).code).toBe('unpinned_mutable_path'); + } + expect(unpinnedFake.calls).toHaveLength(0); + + // 2. Buggy no-op pinner returning the mutable path itself fails closed and still releases + let released = false; + const noopFake = createRecordingExecutor(); + const noopStore = createDuckDbMarketDataStore({ + executor: noopFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + pinAdjFactorsArtifact: (sourcePath) => ({ + pinnedPath: sourcePath, + release() { + released = true; + }, + }), + env: {}, + }); + + try { + await collectBars( + noopStore.bars({ + listingIds: [42], + timeframe: '1d', + from: '2024-06-01', + to: '2024-06-15', + adjustment: 'total', + }) + ); + expect.unreachable('should reject no-op pinner returning mutable path'); + } catch (err) { + expect(err).toBeInstanceOf(AdjFactorsSnapshotError); + expect((err as AdjFactorsSnapshotError).code).toBe('unpinned_mutable_path'); + } + expect(released).toBe(true); + expect(noopFake.queryCalls).toHaveLength(0); + + // 3. Pinner returning malformed handle or invalid path rejects cleanly and releases when possible + const badHandleStore = createDuckDbMarketDataStore({ + executor: noopFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + pinAdjFactorsArtifact: (() => null) as unknown as AdjFactorsArtifactPinner, + env: {}, + }); + await expect( + collectBars( + badHandleStore.bars({ + listingIds: [42], + timeframe: '1d', + from: '2024-06-01', + to: '2024-06-15', + adjustment: 'split', + }) + ) + ).rejects.toThrow(MarketDataStoreValidationError); + + let badPathReleased = false; + const badPathStore = createDuckDbMarketDataStore({ + executor: noopFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + pinAdjFactorsArtifact: () => + ({ + pinnedPath: '/proc/self/fd/0', + release() { + badPathReleased = true; + }, + }) as PinnedAdjFactorsArtifact, + env: {}, + }); + await expect( + collectBars( + badPathStore.bars({ + listingIds: [42], + timeframe: '1d', + from: '2024-06-01', + to: '2024-06-15', + adjustment: 'split', + }) + ) + ).rejects.toThrow(MarketDataStoreValidationError); + expect(badPathReleased).toBe(true); + }); + + it('validates pinned fd handles and .parquet paths strictly in validateAdjFactorsArtifactPath', () => { + expect(validateAdjFactorsArtifactPath('/proc/self/fd/12')).toBe('/proc/self/fd/12'); + expect(validateAdjFactorsArtifactPath('/dev/fd/5')).toBe('/dev/fd/5'); + expect(validateAdjFactorsArtifactPath(DEFAULT_ADJ_PATH)).toBe(DEFAULT_ADJ_PATH); + + for (const bad of [ + '', + 'relative.parquet', + '/data/adj_factors/part.csv', + '/proc/self/fd/0', + '/proc/self/fd/-1', + '/proc/self/fd/abc', + "/proc/self/fd/12'; DROP TABLE x", + '/tmp/pin-*.parquet', + ]) { + expect(() => validateAdjFactorsArtifactPath(bad)).toThrow(MarketDataStoreValidationError); + } + }); + it('rejects retrospective snapshot even under authorized vault_evaluation_only', () => { const retroSnapshot = parseAdjFactorsSnapshotMetadata( DEFAULT_ADJ_PATH, @@ -1441,6 +1732,43 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { }) ).toThrow(MarketDataStoreValidationError); + expect(() => + createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + immutableAdjFactorsPath: DEFAULT_ADJ_PATH, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + immutableAdjFactorsPath: `${CURATED_ROOT}//adj_factors/./sub/../part.parquet`, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + adjFactorsPath: DEFAULT_ADJ_PATH, + immutableAdjFactorsPath: `${CURATED_ROOT}/adj_factors/snapshots/s1.parquet`, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + pinAdjFactorsArtifact: 'not-a-fn' as unknown as AdjFactorsArtifactPinner, + }) + ).toThrow(MarketDataStoreValidationError); + expect(() => createDuckDbMarketDataStore({ executor: fake.executor,