T-119: M1.3e — @stock-bot/research: DuckDB SQL planner + injected-executor MarketDataStore adapter for curated daily Parquet (bars 1d, events, shortsAsOf, fx 1d) with mandatory Vault / known_at predicates, tests and local benchmark (no new dependencies)

This commit is contained in:
Studio 2026-11-29 07:50:21 -05:00
parent 1d4717c48e
commit 9a213f126b
3 changed files with 537 additions and 33 deletions

View file

@ -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
* `<curatedRoot>/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/<fd>`, `/dev/fd/<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/<fd>`,
* `/dev/fd/<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/<fd>` / `/dev/fd/<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> | 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> | PinnedAdjFactorsArtifact;
/** Configuration for {@link createDuckDbMarketDataStore}. */
export interface DuckDbMarketDataStoreOptions
extends Omit<DuckDbPlanContext, 'adjFactorsSnapshot'> {
@ -270,13 +309,26 @@ export interface DuckDbMarketDataStoreOptions
readonly env?: Readonly<Record<string, string | undefined>>;
readonly barBatchSize?: number;
/**
* Optional absolute POSIX `.parquet` path for `adj_factors` reads in
* `'split'` / `'total'` `bars` queries. Defaults to
* `<curatedRoot>/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
* `<curatedRoot>/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/<fd>`, `/dev/fd/<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
* `<curatedRoot>/adj_factors/part.parquet` path). Mutually exclusive with
* {@link adjFactorsPath}.
*/
readonly immutableAdjFactorsPath?: string;
}
export type BarsQuery = Parameters<MarketDataStore['bars']>[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/<fd>` or `/dev/fd/<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/<fd> (/dev/fd/<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 `<curatedRoot>/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<readonly TableRow[]> {
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<BarBatch> {
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> | 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;