/** * `MarketDataStore` contract (`design/DATA-CONTRACTS.md` §4), rolling 6-month * UTC Vault holdout fence (`design/VALIDATION-AND-RIGOR.md` §3.3), and * per-connection DuckDB resource budget (`design/DATA-CONTRACTS.md` §3.A). * * This module is intentionally pure, dependency-free, and browser-safe (no * `node:*` imports, no bare `process` global, no database or filesystem I/O) * so both server adapters and shared browser packages can import it. * * Provisional supporting types: * - `design/DATA-CONTRACTS.md` §4 names `BarBatch`, `Table`, `UniverseRef`, * and `EventKind` without fixing their full wire shapes. The definitions * below are minimal provisional shapes; `listing_id` / `listingIds` use * JavaScript `number` (matching Parquet `INT32`). * * Contract interpretation note for `applyVaultFence`: * - `design/DATA-CONTRACTS.md` §4 specifies that non-vault queries clamp `to` * and `asOf` to `< VAULT_CUTOFF_TS` and reject `from >= VAULT_CUTOFF_TS` * with `VaultHoldoutFenceError`. * - All bounds are interpreted as inclusive UTC instants in integer epoch * milliseconds. * - Date-only `YYYY-MM-DD` strings expand in UTC to `00:00:00.000Z` for `from` * (and `computeVaultCutoffTs`) and to `23:59:59.999Z` for `to` and `asOf`. * - Full ISO-8601 timestamps must carry an explicit UTC offset (`Z` or * `±HH:MM`); naive datetimes without a timezone are rejected. Fractional * seconds finer than milliseconds are truncated toward zero to integer ms. * - Under `'vault_fenced'` (the default when `scope` is omitted): * - `fromMs >= vaultCutoffTs` throws `VaultHoldoutFenceError`. * - `toMs >= vaultCutoffTs` clamps to `vaultCutoffTs - 1` (`clampedTo: true`). * - `asOfMs >= vaultCutoffTs` clamps to `vaultCutoffTs - 1` (`clampedAsOf: true`). * - Omitted `asOf` resolves to `vaultCutoffTs - 1` (`clampedAsOf: false`) so * adapters always enforce a bounded `known_at <= asOf` predicate. * - Under `'vault_evaluation_only'`: * - Fails closed with `VaultScopeNotAuthorizedError` unless * `ctx.vaultOperatorAuthorized === true`. * - When authorized, no Vault clamping is applied and omitted `asOf` * defaults to `toMs`. */ const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/; const ISO_INSTANT_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/; const DUCKDB_MEMORY_LIMIT_PATTERN = /^(\d+(?:\.\d+)?)(MB|GB|MiB|GiB)$/; const DUCKDB_THREADS_PATTERN = /^[1-9]\d*$/; const MIN_DUCKDB_THREADS = 1; const MAX_DUCKDB_THREADS = 64; export const DEFAULT_DUCKDB_MEMORY_LIMIT = '6GB'; export const DEFAULT_DUCKDB_THREADS = 4; export const DEFAULT_DUCKDB_TEMP_DIRECTORY = '/mnt/data/stockbot/tmp/duckdb'; export type DataScope = 'vault_fenced' | 'vault_evaluation_only'; /** Provisional event kinds referenced by `MarketDataStore.events` (§4). */ export type EventKind = 'filing' | 'earnings' | 'ceo_post' | 'corporate_action'; /** Provisional universe identifier referenced by `MarketDataStore` (§4). */ export type UniverseRef = string; /** Provisional OHLCV bar record for `BarBatch` (`listingId` is `INT32`). */ export interface BarRecord { readonly listingId: number; readonly ts: number; readonly open: number; readonly high: number; readonly low: number; readonly close: number; readonly volume: number; readonly vwap?: number | null; readonly knownAt: number; } /** Provisional batch yielded by `MarketDataStore.bars` (§4). */ export interface BarBatch { readonly rows: readonly BarRecord[]; } /** Provisional scalar cell value for tabular `MarketDataStore` results (§4). */ export type TableCell = string | number | boolean | null; /** Provisional row map for tabular `MarketDataStore` results (§4). */ export type TableRow = Readonly>; /** Provisional tabular result returned by `MarketDataStore` methods (§4). */ export interface Table { readonly columns: readonly string[]; readonly rows: readonly TableRow[]; } /** * Unified read contract for curated daily/PIT (DuckDB + Parquet) and intraday * (QuestDB) market data (`design/DATA-CONTRACTS.md` §4). */ export interface MarketDataStore { bars(q: { listingIds: number[]; timeframe: '1m' | '5m' | '1h' | '1d'; from: string; to: string; adjustment: 'raw' | 'split' | 'total'; asOf?: string; scope?: DataScope; }): AsyncIterable; crossSection(q: { features: string[]; date: string; universe: UniverseRef; asOf?: string; }): Promise; fundamentalsAsOf(q: { listingIds: number[]; fields: string[]; asOf: string; allowEstimatedLag?: boolean; }): Promise
; events(q: { kinds: EventKind[]; listingIds?: number[]; from: string; to: string; asOf?: string; }): Promise
; shortsAsOf(q: { listingIds: number[]; from: string; to: string; asOf?: string }): Promise
; macroAsOf(q: { countries: string[]; indicators: string[]; from: string; to: string; asOf?: string; }): Promise
; fx(q: { pair: 'USD.CAD'; timeframe: '1m' | '1d'; from: string; to: string }): Promise
; universe(q: { ref: UniverseRef; date: string }): Promise; } export interface VaultFenceQuery { readonly from: string; readonly to: string; readonly asOf?: string; readonly scope?: DataScope; } export interface VaultFenceContext { readonly vaultCutoffTs: number; readonly vaultOperatorAuthorized?: boolean; } export interface FencedTimeRange { readonly fromMs: number; readonly toMs: number; readonly asOfMs: number; readonly scope: DataScope; readonly clampedTo: boolean; readonly clampedAsOf: boolean; } export interface DuckDbConnectionBudget { readonly memoryLimit: string; readonly threads: number; readonly tempDirectory: string; readonly statements: string[]; } /** Thrown when market-data query bounds, timestamps, or DuckDB budget inputs are invalid. */ export class MarketDataStoreValidationError extends Error { override readonly name = 'MarketDataStoreValidationError'; readonly field?: string; constructor(message: string, field?: string) { super(message); this.field = field; Object.setPrototypeOf(this, new.target.prototype); } } /** Thrown when a fenced query starts at or after the rolling 6-month Vault cutoff. */ export class VaultHoldoutFenceError extends Error { override readonly name = 'VaultHoldoutFenceError'; readonly from: string; readonly fromMs: number; readonly vaultCutoffTs: number; constructor(from: string, fromMs: number, vaultCutoffTs: number, message?: string) { super( message ?? `Query start "${from}" (${fromMs}) reaches or exceeds Vault cutoff (${vaultCutoffTs}).` ); this.from = from; this.fromMs = fromMs; this.vaultCutoffTs = vaultCutoffTs; Object.setPrototypeOf(this, new.target.prototype); } } /** Thrown when `'vault_evaluation_only'` is requested without explicit operator authorization. */ export class VaultScopeNotAuthorizedError extends Error { override readonly name = 'VaultScopeNotAuthorizedError'; constructor(message?: string) { super( message ?? "Data scope 'vault_evaluation_only' requires explicit human operator authorization." ); Object.setPrototypeOf(this, new.target.prototype); } } function isLeapYear(year: number): boolean { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function daysInUtcMonth(year: number, monthIndex: number): number { if (monthIndex === 1 && isLeapYear(year)) { return 29; } const days = DAYS_IN_MONTH[monthIndex]; if (days === undefined) { throw new MarketDataStoreValidationError(`Invalid UTC month index: ${monthIndex}.`); } return days; } function utcDateMs( year: number, monthIndex: number, day: number, hours: number, minutes: number, seconds: number, ms: number ): number { if (year >= 0 && year <= 99) { const date = new Date(0); date.setUTCFullYear(year, monthIndex, day); date.setUTCHours(hours, minutes, seconds, ms); return date.getTime(); } return Date.UTC(year, monthIndex, day, hours, minutes, seconds, ms); } function validateEpochMs(value: number, field: string): number { if ( typeof value !== 'number' || !Number.isFinite(value) || !Number.isSafeInteger(value) || Math.abs(value) > MAX_ECMASCRIPT_EPOCH_MS ) { throw new MarketDataStoreValidationError( `Invalid epoch millisecond timestamp for "${field}": ${String(value)}.`, field ); } return value === 0 ? 0 : value; } function parseTimestampMs(raw: string, boundKind: 'start' | 'end', field: string): number { if (typeof raw !== 'string' || raw.length === 0) { throw new MarketDataStoreValidationError( `Expected a non-empty ISO-8601 date or timestamp for "${field}".`, field ); } const dateMatch = DATE_ONLY_PATTERN.exec(raw); if (dateMatch !== null) { const year = Number(dateMatch[1]); const month = Number(dateMatch[2]); const day = Number(dateMatch[3]); if (month < 1 || month > 12) { throw new MarketDataStoreValidationError( `Invalid calendar month in "${field}": "${raw}".`, field ); } const maxDay = daysInUtcMonth(year, month - 1); if (day < 1 || day > maxDay) { throw new MarketDataStoreValidationError( `Invalid calendar day in "${field}": "${raw}".`, field ); } const ms = boundKind === 'start' ? utcDateMs(year, month - 1, day, 0, 0, 0, 0) : utcDateMs(year, month - 1, day, 23, 59, 59, 999); return validateEpochMs(ms, field); } const instantMatch = ISO_INSTANT_PATTERN.exec(raw); if (instantMatch !== null) { const year = Number(instantMatch[1]); const month = Number(instantMatch[2]); const day = Number(instantMatch[3]); const hours = Number(instantMatch[4]); const minutes = Number(instantMatch[5]); const seconds = Number(instantMatch[6]); const fractional = instantMatch[7]; const tzToken = instantMatch[8]; const tzSign = instantMatch[9]; const tzHoursRaw = instantMatch[10]; const tzMinutesRaw = instantMatch[11]; if (month < 1 || month > 12) { throw new MarketDataStoreValidationError( `Invalid calendar month in "${field}": "${raw}".`, field ); } const maxDay = daysInUtcMonth(year, month - 1); if (day < 1 || day > maxDay) { throw new MarketDataStoreValidationError( `Invalid calendar day in "${field}": "${raw}".`, field ); } if (hours > 23 || minutes > 59 || seconds > 59) { throw new MarketDataStoreValidationError( `Invalid time-of-day in "${field}": "${raw}".`, field ); } let ms = 0; if (fractional !== undefined) { const msDigits = fractional.slice(0, 3).padEnd(3, '0'); ms = Number(msDigits); } let offsetMs = 0; if (tzToken !== 'Z') { const offsetHours = Number(tzHoursRaw); const offsetMinutes = Number(tzMinutesRaw); if (offsetHours > 23 || offsetMinutes > 59) { throw new MarketDataStoreValidationError( `Invalid timezone offset in "${field}": "${raw}".`, field ); } const sign = tzSign === '+' ? 1 : -1; offsetMs = sign * (offsetHours * 60 + offsetMinutes) * 60_000; } const epochMs = utcDateMs(year, month - 1, day, hours, minutes, seconds, ms) - offsetMs; return validateEpochMs(epochMs, field); } throw new MarketDataStoreValidationError( `Invalid ISO-8601 date or UTC timestamp for "${field}": "${raw}".`, field ); } /** * Computes the rolling 6-month Vault cutoff (`maxIngestedTs - 6 calendar months` * in UTC). Month-end dates clamp to the last day of the target month while * preserving the UTC time-of-day. */ export function computeVaultCutoffTs(maxIngestedTs: number | string | Date): number { let epochMs: number; if (typeof maxIngestedTs === 'number') { epochMs = validateEpochMs(maxIngestedTs, 'maxIngestedTs'); } else if (typeof maxIngestedTs === 'string') { epochMs = parseTimestampMs(maxIngestedTs, 'start', 'maxIngestedTs'); } else if (maxIngestedTs instanceof Date) { epochMs = validateEpochMs(maxIngestedTs.getTime(), 'maxIngestedTs'); } else { throw new MarketDataStoreValidationError( 'Invalid `maxIngestedTs`: expected a finite integer epoch-ms, ISO-8601 string, or Date.', 'maxIngestedTs' ); } const date = new Date(epochMs); const year = date.getUTCFullYear(); const month = date.getUTCMonth(); const day = date.getUTCDate(); const hours = date.getUTCHours(); const minutes = date.getUTCMinutes(); const seconds = date.getUTCSeconds(); const ms = date.getUTCMilliseconds(); const totalMonths = year * 12 + month - 6; const targetYear = Math.floor(totalMonths / 12); const targetMonth = ((totalMonths % 12) + 12) % 12; const targetDay = Math.min(day, daysInUtcMonth(targetYear, targetMonth)); const cutoffMs = utcDateMs(targetYear, targetMonth, targetDay, hours, minutes, seconds, ms); return validateEpochMs(cutoffMs, 'maxIngestedTs'); } /** * Enforces the rolling 6-month Vault holdout fence and normalizes query time * bounds to inclusive UTC epoch milliseconds before an adapter builds SQL. */ export function applyVaultFence(query: VaultFenceQuery, ctx: VaultFenceContext): FencedTimeRange { const cutoffMs = validateEpochMs(ctx.vaultCutoffTs, 'vaultCutoffTs'); if (cutoffMs <= -MAX_ECMASCRIPT_EPOCH_MS) { throw new MarketDataStoreValidationError( `Vault cutoff timestamp is out of representable range: ${cutoffMs}.`, 'vaultCutoffTs' ); } const rawScope: unknown = query.scope; let scope: DataScope; if (rawScope === undefined) { scope = 'vault_fenced'; } else if (rawScope === 'vault_fenced' || rawScope === 'vault_evaluation_only') { scope = rawScope; } else { throw new MarketDataStoreValidationError( `Unknown DataScope "${String(rawScope)}". Expected 'vault_fenced' or 'vault_evaluation_only'.`, 'scope' ); } if (scope === 'vault_evaluation_only' && ctx.vaultOperatorAuthorized !== true) { throw new VaultScopeNotAuthorizedError(); } const fromMs = parseTimestampMs(query.from, 'start', 'from'); const toMs = parseTimestampMs(query.to, 'end', 'to'); const parsedAsOfMs = query.asOf !== undefined ? parseTimestampMs(query.asOf, 'end', 'asOf') : undefined; if (fromMs > toMs) { throw new MarketDataStoreValidationError( `Query start "${query.from}" (${fromMs}) must not be after end "${query.to}" (${toMs}).`, 'from' ); } if (scope === 'vault_evaluation_only') { return { fromMs, toMs, asOfMs: parsedAsOfMs ?? toMs, scope, clampedTo: false, clampedAsOf: false, }; } if (fromMs >= cutoffMs) { throw new VaultHoldoutFenceError(query.from, fromMs, cutoffMs); } const maxAllowedMs = cutoffMs - 1; const clampedTo = toMs >= cutoffMs; const effectiveToMs = clampedTo ? maxAllowedMs : toMs; const clampedAsOf = parsedAsOfMs !== undefined && parsedAsOfMs >= cutoffMs; const effectiveAsOfMs = parsedAsOfMs === undefined ? maxAllowedMs : clampedAsOf ? maxAllowedMs : parsedAsOfMs; return { fromMs, toMs: effectiveToMs, asOfMs: effectiveAsOfMs, scope, clampedTo, clampedAsOf, }; } function readDefaultEnv(): Readonly> { const globalRecord = globalThis as { process?: { env?: Readonly> }; }; return globalRecord.process?.env ?? {}; } function hasForbiddenTempDirChar(value: string): boolean { for (let i = 0; i < value.length; i += 1) { const code = value.charCodeAt(i); if (code <= 0x1f || code === 0x7f || code === 0x27 || code === 0x3b) { return true; } } return false; } /** * Resolves and strictly validates per-connection DuckDB budget settings from * environment variables (`STOCKBOT_DUCKDB_MEMORY_LIMIT`, * `STOCKBOT_DUCKDB_THREADS`, `STOCKBOT_DUCKDB_TEMP_DIRECTORY`), returning the * exact `SET` SQL statements to execute at connection open. */ export function resolveDuckDbConnectionBudget( env?: Readonly> ): DuckDbConnectionBudget { const sourceEnv = env ?? readDefaultEnv(); const rawMemoryLimit = sourceEnv.STOCKBOT_DUCKDB_MEMORY_LIMIT; let memoryLimit = DEFAULT_DUCKDB_MEMORY_LIMIT; if (rawMemoryLimit !== undefined) { const match = DUCKDB_MEMORY_LIMIT_PATTERN.exec(rawMemoryLimit); const amount = match !== null ? Number(match[1]) : Number.NaN; if (match === null || !Number.isFinite(amount) || amount <= 0) { throw new MarketDataStoreValidationError( `Invalid STOCKBOT_DUCKDB_MEMORY_LIMIT "${rawMemoryLimit}". Expected a positive number followed by MB, GB, MiB, or GiB.`, 'STOCKBOT_DUCKDB_MEMORY_LIMIT' ); } memoryLimit = rawMemoryLimit; } const rawThreads = sourceEnv.STOCKBOT_DUCKDB_THREADS; let threads = DEFAULT_DUCKDB_THREADS; if (rawThreads !== undefined) { const parsedThreads = DUCKDB_THREADS_PATTERN.test(rawThreads) ? Number(rawThreads) : Number.NaN; if ( !Number.isSafeInteger(parsedThreads) || parsedThreads < MIN_DUCKDB_THREADS || parsedThreads > MAX_DUCKDB_THREADS ) { throw new MarketDataStoreValidationError( `Invalid STOCKBOT_DUCKDB_THREADS "${rawThreads}". Expected an integer between ${MIN_DUCKDB_THREADS} and ${MAX_DUCKDB_THREADS}.`, 'STOCKBOT_DUCKDB_THREADS' ); } threads = parsedThreads; } const rawTempDir = sourceEnv.STOCKBOT_DUCKDB_TEMP_DIRECTORY; let tempDirectory = DEFAULT_DUCKDB_TEMP_DIRECTORY; if (rawTempDir !== undefined) { if ( rawTempDir.length === 0 || !rawTempDir.startsWith('/') || hasForbiddenTempDirChar(rawTempDir) ) { throw new MarketDataStoreValidationError( `Invalid STOCKBOT_DUCKDB_TEMP_DIRECTORY "${rawTempDir}". Expected an absolute path without quotes, semicolons, or control characters.`, 'STOCKBOT_DUCKDB_TEMP_DIRECTORY' ); } tempDirectory = rawTempDir; } return { memoryLimit, threads, tempDirectory, statements: [ `SET memory_limit = '${memoryLimit}';`, `SET threads = ${threads};`, `SET temp_directory = '${tempDirectory}';`, ], }; }