/** * 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` (point-in-time fenced snapshot with * `stock_bot.adj_factors.*` Parquet footer metadata) * - `/events/year=*\/part.parquet` (`hive_partitioning = true`) * - `/shorts/part.parquet` * - `/fx_1d/part.parquet` * - `/fundamentals_pit/year=*\/part.parquet` (`hive_partitioning = true`) * * `bars` (`timeframe: '1d'`) adjustment formulas (`tools/curate-etl/README.md`): * - `bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share * `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'`, because `cum_split_factor` and * `cum_total_factor` are right-to-left suffix products, slicing a * retrospective `adj_factors` file with `known_at <= asOf` would still leak * future or held-out Vault splits/dividends into earlier cumulative factors. * Therefore, `'split'` and `'total'` queries REQUIRE a verified * `point_in_time_fenced` `adj_factors` snapshot artifact (parsed from * Parquet footer `stock_bot.adj_factors.*` metadata) whose effective * inclusive fence matches the query's effective `asOf` and Vault cutoff. * 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 * first `adj_factors` row with `ex_date > session_date`): * - `'split'`: * - `price_adj = price_raw / COALESCE(a.cum_split_factor, 1.0)` for * `open`, `high`, `low`, `close`, and `vwap` (preserving `NULL` `vwap`). * - `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). * * Microsecond upper-bound semantics: * - Curated Parquet `ts` and `known_at` columns are stored as * `TIMESTAMP(MICROS, isAdjustedToUTC=true)` (for example, `curate_fx_1d` * stamps `ts = known_at = 23:59:59.999999Z`). * - Date-only `YYYY-MM-DD` upper bounds (`to`, `asOf`) and default or clamped * Vault upper bounds expand to the last included Parquet microsecond * (`.999999Z` / `vaultCutoffTs * 1000 - 1`), while explicit time-of-day * bounds preserve their caller-specified precision. Under `'vault_fenced'`, * every planned upper bound remains strictly `< vaultCutoffTs`. */ import { type BarBatch, type BarRecord, type EventKind, type FencedTimeRange, type MarketDataStore, MarketDataStoreValidationError, type Table, type TableCell, type TableRow, VaultHoldoutFenceError, 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; const MS_PER_DAY = 86_400_000; // 0000-01-01T00:00:00.000Z: earliest epoch ms that formats as unsigned YYYY-MM-DD. const MIN_ISO_DATE_EPOCH_MS = -62_167_219_200_000; // 9999-12-31T00:00:00.000Z: latest UTC midnight representable as YYYY-MM-DD. const MAX_ISO_DATE_MIDNIGHT_MS = 253_402_214_400_000; const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/; const STRICT_INT_RE = /^-?\d+$/; const STRICT_UINT_RE = /^\d+$/; const SNAPSHOT_CHECKSUM_RE = /^0x[0-9a-f]{16}$/; 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.'; const KV_FORMAT_VERSION = `${ADJ_SNAPSHOT_KV_PREFIX}format_version`; const KV_SNAPSHOT_KIND = `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_kind`; const KV_AS_OF_MICROS = `${ADJ_SNAPSHOT_KV_PREFIX}as_of_micros`; const KV_VAULT_CUTOFF_MICROS = `${ADJ_SNAPSHOT_KV_PREFIX}vault_cutoff_micros`; const KV_ROWS_WRITTEN = `${ADJ_SNAPSHOT_KV_PREFIX}rows_written`; const KV_SNAPSHOT_CHECKSUM = `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_checksum`; export const EVENT_KINDS = ['filing', 'earnings', 'ceo_post', 'corporate_action'] as const; const EVENT_KIND_SET: ReadonlySet = new Set(EVENT_KINDS); 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 UNIVERSE_REFS = ['US_EQ', 'CA_EQ', 'US_CA_EQ'] as const; export type SupportedUniverseRef = (typeof UNIVERSE_REFS)[number]; export const DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7; const UNIVERSE_CURRENCY_MAP: Readonly> = { US_EQ: ['USD'], CA_EQ: ['CAD'], US_CA_EQ: ['USD', 'CAD'], }; 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; export const FUNDAMENTALS_PIT_VALUE_FIELDS = [ 'revenue', 'net_income', 'operating_cash_flow', 'total_assets', 'total_equity', 'shares_outstanding', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow', ] as const; export type FundamentalsPitValueField = (typeof FUNDAMENTALS_PIT_VALUE_FIELDS)[number]; const FUNDAMENTALS_PIT_VALUE_FIELD_MAP: ReadonlyMap = new Map( FUNDAMENTALS_PIT_VALUE_FIELDS.map(field => [field, field]) ); const FUNDAMENTALS_TTM_VALUE_FIELD_SET: ReadonlySet = new Set([ 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow', ]); type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string' | 'boolean'; interface TableColumnSpec { readonly name: string; readonly kind: ColumnScalarKind; readonly nullable: boolean; } const EVENTS_SCHEMA: readonly TableColumnSpec[] = [ { name: 'listing_id', kind: 'int32', nullable: false }, { name: 'ts', kind: 'safe_int', nullable: false }, { name: 'known_at', kind: 'safe_int', nullable: false }, { name: 'known_at_source', kind: 'string', nullable: false }, { name: 'kind', kind: 'string', nullable: false }, { name: 'subtype', kind: 'string', nullable: false }, { name: 'payload_json', kind: 'string', nullable: false }, ]; const SHORTS_SCHEMA: readonly TableColumnSpec[] = [ { name: 'listing_id', kind: 'int32', nullable: false }, { name: 'report_date', kind: 'string', nullable: false }, { name: 'known_at', kind: 'safe_int', nullable: false }, { name: 'shares_short', kind: 'number', nullable: false }, { name: 'net_change', kind: 'number', nullable: true }, { name: 'pct_float', kind: 'number', nullable: true }, { name: 'source', kind: 'string', nullable: false }, ]; const FX_1D_SCHEMA: readonly TableColumnSpec[] = [ { name: 'pair', kind: 'string', nullable: false }, { name: 'session_date', kind: 'string', nullable: false }, { name: 'ts', kind: 'safe_int', nullable: false }, { name: 'open', kind: 'number', nullable: false }, { name: 'high', kind: 'number', nullable: false }, { name: 'low', kind: 'number', nullable: false }, { name: 'close', kind: 'number', nullable: false }, { name: 'source', kind: 'string', nullable: false }, { name: 'known_at', kind: 'safe_int', nullable: false }, ]; const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [ { name: 'listing_id', kind: 'int32', nullable: false }, { name: 'effective_known_at', kind: 'safe_int', nullable: false }, { name: 'known_at_source', kind: 'string', nullable: false }, { name: 'has_estimated_lag', kind: 'boolean', nullable: false }, { name: 'period_end', kind: 'string', nullable: false }, { name: 'fiscal_period', kind: 'string', nullable: false }, { name: 'currency', kind: 'string', nullable: false }, { name: 'period_known_at', kind: 'safe_int', nullable: false }, ]; const FUNDAMENTALS_TTM_META_SCHEMA: readonly TableColumnSpec[] = [ { name: 'ttm_period_end', kind: 'string', nullable: true }, { name: 'ttm_currency', kind: 'string', nullable: true }, { name: 'ttm_has_estimated_lag', kind: 'boolean', nullable: true }, ]; /** Scalar parameter value bound separately from SQL text. */ export type DuckDbParam = string | number | boolean | null; /** * 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; } /** Snapshot classification written by `tools/curate-etl` into `adj_factors/part.parquet`. */ export type AdjFactorsSnapshotKind = 'retrospective' | 'point_in_time_fenced'; /** Point-in-time and Vault fence embedded in `adj_factors/part.parquet` footer metadata. */ export interface AdjFactorsPointInTimeFence { readonly asOfMicros: number | null; readonly vaultCutoffMicros: number | null; } /** * Verified `adj_factors` Parquet footer metadata parsed via * {@link parseAdjFactorsSnapshotMetadata}, bound to a concrete `.parquet` file * path. */ export interface AdjFactorsSnapshotMetadata { readonly path: string; readonly formatVersion: number; readonly snapshotKind: AdjFactorsSnapshotKind; readonly fence: AdjFactorsPointInTimeFence; readonly rowsWritten: number; readonly snapshotChecksum: string; } /** Pure output of {@link planAdjFactorsMetadataQuery}. */ export interface PlannedAdjFactorsMetadataQuery { readonly path: string; readonly sql: string; readonly params: readonly DuckDbParam[]; } export type AdjFactorsSnapshotErrorCode = | 'missing_snapshot' | 'missing_metadata' | 'invalid_metadata' | 'unsupported_version' | 'retrospective_rejected' | 'incompatible_fence' | 'path_mismatch' | 'unpinned_mutable_path'; /** * Thrown when an adjusted `bars` (`'split'` or `'total'`) query lacks a * verified `point_in_time_fenced` `adj_factors` snapshot artifact matching the * query's effective `asOf` and Vault fence, or when Parquet footer metadata is * missing, retrospective, malformed, or mismatched. */ export class AdjFactorsSnapshotError extends Error { override readonly name = 'AdjFactorsSnapshotError'; readonly code: AdjFactorsSnapshotErrorCode; readonly path?: string; constructor(code: AdjFactorsSnapshotErrorCode, message: string, path?: string) { super(message); this.code = code; this.path = path; Object.setPrototypeOf(this, new.target.prototype); } } /** Context required to plan fenced DuckDB queries against curated Parquet. */ export interface DuckDbPlanContext { readonly curatedRoot: string; readonly vaultCutoffTs: number; readonly vaultOperatorAuthorized?: boolean; /** * Optional calendar-day lookback window for {@link planUniverseQuery} * (`[date - universeLookbackDays, date]`). Defaults to * {@link DEFAULT_UNIVERSE_LOOKBACK_DAYS} (`7`). */ readonly universeLookbackDays?: number; /** * Verified `adj_factors` snapshot metadata bound to the `.parquet` file to * be read. Required for `'split'` and `'total'` `bars` queries; rejected if * retrospective or mismatched for the query's effective `asOf` / Vault fence. */ readonly adjFactorsSnapshot?: AdjFactorsSnapshotMetadata; } /** * 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 { readonly executor: DuckDbExecutor; readonly env?: Readonly>; readonly barBatchSize?: number; /** * 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]; export type EventsQuery = Parameters[0]; export type ShortsAsOfQuery = Parameters[0]; export type FxQuery = Parameters[0]; export type UniverseQuery = Parameters[0]; export type FundamentalsAsOfQuery = Parameters[0]; /** * Thrown when a `MarketDataStore` method or timeframe is outside the curated * 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); } /** * Strictly validates a concrete Parquet file path (absolute POSIX `.parquet` * path with no control characters, quotes, semicolons, or glob metacharacters). */ export function validateParquetFilePath(raw: string, field = 'adjFactorsPath'): string { if ( typeof raw !== 'string' || raw.length === 0 || !raw.startsWith('/') || !raw.endsWith('.parquet') || hasForbiddenCuratedRootChar(raw) ) { throw new MarketDataStoreValidationError( `Invalid Parquet file path "${String(raw)}" for "${field}". Expected an absolute POSIX .parquet path without quotes, semicolons, control characters, or glob characters (*, ?, [, ]).`, field ); } return raw; } /** * 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}`; } 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 validateFundamentalsFields( raw: readonly string[], field = 'fields' ): FundamentalsPitValueField[] { if (!Array.isArray(raw) || raw.length === 0) { throw new MarketDataStoreValidationError( `Expected a non-empty array of fundamentals value fields for "${field}".`, field ); } const seen = new Set(); const normalized: FundamentalsPitValueField[] = []; for (let i = 0; i < raw.length; i += 1) { const name: unknown = raw[i]; const canonical = typeof name === 'string' ? FUNDAMENTALS_PIT_VALUE_FIELD_MAP.get(name) : undefined; if (canonical === undefined) { throw new MarketDataStoreValidationError( `Unknown fundamentals field "${String(name)}". Expected one of: ${FUNDAMENTALS_PIT_VALUE_FIELDS.join(', ')}.`, field ); } if (!seen.has(canonical)) { seen.add(canonical); normalized.push(canonical); } } return normalized; } function validateAllowEstimatedLag(raw: unknown): boolean { if (raw === undefined) { return true; } if (typeof raw !== 'boolean') { throw new MarketDataStoreValidationError( `Invalid allowEstimatedLag "${String(raw)}". Expected a boolean.`, 'allowEstimatedLag' ); } return raw; } function validateAdjustment(raw: unknown): (typeof BARS_ADJUSTMENTS)[number] { if (typeof raw !== 'string' || !BARS_ADJUSTMENT_SET.has(raw)) { throw new MarketDataStoreValidationError( `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 validateUniverseRef(raw: unknown): readonly string[] { if (typeof raw === 'string' && Object.prototype.hasOwnProperty.call(UNIVERSE_CURRENCY_MAP, raw)) { return UNIVERSE_CURRENCY_MAP[raw as SupportedUniverseRef]; } throw new MarketDataStoreValidationError( `Unsupported universe ref "${String(raw)}". Expected one of: ${UNIVERSE_REFS.join(', ')}.`, 'ref' ); } function validateUniverseLookbackDays(raw: unknown, vaultCutoffTs?: number): number { const days = raw === undefined ? DEFAULT_UNIVERSE_LOOKBACK_DAYS : raw; if (typeof days !== 'number' || !Number.isSafeInteger(days) || days < 1) { throw new MarketDataStoreValidationError( `Invalid universeLookbackDays "${String(raw)}". Expected a positive safe integer.`, 'universeLookbackDays' ); } const lookbackMs = days * MS_PER_DAY; if ( !Number.isSafeInteger(lookbackMs) || MAX_ISO_DATE_MIDNIGHT_MS - lookbackMs < MIN_ISO_DATE_EPOCH_MS ) { throw new MarketDataStoreValidationError( `Invalid universeLookbackDays "${days}". Lookback window exceeds supported YYYY-MM-DD UTC date range.`, 'universeLookbackDays' ); } if (vaultCutoffTs !== undefined) { const latestPermittedDateMs = Math.floor(Math.min(vaultCutoffTs - 1, MAX_ISO_DATE_MIDNIGHT_MS) / MS_PER_DAY) * MS_PER_DAY; const latestLookbackStartMs = latestPermittedDateMs - lookbackMs; if ( !Number.isSafeInteger(latestLookbackStartMs) || latestLookbackStartMs < MIN_ISO_DATE_EPOCH_MS ) { throw new MarketDataStoreValidationError( `Invalid universeLookbackDays "${days}". Lookback window exceeds supported YYYY-MM-DD UTC date range for vaultCutoffTs.`, 'universeLookbackDays' ); } } return days; } 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 extractExplicitSubMsMicros(raw: string): number { const match = ISO_FRACTIONAL_RE.exec(raw); if (match === null) { return 0; } const frac = match[1] ?? ''; if (frac.length <= 3) { return 0; } const microDigits = frac.slice(3, 6).padEnd(3, '0'); return Number(microDigits); } function resolveFromSubMsMicros(rawFrom: string): number { if (DATE_ONLY_RE.test(rawFrom)) { return 0; } return extractExplicitSubMsMicros(rawFrom); } function resolveToSubMsMicros(rawTo: string, fenced: FencedTimeRange): number { if (fenced.clampedTo || DATE_ONLY_RE.test(rawTo)) { return 999; } return extractExplicitSubMsMicros(rawTo); } function resolveAsOfSubMsMicros( rawAsOf: string | undefined, rawTo: string, fenced: FencedTimeRange ): number { if (fenced.clampedAsOf) { return 999; } if (rawAsOf === undefined) { if (fenced.scope === 'vault_fenced') { return 999; } return resolveToSubMsMicros(rawTo, fenced); } if (DATE_ONLY_RE.test(rawAsOf)) { return 999; } return extractExplicitSubMsMicros(rawAsOf); } function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { const isoMs = new Date(epochMs).toISOString(); if (subMsMicros === 0) { return isoMs; } const extra = String(subMsMicros).padStart(3, '0'); return `${isoMs.slice(0, -1)}${extra}Z`; } function formatUtcDate(epochMs: number): string { return new Date(epochMs).toISOString().slice(0, 10); } function toEpochMicros(epochMs: number, subMsMicros: number, field: string): number { const micros = epochMs * 1000 + subMsMicros; if (!Number.isSafeInteger(micros)) { throw new MarketDataStoreValidationError( `Timestamp for "${field}" exceeds safe microsecond integer precision.`, field ); } return micros === 0 ? 0 : micros; } function parseOptionalMicrosKv(value: string, key: string, path: string): number | null { if (value === 'none') { return null; } if (!STRICT_INT_RE.test(value)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Invalid microsecond integer value "${value}" for "${key}" in "${path}".`, path ); } const parsed = Number(value); if (!Number.isSafeInteger(parsed)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Out-of-range microsecond integer value "${value}" for "${key}" in "${path}".`, path ); } return parsed === 0 ? 0 : parsed; } /** * Plans the DuckDB `parquet_kv_metadata` query that reads * `stock_bot.adj_factors.*` footer metadata from a concrete `adj_factors` * Parquet file. */ export function planAdjFactorsMetadataQuery(adjPath: string): PlannedAdjFactorsMetadataQuery { const validPath = validateAdjFactorsArtifactPath(adjPath, 'adjFactorsPath'); const sql = 'SELECT decode(key) AS key, decode(value) AS value ' + `FROM parquet_kv_metadata('${validPath}') ` + 'WHERE decode(key) LIKE ?'; return { path: validPath, sql, params: [`${ADJ_SNAPSHOT_KV_PREFIX}%`], }; } /** * Parses and strictly validates `stock_bot.adj_factors.*` Parquet footer * key-value metadata rows (matching `tools/curate-etl/src/curate_adj.rs`) * and binds the resulting metadata object to `adjPath`. */ export function parseAdjFactorsSnapshotMetadata( adjPath: string, kvRows: readonly TableRow[] ): AdjFactorsSnapshotMetadata { const validPath = validateAdjFactorsArtifactPath(adjPath, 'adjFactorsPath'); if (!Array.isArray(kvRows)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Expected an array of Parquet metadata rows for "${validPath}".`, validPath ); } let foundAny = false; let formatVersion: number | undefined; let snapshotKindStr: string | undefined; let asOfMicros: number | null | undefined; let vaultCutoffMicros: number | null | undefined; let rowsWritten: number | undefined; let snapshotChecksum: string | undefined; for (let i = 0; i < kvRows.length; i += 1) { const row = kvRows[i]; if (!isPlainRecord(row) || typeof row.key !== 'string') { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Malformed Parquet metadata row at index ${i} for "${validPath}".`, validPath ); } const key = row.key; if (!key.startsWith(ADJ_SNAPSHOT_KV_PREFIX)) { continue; } foundAny = true; const rawVal = row.value; if (typeof rawVal !== 'string') { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Missing or non-string value for metadata key "${key}" in "${validPath}".`, validPath ); } switch (key) { case KV_FORMAT_VERSION: { if (formatVersion !== undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Duplicate metadata key "${KV_FORMAT_VERSION}" in "${validPath}".`, validPath ); } if (!STRICT_UINT_RE.test(rawVal)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Invalid "${KV_FORMAT_VERSION}" value "${rawVal}" in "${validPath}".`, validPath ); } const parsed = Number(rawVal); if (!Number.isSafeInteger(parsed)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Out-of-range "${KV_FORMAT_VERSION}" value "${rawVal}" in "${validPath}".`, validPath ); } formatVersion = parsed; break; } case KV_SNAPSHOT_KIND: { if (snapshotKindStr !== undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Duplicate metadata key "${KV_SNAPSHOT_KIND}" in "${validPath}".`, validPath ); } snapshotKindStr = rawVal; break; } case KV_AS_OF_MICROS: { if (asOfMicros !== undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Duplicate metadata key "${KV_AS_OF_MICROS}" in "${validPath}".`, validPath ); } asOfMicros = parseOptionalMicrosKv(rawVal, KV_AS_OF_MICROS, validPath); break; } case KV_VAULT_CUTOFF_MICROS: { if (vaultCutoffMicros !== undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Duplicate metadata key "${KV_VAULT_CUTOFF_MICROS}" in "${validPath}".`, validPath ); } vaultCutoffMicros = parseOptionalMicrosKv(rawVal, KV_VAULT_CUTOFF_MICROS, validPath); break; } case KV_ROWS_WRITTEN: { if (rowsWritten !== undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Duplicate metadata key "${KV_ROWS_WRITTEN}" in "${validPath}".`, validPath ); } if (!STRICT_UINT_RE.test(rawVal)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Invalid "${KV_ROWS_WRITTEN}" value "${rawVal}" in "${validPath}".`, validPath ); } const parsed = Number(rawVal); if (!Number.isSafeInteger(parsed)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Out-of-range "${KV_ROWS_WRITTEN}" value "${rawVal}" in "${validPath}".`, validPath ); } rowsWritten = parsed; break; } case KV_SNAPSHOT_CHECKSUM: { if (snapshotChecksum !== undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Duplicate metadata key "${KV_SNAPSHOT_CHECKSUM}" in "${validPath}".`, validPath ); } if (!SNAPSHOT_CHECKSUM_RE.test(rawVal)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Invalid "${KV_SNAPSHOT_CHECKSUM}" value "${rawVal}" in "${validPath}". Expected 0x followed by 16 lowercase hex digits.`, validPath ); } snapshotChecksum = rawVal; break; } default: throw new AdjFactorsSnapshotError( 'invalid_metadata', `Unknown metadata key "${key}" in "${validPath}".`, validPath ); } } if (!foundAny) { throw new AdjFactorsSnapshotError( 'missing_metadata', `Missing "${ADJ_SNAPSHOT_KV_PREFIX}*" metadata in Parquet footer at "${validPath}" (refusing to read unverified adj_factors Parquet).`, validPath ); } if (formatVersion === undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Missing "${KV_FORMAT_VERSION}" in "${validPath}".`, validPath ); } if (formatVersion !== ADJ_SNAPSHOT_FORMAT_VERSION) { throw new AdjFactorsSnapshotError( 'unsupported_version', `Unsupported adj_factors snapshot metadata version ${formatVersion} at "${validPath}" (supported: ${ADJ_SNAPSHOT_FORMAT_VERSION}).`, validPath ); } if (snapshotKindStr === undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Missing "${KV_SNAPSHOT_KIND}" in "${validPath}".`, validPath ); } if (asOfMicros === undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Missing "${KV_AS_OF_MICROS}" in "${validPath}".`, validPath ); } if (vaultCutoffMicros === undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Missing "${KV_VAULT_CUTOFF_MICROS}" in "${validPath}".`, validPath ); } if (rowsWritten === undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Missing "${KV_ROWS_WRITTEN}" in "${validPath}".`, validPath ); } if (snapshotChecksum === undefined) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Missing "${KV_SNAPSHOT_CHECKSUM}" in "${validPath}".`, validPath ); } let snapshotKind: AdjFactorsSnapshotKind; if (snapshotKindStr === 'retrospective') { if (asOfMicros !== null || vaultCutoffMicros !== null) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Retrospective adj_factors snapshot at "${validPath}" must have 'none' for as_of_micros and vault_cutoff_micros.`, validPath ); } snapshotKind = 'retrospective'; } else if (snapshotKindStr === 'point_in_time_fenced') { if (asOfMicros === null && vaultCutoffMicros === null) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Fenced adj_factors snapshot at "${validPath}" must specify at least one of as_of_micros or vault_cutoff_micros.`, validPath ); } snapshotKind = 'point_in_time_fenced'; } else { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Unknown "${KV_SNAPSHOT_KIND}" value "${snapshotKindStr}" in "${validPath}".`, validPath ); } return { path: validPath, formatVersion, snapshotKind, fence: { asOfMicros, vaultCutoffMicros, }, rowsWritten, snapshotChecksum, }; } function effectiveSnapshotCeilingMicros(fence: AdjFactorsPointInTimeFence): number { const asOfCeiling = fence.asOfMicros; const vaultCeiling = fence.vaultCutoffMicros !== null ? fence.vaultCutoffMicros - 1 : null; if (asOfCeiling !== null && vaultCeiling !== null) { return Math.min(asOfCeiling, vaultCeiling); } if (asOfCeiling !== null) { return asOfCeiling; } if (vaultCeiling !== null) { return vaultCeiling; } throw new AdjFactorsSnapshotError( 'invalid_metadata', 'Fenced adj_factors snapshot must carry at least one non-null fence bound.' ); } /** * Verifies that `snapshot` is a well-formed, `point_in_time_fenced` * `adj_factors` artifact whose effective inclusive microsecond ceiling matches * the query's effective `asOf` and Vault fence, returning its validated * `.parquet` path so the SQL planner binds `read_parquet(...)` directly to the * verified file. */ function verifyAdjFactorsSnapshotForQuery( snapshot: AdjFactorsSnapshotMetadata | undefined, requiredAsOfMicros: number, requiredVaultCutoffMicros: number | null ): string { if (snapshot === undefined) { throw new AdjFactorsSnapshotError( 'missing_snapshot', 'Adjusted bars queries ("split" / "total") require a verified point_in_time_fenced adj_factors snapshot matching the query asOf and Vault fence.' ); } if (!isPlainRecord(snapshot)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', 'Expected an AdjFactorsSnapshotMetadata object for adjFactorsSnapshot.' ); } const validPath = validateAdjFactorsArtifactPath(snapshot.path, 'adjFactorsSnapshot.path'); if ( typeof snapshot.formatVersion !== 'number' || !Number.isSafeInteger(snapshot.formatVersion) ) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Invalid adj_factors snapshot formatVersion "${String(snapshot.formatVersion)}" at "${validPath}".`, validPath ); } if (snapshot.formatVersion !== ADJ_SNAPSHOT_FORMAT_VERSION) { throw new AdjFactorsSnapshotError( 'unsupported_version', `Unsupported adj_factors snapshot version ${snapshot.formatVersion} at "${validPath}" (supported: ${ADJ_SNAPSHOT_FORMAT_VERSION}).`, validPath ); } if ( typeof snapshot.rowsWritten !== 'number' || !Number.isSafeInteger(snapshot.rowsWritten) || snapshot.rowsWritten < 0 ) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Invalid adj_factors snapshot rowsWritten "${String(snapshot.rowsWritten)}" at "${validPath}".`, validPath ); } if ( typeof snapshot.snapshotChecksum !== 'string' || !SNAPSHOT_CHECKSUM_RE.test(snapshot.snapshotChecksum) ) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Invalid adj_factors snapshotChecksum "${String(snapshot.snapshotChecksum)}" at "${validPath}".`, validPath ); } if (snapshot.snapshotKind === 'retrospective') { throw new AdjFactorsSnapshotError( 'retrospective_rejected', `Refusing retrospective adj_factors snapshot at "${validPath}" for point-in-time adjusted bars query (cumulative factors may embed post-asOf or held-out Vault actions).`, validPath ); } if (snapshot.snapshotKind !== 'point_in_time_fenced') { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Unknown adj_factors snapshotKind "${String(snapshot.snapshotKind)}" at "${validPath}".`, validPath ); } if (!isPlainRecord(snapshot.fence)) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Missing fence object in adj_factors snapshot metadata at "${validPath}".`, validPath ); } const { asOfMicros, vaultCutoffMicros } = snapshot.fence; if ( (asOfMicros !== null && (typeof asOfMicros !== 'number' || !Number.isSafeInteger(asOfMicros))) || (vaultCutoffMicros !== null && (typeof vaultCutoffMicros !== 'number' || !Number.isSafeInteger(vaultCutoffMicros))) ) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Invalid microsecond fence bounds in adj_factors snapshot metadata at "${validPath}".`, validPath ); } if (asOfMicros === null && vaultCutoffMicros === null) { throw new AdjFactorsSnapshotError( 'invalid_metadata', `Fenced adj_factors snapshot at "${validPath}" has no non-null fence bounds.`, validPath ); } const actualCeiling = effectiveSnapshotCeilingMicros(snapshot.fence); if ( requiredVaultCutoffMicros !== null && actualCeiling >= requiredVaultCutoffMicros ) { throw new AdjFactorsSnapshotError( 'incompatible_fence', `adj_factors snapshot at "${validPath}" admits actions at or past Vault cutoff (${actualCeiling} >= ${requiredVaultCutoffMicros}).`, validPath ); } if (actualCeiling !== requiredAsOfMicros) { throw new AdjFactorsSnapshotError( 'incompatible_fence', `adj_factors snapshot at "${validPath}" has effective fence ceiling ${actualCeiling} µs, which does not match query effective asOf ${requiredAsOfMicros} µs.`, validPath ); } return validPath; } interface ValidatedBarsInputs { readonly curatedRoot: string; readonly adjustment: (typeof BARS_ADJUSTMENTS)[number]; readonly listingIds: number[]; readonly fenced: FencedTimeRange; readonly fromSubMs: number; readonly toSubMs: number; readonly asOfSubMs: number; } function validateBarsQueryInputs(q: BarsQuery, ctx: DuckDbPlanContext): ValidatedBarsInputs { const curatedRoot = validateContext(ctx); if (!isPlainRecord(q)) { throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); } 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 fromSubMs = resolveFromSubMsMicros(q.from); const toSubMs = resolveToSubMsMicros(q.to, fenced); const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); if (fenced.fromMs === fenced.toMs && fromSubMs > toSubMs) { throw new MarketDataStoreValidationError( `Query start "${q.from}" must not be after end "${q.to}".`, 'from' ); } return { curatedRoot, adjustment, listingIds, fenced, fromSubMs, toSubMs, asOfSubMs, }; } /** * Plans a fenced DuckDB SQL query for daily curated OHLCV bars (`bars_1d`) with * optional point-in-time `adj_factors` split or total-return adjustment. * * For `'split'` and `'total'`, `ctx.adjFactorsSnapshot` must supply verified * `point_in_time_fenced` Parquet footer metadata matching the query's effective * `asOf` and Vault fence; `read_parquet(...)` is bound directly to * `ctx.adjFactorsSnapshot.path`. */ export function planBars1dQuery(q: BarsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { const { curatedRoot, adjustment, listingIds, fenced, fromSubMs, toSubMs, asOfSubMs } = validateBarsQueryInputs(q, ctx); const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet'); const listingPlaceholders = buildPlaceholders(listingIds.length); 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 requiredAsOfMicros = toEpochMicros(fenced.asOfMs, asOfSubMs, 'asOf'); const requiredVaultCutoffMicros = fenced.scope === 'vault_fenced' ? toEpochMicros(ctx.vaultCutoffTs, 0, 'vaultCutoffTs') : null; const verifiedAdjPath = verifyAdjFactorsSnapshotForQuery( ctx.adjFactorsSnapshot, requiredAsOfMicros, requiredVaultCutoffMicros ); const priceDivisor = adjustment === 'split' ? 'COALESCE(a.cum_split_factor, 1.0)' : '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('${verifiedAdjPath}') WHERE listing_id IN (${listingPlaceholders}) AND known_at <= ?) AS a ` + 'ON b.listing_id = a.listing_id AND b.session_date < a.ex_date ' + `WHERE b.listing_id IN (${listingPlaceholders}) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ` + 'ORDER BY b.listing_id ASC, b.ts ASC'; 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`). * Preserves the Parquet writer's total sort order: * `(listing_id, ts, kind, subtype, payload_json, known_at, known_at_source)`. */ export function planEventsQuery(q: EventsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { const curatedRoot = validateContext(ctx); 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 fromSubMs = resolveFromSubMsMicros(q.from); const toSubMs = resolveToSubMsMicros(q.to, fenced); const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); if (fenced.fromMs === fenced.toMs && fromSubMs > toSubMs) { throw new MarketDataStoreValidationError( `Query start "${q.from}" must not be after end "${q.to}".`, 'from' ); } const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); const eventsPath = joinCuratedPath(curatedRoot, 'events/year=*/part.parquet'); const kindPlaceholders = buildPlaceholders(kinds.length); const orderBy = 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC'; if (listingIds !== undefined) { const listingPlaceholders = buildPlaceholders(listingIds.length); 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 <= ? ` + orderBy; 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 <= ? ` + orderBy; 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 asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); const fromDate = formatUtcDate(fenced.fromMs); const toDate = formatUtcDate(fenced.toMs); const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); 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 * 1000 - 1` µs. * Date-only `to` and clamped/default Vault upper bounds expand to the last * included Parquet microsecond (`23:59:59.999999Z`), matching `curate_fx_1d`'s * `23:59:59.999999Z` session timestamps. */ export function planFx1dQuery(q: FxQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { const curatedRoot = validateContext(ctx); 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 fromSubMs = resolveFromSubMsMicros(q.from); const toSubMs = resolveToSubMsMicros(q.to, fenced); const asOfSubMs = resolveAsOfSubMsMicros(undefined, q.to, fenced); if (fenced.fromMs === fenced.toMs && fromSubMs > toSubMs) { throw new MarketDataStoreValidationError( `Query start "${q.from}" must not be after end "${q.to}".`, 'from' ); } const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); const fxPath = joinCuratedPath(curatedRoot, 'fx_1d/part.parquet'); const sql = '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 }; } /** * Plans a Vault-fenced, survivorship-free DuckDB SQL query resolving active * listing IDs on `q.date` from curated `bars_1d` Parquet (`US_EQ`, `CA_EQ`, * `US_CA_EQ`). * * A listing is considered active on `q.date` when it has at least one `bars_1d` * row with `session_date` in `[date - lookbackDays, date]` (default `7` * calendar days), bounded by `b.ts <= ?` and `b.known_at <= ?` under * `'vault_fenced'` scope so no post-date or Vault rows can ever be read. */ export function planUniverseQuery(q: UniverseQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { const curatedRoot = validateContext(ctx); const lookbackDays = validateUniverseLookbackDays(ctx.universeLookbackDays); if (!isPlainRecord(q)) { throw new MarketDataStoreValidationError('Expected a universe query object.', 'query'); } const currencies = validateUniverseRef(q.ref); if (typeof q.date !== 'string' || !DATE_ONLY_RE.test(q.date)) { throw new MarketDataStoreValidationError( `Invalid universe date "${String(q.date)}". Expected a UTC calendar date in YYYY-MM-DD format.`, 'date' ); } let fencedDate: FencedTimeRange; try { fencedDate = applyVaultFence( { from: q.date, to: q.date, asOf: q.date, scope: 'vault_fenced', }, { vaultCutoffTs: ctx.vaultCutoffTs, } ); } catch (err: unknown) { if ( err instanceof MarketDataStoreValidationError && (err.field === 'from' || err.field === 'to' || err.field === 'asOf') ) { throw new MarketDataStoreValidationError(err.message, 'date'); } throw err; } const lookbackStartMs = fencedDate.fromMs - lookbackDays * MS_PER_DAY; if (!Number.isSafeInteger(lookbackStartMs) || lookbackStartMs < MIN_ISO_DATE_EPOCH_MS) { throw new MarketDataStoreValidationError( `Invalid universeLookbackDays "${lookbackDays}". Lookback start precedes supported YYYY-MM-DD UTC date range.`, 'universeLookbackDays' ); } const lookbackStartDate = formatUtcDate(lookbackStartMs); const endDate = formatUtcDate(fencedDate.toMs); const toIso = formatUtcIsoWithMicros(fencedDate.toMs, resolveToSubMsMicros(q.date, fencedDate)); const asOfIso = formatUtcIsoWithMicros( fencedDate.asOfMs, resolveAsOfSubMsMicros(q.date, q.date, fencedDate) ); const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet'); const currencyPredicate = currencies.length === 1 ? 'b.currency = ?' : `b.currency IN (${buildPlaceholders(currencies.length)})`; const sql = 'SELECT DISTINCT b.listing_id ' + `FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` + `WHERE ${currencyPredicate} AND b.session_date >= ? AND b.session_date <= ? AND b.ts <= ? AND b.known_at <= ? ` + 'ORDER BY b.listing_id ASC'; const params: DuckDbParam[] = [...currencies, lookbackStartDate, endDate, toIso, asOfIso]; return { sql, params, fenced: { ...fencedDate, fromMs: lookbackStartMs, }, }; } interface PlannedFundamentalsAsOfInternal { readonly planned: PlannedDuckDbQuery; readonly columns: readonly string[]; readonly schema: readonly TableColumnSpec[]; } function planFundamentalsAsOfInternal( q: FundamentalsAsOfQuery, ctx: DuckDbPlanContext ): PlannedFundamentalsAsOfInternal { const curatedRoot = validateContext(ctx); if (!isPlainRecord(q)) { throw new MarketDataStoreValidationError( 'Expected a fundamentalsAsOf query object.', 'query' ); } const listingIds = validateListingIds(q.listingIds); const fields = validateFundamentalsFields(q.fields); const allowEstimatedLag = validateAllowEstimatedLag(q.allowEstimatedLag); let fenced: FencedTimeRange; try { fenced = applyVaultFence( { from: q.asOf, to: q.asOf, asOf: q.asOf, scope: 'vault_fenced', }, { vaultCutoffTs: ctx.vaultCutoffTs, } ); } catch (err: unknown) { if (err instanceof VaultHoldoutFenceError) { const maxAllowedMs = ctx.vaultCutoffTs - 1; fenced = { fromMs: maxAllowedMs, toMs: maxAllowedMs, asOfMs: maxAllowedMs, scope: 'vault_fenced', clampedTo: true, clampedAsOf: true, }; } else if ( err instanceof MarketDataStoreValidationError && (err.field === 'from' || err.field === 'to') ) { throw new MarketDataStoreValidationError(err.message, 'asOf'); } else { throw err; } } const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.asOf, fenced); const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); const fundamentalsPath = joinCuratedPath(curatedRoot, 'fundamentals_pit/year=*/part.parquet'); const listingPlaceholders = buildPlaceholders(listingIds.length); let hasTtmField = false; for (const field of fields) { if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) { hasTtmField = true; break; } } const innerCols: string[] = [ 'f.listing_id', 'f.effective_known_at', 'f.known_at_source', 'f.has_estimated_lag', 'f.period_end', 'f.fiscal_period', 'f.currency', 'f.period_known_at', ]; const outerCols: string[] = [ 's.listing_id', 'epoch_ms(s.effective_known_at) AS effective_known_at', 's.known_at_source', 's.has_estimated_lag', 'CAST(s.period_end AS VARCHAR) AS period_end', 's.fiscal_period', 's.currency', 'epoch_ms(s.period_known_at) AS period_known_at', ]; const schema: TableColumnSpec[] = [...FUNDAMENTALS_BASE_SCHEMA]; for (const field of fields) { innerCols.push(`f.${field}`); if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) { outerCols.push( `CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.${field} ELSE NULL END AS ${field}` ); } else { outerCols.push(`s.${field}`); } schema.push({ name: field, kind: 'number', nullable: true }); } if (hasTtmField) { innerCols.push('f.ttm_period_end', 'f.ttm_currency', 'f.ttm_has_estimated_lag'); outerCols.push( 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end', 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency', 's.ttm_has_estimated_lag' ); schema.push(...FUNDAMENTALS_TTM_META_SCHEMA); } const columns = schema.map(spec => spec.name); const sql = `WITH latest AS (SELECT ${innerCols.join(', ')} ` + 'FROM read_parquet(?, hive_partitioning = true) AS f ' + `WHERE f.listing_id IN (${listingPlaceholders}) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ` + 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + `SELECT ${outerCols.join(', ')} ` + 'FROM latest AS s ' + 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + 'ORDER BY s.listing_id ASC'; const params: DuckDbParam[] = [fundamentalsPath, ...listingIds, asOfIso, allowEstimatedLag]; return { planned: { sql, params, fenced }, columns, schema, }; } /** * Plans a Vault-fenced point-in-time DuckDB SQL query over curated * `fundamentals_pit/year=*\/part.parquet` snapshots. * * Selects at most one snapshot per requested `listing_id` — the latest with * `effective_known_at <= asOf` (clamped strictly below `vaultCutoffTs`). When * `allowEstimatedLag` is `false`, listings whose selected snapshot has * `has_estimated_lag = true` are omitted without falling back to an older * snapshot, and requested `ttm_*` value fields plus `ttm_period_end` / * `ttm_currency` are masked to `NULL` when `ttm_has_estimated_lag` is `true` * while preserving `ttm_has_estimated_lag`. */ export function planFundamentalsAsOfQuery( q: FundamentalsAsOfQuery, ctx: DuckDbPlanContext ): PlannedDuckDbQuery { return planFundamentalsAsOfInternal(q, ctx).planned; } function readRequiredInt32(row: Record, key: string, rowIndex: number): number { const val = row[key]; if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) { 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 readValidatedTableCell( row: Record, spec: TableColumnSpec, rowIndex: number ): TableCell { const val = row[spec.name]; if (val === null) { if (spec.nullable) { return null; } throw new MarketDataStoreValidationError( `Unexpected null for non-nullable column "${spec.name}" in result row ${rowIndex}.`, spec.name ); } switch (spec.kind) { case 'int32': if ( typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX ) { throw new MarketDataStoreValidationError( `Expected INT32 for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, spec.name ); } return val === 0 ? 0 : val; case 'safe_int': if (typeof val !== 'number' || !Number.isSafeInteger(val)) { throw new MarketDataStoreValidationError( `Expected integer timestamp for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, spec.name ); } return val === 0 ? 0 : val; case 'number': if (typeof val !== 'number' || !Number.isFinite(val)) { throw new MarketDataStoreValidationError( `Expected finite number for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, spec.name ); } return val === 0 ? 0 : val; case 'string': if (typeof val !== 'string') { throw new MarketDataStoreValidationError( `Expected string for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, spec.name ); } return val; case 'boolean': if (typeof val !== 'boolean') { throw new MarketDataStoreValidationError( `Expected boolean for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, spec.name ); } return val; } } function mapTableRows( columns: readonly string[], schema: readonly TableColumnSpec[], rows: readonly TableRow[] ): Table { if (!Array.isArray(rows)) { throw new MarketDataStoreValidationError('Executor returned a non-array table result.', 'rows'); } 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 spec of schema) { if (!Object.prototype.hasOwnProperty.call(raw, spec.name)) { throw new MarketDataStoreValidationError( `Missing expected column "${spec.name}" in result row ${i}.`, spec.name ); } cleanRow[spec.name] = readValidatedTableCell(raw, spec, i); } mappedRows[i] = cleanRow; } return { columns: [...columns], rows: mappedRows, }; } function mapUniverseRows(rows: readonly TableRow[]): number[] { if (!Array.isArray(rows)) { throw new MarketDataStoreValidationError( 'Executor returned a non-array universe result.', 'rows' ); } const out: number[] = new Array(rows.length); let prev: number | undefined; for (let i = 0; i < rows.length; i += 1) { const raw = rows[i]; if (!isPlainRecord(raw)) { throw new MarketDataStoreValidationError( `Executor returned a non-object universe row at index ${i}.`, 'rows' ); } if (!Object.prototype.hasOwnProperty.call(raw, 'listing_id')) { throw new MarketDataStoreValidationError( `Missing expected column "listing_id" in universe result row ${i}.`, 'listing_id' ); } const id = readRequiredInt32(raw, 'listing_id', i); if (prev !== undefined) { if (id === prev) { throw new MarketDataStoreValidationError( `Duplicate listing_id ${id} in universe result row ${i}.`, 'listing_id' ); } if (id < prev) { throw new MarketDataStoreValidationError( `Unsorted listing_id ${id} after ${prev} in universe result row ${i}. Expected strictly ascending order.`, 'listing_id' ); } } prev = id; out[i] = id; } return out; } /** * 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 validates cleanly * and strictly before the first `executor.query(...)` call. * * 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)) { 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 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') : 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 ( 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 universeLookbackDays = validateUniverseLookbackDays( options.universeLookbackDays, vaultCutoffTs ); const budget = resolveDuckDbConnectionBudget(options.env); const planCtx: DuckDbPlanContext = { curatedRoot, vaultCutoffTs: vaultCutoffTs === 0 ? 0 : vaultCutoffTs, vaultOperatorAuthorized: options.vaultOperatorAuthorized, universeLookbackDays, }; 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; } 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 rawRows: readonly TableRow[]; if (q.adjustment === 'split' || q.adjustment === 'total') { // Validate timeframe, listingIds, adjustment, and Vault fence before any executor/pinner call. validateBarsQueryInputs(q, planCtx); 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 pin = rawPin as unknown as PinnedAdjFactorsArtifact; try { const pinnedPath = validateAdjFactorsArtifactPath( pin.pinnedPath, '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 pin.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 { const planned = planBars1dQuery(q, planCtx); await ensureBudgetInitialized(); 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, EVENTS_SCHEMA, rawRows); }, async shortsAsOf(q: ShortsAsOfQuery): Promise
{ const planned = planShortsAsOfQuery(q, planCtx); await ensureBudgetInitialized(); const rawRows = await typedExecutor.query(planned.sql, planned.params); return mapTableRows(SHORTS_COLUMNS, SHORTS_SCHEMA, rawRows); }, async fx(q: FxQuery): Promise
{ const planned = planFx1dQuery(q, planCtx); await ensureBudgetInitialized(); const rawRows = await typedExecutor.query(planned.sql, planned.params); return mapTableRows(FX_1D_COLUMNS, FX_1D_SCHEMA, rawRows); }, crossSection(): Promise
{ return Promise.reject(new MarketDataStoreNotImplementedError('crossSection')); }, async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ const { planned, columns, schema } = planFundamentalsAsOfInternal(q, planCtx); await ensureBudgetInitialized(); const rawRows = await typedExecutor.query(planned.sql, planned.params); return mapTableRows(columns, schema, rawRows); }, macroAsOf(): Promise
{ return Promise.reject(new MarketDataStoreNotImplementedError('macroAsOf')); }, async universe(q: UniverseQuery): Promise { const planned = planUniverseQuery(q, planCtx); await ensureBudgetInitialized(); const rawRows = await typedExecutor.query(planned.sql, planned.params); return mapUniverseRows(rawRows); }, }; }