diff --git a/libs/research/package.json b/libs/research/package.json index 5c40161b..d4190a7f 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -10,11 +10,13 @@ ".": "./src/index.ts", "./dataset-contracts": "./src/dataset-contracts.ts", "./datasets": "./src/datasets.ts", + "./market-data-store": "./src/market-data-store.ts", "./results": "./src/results.ts", "./strategy-api": "./src/strategy-api.ts" }, "scripts": { - "build": "tsc" + "build": "tsc", + "test": "bun test" }, "dependencies": { "@stock-bot/types": "workspace:*", diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index 94c42ab2..c979d987 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -1,2 +1,3 @@ // The default entrypoint is browser safe; server validation is an explicit subpath. export * from './dataset-contracts'; +export * from './market-data-store'; diff --git a/libs/research/src/market-data-store.ts b/libs/research/src/market-data-store.ts new file mode 100644 index 00000000..4e13dc96 --- /dev/null +++ b/libs/research/src/market-data-store.ts @@ -0,0 +1,555 @@ +/** + * `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}';`, + ], + }; +} diff --git a/libs/research/test/market-data-store.test.ts b/libs/research/test/market-data-store.test.ts new file mode 100644 index 00000000..36378423 --- /dev/null +++ b/libs/research/test/market-data-store.test.ts @@ -0,0 +1,447 @@ +import { describe, expect, it } from 'bun:test'; +import { + applyVaultFence, + computeVaultCutoffTs, + DEFAULT_DUCKDB_MEMORY_LIMIT, + DEFAULT_DUCKDB_TEMP_DIRECTORY, + DEFAULT_DUCKDB_THREADS, + MarketDataStoreValidationError, + resolveDuckDbConnectionBudget, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, +} from '@stock-bot/research'; +import { + applyVaultFence as subpathApplyVaultFence, + computeVaultCutoffTs as subpathComputeVaultCutoffTs, + resolveDuckDbConnectionBudget as subpathResolveDuckDbConnectionBudget, +} from '@stock-bot/research/market-data-store'; + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function formatUtcDateOnly(epochMs: number): string { + return new Date(epochMs).toISOString().slice(0, 10); +} + +describe('market-data-store exports', () => { + it('exposes identical runtime functions from package root and subpath', () => { + expect(computeVaultCutoffTs).toBe(subpathComputeVaultCutoffTs); + expect(applyVaultFence).toBe(subpathApplyVaultFence); + expect(resolveDuckDbConnectionBudget).toBe(subpathResolveDuckDbConnectionBudget); + }); +}); + +describe('computeVaultCutoffTs', () => { + it('subtracts 6 calendar months in UTC for standard dates', () => { + expect(computeVaultCutoffTs('2026-11-28T00:00:00Z')).toBe(Date.UTC(2026, 4, 28, 0, 0, 0, 0)); + expect(computeVaultCutoffTs('2026-11-28')).toBe(Date.UTC(2026, 4, 28, 0, 0, 0, 0)); + }); + + it('clamps month-end dates to the last day of the target month, including leap years', () => { + expect(computeVaultCutoffTs('2026-08-31')).toBe(Date.UTC(2026, 1, 28, 0, 0, 0, 0)); + expect(computeVaultCutoffTs('2024-08-31')).toBe(Date.UTC(2024, 1, 29, 0, 0, 0, 0)); + expect(computeVaultCutoffTs('2026-10-31')).toBe(Date.UTC(2026, 3, 30, 0, 0, 0, 0)); + }); + + it('crosses year boundaries correctly', () => { + expect(computeVaultCutoffTs('2026-01-15')).toBe(Date.UTC(2025, 6, 15, 0, 0, 0, 0)); + expect(computeVaultCutoffTs('2026-06-30')).toBe(Date.UTC(2025, 11, 30, 0, 0, 0, 0)); + }); + + it('preserves exact UTC time-of-day across month-end clamping', () => { + expect(computeVaultCutoffTs('2026-08-31T14:35:22.789Z')).toBe( + Date.UTC(2026, 1, 28, 14, 35, 22, 789) + ); + }); + + it('accepts integer epoch-ms numbers and valid Date instances', () => { + const inputMs = Date.UTC(2026, 10, 28, 13, 45, 59, 123); + const expectedMs = Date.UTC(2026, 4, 28, 13, 45, 59, 123); + expect(computeVaultCutoffTs(inputMs)).toBe(expectedMs); + expect(computeVaultCutoffTs(new Date(inputMs))).toBe(expectedMs); + }); + + it('rejects invalid, non-finite, non-integer, and naive inputs with MarketDataStoreValidationError', () => { + const invalidInputs: Array = [ + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + Date.UTC(2026, 4, 28) + 0.5, + '', + 'not-a-date', + '2026-02-29', + '2026-05-01T12:00:00', + new Date('invalid'), + ]; + + for (const input of invalidInputs) { + expect(() => computeVaultCutoffTs(input)).toThrow(MarketDataStoreValidationError); + } + }); +}); + +describe('applyVaultFence', () => { + const cutoffMs = Date.UTC(2026, 4, 28, 0, 0, 0, 0); + + it('defaults omitted scope to vault_fenced and passes fully pre-cutoff queries unclamped', () => { + const result = applyVaultFence( + { + from: '2025-01-01T00:00:00Z', + to: '2026-05-27T23:59:59.999Z', + asOf: '2026-05-27T23:59:59.999Z', + }, + { vaultCutoffTs: cutoffMs } + ); + + expect(result).toEqual({ + fromMs: Date.UTC(2025, 0, 1, 0, 0, 0, 0), + toMs: cutoffMs - 1, + asOfMs: cutoffMs - 1, + scope: 'vault_fenced', + clampedTo: false, + clampedAsOf: false, + }); + }); + + it('throws VaultHoldoutFenceError when from >= cutoff (strictly greater or equal)', () => { + for (const from of ['2026-05-28T00:00:00Z', '2026-05-28', '2026-06-01T00:00:00Z']) { + let caught: unknown; + try { + applyVaultFence({ from, to: '2026-07-01T00:00:00Z' }, { vaultCutoffTs: cutoffMs }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(VaultHoldoutFenceError); + const fenceErr = caught as VaultHoldoutFenceError; + expect(fenceErr.from).toBe(from); + expect(fenceErr.vaultCutoffTs).toBe(cutoffMs); + expect(fenceErr.fromMs).toBeGreaterThanOrEqual(cutoffMs); + } + }); + + it('clamps to >= cutoff and asOf >= cutoff to cutoffMs - 1', () => { + const atCutoff = applyVaultFence( + { + from: '2026-01-01T00:00:00Z', + to: '2026-05-28T00:00:00Z', + asOf: '2026-05-28T00:00:00Z', + }, + { vaultCutoffTs: cutoffMs } + ); + expect(atCutoff.toMs).toBe(cutoffMs - 1); + expect(atCutoff.asOfMs).toBe(cutoffMs - 1); + expect(atCutoff.clampedTo).toBe(true); + expect(atCutoff.clampedAsOf).toBe(true); + + const pastCutoff = applyVaultFence( + { + from: '2026-01-01', + to: '2026-11-28', + asOf: '2026-11-28', + }, + { vaultCutoffTs: cutoffMs } + ); + expect(pastCutoff.toMs).toBe(cutoffMs - 1); + expect(pastCutoff.asOfMs).toBe(cutoffMs - 1); + expect(pastCutoff.clampedTo).toBe(true); + expect(pastCutoff.clampedAsOf).toBe(true); + }); + + it('defaults omitted asOf in vault_fenced scope to cutoffMs - 1 with clampedAsOf=false', () => { + const result = applyVaultFence( + { + from: '2026-01-01', + to: '2026-03-01', + }, + { vaultCutoffTs: cutoffMs } + ); + expect(result.asOfMs).toBe(cutoffMs - 1); + expect(result.clampedTo).toBe(false); + expect(result.clampedAsOf).toBe(false); + }); + + it('fails closed on vault_evaluation_only unless vaultOperatorAuthorized is true', () => { + expect(() => + applyVaultFence( + { + from: '2026-05-28', + to: '2026-11-28', + scope: 'vault_evaluation_only', + }, + { vaultCutoffTs: cutoffMs } + ) + ).toThrow(VaultScopeNotAuthorizedError); + + expect(() => + applyVaultFence( + { + from: '2026-05-28', + to: '2026-11-28', + scope: 'vault_evaluation_only', + }, + { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: false } + ) + ).toThrow(VaultScopeNotAuthorizedError); + + const authorized = applyVaultFence( + { + from: '2026-05-28', + to: '2026-11-28', + scope: 'vault_evaluation_only', + }, + { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: true } + ); + expect(authorized).toEqual({ + fromMs: Date.UTC(2026, 4, 28, 0, 0, 0, 0), + toMs: Date.UTC(2026, 10, 28, 23, 59, 59, 999), + asOfMs: Date.UTC(2026, 10, 28, 23, 59, 59, 999), + scope: 'vault_evaluation_only', + clampedTo: false, + clampedAsOf: false, + }); + }); + + it('expands date-only from to 00:00:00.000Z and date-only to/asOf to 23:59:59.999Z', () => { + const result = applyVaultFence( + { + from: '2026-03-10', + to: '2026-03-10', + asOf: '2026-03-10', + }, + { vaultCutoffTs: cutoffMs } + ); + expect(result.fromMs).toBe(Date.UTC(2026, 2, 10, 0, 0, 0, 0)); + expect(result.toMs).toBe(Date.UTC(2026, 2, 10, 23, 59, 59, 999)); + expect(result.asOfMs).toBe(Date.UTC(2026, 2, 10, 23, 59, 59, 999)); + }); + + it('normalizes explicit UTC offsets and truncates sub-millisecond fractions to integer ms', () => { + const result = applyVaultFence( + { + from: '2026-03-10T08:00:00.987654-04:00', + to: '2026-03-10T18:30:00.1+05:30', + }, + { vaultCutoffTs: cutoffMs } + ); + expect(result.fromMs).toBe(Date.UTC(2026, 2, 10, 12, 0, 0, 987)); + expect(result.toMs).toBe(Date.UTC(2026, 2, 10, 13, 0, 0, 100)); + }); + + it('rejects unknown scope, malformed timestamps, from > to, and non-finite cutoffs', () => { + expect(() => + applyVaultFence( + { + from: '2026-01-01', + to: '2026-02-01', + scope: 'unrestricted' as never, + }, + { vaultCutoffTs: cutoffMs } + ) + ).toThrow(MarketDataStoreValidationError); + + const invalidQueries = [ + { from: 'bad-date', to: '2026-02-01' }, + { from: '2026-01-01', to: 'bad-date' }, + { from: '2026-01-01', to: '2026-02-01', asOf: 'bad-date' }, + { from: '2026-01-01', to: '2026-02-01', asOf: '' }, + { from: '2026-01-01T00:00:00', to: '2026-02-01' }, + { from: '2026-02-30', to: '2026-03-01' }, + { from: '2026-04-01', to: '2026-03-01' }, + { from: '2026-09-01', to: '2026-08-01' }, + ]; + for (const q of invalidQueries) { + expect(() => applyVaultFence(q, { vaultCutoffTs: cutoffMs })).toThrow( + MarketDataStoreValidationError + ); + } + + for (const badCutoff of [ + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + cutoffMs + 0.25, + ]) { + expect(() => + applyVaultFence({ from: '2026-01-01', to: '2026-02-01' }, { vaultCutoffTs: badCutoff }) + ).toThrow(MarketDataStoreValidationError); + } + }); + + it('produces identical epoch-ms results under TZ=America/Toronto and TZ=UTC', () => { + const previousTz = process.env.TZ; + try { + process.env.TZ = 'UTC'; + const utcCutoff = computeVaultCutoffTs('2026-08-31T23:30:00.500Z'); + const utcFenced = applyVaultFence( + { from: '2026-01-01', to: '2026-03-15', asOf: '2026-02-28' }, + { vaultCutoffTs: utcCutoff } + ); + + process.env.TZ = 'America/Toronto'; + const torontoCutoff = computeVaultCutoffTs('2026-08-31T23:30:00.500Z'); + const torontoFenced = applyVaultFence( + { from: '2026-01-01', to: '2026-03-15', asOf: '2026-02-28' }, + { vaultCutoffTs: torontoCutoff } + ); + + expect(torontoCutoff).toBe(utcCutoff); + expect(torontoFenced).toEqual(utcFenced); + } finally { + if (previousTz === undefined) { + delete process.env.TZ; + } else { + process.env.TZ = previousTz; + } + } + }); + + it('enforces fromMs <= toMs < cutoffMs and asOfMs < cutoffMs across 1,500 seeded random cases', () => { + const rng = createSeededRng(0x5eed1234); + const baseMs = Date.UTC(2020, 0, 1, 0, 0, 0, 0); + const spanMs = 8 * 365 * 86_400_000; + let passedCount = 0; + let fenceErrorCount = 0; + let validationErrorCount = 0; + + for (let i = 0; i < 1_500; i += 1) { + const randCutoff = baseMs + Math.floor(rng() * spanMs); + const bucket = i % 5; + const offsetFrom = + bucket === 0 + ? -Math.floor(rng() * 180 * 86_400_000) - 1 + : bucket === 1 + ? 0 + : Math.floor((rng() - 0.5) * 360 * 86_400_000); + const offsetTo = Math.floor((rng() - 0.3) * 360 * 86_400_000); + const rawFromMs = randCutoff + offsetFrom; + const rawToMs = randCutoff + offsetTo; + + const useDateOnlyFrom = rng() < 0.35; + const useDateOnlyTo = rng() < 0.35; + const fromStr = useDateOnlyFrom + ? formatUtcDateOnly(rawFromMs) + : new Date(rawFromMs).toISOString(); + const toStr = useDateOnlyTo ? formatUtcDateOnly(rawToMs) : new Date(rawToMs).toISOString(); + + const asOfMode = i % 4; + let asOfStr: string | undefined; + if (asOfMode === 1) { + const rawAsOfMs = randCutoff + Math.floor((rng() - 0.5) * 360 * 86_400_000); + asOfStr = new Date(rawAsOfMs).toISOString(); + } else if (asOfMode === 2) { + const rawAsOfMs = randCutoff + Math.floor((rng() - 0.5) * 360 * 86_400_000); + asOfStr = formatUtcDateOnly(rawAsOfMs); + } else if (asOfMode === 3) { + asOfStr = new Date(randCutoff).toISOString(); + } + + try { + const fenced = applyVaultFence( + { from: fromStr, to: toStr, asOf: asOfStr }, + { vaultCutoffTs: randCutoff } + ); + expect(fenced.scope).toBe('vault_fenced'); + expect(fenced.fromMs).toBeLessThanOrEqual(fenced.toMs); + expect(fenced.toMs).toBeLessThan(randCutoff); + expect(fenced.asOfMs).toBeLessThan(randCutoff); + passedCount += 1; + } catch (err) { + if (err instanceof VaultHoldoutFenceError) { + expect(err.fromMs).toBeGreaterThanOrEqual(randCutoff); + fenceErrorCount += 1; + } else if (err instanceof MarketDataStoreValidationError) { + validationErrorCount += 1; + } else { + throw err; + } + } + } + + expect(passedCount).toBeGreaterThan(200); + expect(fenceErrorCount).toBeGreaterThan(200); + expect(validationErrorCount).toBeGreaterThan(100); + }); +}); + +describe('resolveDuckDbConnectionBudget', () => { + it('returns the exact default budget and SET statements when env is empty', () => { + const budget = resolveDuckDbConnectionBudget({}); + expect(budget).toEqual({ + memoryLimit: DEFAULT_DUCKDB_MEMORY_LIMIT, + threads: DEFAULT_DUCKDB_THREADS, + tempDirectory: DEFAULT_DUCKDB_TEMP_DIRECTORY, + statements: [ + "SET memory_limit = '6GB';", + 'SET threads = 4;', + "SET temp_directory = '/mnt/data/stockbot/tmp/duckdb';", + ], + }); + }); + + it('applies valid environment overrides including decimal sizes and boundary thread counts', () => { + const localDev = resolveDuckDbConnectionBudget({ + STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCKBOT_DUCKDB_THREADS: '2', + STOCKBOT_DUCKDB_TEMP_DIRECTORY: '/tmp/duckdb', + }); + expect(localDev.statements).toEqual([ + "SET memory_limit = '2GB';", + 'SET threads = 2;', + "SET temp_directory = '/tmp/duckdb';", + ]); + + const decimalMin = resolveDuckDbConnectionBudget({ + STOCKBOT_DUCKDB_MEMORY_LIMIT: '1.5GiB', + STOCKBOT_DUCKDB_THREADS: '1', + STOCKBOT_DUCKDB_TEMP_DIRECTORY: '/var/tmp/stockbot-duckdb', + }); + expect(decimalMin.memoryLimit).toBe('1.5GiB'); + expect(decimalMin.threads).toBe(1); + + const maxThreads = resolveDuckDbConnectionBudget({ + STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MiB', + STOCKBOT_DUCKDB_THREADS: '64', + }); + expect(maxThreads.memoryLimit).toBe('512MiB'); + expect(maxThreads.threads).toBe(64); + }); + + it('rejects malformed memory limits, out-of-range threads, and unsafe temp paths', () => { + const badMemoryLimits = ['0GB', '0.0GiB', '2gb', '2TB', '2 GB', '', "2GB'; DROP TABLE t;--"]; + for (const value of badMemoryLimits) { + expect(() => resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_MEMORY_LIMIT: value })).toThrow( + MarketDataStoreValidationError + ); + } + + const badThreads = ['0', '65', '-1', '2.5', '04', 'abc', '']; + for (const value of badThreads) { + expect(() => resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_THREADS: value })).toThrow( + MarketDataStoreValidationError + ); + } + + const badTempDirs = [ + 'relative/path', + './tmp', + '', + "/tmp/a'b", + '/tmp/a;b', + '/tmp/a\nb', + '/tmp/a\rb', + '/tmp/a\0b', + ]; + for (const value of badTempDirs) { + expect(() => + resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_TEMP_DIRECTORY: value }) + ).toThrow(MarketDataStoreValidationError); + } + }); +}); diff --git a/test/contracts/market-data-store.type-test.ts b/test/contracts/market-data-store.type-test.ts new file mode 100644 index 00000000..406ac0de --- /dev/null +++ b/test/contracts/market-data-store.type-test.ts @@ -0,0 +1,232 @@ +import type { + BarBatch, + DataScope, + DuckDbConnectionBudget, + EventKind, + FencedTimeRange, + MarketDataStore, + Table, + UniverseRef, + VaultFenceContext, + VaultFenceQuery, +} from '@stock-bot/research'; +import type { + DataScope as SubpathDataScope, + MarketDataStore as SubpathMarketDataStore, +} from '@stock-bot/research/market-data-store'; + +type AssertEqual = + (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 ? true : false; + +const _sameStore: AssertEqual = true; +const _sameScope: AssertEqual = true; +void _sameStore; +void _sameScope; + +const emptyTable: Table = { columns: [], rows: [] }; +const emptyBatch: BarBatch = { rows: [] }; + +const stubStore: MarketDataStore = { + bars(_q: { + listingIds: number[]; + timeframe: '1m' | '5m' | '1h' | '1d'; + from: string; + to: string; + adjustment: 'raw' | 'split' | 'total'; + asOf?: string; + scope?: DataScope; + }): AsyncIterable { + return { + async *[Symbol.asyncIterator]() { + yield emptyBatch; + }, + }; + }, + + async crossSection(_q: { + features: string[]; + date: string; + universe: UniverseRef; + asOf?: string; + }): Promise
{ + return emptyTable; + }, + + async fundamentalsAsOf(_q: { + listingIds: number[]; + fields: string[]; + asOf: string; + allowEstimatedLag?: boolean; + }): Promise
{ + return emptyTable; + }, + + async events(_q: { + kinds: EventKind[]; + listingIds?: number[]; + from: string; + to: string; + asOf?: string; + }): Promise
{ + return emptyTable; + }, + + async shortsAsOf(_q: { + listingIds: number[]; + from: string; + to: string; + asOf?: string; + }): Promise
{ + return emptyTable; + }, + + async macroAsOf(_q: { + countries: string[]; + indicators: string[]; + from: string; + to: string; + asOf?: string; + }): Promise
{ + return emptyTable; + }, + + async fx(_q: { + pair: 'USD.CAD'; + timeframe: '1m' | '1d'; + from: string; + to: string; + }): Promise
{ + return emptyTable; + }, + + async universe(_q: { ref: UniverseRef; date: string }): Promise { + return [101, 202]; + }, +}; + +function verifyAllMethods(store: MarketDataStore): void { + const _bars: AsyncIterable = store.bars({ + listingIds: [1, 2], + timeframe: '1d', + from: '2024-01-01', + to: '2025-12-31', + adjustment: 'raw', + }); + const _barsWithOpts: AsyncIterable = store.bars({ + listingIds: [1], + timeframe: '1m', + from: '2025-01-01T00:00:00Z', + to: '2025-06-01T00:00:00Z', + adjustment: 'total', + asOf: '2025-06-01T00:00:00Z', + scope: 'vault_fenced', + }); + const _cross: Promise
= store.crossSection({ + features: ['rsi_14@v1'], + date: '2025-05-01', + universe: 'us_liquid_top3000', + asOf: '2025-05-01', + }); + const _fundamentals: Promise
= store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue_ttm'], + asOf: '2025-05-01', + allowEstimatedLag: false, + }); + const _events: Promise
= store.events({ + kinds: ['filing', 'earnings', 'ceo_post', 'corporate_action'], + from: '2025-01-01', + to: '2025-05-01', + }); + const _shorts: Promise
= store.shortsAsOf({ + listingIds: [1], + from: '2025-01-01', + to: '2025-05-01', + }); + const _macro: Promise
= store.macroAsOf({ + countries: ['US', 'CA'], + indicators: ['CPI'], + from: '2025-01-01', + to: '2025-05-01', + }); + const _fx: Promise
= store.fx({ + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-05-01', + }); + const _universe: Promise = store.universe({ + ref: 'us_liquid_top3000', + date: '2025-05-01', + }); + + void _bars; + void _barsWithOpts; + void _cross; + void _fundamentals; + void _events; + void _shorts; + void _macro; + void _fx; + void _universe; + + // Negative checks: unknown DataScope, non-numeric listingIds, missing required fields. + // @ts-expect-error Only 'vault_fenced' and 'vault_evaluation_only' are valid DataScope values. + const _badScope: DataScope = 'unrestricted'; + void _badScope; + + store.bars({ + // @ts-expect-error listingIds must be INT32 number[], not string[]. + listingIds: ['AAPL'], + timeframe: '1d', + from: '2025-01-01', + to: '2025-05-01', + adjustment: 'raw', + }); + + // @ts-expect-error adjustment is required on bars(). + store.bars({ + listingIds: [1], + timeframe: '1d', + from: '2025-01-01', + to: '2025-05-01', + }); + + // @ts-expect-error asOf is required on fundamentalsAsOf(). + store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue_ttm'], + }); + + store.fx({ + // @ts-expect-error pair is locked to 'USD.CAD' in §4. + pair: 'EUR.USD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-05-01', + }); +} + +verifyAllMethods(stubStore); + +// Ensure auxiliary exported contract types remain structurally usable. +const _query: VaultFenceQuery = { from: '2025-01-01', to: '2025-05-01' }; +const _ctx: VaultFenceContext = { vaultCutoffTs: Date.UTC(2026, 4, 28) }; +const _range: FencedTimeRange = { + fromMs: 0, + toMs: 1, + asOfMs: 1, + scope: 'vault_fenced', + clampedTo: false, + clampedAsOf: false, +}; +const _budget: DuckDbConnectionBudget = { + memoryLimit: '6GB', + threads: 4, + tempDirectory: '/mnt/data/stockbot/tmp/duckdb', + statements: [], +}; +void _query; +void _ctx; +void _range; +void _budget; diff --git a/tsconfig.contracts.json b/tsconfig.contracts.json index 4e26c81c..716a4f58 100644 --- a/tsconfig.contracts.json +++ b/tsconfig.contracts.json @@ -3,6 +3,7 @@ "include": [ "libs/core/services/test/contracts.type-test.ts", "test/contracts/strategy-runtime.type-test.ts", - "test/contracts/canonical-runner.type-test.ts" + "test/contracts/canonical-runner.type-test.ts", + "test/contracts/market-data-store.type-test.ts" ] }