stock-bot/libs/research/test/market-data-store-duckdb.test.ts
2026-12-01 23:50:33 -05:00

3279 lines
110 KiB
TypeScript

import { describe, expect, it } from 'bun:test';
import {
ADJ_SNAPSHOT_FORMAT_VERSION,
ADJ_SNAPSHOT_KV_PREFIX,
type AdjFactorsArtifactPinner,
AdjFactorsSnapshotError,
type AdjFactorsSnapshotMetadata,
BARS_ADJUSTMENTS,
type BarBatch,
DEFAULT_UNIVERSE_LOOKBACK_DAYS,
type DuckDbExecutor,
type DuckDbParam,
type DuckDbPlanContext,
EVENT_KINDS,
EVENTS_COLUMNS,
FUNDAMENTALS_PIT_VALUE_FIELDS,
FX_1D_COLUMNS,
FX_PAIR_MAP,
MarketDataStoreNotImplementedError,
MarketDataStoreValidationError,
type PinnedAdjFactorsArtifact,
SHORTS_COLUMNS,
type TableRow,
UNIVERSE_REFS,
VaultHoldoutFenceError,
VaultScopeNotAuthorizedError,
createDuckDbMarketDataStore,
parseAdjFactorsSnapshotMetadata,
planAdjFactorsMetadataQuery,
planBars1dQuery,
planEventsQuery,
planFundamentalsAsOfQuery,
planFx1dQuery,
planShortsAsOfQuery,
planUniverseQuery,
resolveDuckDbConnectionBudget,
validateAdjFactorsArtifactPath,
validateCuratedRoot,
validateParquetFilePath,
} from '@stock-bot/research';
import {
ADJ_SNAPSHOT_FORMAT_VERSION as subpathAdjSnapshotFormatVersion,
ADJ_SNAPSHOT_KV_PREFIX as subpathAdjSnapshotKvPrefix,
AdjFactorsSnapshotError as SubpathAdjFactorsSnapshotError,
BARS_ADJUSTMENTS as subpathBarsAdjustments,
DEFAULT_UNIVERSE_LOOKBACK_DAYS as subpathDefaultUniverseLookbackDays,
EVENT_KINDS as subpathEventKinds,
EVENTS_COLUMNS as subpathEventsColumns,
FUNDAMENTALS_PIT_VALUE_FIELDS as subpathFundamentalsPitValueFields,
FX_1D_COLUMNS as subpathFx1dColumns,
FX_PAIR_MAP as subpathFxPairMap,
MarketDataStoreNotImplementedError as SubpathNotImplementedError,
SHORTS_COLUMNS as subpathShortsColumns,
UNIVERSE_REFS as subpathUniverseRefs,
createDuckDbMarketDataStore as subpathCreateDuckDbMarketDataStore,
parseAdjFactorsSnapshotMetadata as subpathParseAdjFactorsSnapshotMetadata,
planAdjFactorsMetadataQuery as subpathPlanAdjFactorsMetadataQuery,
planBars1dQuery as subpathPlanBars1dQuery,
planEventsQuery as subpathPlanEventsQuery,
planFundamentalsAsOfQuery as subpathPlanFundamentalsAsOfQuery,
planFx1dQuery as subpathPlanFx1dQuery,
planShortsAsOfQuery as subpathPlanShortsAsOfQuery,
planUniverseQuery as subpathPlanUniverseQuery,
validateAdjFactorsArtifactPath as subpathValidateAdjFactorsArtifactPath,
validateCuratedRoot as subpathValidateCuratedRoot,
validateParquetFilePath as subpathValidateParquetFilePath,
} from '@stock-bot/research/market-data-store-duckdb';
const CURATED_ROOT = '/mnt/data/stockbot/curated';
const DEFAULT_ADJ_PATH = `${CURATED_ROOT}/adj_factors/part.parquet`;
const CUTOFF_MS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); // 2026-05-28T00:00:00.000Z
const CUTOFF_MICROS = CUTOFF_MS * 1000;
const MAX_ALLOWED_ISO_MICROS = '2026-05-27T23:59:59.999999Z';
const MAX_ALLOWED_DATE = '2026-05-27';
const DEFAULT_CTX: DuckDbPlanContext = {
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
};
function makeFencedKvRows(opts: {
snapshotKind?: string;
asOfMicros?: number | null;
vaultCutoffMicros?: number | null;
rowsWritten?: number;
checksum?: string;
formatVersion?: string;
}): TableRow[] {
return [
{ key: 'stock_bot.adj_factors.format_version', value: opts.formatVersion ?? '1' },
{ key: 'stock_bot.adj_factors.snapshot_kind', value: opts.snapshotKind ?? 'point_in_time_fenced' },
{
key: 'stock_bot.adj_factors.as_of_micros',
value: opts.asOfMicros === undefined || opts.asOfMicros === null ? 'none' : String(opts.asOfMicros),
},
{
key: 'stock_bot.adj_factors.vault_cutoff_micros',
value:
opts.vaultCutoffMicros === undefined || opts.vaultCutoffMicros === null
? 'none'
: String(opts.vaultCutoffMicros),
},
{ key: 'stock_bot.adj_factors.rows_written', value: String(opts.rowsWritten ?? 1) },
{
key: 'stock_bot.adj_factors.snapshot_checksum',
value: opts.checksum ?? '0x024ec73a1afe7e6b',
},
];
}
function makeFencedSnapshot(opts: {
path?: string;
asOfMicros?: number | null;
vaultCutoffMicros?: number | null;
rowsWritten?: number;
}): AdjFactorsSnapshotMetadata {
return parseAdjFactorsSnapshotMetadata(
opts.path ?? DEFAULT_ADJ_PATH,
makeFencedKvRows({
asOfMicros: opts.asOfMicros,
vaultCutoffMicros: opts.vaultCutoffMicros,
rowsWritten: opts.rowsWritten,
})
);
}
/** Parses a UTC ISO-8601 timestamp with optional up-to-microsecond fractional digits into epoch µs. */
function parseIsoToMicros(iso: string): number {
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/.exec(iso);
if (m === null) {
throw new Error(`Unexpected UTC ISO timestamp: ${iso}`);
}
const frac = (m[7] ?? '').padEnd(6, '0').slice(0, 6);
const ms = Number(frac.slice(0, 3));
const subMs = Number(frac.slice(3, 6));
const epochMs = Date.UTC(
Number(m[1]),
Number(m[2]) - 1,
Number(m[3]),
Number(m[4]),
Number(m[5]),
Number(m[6]),
ms
);
return epochMs * 1000 + subMs;
}
interface RecordedCall {
readonly kind: 'run' | 'query';
readonly sql: string;
readonly params?: readonly DuckDbParam[];
}
interface RecordingFakeExecutor {
readonly executor: DuckDbExecutor;
readonly calls: RecordedCall[];
readonly runCalls: string[];
readonly queryCalls: Array<{ sql: string; params: readonly DuckDbParam[] }>;
}
function createRecordingExecutor(options?: {
onRun?: (sql: string, callIndex: number) => Promise<void> | void;
onQuery?: (
sql: string,
params: readonly DuckDbParam[],
callIndex: number
) => Promise<readonly TableRow[]> | readonly TableRow[];
}): RecordingFakeExecutor {
const calls: RecordedCall[] = [];
const runCalls: string[] = [];
const queryCalls: Array<{ sql: string; params: readonly DuckDbParam[] }> = [];
const executor: DuckDbExecutor = {
async run(sql: string): Promise<void> {
const idx = runCalls.length;
calls.push({ kind: 'run', sql });
runCalls.push(sql);
if (options?.onRun !== undefined) {
await options.onRun(sql, idx);
}
},
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
const idx = queryCalls.length;
const snapshot = [...params];
calls.push({ kind: 'query', sql, params: snapshot });
queryCalls.push({ sql, params: snapshot });
if (options?.onQuery !== undefined) {
return await options.onQuery(sql, snapshot, idx);
}
return [];
},
};
return { executor, calls, runCalls, queryCalls };
}
async function collectBars(iterable: AsyncIterable<BarBatch>): Promise<BarBatch[]> {
const batches: BarBatch[] = [];
for await (const batch of iterable) {
batches.push(batch);
}
return batches;
}
function createMulberry32(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;
};
}
describe('market-data-store-duckdb exports', () => {
it('exposes identical runtime symbols from package root and subpath', () => {
expect(planBars1dQuery).toBe(subpathPlanBars1dQuery);
expect(planEventsQuery).toBe(subpathPlanEventsQuery);
expect(planShortsAsOfQuery).toBe(subpathPlanShortsAsOfQuery);
expect(planFx1dQuery).toBe(subpathPlanFx1dQuery);
expect(planUniverseQuery).toBe(subpathPlanUniverseQuery);
expect(planFundamentalsAsOfQuery).toBe(subpathPlanFundamentalsAsOfQuery);
expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toBe(subpathFundamentalsPitValueFields);
expect(planAdjFactorsMetadataQuery).toBe(subpathPlanAdjFactorsMetadataQuery);
expect(parseAdjFactorsSnapshotMetadata).toBe(subpathParseAdjFactorsSnapshotMetadata);
expect(createDuckDbMarketDataStore).toBe(subpathCreateDuckDbMarketDataStore);
expect(validateCuratedRoot).toBe(subpathValidateCuratedRoot);
expect(validateParquetFilePath).toBe(subpathValidateParquetFilePath);
expect(validateAdjFactorsArtifactPath).toBe(subpathValidateAdjFactorsArtifactPath);
expect(MarketDataStoreNotImplementedError).toBe(SubpathNotImplementedError);
expect(AdjFactorsSnapshotError).toBe(SubpathAdjFactorsSnapshotError);
expect(ADJ_SNAPSHOT_FORMAT_VERSION).toBe(subpathAdjSnapshotFormatVersion);
expect(ADJ_SNAPSHOT_KV_PREFIX).toBe(subpathAdjSnapshotKvPrefix);
expect(EVENT_KINDS).toBe(subpathEventKinds);
expect(FX_PAIR_MAP).toBe(subpathFxPairMap);
expect(BARS_ADJUSTMENTS).toBe(subpathBarsAdjustments);
expect(UNIVERSE_REFS).toBe(subpathUniverseRefs);
expect(DEFAULT_UNIVERSE_LOOKBACK_DAYS).toBe(subpathDefaultUniverseLookbackDays);
expect(EVENTS_COLUMNS).toBe(subpathEventsColumns);
expect(SHORTS_COLUMNS).toBe(subpathShortsColumns);
expect(FX_1D_COLUMNS).toBe(subpathFx1dColumns);
});
});
describe('pure DuckDB query planners — exact SQL and bound parameters', () => {
it('plans bars 1d raw query with hive_partitioning, bound listingIds, and PIT/Vault predicates', () => {
const inputListingIds = [101, 202, 101, -0];
const planned = planBars1dQuery(
{
listingIds: inputListingIds,
timeframe: '1d',
from: '2024-01-02',
to: '2025-12-31',
adjustment: 'raw',
asOf: '2026-01-15T12:00:00Z',
},
{ curatedRoot: `${CURATED_ROOT}///`, vaultCutoffTs: CUTOFF_MS }
);
// Caller array must not be mutated
expect(inputListingIds).toEqual([101, 202, 101, -0]);
expect(Object.is(planned.params[2], 0)).toBe(true);
expect(planned.sql).toBe(
'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('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b ` +
'WHERE b.listing_id IN (?, ?, ?) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ' +
'ORDER BY b.listing_id ASC, b.ts ASC'
);
expect(planned.params).toEqual([
101,
202,
0,
'2024-01-02T00:00:00.000Z',
'2025-12-31T23:59:59.999999Z',
'2026-01-15T12:00:00.000Z',
]);
expect(planned.fenced.scope).toBe('vault_fenced');
expect(planned.fenced.clampedTo).toBe(false);
expect(planned.fenced.clampedAsOf).toBe(false);
});
it('plans bars 1d split query with verified fenced adj_factors snapshot bound to read_parquet', () => {
const asOfMicros = parseIsoToMicros('2025-07-01T23:59:59.999999Z');
const snapshot = makeFencedSnapshot({
path: DEFAULT_ADJ_PATH,
asOfMicros,
vaultCutoffMicros: CUTOFF_MICROS,
});
const planned = planBars1dQuery(
{
listingIds: [42, 77],
timeframe: '1d',
from: '2023-01-01',
to: '2025-06-30',
adjustment: 'split',
asOf: '2025-07-01',
},
{ ...DEFAULT_CTX, adjFactorsSnapshot: snapshot }
);
expect(planned.sql).toBe(
'SELECT b.listing_id, epoch_ms(b.ts) AS ts, ' +
'b.open / COALESCE(a.cum_split_factor, 1.0) AS open, ' +
'b.high / COALESCE(a.cum_split_factor, 1.0) AS high, ' +
'b.low / COALESCE(a.cum_split_factor, 1.0) AS low, ' +
'b.close / COALESCE(a.cum_split_factor, 1.0) AS close, ' +
'b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume, ' +
'b.vwap / COALESCE(a.cum_split_factor, 1.0) AS vwap, ' +
'epoch_ms(b.known_at) AS known_at ' +
`FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b ` +
`ASOF LEFT JOIN (SELECT listing_id, ex_date, cum_split_factor FROM read_parquet('${DEFAULT_ADJ_PATH}') WHERE listing_id IN (?, ?) AND known_at <= ?) AS a ` +
'ON b.listing_id = a.listing_id AND b.session_date < a.ex_date ' +
'WHERE b.listing_id IN (?, ?) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ' +
'ORDER BY b.listing_id ASC, b.ts ASC'
);
expect(planned.params).toEqual([
42,
77,
'2025-07-01T23:59:59.999999Z',
42,
77,
'2023-01-01T00:00:00.000Z',
'2025-06-30T23:59:59.999999Z',
'2025-07-01T23:59:59.999999Z',
]);
});
it('plans bars 1d total query dividing prices by cum_total_factor and multiplying volume by cum_split_factor', () => {
const snapshot = makeFencedSnapshot({
path: '/adj_factors/part.parquet',
asOfMicros: null,
vaultCutoffMicros: CUTOFF_MICROS,
});
const planned = planBars1dQuery(
{
listingIds: [7],
timeframe: '1d',
from: '2020-01-01',
to: '2025-01-01',
adjustment: 'total',
},
{ curatedRoot: '/', vaultCutoffTs: CUTOFF_MS, adjFactorsSnapshot: snapshot }
);
expect(planned.sql).toBe(
'SELECT b.listing_id, epoch_ms(b.ts) AS ts, ' +
'b.open / COALESCE(a.cum_total_factor, 1.0) AS open, ' +
'b.high / COALESCE(a.cum_total_factor, 1.0) AS high, ' +
'b.low / COALESCE(a.cum_total_factor, 1.0) AS low, ' +
'b.close / COALESCE(a.cum_total_factor, 1.0) AS close, ' +
'b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume, ' +
'b.vwap / COALESCE(a.cum_total_factor, 1.0) AS vwap, ' +
'epoch_ms(b.known_at) AS known_at ' +
"FROM read_parquet('/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b " +
"ASOF LEFT JOIN (SELECT listing_id, ex_date, cum_split_factor, cum_total_factor FROM read_parquet('/adj_factors/part.parquet') WHERE listing_id IN (?) AND known_at <= ?) AS a " +
'ON b.listing_id = a.listing_id AND b.session_date < a.ex_date ' +
'WHERE b.listing_id IN (?) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ' +
'ORDER BY b.listing_id ASC, b.ts ASC'
);
expect(planned.params).toEqual([
7,
MAX_ALLOWED_ISO_MICROS,
7,
'2020-01-01T00:00:00.000Z',
'2025-01-01T23:59:59.999999Z',
MAX_ALLOWED_ISO_MICROS,
]);
});
it('plans events query with and without listingIds using complete Parquet writer tie-breaker ordering', () => {
const kinds: Array<'filing' | 'earnings'> = ['filing', 'earnings', 'filing'];
const withListings = planEventsQuery(
{
kinds,
listingIds: [10, 20],
from: '2025-01-01',
to: '2025-03-31',
asOf: '2025-04-01T00:00:00Z',
},
DEFAULT_CTX
);
expect(kinds).toEqual(['filing', 'earnings', 'filing']);
expect(withListings.sql).toBe(
'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('${CURATED_ROOT}/events/year=*/part.parquet', hive_partitioning = true) AS e ` +
'WHERE e.kind IN (?, ?) AND e.listing_id IN (?, ?) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ' +
'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'
);
expect(withListings.params).toEqual([
'filing',
'earnings',
10,
20,
'2025-01-01T00:00:00.000Z',
'2025-03-31T23:59:59.999999Z',
'2025-04-01T00:00:00.000Z',
]);
const withoutListings = planEventsQuery(
{
kinds: ['corporate_action'],
from: '2025-01-01',
to: '2025-03-31',
},
DEFAULT_CTX
);
expect(withoutListings.sql).toBe(
'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('${CURATED_ROOT}/events/year=*/part.parquet', hive_partitioning = true) AS e ` +
'WHERE e.kind IN (?) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ' +
'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'
);
expect(withoutListings.params).toEqual([
'corporate_action',
'2025-01-01T00:00:00.000Z',
'2025-03-31T23:59:59.999999Z',
MAX_ALLOWED_ISO_MICROS,
]);
});
it('orders two distinct filings sharing (listing_id, ts, kind, subtype) deterministically via payload_json tie-breaker', async () => {
const sameSecondMs = Date.UTC(2025, 2, 10, 21, 5, 0);
const filingA: TableRow = {
listing_id: 10,
ts: sameSecondMs,
known_at: sameSecondMs,
known_at_source: 'filing_timestamp',
kind: 'filing',
subtype: '8-k',
payload_json: '{"accession":"0001","item":"2.02"}',
};
const filingB: TableRow = {
listing_id: 10,
ts: sameSecondMs,
known_at: sameSecondMs,
known_at_source: 'filing_timestamp',
kind: 'filing',
subtype: '8-k',
payload_json: '{"accession":"0002","item":"7.01"}',
};
const fake = createRecordingExecutor({
onQuery: (sql) => {
// Confirm the SQL query requests the complete writer tie-breaker order.
expect(sql).toContain(
'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'
);
// Simulate DuckDB sorting rows by the exact ORDER BY key.
return [filingB, filingA].sort((a, b) =>
String(a.payload_json).localeCompare(String(b.payload_json))
);
},
});
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env: {},
});
const result = await store.events({
kinds: ['filing'],
listingIds: [10],
from: '2025-03-10',
to: '2025-03-10',
});
expect(result.rows).toEqual([filingA, filingB]);
});
it('plans shortsAsOf query binding UTC YYYY-MM-DD report_date bounds and microsecond ISO known_at bound', () => {
const planned = planShortsAsOfQuery(
{
listingIds: [500, 600],
from: '2024-06-01',
to: '2026-08-01', // clamped to 2026-05-27T23:59:59.999999Z
asOf: '2026-09-01', // clamped to 2026-05-27T23:59:59.999999Z
},
DEFAULT_CTX
);
expect(planned.sql).toBe(
'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('${CURATED_ROOT}/shorts/part.parquet') AS s ` +
'WHERE s.listing_id IN (?, ?) AND s.report_date >= ? AND s.report_date <= ? AND s.known_at <= ? ' +
'ORDER BY s.listing_id ASC, s.report_date ASC'
);
expect(planned.params).toEqual([
500,
600,
'2024-06-01',
MAX_ALLOWED_DATE,
MAX_ALLOWED_ISO_MICROS,
]);
expect(planned.fenced.clampedTo).toBe(true);
expect(planned.fenced.clampedAsOf).toBe(true);
});
it('plans fx 1d query mapping USD.CAD to bound USDCAD and enforcing vault_fenced microsecond default asOf', () => {
const planned = planFx1dQuery(
{
pair: 'USD.CAD',
timeframe: '1d',
from: '2022-01-01',
to: '2026-10-01', // clamped
},
DEFAULT_CTX
);
expect(planned.sql).toBe(
'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('${CURATED_ROOT}/fx_1d/part.parquet') AS f ` +
'WHERE f.pair = ? AND f.ts >= ? AND f.ts <= ? AND f.known_at <= ? ' +
'ORDER BY f.session_date ASC'
);
expect(planned.params).toEqual([
'USDCAD',
'2022-01-01T00:00:00.000Z',
MAX_ALLOWED_ISO_MICROS,
MAX_ALLOWED_ISO_MICROS,
]);
expect(planned.fenced.scope).toBe('vault_fenced');
expect(planned.fenced.clampedTo).toBe(true);
expect(planned.fenced.asOfMs).toBe(CUTOFF_MS - 1);
});
});
describe('FX 1d microsecond bounds (curate_fx_1d 23:59:59.999999Z compatibility)', () => {
it('includes a single-day FX session stamped at 23:59:59.999999Z for date-only from=to', () => {
const planned = planFx1dQuery(
{
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-01-15',
to: '2025-01-15',
},
DEFAULT_CTX
);
expect(planned.params).toEqual([
'USDCAD',
'2025-01-15T00:00:00.000Z',
'2025-01-15T23:59:59.999999Z',
MAX_ALLOWED_ISO_MICROS,
]);
const writerTsMicros = parseIsoToMicros('2025-01-15T23:59:59.999999Z');
const boundFromMicros = parseIsoToMicros(planned.params[1] as string);
const boundToMicros = parseIsoToMicros(planned.params[2] as string);
const boundAsOfMicros = parseIsoToMicros(planned.params[3] as string);
expect(writerTsMicros).toBeGreaterThanOrEqual(boundFromMicros);
expect(writerTsMicros).toBeLessThanOrEqual(boundToMicros);
expect(writerTsMicros).toBeLessThanOrEqual(boundAsOfMicros);
expect(boundToMicros).toBeLessThan(CUTOFF_MICROS);
expect(boundAsOfMicros).toBeLessThan(CUTOFF_MICROS);
});
it('includes the last pre-Vault FX session (2026-05-27T23:59:59.999999Z) while excluding the Vault cutoff day', () => {
const planned = planFx1dQuery(
{
pair: 'USD.CAD',
timeframe: '1d',
from: '2026-05-27',
to: '2026-05-27',
},
DEFAULT_CTX
);
expect(planned.params).toEqual([
'USDCAD',
'2026-05-27T00:00:00.000Z',
'2026-05-27T23:59:59.999999Z',
'2026-05-27T23:59:59.999999Z',
]);
const lastPreVaultMicros = parseIsoToMicros('2026-05-27T23:59:59.999999Z');
const firstVaultMicros = parseIsoToMicros('2026-05-28T00:00:00.000000Z');
const boundToMicros = parseIsoToMicros(planned.params[2] as string);
const boundAsOfMicros = parseIsoToMicros(planned.params[3] as string);
expect(lastPreVaultMicros).toBeLessThanOrEqual(boundToMicros);
expect(lastPreVaultMicros).toBeLessThanOrEqual(boundAsOfMicros);
expect(boundToMicros).toBeLessThan(firstVaultMicros);
expect(boundAsOfMicros).toBeLessThan(firstVaultMicros);
});
it('preserves explicit time-of-day upper bounds without expanding to .999999Z', () => {
const explicitSec = planFx1dQuery(
{
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-01-15T00:00:00Z',
to: '2025-01-15T16:00:00Z',
},
DEFAULT_CTX
);
expect(explicitSec.params[2]).toBe('2025-01-15T16:00:00.000Z');
const explicitMs = planFx1dQuery(
{
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-01-15T00:00:00Z',
to: '2025-01-15T23:59:59.999Z',
},
DEFAULT_CTX
);
expect(explicitMs.params[2]).toBe('2025-01-15T23:59:59.999Z');
// Writer's 23:59:59.999999Z is excluded when caller explicitly asks for <= 23:59:59.999Z.
expect(parseIsoToMicros('2025-01-15T23:59:59.999999Z')).toBeGreaterThan(
parseIsoToMicros(explicitMs.params[2] as string)
);
});
it('keeps clamped/default upper bounds strictly before non-midnight Vault cutoffs', () => {
const nonMidnightCutoffMs = Date.UTC(2026, 4, 28, 12, 30, 0, 500);
const planned = planFx1dQuery(
{
pair: 'USD.CAD',
timeframe: '1d',
from: '2026-05-01',
to: '2026-06-01',
},
{ curatedRoot: CURATED_ROOT, vaultCutoffTs: nonMidnightCutoffMs }
);
expect(planned.params[2]).toBe('2026-05-28T12:30:00.499999Z');
expect(planned.params[3]).toBe('2026-05-28T12:30:00.499999Z');
expect(parseIsoToMicros(planned.params[2] as string)).toBe(nonMidnightCutoffMs * 1000 - 1);
});
});
describe('adj_factors snapshot verification & Vault future-split leakage prevention', () => {
it('plans parquet_kv_metadata query bound to the exact adj_factors file path', () => {
const metaQuery = planAdjFactorsMetadataQuery(DEFAULT_ADJ_PATH);
expect(metaQuery).toEqual({
path: DEFAULT_ADJ_PATH,
sql:
'SELECT decode(key) AS key, decode(value) AS value ' +
`FROM parquet_kv_metadata('${DEFAULT_ADJ_PATH}') ` +
'WHERE decode(key) LIKE ?',
params: ['stock_bot.adj_factors.%'],
});
expect(() => planAdjFactorsMetadataQuery("'/evil.parquet")).toThrow(
MarketDataStoreValidationError
);
expect(() => planAdjFactorsMetadataQuery('/data/adj_factors/part.csv')).toThrow(
MarketDataStoreValidationError
);
});
it('parses valid curate-etl footer metadata and rejects missing, malformed, or unsupported metadata', () => {
const asOfMicros = Date.UTC(2018, 2, 14, 12, 0, 0) * 1000;
const parsed = parseAdjFactorsSnapshotMetadata(
DEFAULT_ADJ_PATH,
makeFencedKvRows({ asOfMicros, vaultCutoffMicros: null, rowsWritten: 42 })
);
expect(parsed).toEqual({
path: DEFAULT_ADJ_PATH,
formatVersion: 1,
snapshotKind: 'point_in_time_fenced',
fence: { asOfMicros, vaultCutoffMicros: null },
rowsWritten: 42,
snapshotChecksum: '0x024ec73a1afe7e6b',
});
// Missing metadata
expect(() => parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, [])).toThrow(
AdjFactorsSnapshotError
);
try {
parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, []);
} catch (err) {
expect((err as AdjFactorsSnapshotError).code).toBe('missing_metadata');
}
// Unsupported version
try {
parseAdjFactorsSnapshotMetadata(
DEFAULT_ADJ_PATH,
makeFencedKvRows({ formatVersion: '2', asOfMicros })
);
expect.unreachable('should throw unsupported_version');
} catch (err) {
expect(err).toBeInstanceOf(AdjFactorsSnapshotError);
expect((err as AdjFactorsSnapshotError).code).toBe('unsupported_version');
}
// Duplicate key
expect(() =>
parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, [
...makeFencedKvRows({ asOfMicros }),
{ key: 'stock_bot.adj_factors.format_version', value: '1' },
])
).toThrow(AdjFactorsSnapshotError);
// Unknown stock_bot.adj_factors.* key
expect(() =>
parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, [
...makeFencedKvRows({ asOfMicros }),
{ key: 'stock_bot.adj_factors.extra', value: '1' },
])
).toThrow(AdjFactorsSnapshotError);
// Invalid checksum
expect(() =>
parseAdjFactorsSnapshotMetadata(
DEFAULT_ADJ_PATH,
makeFencedKvRows({ asOfMicros, checksum: 'deadbeef' })
)
).toThrow(AdjFactorsSnapshotError);
// Retrospective with non-none fence
expect(() =>
parseAdjFactorsSnapshotMetadata(
DEFAULT_ADJ_PATH,
makeFencedKvRows({ snapshotKind: 'retrospective', asOfMicros })
)
).toThrow(AdjFactorsSnapshotError);
// Fenced with both bounds none
expect(() =>
parseAdjFactorsSnapshotMetadata(
DEFAULT_ADJ_PATH,
makeFencedKvRows({
snapshotKind: 'point_in_time_fenced',
asOfMicros: null,
vaultCutoffMicros: null,
})
)
).toThrow(AdjFactorsSnapshotError);
});
it('rejects retrospective and mismatched-fence snapshots and prevents Vault future-split leakage', async () => {
// Fixture mirroring tools/curate-etl/tests/curate_adj_qa_contract.rs:
// - Listing 42 has a visible 2-for-1 split on 2024-06-10 (pre-Vault)
// - Listing 42 has a held-out 2-for-1 split on 2026-07-15 (inside Vault, after CUTOFF_MS)
// - Raw close on 2024-06-07 (immediately before visible split) is 100.0.
// - Retrospective snapshot has cum_split_factor = 4.0 -> 100 / 4 = 25.0 (LEAK!).
// - Fenced snapshot (vault_cutoff = CUTOFF_MICROS) excludes the 2026-07-15 split before
// compounding, so cum_split_factor = 2.0 -> 100 / 2 = 50.0 (CLEAN!).
const rawPreSplitClose = 100.0;
// 1. Planner rejects missing adjFactorsSnapshot for split/total
try {
planBars1dQuery(
{
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
},
DEFAULT_CTX
);
expect.unreachable('should throw missing_snapshot');
} catch (err) {
expect(err).toBeInstanceOf(AdjFactorsSnapshotError);
expect((err as AdjFactorsSnapshotError).code).toBe('missing_snapshot');
}
// 2. Adapter rejects retrospective adj_factors snapshot without executing bars query
const retroPath = `${CURATED_ROOT}/adj_factors/snapshots/retro.parquet`;
const retroFake = createRecordingExecutor({
onQuery: (sql) => {
if (sql.includes('parquet_kv_metadata')) {
return makeFencedKvRows({
snapshotKind: 'retrospective',
asOfMicros: null,
vaultCutoffMicros: null,
rowsWritten: 2,
});
}
throw new Error('bars query must never run against retrospective adj_factors');
},
});
const retroStore = createDuckDbMarketDataStore({
executor: retroFake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
immutableAdjFactorsPath: retroPath,
env: {},
});
try {
await collectBars(
retroStore.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})
);
expect.unreachable('should reject retrospective snapshot');
} catch (err) {
expect(err).toBeInstanceOf(AdjFactorsSnapshotError);
expect((err as AdjFactorsSnapshotError).code).toBe('retrospective_rejected');
}
expect(retroFake.queryCalls).toHaveLength(1);
expect(retroFake.queryCalls[0]!.sql).toContain('parquet_kv_metadata');
// 3. Adapter rejects neighbouring fence 1 microsecond off (curate_adj_qa_contract.rs:282)
// and rejects a snapshot fenced past the Vault cutoff (which would embed the 2026-07-15 split).
const laterCutoffMicros = Date.UTC(2026, 7, 1, 0, 0, 0) * 1000;
const badPath = `${CURATED_ROOT}/adj_factors/snapshots/mismatched.parquet`;
for (const badFence of [
{ asOfMicros: CUTOFF_MICROS - 2, vaultCutoffMicros: CUTOFF_MICROS }, // 1 µs too early
{ asOfMicros: null, vaultCutoffMicros: CUTOFF_MICROS + 1 }, // 1 µs past cutoff
{ asOfMicros: null, vaultCutoffMicros: laterCutoffMicros }, // includes Vault split
]) {
const badFake = createRecordingExecutor({
onQuery: (sql) => {
if (sql.includes('parquet_kv_metadata')) {
return makeFencedKvRows({ ...badFence, rowsWritten: 2 });
}
throw new Error('bars query must never run against mismatched fence');
},
});
const badStore = createDuckDbMarketDataStore({
executor: badFake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
immutableAdjFactorsPath: badPath,
env: {},
});
try {
await collectBars(
badStore.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})
);
expect.unreachable('should reject incompatible fence');
} catch (err) {
expect(err).toBeInstanceOf(AdjFactorsSnapshotError);
expect((err as AdjFactorsSnapshotError).code).toBe('incompatible_fence');
}
expect(badFake.queryCalls).toHaveLength(1);
}
// 4. Adapter accepts exact fenced snapshot (vault_cutoff wins over later as_of, matching
// curate_adj_qa_contract.rs:303) bound to immutableAdjFactorsPath, and adjusts close by 2.0 (not 4.0).
const fencedAdjPath = `${CURATED_ROOT}/adj_factors/vault_2026_05_28/part.parquet`;
const fencedFake = createRecordingExecutor({
onQuery: (sql) => {
if (sql.includes('parquet_kv_metadata')) {
expect(sql).toContain(`parquet_kv_metadata('${fencedAdjPath}')`);
return makeFencedKvRows({
asOfMicros: Date.UTC(2026, 9, 1, 0, 0, 0) * 1000, // later as_of; vault_cutoff wins
vaultCutoffMicros: CUTOFF_MICROS,
rowsWritten: 1, // only the visible 2024-06-10 split
});
}
// Verification is bound to the exact file read in the bars SQL.
expect(sql).toContain(`read_parquet('${fencedAdjPath}')`);
const fencedCumSplitFactor = 2.0; // Vault 2026-07-15 split excluded before compounding
return [
{
listing_id: 42,
ts: Date.UTC(2024, 5, 7, 20, 0, 0),
open: rawPreSplitClose / fencedCumSplitFactor,
high: rawPreSplitClose / fencedCumSplitFactor,
low: rawPreSplitClose / fencedCumSplitFactor,
close: rawPreSplitClose / fencedCumSplitFactor,
volume: 1000 * fencedCumSplitFactor,
vwap: null,
known_at: Date.UTC(2024, 5, 7, 20, 0, 0),
},
];
},
});
const fencedStore = createDuckDbMarketDataStore({
executor: fencedFake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
immutableAdjFactorsPath: fencedAdjPath,
env: {},
});
const batches = await collectBars(
fencedStore.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})
);
expect(batches).toHaveLength(1);
expect(batches[0]!.rows[0]!.close).toBe(50.0);
expect(batches[0]!.rows[0]!.volume).toBe(2000);
expect(fencedFake.runCalls).toHaveLength(3);
expect(fencedFake.queryCalls).toHaveLength(2);
expect(fencedFake.calls.slice(0, 3).map(c => c.kind)).toEqual(['run', 'run', 'run']);
});
it('pins a single artifact version across footer check and factor scan when ETL atomically replaces part.parquet', async () => {
// Regression for TOCTOU between parquet_kv_metadata and read_parquet:
// Fixture mirrors tools/curate-etl/tests/curate_adj_qa_contract.rs:
// - Listing 42: visible 2-for-1 split (2024-06-10) + held-out Vault 2-for-1 split (2026-07-15)
// - Raw close on 2024-06-07: 100.0
// - Inode 1 (fenced, vault_cutoff = CUTOFF_MICROS): cum_split_factor = 2.0 -> close = 50.0
// - Inode 2 (retrospective replacement): cum_split_factor = 4.0 -> close = 25.0 (LEAK!)
interface VirtualAdjInode {
readonly id: number;
readonly kvRows: TableRow[];
readonly cumSplitFactor: number;
}
const fencedInode: VirtualAdjInode = {
id: 1,
kvRows: makeFencedKvRows({
asOfMicros: null,
vaultCutoffMicros: CUTOFF_MICROS,
rowsWritten: 1,
checksum: '0x024ec73a1afe7e6b',
}),
cumSplitFactor: 2.0,
};
const retrospectiveInode: VirtualAdjInode = {
id: 2,
kvRows: makeFencedKvRows({
snapshotKind: 'retrospective',
asOfMicros: null,
vaultCutoffMicros: null,
rowsWritten: 2,
checksum: '0x9999999999999999',
}),
cumSplitFactor: 4.0,
};
// Simulated POSIX directory entry + open file-descriptor table
const dirEntries = new Map<string, VirtualAdjInode>([[DEFAULT_ADJ_PATH, fencedInode]]);
const openFds = new Map<string, VirtualAdjInode>();
let nextFd = 42;
const releasedFds: string[] = [];
const pinAdjFactorsArtifact: AdjFactorsArtifactPinner = (sourcePath) => {
const inode = dirEntries.get(sourcePath);
if (inode === undefined) {
throw new Error(`ENOENT: ${sourcePath}`);
}
const fdPath = `/proc/self/fd/${nextFd}`;
nextFd += 1;
openFds.set(fdPath, inode);
return {
pinnedPath: fdPath,
release() {
openFds.delete(fdPath);
releasedFds.push(fdPath);
},
};
};
const resolvePath = (path: string): VirtualAdjInode => {
const inode = openFds.get(path) ?? dirEntries.get(path);
if (inode === undefined) {
throw new Error(`ENOENT: ${path}`);
}
return inode;
};
const rawPreSplitClose = 100.0;
let swapped = false;
const fake = createRecordingExecutor({
onQuery: (sql) => {
const metaMatch = /parquet_kv_metadata\('([^']+)'\)/.exec(sql);
if (metaMatch !== null) {
const path = metaMatch[1]!;
const inode = resolvePath(path);
// Simulate ETL atomically replacing the published path RIGHT BETWEEN
// footer verification and the bars factor scan.
if (!swapped) {
swapped = true;
dirEntries.set(DEFAULT_ADJ_PATH, retrospectiveInode);
}
return inode.kvRows;
}
const readMatches = [...sql.matchAll(/read_parquet\('([^']+)'\)/g)];
expect(readMatches).toHaveLength(1);
const adjPath = readMatches[0]![1]!;
const inode = resolvePath(adjPath);
return [
{
listing_id: 42,
ts: Date.UTC(2024, 5, 7, 20, 0, 0),
open: rawPreSplitClose / inode.cumSplitFactor,
high: rawPreSplitClose / inode.cumSplitFactor,
low: rawPreSplitClose / inode.cumSplitFactor,
close: rawPreSplitClose / inode.cumSplitFactor,
volume: 1000 * inode.cumSplitFactor,
vwap: null,
known_at: Date.UTC(2024, 5, 7, 20, 0, 0),
},
];
},
});
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
pinAdjFactorsArtifact,
env: {},
});
// 1. In-flight query pinned Inode 1 before ETL replaced DEFAULT_ADJ_PATH with Inode 2.
// Both parquet_kv_metadata and read_parquet read /proc/self/fd/42 -> Inode 1 -> close = 50.0.
const batches = await collectBars(
store.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})
);
expect(swapped).toBe(true);
expect(batches).toHaveLength(1);
expect(batches[0]!.rows[0]!.close).toBe(50.0);
expect(batches[0]!.rows[0]!.volume).toBe(2000);
expect(fake.queryCalls).toHaveLength(2);
expect(fake.queryCalls[0]!.sql).toContain("parquet_kv_metadata('/proc/self/fd/42')");
expect(fake.queryCalls[1]!.sql).toContain("read_parquet('/proc/self/fd/42')");
expect(releasedFds).toEqual(['/proc/self/fd/42']);
expect(openFds.size).toBe(0);
// 2. Next query opens the newly published retrospective Inode 2 via /proc/self/fd/43,
// fails closed on footer verification without scanning bars, and still releases the fd.
try {
await collectBars(
store.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})
);
expect.unreachable('should fail closed on retrospective replacement');
} catch (err) {
expect(err).toBeInstanceOf(AdjFactorsSnapshotError);
expect((err as AdjFactorsSnapshotError).code).toBe('retrospective_rejected');
}
expect(fake.queryCalls).toHaveLength(3);
expect(fake.queryCalls[2]!.sql).toContain("parquet_kv_metadata('/proc/self/fd/43')");
expect(releasedFds).toEqual(['/proc/self/fd/42', '/proc/self/fd/43']);
expect(openFds.size).toBe(0);
});
it('preserves the `this` receiver when calling pinned artifact `release()` after successful and failed scans', async () => {
class HandlePinnedArtifact implements PinnedAdjFactorsArtifact {
readonly pinnedPath: string;
released = false;
releaseCount = 0;
readonly fileHandle: { closed: boolean; close: () => Promise<void> };
constructor(pinnedPath: string) {
this.pinnedPath = pinnedPath;
this.fileHandle = {
closed: false,
close: () => {
this.fileHandle.closed = true;
return Promise.resolve();
},
};
}
async release(): Promise<void> {
if (!(this instanceof HandlePinnedArtifact)) {
throw new TypeError('release() was invoked without its PinnedAdjFactorsArtifact receiver');
}
await this.fileHandle.close();
this.released = true;
this.releaseCount += 1;
}
}
const createdPins: HandlePinnedArtifact[] = [];
let nextFd = 100;
const pinAdjFactorsArtifact: AdjFactorsArtifactPinner = () => {
const pin = new HandlePinnedArtifact(`/proc/self/fd/${nextFd}`);
nextFd += 1;
createdPins.push(pin);
return pin;
};
let shouldFailScan = false;
const fake = createRecordingExecutor({
onQuery: (sql) => {
if (sql.includes('parquet_kv_metadata')) {
return makeFencedKvRows({
asOfMicros: null,
vaultCutoffMicros: CUTOFF_MICROS,
rowsWritten: 1,
});
}
if (shouldFailScan) {
throw new Error('simulated DuckDB bars scan failure');
}
return [
{
listing_id: 42,
ts: Date.UTC(2024, 5, 7, 20, 0, 0),
open: 50.0,
high: 51.0,
low: 49.5,
close: 50.0,
volume: 2000,
vwap: 50.25,
known_at: Date.UTC(2024, 5, 7, 20, 0, 0),
},
];
},
});
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
pinAdjFactorsArtifact,
env: {},
});
// 1. Successful split-adjusted scan: returns rows and invokes pin.release() with `this` intact.
const batches = await collectBars(
store.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})
);
expect(batches).toHaveLength(1);
expect(batches[0]!.rows[0]!.close).toBe(50.0);
expect(createdPins).toHaveLength(1);
expect(createdPins[0]!.released).toBe(true);
expect(createdPins[0]!.fileHandle.closed).toBe(true);
expect(createdPins[0]!.releaseCount).toBe(1);
// 2. Failed scan (executor error): propagates error and still invokes pin.release() with `this` intact.
shouldFailScan = true;
await expect(
collectBars(
store.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})
)
).rejects.toThrow('simulated DuckDB bars scan failure');
expect(createdPins).toHaveLength(2);
expect(createdPins[1]!.released).toBe(true);
expect(createdPins[1]!.fileHandle.closed).toBe(true);
expect(createdPins[1]!.releaseCount).toBe(1);
});
it('fails closed on unpinned mutable adj_factors paths and buggy no-op pinners', async () => {
// 1. Default mutable path with neither pinAdjFactorsArtifact nor immutableAdjFactorsPath
const unpinnedFake = createRecordingExecutor();
const unpinnedStore = createDuckDbMarketDataStore({
executor: unpinnedFake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env: {},
});
try {
await collectBars(
unpinnedStore.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})
);
expect.unreachable('should fail closed on unpinned mutable path');
} catch (err) {
expect(err).toBeInstanceOf(AdjFactorsSnapshotError);
expect((err as AdjFactorsSnapshotError).code).toBe('unpinned_mutable_path');
}
expect(unpinnedFake.calls).toHaveLength(0);
// 2. Buggy no-op pinner returning the mutable path itself fails closed and still releases
let released = false;
const noopFake = createRecordingExecutor();
const noopStore = createDuckDbMarketDataStore({
executor: noopFake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
pinAdjFactorsArtifact: (sourcePath) => ({
pinnedPath: sourcePath,
release() {
released = true;
},
}),
env: {},
});
try {
await collectBars(
noopStore.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'total',
})
);
expect.unreachable('should reject no-op pinner returning mutable path');
} catch (err) {
expect(err).toBeInstanceOf(AdjFactorsSnapshotError);
expect((err as AdjFactorsSnapshotError).code).toBe('unpinned_mutable_path');
}
expect(released).toBe(true);
expect(noopFake.queryCalls).toHaveLength(0);
// 3. Pinner returning malformed handle or invalid path rejects cleanly and releases when possible
const badHandleStore = createDuckDbMarketDataStore({
executor: noopFake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
pinAdjFactorsArtifact: (() => null) as unknown as AdjFactorsArtifactPinner,
env: {},
});
await expect(
collectBars(
badHandleStore.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})
)
).rejects.toThrow(MarketDataStoreValidationError);
let badPathReleased = false;
const badPathStore = createDuckDbMarketDataStore({
executor: noopFake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
pinAdjFactorsArtifact: () =>
({
pinnedPath: '/proc/self/fd/0',
release() {
badPathReleased = true;
},
}) as PinnedAdjFactorsArtifact,
env: {},
});
await expect(
collectBars(
badPathStore.bars({
listingIds: [42],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})
)
).rejects.toThrow(MarketDataStoreValidationError);
expect(badPathReleased).toBe(true);
});
it('validates pinned fd handles and .parquet paths strictly in validateAdjFactorsArtifactPath', () => {
expect(validateAdjFactorsArtifactPath('/proc/self/fd/12')).toBe('/proc/self/fd/12');
expect(validateAdjFactorsArtifactPath('/dev/fd/5')).toBe('/dev/fd/5');
expect(validateAdjFactorsArtifactPath(DEFAULT_ADJ_PATH)).toBe(DEFAULT_ADJ_PATH);
for (const bad of [
'',
'relative.parquet',
'/data/adj_factors/part.csv',
'/proc/self/fd/0',
'/proc/self/fd/-1',
'/proc/self/fd/abc',
"/proc/self/fd/12'; DROP TABLE x",
'/tmp/pin-*.parquet',
]) {
expect(() => validateAdjFactorsArtifactPath(bad)).toThrow(MarketDataStoreValidationError);
}
});
it('rejects retrospective snapshot even under authorized vault_evaluation_only', () => {
const retroSnapshot = parseAdjFactorsSnapshotMetadata(
DEFAULT_ADJ_PATH,
makeFencedKvRows({ snapshotKind: 'retrospective', asOfMicros: null, vaultCutoffMicros: null })
);
try {
planBars1dQuery(
{
listingIds: [42],
timeframe: '1d',
from: '2026-06-01',
to: '2026-07-01',
adjustment: 'split',
scope: 'vault_evaluation_only',
},
{
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
vaultOperatorAuthorized: true,
adjFactorsSnapshot: retroSnapshot,
}
);
expect.unreachable('should reject retrospective snapshot under vault_evaluation_only');
} catch (err) {
expect(err).toBeInstanceOf(AdjFactorsSnapshotError);
expect((err as AdjFactorsSnapshotError).code).toBe('retrospective_rejected');
}
});
});
describe('mandatory Vault & PIT invariants + TZ invariance', () => {
it('enforces bound known_at <= ? and upper bounds < vaultCutoffTs across 400 seeded mixed queries', () => {
const rng = createMulberry32(20261129);
const baseMs = Date.UTC(2015, 0, 1, 0, 0, 0, 0);
const preCutoffSpanMs = CUTOFF_MS - baseMs - 86_400_000;
const postCutoffSpanMs = 365 * 86_400_000;
for (let i = 0; i < 400; i += 1) {
const fromMs = baseMs + Math.floor(rng() * preCutoffSpanMs);
const toMs = fromMs + Math.floor(rng() * (CUTOFF_MS - fromMs + postCutoffSpanMs));
const asOfMs =
rng() < 0.35
? undefined
: baseMs + Math.floor(rng() * (CUTOFF_MS - baseMs + postCutoffSpanMs));
const fromStr =
rng() < 0.5 ? new Date(fromMs).toISOString().slice(0, 10) : new Date(fromMs).toISOString();
const toStr =
rng() < 0.5 ? new Date(toMs).toISOString().slice(0, 10) : new Date(toMs).toISOString();
const asOfStr =
asOfMs === undefined
? undefined
: rng() < 0.5
? new Date(asOfMs).toISOString().slice(0, 10)
: new Date(asOfMs).toISOString();
const kindIdx = i % 4;
let planned;
if (kindIdx === 0) {
const adj = BARS_ADJUSTMENTS[i % 3]!;
// Compute matching fenced snapshot for split/total
const rawPlan = planBars1dQuery(
{
listingIds: [1],
timeframe: '1d',
from: fromStr,
to: toStr,
adjustment: 'raw',
asOf: asOfStr,
},
DEFAULT_CTX
);
const effAsOfMicros = parseIsoToMicros(rawPlan.params[rawPlan.params.length - 1] as string);
const snapshot = makeFencedSnapshot({
asOfMicros: effAsOfMicros,
vaultCutoffMicros: CUTOFF_MICROS,
});
planned = planBars1dQuery(
{
listingIds: [1 + Math.floor(rng() * 100_000)],
timeframe: '1d',
from: fromStr,
to: toStr,
adjustment: adj,
asOf: asOfStr,
},
adj === 'raw' ? DEFAULT_CTX : { ...DEFAULT_CTX, adjFactorsSnapshot: snapshot }
);
expect(planned.sql).toContain('known_at <= ?');
expect(planned.sql).toContain('b.ts <= ?');
const boundTo = planned.params[planned.params.length - 2] as string;
const boundAsOf = planned.params[planned.params.length - 1] as string;
expect(parseIsoToMicros(boundTo)).toBeLessThan(CUTOFF_MICROS);
expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS);
if (adj !== 'raw') {
const adjAsOf = planned.params[1] as string;
expect(parseIsoToMicros(adjAsOf)).toBeLessThan(CUTOFF_MICROS);
}
} else if (kindIdx === 1) {
planned = planEventsQuery(
{
kinds: [EVENT_KINDS[i % EVENT_KINDS.length]!],
listingIds: rng() < 0.5 ? [1 + Math.floor(rng() * 100_000)] : undefined,
from: fromStr,
to: toStr,
asOf: asOfStr,
},
DEFAULT_CTX
);
expect(planned.sql).toContain('e.known_at <= ?');
expect(planned.sql).toContain('e.ts <= ?');
const boundTo = planned.params[planned.params.length - 2] as string;
const boundAsOf = planned.params[planned.params.length - 1] as string;
expect(parseIsoToMicros(boundTo)).toBeLessThan(CUTOFF_MICROS);
expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS);
} else if (kindIdx === 2) {
planned = planShortsAsOfQuery(
{
listingIds: [1 + Math.floor(rng() * 100_000)],
from: fromStr,
to: toStr,
asOf: asOfStr,
},
DEFAULT_CTX
);
expect(planned.sql).toContain('s.known_at <= ?');
expect(planned.sql).toContain('s.report_date <= ?');
const boundToDate = planned.params[planned.params.length - 2] as string;
const boundAsOf = planned.params[planned.params.length - 1] as string;
expect(Date.parse(`${boundToDate}T00:00:00.000Z`)).toBeLessThan(CUTOFF_MS);
expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS);
} else {
planned = planFx1dQuery(
{
pair: 'USD.CAD',
timeframe: '1d',
from: fromStr,
to: toStr,
},
DEFAULT_CTX
);
expect(planned.sql).toContain('f.known_at <= ?');
expect(planned.sql).toContain('f.ts <= ?');
const boundTo = planned.params[planned.params.length - 2] as string;
const boundAsOf = planned.params[planned.params.length - 1] as string;
expect(parseIsoToMicros(boundTo)).toBeLessThan(CUTOFF_MICROS);
expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS);
}
expect(planned.fenced.toMs).toBeLessThan(CUTOFF_MS);
expect(planned.fenced.asOfMs).toBeLessThan(CUTOFF_MS);
}
});
it('produces identical SQL and bound params under TZ=UTC and TZ=America/Toronto', () => {
const previousTz = process.env.TZ;
const asOfMicros = Date.UTC(2025, 10, 3, 6, 30, 0) * 1000; // 2025-11-03T01:30:00-05:00
const snapshot = makeFencedSnapshot({ asOfMicros, vaultCutoffMicros: CUTOFF_MICROS });
try {
const runAll = () => ({
bars: planBars1dQuery(
{
listingIds: [101],
timeframe: '1d',
from: '2025-03-08',
to: '2025-11-02',
adjustment: 'total',
asOf: '2025-11-03T01:30:00-05:00',
},
{ ...DEFAULT_CTX, adjFactorsSnapshot: snapshot }
),
events: planEventsQuery(
{
kinds: ['filing', 'earnings'],
from: '2025-03-08',
to: '2025-11-02',
},
DEFAULT_CTX
),
shorts: planShortsAsOfQuery(
{
listingIds: [101],
from: '2025-03-08',
to: '2025-11-02',
},
DEFAULT_CTX
),
fx: planFx1dQuery(
{
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-03-08',
to: '2025-11-02',
},
DEFAULT_CTX
),
});
process.env.TZ = 'UTC';
const utcResult = runAll();
process.env.TZ = 'America/Toronto';
const torontoResult = runAll();
expect(torontoResult).toEqual(utcResult);
} finally {
if (previousTz === undefined) {
delete process.env.TZ;
} else {
process.env.TZ = previousTz;
}
}
});
});
describe('Vault fence enforcement with zero executor calls', () => {
it('throws VaultHoldoutFenceError when from >= vaultCutoffTs across all 4 endpoints (incl. split bars) with 0 executor calls', async () => {
const fake = createRecordingExecutor();
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
});
await expect(
collectBars(
store.bars({
listingIds: [1],
timeframe: '1d',
from: '2026-05-28',
to: '2026-06-01',
adjustment: 'raw',
})
)
).rejects.toThrow(VaultHoldoutFenceError);
await expect(
collectBars(
store.bars({
listingIds: [1],
timeframe: '1d',
from: '2026-05-28',
to: '2026-06-01',
adjustment: 'split',
})
)
).rejects.toThrow(VaultHoldoutFenceError);
await expect(
store.events({
kinds: ['filing'],
from: '2026-05-28T00:00:00Z',
to: '2026-06-01',
})
).rejects.toThrow(VaultHoldoutFenceError);
await expect(
store.shortsAsOf({
listingIds: [1],
from: '2026-05-29',
to: '2026-06-01',
})
).rejects.toThrow(VaultHoldoutFenceError);
await expect(
store.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2026-05-28',
to: '2026-06-01',
})
).rejects.toThrow(VaultHoldoutFenceError);
expect(fake.calls).toHaveLength(0);
});
it('throws VaultScopeNotAuthorizedError for unauthorized vault_evaluation_only with 0 executor calls', async () => {
const fake = createRecordingExecutor();
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
});
await expect(
collectBars(
store.bars({
listingIds: [1],
timeframe: '1d',
from: '2026-06-01',
to: '2026-07-01',
adjustment: 'split',
scope: 'vault_evaluation_only',
})
)
).rejects.toThrow(VaultScopeNotAuthorizedError);
expect(fake.calls).toHaveLength(0);
});
it('permits unclamped bars query when vault_evaluation_only is explicitly authorized', () => {
const planned = planBars1dQuery(
{
listingIds: [1],
timeframe: '1d',
from: '2026-06-01',
to: '2026-07-01',
adjustment: 'raw',
scope: 'vault_evaluation_only',
},
{
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
vaultOperatorAuthorized: true,
}
);
expect(planned.fenced.scope).toBe('vault_evaluation_only');
expect(planned.fenced.clampedTo).toBe(false);
expect(planned.params).toEqual([
1,
'2026-06-01T00:00:00.000Z',
'2026-07-01T23:59:59.999999Z',
'2026-07-01T23:59:59.999999Z',
]);
});
it('keeps events, shortsAsOf, and fx vault_fenced even when vaultOperatorAuthorized is true', () => {
const authCtx: DuckDbPlanContext = {
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
vaultOperatorAuthorized: true,
};
expect(() =>
planEventsQuery({ kinds: ['filing'], from: '2026-06-01', to: '2026-07-01' }, authCtx)
).toThrow(VaultHoldoutFenceError);
expect(() =>
planShortsAsOfQuery({ listingIds: [1], from: '2026-06-01', to: '2026-07-01' }, authCtx)
).toThrow(VaultHoldoutFenceError);
expect(() =>
planFx1dQuery({ pair: 'USD.CAD', timeframe: '1d', from: '2026-06-01', to: '2026-07-01' }, authCtx)
).toThrow(VaultHoldoutFenceError);
});
});
describe('SQL injection & strict boundary validation', () => {
it('rejects malicious or malformed curatedRoot values with MarketDataStoreValidationError', () => {
const badRoots = [
'',
'relative/path',
'/data/curated; DROP TABLE x',
"/data/curated' OR '1'='1",
'/data/curated\n/evil',
'/data/curated\r/evil',
'/data/curated\0/evil',
'/data/curated\x7f/evil',
'/data/curated/*',
'/data/curated/?',
'/data/curated/[a-z]',
'/data/curated/]',
];
for (const root of badRoots) {
expect(() => validateCuratedRoot(root)).toThrow(MarketDataStoreValidationError);
expect(() =>
planFx1dQuery(
{ pair: 'USD.CAD', timeframe: '1d', from: '2025-01-01', to: '2025-02-01' },
{ curatedRoot: root, vaultCutoffTs: CUTOFF_MS }
)
).toThrow(MarketDataStoreValidationError);
}
});
it('rejects non-INT32, non-integer, non-number, or empty listingIds with zero executor calls', async () => {
const fake = createRecordingExecutor();
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
});
const badListingIdInputs: unknown[] = [
[],
[1.5],
[Number.NaN],
[Number.POSITIVE_INFINITY],
[Number.NEGATIVE_INFINITY],
[2_147_483_648],
[-2_147_483_649],
['101' as unknown as number],
];
for (const badIds of badListingIdInputs) {
await expect(
collectBars(
store.bars({
listingIds: badIds as number[],
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
adjustment: 'raw',
})
)
).rejects.toThrow(MarketDataStoreValidationError);
await expect(
store.shortsAsOf({
listingIds: badIds as number[],
from: '2025-01-01',
to: '2025-02-01',
})
).rejects.toThrow(MarketDataStoreValidationError);
}
expect(fake.calls).toHaveLength(0);
});
it('rejects unknown/empty kinds, unsupported pair, invalid adjustment, and unknown timeframe with zero executor calls', async () => {
const fake = createRecordingExecutor();
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
});
await expect(
store.events({
kinds: [],
from: '2025-01-01',
to: '2025-02-01',
})
).rejects.toThrow(MarketDataStoreValidationError);
await expect(
store.events({
kinds: ["filing' OR '1'='1" as unknown as 'filing'],
from: '2025-01-01',
to: '2025-02-01',
})
).rejects.toThrow(MarketDataStoreValidationError);
await expect(
store.fx({
pair: 'EUR.USD' as unknown as 'USD.CAD',
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
})
).rejects.toThrow(MarketDataStoreValidationError);
await expect(
store.fx({
pair: 'USD.CAD',
timeframe: '2d' as unknown as '1d',
from: '2025-01-01',
to: '2025-02-01',
})
).rejects.toThrow(MarketDataStoreValidationError);
await expect(
collectBars(
store.bars({
listingIds: [1],
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
adjustment: 'dividend' as unknown as 'raw',
})
)
).rejects.toThrow(MarketDataStoreValidationError);
await expect(
collectBars(
store.bars({
listingIds: [1],
timeframe: '2d' as unknown as '1d',
from: '2025-01-01',
to: '2025-02-01',
adjustment: 'raw',
})
)
).rejects.toThrow(MarketDataStoreValidationError);
expect(fake.calls).toHaveLength(0);
});
it('never embeds caller-supplied values other than validated curatedRoot/adjPath in SQL text', () => {
const sentinelId = 987654321;
const asOfMicros = Date.UTC(2025, 9, 5, 15, 45, 0) * 1000;
const snapshot = makeFencedSnapshot({ asOfMicros, vaultCutoffMicros: CUTOFF_MICROS });
const barsPlan = planBars1dQuery(
{
listingIds: [sentinelId],
timeframe: '1d',
from: '2024-03-14',
to: '2025-09-22',
adjustment: 'total',
asOf: '2025-10-05T15:45:00Z',
},
{ ...DEFAULT_CTX, adjFactorsSnapshot: snapshot }
);
expect(barsPlan.sql).not.toContain(String(sentinelId));
expect(barsPlan.sql).not.toContain('2024-03-14');
expect(barsPlan.sql).not.toContain('2025-09-22');
expect(barsPlan.sql).not.toContain('2025-10-05');
const eventsPlan = planEventsQuery(
{
kinds: ['ceo_post'],
listingIds: [sentinelId],
from: '2024-03-14',
to: '2025-09-22',
},
DEFAULT_CTX
);
expect(eventsPlan.sql).not.toContain('ceo_post');
expect(eventsPlan.sql).not.toContain(String(sentinelId));
expect(eventsPlan.sql).not.toContain('2024-03-14');
const fxPlan = planFx1dQuery(
{
pair: 'USD.CAD',
timeframe: '1d',
from: '2024-03-14',
to: '2025-09-22',
},
DEFAULT_CTX
);
expect(fxPlan.sql).not.toContain('USD.CAD');
expect(fxPlan.sql).not.toContain('USDCAD');
expect(fxPlan.sql).not.toContain('2024-03-14');
});
});
describe('createDuckDbMarketDataStore adapter behavior', () => {
it('validates options eagerly at construction', () => {
const fake = createRecordingExecutor();
expect(() =>
createDuckDbMarketDataStore({
executor: {} as unknown as DuckDbExecutor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
})
).toThrow(MarketDataStoreValidationError);
expect(() =>
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: 'relative',
vaultCutoffTs: CUTOFF_MS,
})
).toThrow(MarketDataStoreValidationError);
expect(() =>
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
adjFactorsPath: "/evil'; DROP TABLE x;.parquet",
})
).toThrow(MarketDataStoreValidationError);
expect(() =>
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
immutableAdjFactorsPath: DEFAULT_ADJ_PATH,
})
).toThrow(MarketDataStoreValidationError);
expect(() =>
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
immutableAdjFactorsPath: `${CURATED_ROOT}//adj_factors/./sub/../part.parquet`,
})
).toThrow(MarketDataStoreValidationError);
expect(() =>
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
adjFactorsPath: DEFAULT_ADJ_PATH,
immutableAdjFactorsPath: `${CURATED_ROOT}/adj_factors/snapshots/s1.parquet`,
})
).toThrow(MarketDataStoreValidationError);
expect(() =>
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
pinAdjFactorsArtifact: 'not-a-fn' as unknown as AdjFactorsArtifactPinner,
})
).toThrow(MarketDataStoreValidationError);
expect(() =>
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: Number.NaN,
})
).toThrow(MarketDataStoreValidationError);
expect(() =>
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
barBatchSize: 0,
})
).toThrow(MarketDataStoreValidationError);
expect(() =>
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env: { STOCKBOT_DUCKDB_THREADS: '0' },
})
).toThrow(MarketDataStoreValidationError);
expect(fake.calls).toHaveLength(0);
});
it('runs the three budget SET statements sequentially, once, and strictly before the first query (including concurrent first calls)', async () => {
const env = {
STOCKBOT_DUCKDB_MEMORY_LIMIT: '4GB',
STOCKBOT_DUCKDB_THREADS: '2',
STOCKBOT_DUCKDB_TEMP_DIRECTORY: '/tmp/duckdb-test',
};
const expectedStatements = resolveDuckDbConnectionBudget(env).statements;
const fake = createRecordingExecutor({
async onRun() {
await Promise.resolve();
},
async onQuery() {
return [];
},
});
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env,
});
// Zero calls before first query
expect(fake.calls).toHaveLength(0);
await Promise.all([
collectBars(
store.bars({
listingIds: [1],
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
adjustment: 'raw',
})
),
store.events({
kinds: ['filing'],
from: '2025-01-01',
to: '2025-02-01',
}),
store.shortsAsOf({
listingIds: [1],
from: '2025-01-01',
to: '2025-02-01',
}),
store.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
}),
]);
expect(fake.runCalls).toEqual(expectedStatements);
expect(fake.queryCalls).toHaveLength(4);
expect(fake.calls.slice(0, 3).map(c => c.kind)).toEqual(['run', 'run', 'run']);
expect(fake.calls.slice(3).map(c => c.kind)).toEqual(['query', 'query', 'query', 'query']);
// Subsequent call does not re-run SET statements
await store.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
});
expect(fake.runCalls).toHaveLength(3);
expect(fake.queryCalls).toHaveLength(5);
});
it('retries budget initialization cleanly if an initial executor.run call rejects', async () => {
let failOnce = true;
const fake = createRecordingExecutor({
async onRun(_sql, callIndex) {
if (failOnce && callIndex === 1) {
failOnce = false;
throw new Error('transient DuckDB SET failure');
}
},
onQuery: () => [],
});
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env: {},
});
await expect(
store.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
})
).rejects.toThrow('transient DuckDB SET failure');
expect(fake.queryCalls).toHaveLength(0);
// Second attempt retries all 3 SET statements and executes the query
const table = await store.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
});
expect(table).toEqual({ columns: [...FX_1D_COLUMNS], rows: [] });
expect(fake.runCalls).toHaveLength(5); // 2 from failed attempt + 3 from retry
expect(fake.queryCalls).toHaveLength(1);
});
it('maps BarBatch rows with nullable vwap, empty results, and barBatchSize chunking', async () => {
const sampleRows: TableRow[] = [
{
listing_id: 101,
ts: Date.UTC(2025, 0, 2, 21, 0, 0),
open: 10,
high: 12,
low: 9.5,
close: 11.25,
volume: 1000,
vwap: 10.8,
known_at: Date.UTC(2025, 0, 2, 22, 0, 0),
},
{
listing_id: 101,
ts: Date.UTC(2025, 0, 3, 21, 0, 0),
open: 11.25,
high: 11.5,
low: 10.9,
close: 11.1,
volume: 0,
vwap: null,
known_at: Date.UTC(2025, 0, 3, 22, 0, 0),
},
{
listing_id: 202,
ts: Date.UTC(2025, 0, 2, 21, 0, 0),
open: 50,
high: 52,
low: 49,
close: 51,
volume: 500,
vwap: null,
known_at: Date.UTC(2025, 0, 2, 22, 0, 0),
},
];
const fake = createRecordingExecutor({
onQuery: (_sql, _params, idx) => (idx === 0 ? sampleRows : []),
});
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env: {},
barBatchSize: 2,
});
const batches = await collectBars(
store.bars({
listingIds: [101, 202],
timeframe: '1d',
from: '2025-01-01',
to: '2025-01-10',
adjustment: 'raw',
})
);
expect(batches).toHaveLength(2);
expect(batches[0]!.rows).toEqual([
{
listingId: 101,
ts: Date.UTC(2025, 0, 2, 21, 0, 0),
open: 10,
high: 12,
low: 9.5,
close: 11.25,
volume: 1000,
vwap: 10.8,
knownAt: Date.UTC(2025, 0, 2, 22, 0, 0),
},
{
listingId: 101,
ts: Date.UTC(2025, 0, 3, 21, 0, 0),
open: 11.25,
high: 11.5,
low: 10.9,
close: 11.1,
volume: 0,
vwap: null,
knownAt: Date.UTC(2025, 0, 3, 22, 0, 0),
},
]);
expect(batches[1]!.rows).toHaveLength(1);
expect(batches[1]!.rows[0]!.listingId).toBe(202);
// Empty result yields 0 batches
const emptyBatches = await collectBars(
store.bars({
listingIds: [101],
timeframe: '1d',
from: '2025-01-01',
to: '2025-01-10',
adjustment: 'raw',
})
);
expect(emptyBatches).toEqual([]);
});
it('maps Table rows for events, shortsAsOf, and fx and strips unexpected extra columns', async () => {
const fake = createRecordingExecutor({
onQuery: (sql) => {
if (sql.includes('/events/')) {
return [
{
listing_id: 10,
ts: 1_700_000_000_000,
known_at: 1_700_000_000_000,
known_at_source: 'filing_timestamp',
kind: 'filing',
subtype: '10-k',
payload_json: '{"form":"10-K"}',
extra_ignored: 'should-not-appear',
},
];
}
if (sql.includes('/shorts/')) {
return [
{
listing_id: 10,
report_date: '2025-01-15',
known_at: 1_737_500_000_000,
shares_short: 125_000,
net_change: null,
pct_float: null,
source: 'ceo_shorts',
},
];
}
return [
{
pair: 'USDCAD',
session_date: '2025-01-15',
ts: 1_736_985_599_999,
open: 1.43,
high: 1.44,
low: 1.425,
close: 1.435,
source: 'eod_cad_forex',
known_at: 1_736_985_599_999,
},
];
},
});
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env: {},
});
const events = await store.events({
kinds: ['filing'],
from: '2023-01-01',
to: '2025-02-01',
});
expect(events.columns).toEqual([...EVENTS_COLUMNS]);
expect(events.rows).toEqual([
{
listing_id: 10,
ts: 1_700_000_000_000,
known_at: 1_700_000_000_000,
known_at_source: 'filing_timestamp',
kind: 'filing',
subtype: '10-k',
payload_json: '{"form":"10-K"}',
},
]);
const shorts = await store.shortsAsOf({
listingIds: [10],
from: '2025-01-01',
to: '2025-02-01',
});
expect(shorts.columns).toEqual([...SHORTS_COLUMNS]);
expect(shorts.rows[0]!.net_change).toBeNull();
expect(shorts.rows[0]!.pct_float).toBeNull();
const fx = await store.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
});
expect(fx.columns).toEqual([...FX_1D_COLUMNS]);
expect(fx.rows[0]!.pair).toBe('USDCAD');
});
it('validates per-column scalar types and nullability even when all expected columns are present', async () => {
const cases: Array<{
label: string;
row: TableRow;
run: (store: ReturnType<typeof createDuckDbMarketDataStore>) => Promise<unknown>;
}> = [
{
label: 'fx stringified ts',
row: {
pair: 'USDCAD',
session_date: '2025-01-15',
ts: '2025-01-15T23:59:59.999999Z', // wrong scalar type (string instead of safe_int)
open: 1.43,
high: 1.44,
low: 1.425,
close: 1.435,
source: 'eod_cad_forex',
known_at: 1_736_985_599_999,
},
run: (s) => s.fx({ pair: 'USD.CAD', timeframe: '1d', from: '2025-01-15', to: '2025-01-15' }),
},
{
label: 'fx null close',
row: {
pair: 'USDCAD',
session_date: '2025-01-15',
ts: 1_736_985_599_999,
open: 1.43,
high: 1.44,
low: 1.425,
close: null, // forbidden null
source: 'eod_cad_forex',
known_at: 1_736_985_599_999,
},
run: (s) => s.fx({ pair: 'USD.CAD', timeframe: '1d', from: '2025-01-15', to: '2025-01-15' }),
},
{
label: 'events stringified listing_id',
row: {
listing_id: '10', // wrong scalar type (string instead of int32)
ts: 1_700_000_000_000,
known_at: 1_700_000_000_000,
known_at_source: 'filing_timestamp',
kind: 'filing',
subtype: '10-k',
payload_json: '{}',
},
run: (s) => s.events({ kinds: ['filing'], from: '2023-01-01', to: '2025-02-01' }),
},
{
label: 'shorts null required shares_short',
row: {
listing_id: 10,
report_date: '2025-01-15',
known_at: 1_737_500_000_000,
shares_short: null, // forbidden null
net_change: null,
pct_float: null,
source: 'ceo_shorts',
},
run: (s) => s.shortsAsOf({ listingIds: [10], from: '2025-01-01', to: '2025-02-01' }),
},
];
for (const c of cases) {
const fake = createRecordingExecutor({ onQuery: () => [c.row] });
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env: {},
});
await expect(c.run(store)).rejects.toThrow(MarketDataStoreValidationError);
}
});
it('rejects malformed driver rows with MarketDataStoreValidationError and propagates executor errors', async () => {
const malformedFake = createRecordingExecutor({
onQuery: (sql) => {
if (sql.includes('/bars_1d/')) {
return [{ listing_id: 101, ts: 1000, open: Number.NaN, high: 1, low: 1, close: 1, volume: 1, vwap: null, known_at: 1000 }];
}
return [{ pair: 'USDCAD' }]; // missing columns
},
});
const malformedStore = createDuckDbMarketDataStore({
executor: malformedFake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env: {},
});
await expect(
collectBars(
malformedStore.bars({
listingIds: [101],
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
adjustment: 'raw',
})
)
).rejects.toThrow(MarketDataStoreValidationError);
await expect(
malformedStore.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-01-01',
to: '2025-02-01',
})
).rejects.toThrow(MarketDataStoreValidationError);
const failingFake = createRecordingExecutor({
onQuery: async () => {
throw new Error('parquet file missing');
},
});
const failingStore = createDuckDbMarketDataStore({
executor: failingFake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env: {},
});
await expect(
failingStore.events({
kinds: ['filing'],
from: '2025-01-01',
to: '2025-02-01',
})
).rejects.toThrow('parquet file missing');
});
it('rejects all out-of-slice methods and timeframes with MarketDataStoreNotImplementedError and 0 executor calls', async () => {
const fake = createRecordingExecutor();
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
env: {},
});
const cases: Array<{ method: string; run: () => Promise<unknown> }> = [
{
method: 'bars',
run: () =>
collectBars(
store.bars({
listingIds: [1],
timeframe: '1m',
from: '2025-01-01',
to: '2025-02-01',
adjustment: 'raw',
})
),
},
{
method: 'bars',
run: () =>
collectBars(
store.bars({
listingIds: [1],
timeframe: '5m',
from: '2025-01-01',
to: '2025-02-01',
adjustment: 'split',
})
),
},
{
method: 'bars',
run: () =>
collectBars(
store.bars({
listingIds: [1],
timeframe: '1h',
from: '2025-01-01',
to: '2025-02-01',
adjustment: 'total',
})
),
},
{
method: 'fx',
run: () =>
store.fx({
pair: 'USD.CAD',
timeframe: '1m',
from: '2025-01-01',
to: '2025-02-01',
}),
},
{
method: 'crossSection',
run: () =>
store.crossSection({
features: ['ret_20d'],
date: '2025-01-15',
universe: 'US_EQ',
}),
},
{
method: 'macroAsOf',
run: () =>
store.macroAsOf({
countries: ['US'],
indicators: ['CPI'],
from: '2025-01-01',
to: '2025-02-01',
}),
},
];
for (const c of cases) {
let caught: unknown;
try {
await c.run();
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(MarketDataStoreNotImplementedError);
expect((caught as MarketDataStoreNotImplementedError).method).toBe(c.method);
}
expect(fake.calls).toHaveLength(0);
});
});
describe('planUniverseQuery & createDuckDbMarketDataStore().universe()', () => {
it('plans exact SQL and ordered bound parameters for US_EQ, CA_EQ, and US_CA_EQ without interpolation', () => {
expect(UNIVERSE_REFS).toEqual(['US_EQ', 'CA_EQ', 'US_CA_EQ']);
expect(DEFAULT_UNIVERSE_LOOKBACK_DAYS).toBe(7);
const expectedSingleCurrencySql =
'SELECT DISTINCT b.listing_id ' +
`FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b ` +
'WHERE b.currency = ? AND b.session_date >= ? AND b.session_date <= ? AND b.ts <= ? AND b.known_at <= ? ' +
'ORDER BY b.listing_id ASC';
const expectedDualCurrencySql =
'SELECT DISTINCT b.listing_id ' +
`FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b ` +
'WHERE b.currency IN (?, ?) AND b.session_date >= ? AND b.session_date <= ? AND b.ts <= ? AND b.known_at <= ? ' +
'ORDER BY b.listing_id ASC';
const us = planUniverseQuery({ ref: 'US_EQ', date: '2025-06-15' }, DEFAULT_CTX);
expect(us.sql).toBe(expectedSingleCurrencySql);
expect(us.params).toEqual([
'USD',
'2025-06-08',
'2025-06-15',
'2025-06-15T23:59:59.999999Z',
'2025-06-15T23:59:59.999999Z',
]);
expect(us.fenced).toEqual({
fromMs: Date.UTC(2025, 5, 8, 0, 0, 0, 0),
toMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999),
asOfMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999),
scope: 'vault_fenced',
clampedTo: false,
clampedAsOf: false,
});
const ca = planUniverseQuery({ ref: 'CA_EQ', date: '2025-06-15' }, DEFAULT_CTX);
expect(ca.sql).toBe(expectedSingleCurrencySql);
expect(ca.params).toEqual([
'CAD',
'2025-06-08',
'2025-06-15',
'2025-06-15T23:59:59.999999Z',
'2025-06-15T23:59:59.999999Z',
]);
const usCa = planUniverseQuery({ ref: 'US_CA_EQ', date: '2025-06-15' }, DEFAULT_CTX);
expect(usCa.sql).toBe(expectedDualCurrencySql);
expect(usCa.params).toEqual([
'USD',
'CAD',
'2025-06-08',
'2025-06-15',
'2025-06-15T23:59:59.999999Z',
'2025-06-15T23:59:59.999999Z',
]);
// Verify no query values are interpolated into SQL text.
for (const planned of [us, ca, usCa]) {
expect(planned.sql).not.toContain('USD');
expect(planned.sql).not.toContain('CAD');
expect(planned.sql).not.toContain('2025-06-15');
expect(planned.sql).not.toContain('2025-06-08');
expect(planned.sql).not.toContain('23:59:59');
}
});
it('enforces Vault holdout fence identically to bars under vault_fenced scope with zero executor calls', async () => {
const fake = createRecordingExecutor();
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
vaultOperatorAuthorized: true,
});
// On and after midnight cutoff must throw VaultHoldoutFenceError even when vaultOperatorAuthorized is true.
for (const blockedDate of ['2026-05-28', '2026-05-29', '2026-10-01']) {
expect(() =>
planUniverseQuery(
{ ref: 'US_CA_EQ', date: blockedDate },
{ ...DEFAULT_CTX, vaultOperatorAuthorized: true }
)
).toThrow(VaultHoldoutFenceError);
await expect(store.universe({ ref: 'US_CA_EQ', date: blockedDate })).rejects.toBeInstanceOf(
VaultHoldoutFenceError
);
}
expect(fake.calls).toHaveLength(0);
// Day before midnight cutoff succeeds with upper bounds strictly < vaultCutoffTs.
const dayBefore = planUniverseQuery({ ref: 'US_EQ', date: MAX_ALLOWED_DATE }, DEFAULT_CTX);
expect(dayBefore.params).toEqual([
'USD',
'2026-05-20',
MAX_ALLOWED_DATE,
MAX_ALLOWED_ISO_MICROS,
MAX_ALLOWED_ISO_MICROS,
]);
expect(parseIsoToMicros(dayBefore.params[3] as string)).toBe(CUTOFF_MICROS - 1);
expect(parseIsoToMicros(dayBefore.params[4] as string)).toBe(CUTOFF_MICROS - 1);
expect(dayBefore.fenced.clampedTo).toBe(false);
expect(dayBefore.fenced.clampedAsOf).toBe(false);
// Mid-day Vault cutoff on date clamps both ts and known_at to vaultCutoffTs * 1000 - 1 µs.
const midDayCutoffMs = Date.UTC(2026, 4, 27, 12, 0, 0, 0);
const midDayCutoffMicros = midDayCutoffMs * 1000;
const clamped = planUniverseQuery(
{ ref: 'CA_EQ', date: '2026-05-27' },
{ curatedRoot: CURATED_ROOT, vaultCutoffTs: midDayCutoffMs }
);
expect(clamped.params).toEqual([
'CAD',
'2026-05-20',
'2026-05-27',
'2026-05-27T11:59:59.999999Z',
'2026-05-27T11:59:59.999999Z',
]);
expect(parseIsoToMicros(clamped.params[3] as string)).toBe(midDayCutoffMicros - 1);
expect(parseIsoToMicros(clamped.params[4] as string)).toBe(midDayCutoffMicros - 1);
expect(clamped.fenced.clampedTo).toBe(true);
expect(clamped.fenced.clampedAsOf).toBe(true);
});
it('computes calendar-day lookback across month, year, leap-day, and custom universeLookbackDays boundaries', () => {
// Month boundary: 2025-05-03 - 7d = 2025-04-26
const monthBoundary = planUniverseQuery({ ref: 'US_EQ', date: '2025-05-03' }, DEFAULT_CTX);
expect(monthBoundary.params[1]).toBe('2025-04-26');
expect(monthBoundary.params[2]).toBe('2025-05-03');
// Year boundary: 2025-01-03 - 7d = 2024-12-27
const yearBoundary = planUniverseQuery({ ref: 'US_EQ', date: '2025-01-03' }, DEFAULT_CTX);
expect(yearBoundary.params[1]).toBe('2024-12-27');
expect(yearBoundary.params[2]).toBe('2025-01-03');
// Leap year vs non-leap year
const leapYear = planUniverseQuery({ ref: 'US_EQ', date: '2024-03-04' }, DEFAULT_CTX);
expect(leapYear.params[1]).toBe('2024-02-26');
const nonLeapYear = planUniverseQuery({ ref: 'US_EQ', date: '2023-03-04' }, DEFAULT_CTX);
expect(nonLeapYear.params[1]).toBe('2023-02-25');
// 1-day lookback across leap day: 2024-03-01 - 1d = 2024-02-29
const leapDayOne = planUniverseQuery(
{ ref: 'US_EQ', date: '2024-03-01' },
{ ...DEFAULT_CTX, universeLookbackDays: 1 }
);
expect(leapDayOne.params[1]).toBe('2024-02-29');
// Custom universeLookbackDays changes ONLY the lower session_date bound param.
const defaultPlan = planUniverseQuery({ ref: 'US_CA_EQ', date: '2025-05-15' }, DEFAULT_CTX);
const customPlan = planUniverseQuery(
{ ref: 'US_CA_EQ', date: '2025-05-15' },
{ ...DEFAULT_CTX, universeLookbackDays: 14 }
);
expect(customPlan.sql).toBe(defaultPlan.sql);
expect(customPlan.params[0]).toBe(defaultPlan.params[0]);
expect(customPlan.params[1]).toBe(defaultPlan.params[1]);
expect(customPlan.params[2]).toBe('2025-05-01');
expect(defaultPlan.params[2]).toBe('2025-05-08');
expect(customPlan.params.slice(3)).toEqual(defaultPlan.params.slice(3));
});
it('rejects invalid ref, date, query, and universeLookbackDays upfront with zero executor calls', async () => {
const fake = createRecordingExecutor();
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
});
const badRefs: unknown[] = ['FX', '', 'us_eq', 'toString', '__proto__', 123, null, undefined];
for (const ref of badRefs) {
let caught: unknown;
try {
planUniverseQuery({ ref: ref as string, date: '2025-01-15' }, DEFAULT_CTX);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
expect((caught as MarketDataStoreValidationError).field).toBe('ref');
await expect(store.universe({ ref: ref as string, date: '2025-01-15' })).rejects.toBeInstanceOf(
MarketDataStoreValidationError
);
}
const badDates: unknown[] = [
'',
'2025-01-15T12:00:00Z',
'2025/01/15',
'2025-02-29',
'2025-04-31',
'2025-13-01',
null,
undefined,
];
for (const date of badDates) {
let caught: unknown;
try {
planUniverseQuery({ ref: 'US_EQ', date: date as string }, DEFAULT_CTX);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
expect((caught as MarketDataStoreValidationError).field).toBe('date');
await expect(store.universe({ ref: 'US_EQ', date: date as string })).rejects.toBeInstanceOf(
MarketDataStoreValidationError
);
}
const badQueries: unknown[] = [null, [], 'US_EQ', undefined];
for (const q of badQueries) {
let caught: unknown;
try {
planUniverseQuery(q as { ref: string; date: string }, DEFAULT_CTX);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
expect((caught as MarketDataStoreValidationError).field).toBe('query');
await expect(store.universe(q as { ref: string; date: string })).rejects.toBeInstanceOf(
MarketDataStoreValidationError
);
}
const badLookbacks: unknown[] = [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, '7', null];
for (const lookback of badLookbacks) {
let caughtPlan: unknown;
try {
planUniverseQuery(
{ ref: 'US_EQ', date: '2025-01-15' },
{ ...DEFAULT_CTX, universeLookbackDays: lookback as number }
);
} catch (err) {
caughtPlan = err;
}
expect(caughtPlan).toBeInstanceOf(MarketDataStoreValidationError);
expect((caughtPlan as MarketDataStoreValidationError).field).toBe('universeLookbackDays');
let caughtStore: unknown;
try {
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
universeLookbackDays: lookback as number,
});
} catch (err) {
caughtStore = err;
}
expect(caughtStore).toBeInstanceOf(MarketDataStoreValidationError);
expect((caughtStore as MarketDataStoreValidationError).field).toBe('universeLookbackDays');
}
// Safe-integer overflow, epoch-underflow, and cutoff-impossible lookbacks must fail
// upfront at both planUniverseQuery and createDuckDbMarketDataStore with zero executor calls.
for (const impossibleLookback of [
Number.MAX_SAFE_INTEGER,
100_000_000_000,
604_800_000, // 7 days accidentally passed in milliseconds
100_100_000, // fits in safe ms (8.64864e15) but underflows supported date range
740_129, // 1 day beyond 2026-05-27 -> 0000-01-01 at the 2026 fixture cutoff
]) {
let caughtPlan: unknown;
try {
planUniverseQuery(
{ ref: 'US_EQ', date: '2025-01-15' },
{ ...DEFAULT_CTX, universeLookbackDays: impossibleLookback }
);
} catch (err) {
caughtPlan = err;
}
expect(caughtPlan).toBeInstanceOf(MarketDataStoreValidationError);
expect((caughtPlan as MarketDataStoreValidationError).field).toBe('universeLookbackDays');
let caughtStore: unknown;
try {
createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
universeLookbackDays: impossibleLookback,
});
} catch (err) {
caughtStore = err;
}
expect(caughtStore).toBeInstanceOf(MarketDataStoreValidationError);
expect((caughtStore as MarketDataStoreValidationError).field).toBe('universeLookbackDays');
}
// Crossing before year 0000 (while still inside JS Date epoch range) must reject
// cleanly in both planUniverseQuery and store.universe with zero executor calls
// rather than truncating an extended signed ISO year (`-000001-...`).
let caughtYearZeroPlan: unknown;
try {
planUniverseQuery({ ref: 'US_EQ', date: '0000-01-05' }, DEFAULT_CTX);
} catch (err) {
caughtYearZeroPlan = err;
}
expect(caughtYearZeroPlan).toBeInstanceOf(MarketDataStoreValidationError);
expect((caughtYearZeroPlan as MarketDataStoreValidationError).field).toBe(
'universeLookbackDays'
);
await expect(store.universe({ ref: 'US_EQ', date: '0000-01-05' })).rejects.toMatchObject({
name: 'MarketDataStoreValidationError',
field: 'universeLookbackDays',
});
// Exact 0000-01-01 boundary succeeds with a valid YYYY-MM-DD lower bound.
const exactYearZero = planUniverseQuery({ ref: 'US_EQ', date: '0000-01-08' }, DEFAULT_CTX);
expect(exactYearZero.params[1]).toBe('0000-01-01');
// A lookback valid on the latest permitted date (2026-05-27 -> 0000-01-01) is accepted
// at store creation, but still rejected on earlier query dates with zero executor calls.
const boundaryStore = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
universeLookbackDays: 740_128,
});
const maxBoundaryPlan = planUniverseQuery(
{ ref: 'US_EQ', date: MAX_ALLOWED_DATE },
{ ...DEFAULT_CTX, universeLookbackDays: 740_128 }
);
expect(maxBoundaryPlan.params[1]).toBe('0000-01-01');
await expect(
boundaryStore.universe({ ref: 'US_EQ', date: '2026-05-26' })
).rejects.toMatchObject({
name: 'MarketDataStoreValidationError',
field: 'universeLookbackDays',
});
expect(fake.calls).toHaveLength(0);
});
it('runs budget SET statements once before first store.universe query, maps strictly ascending IDs, normalizes -0, and handles empty results', async () => {
let callCount = 0;
const fake = createRecordingExecutor({
onQuery: () => {
callCount += 1;
if (callCount === 1) {
return [{ listing_id: -2_147_483_648 }, { listing_id: -0 }, { listing_id: 42 }, { listing_id: 2_147_483_647 }];
}
return [];
},
});
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
universeLookbackDays: 10,
});
const expectedBudget = resolveDuckDbConnectionBudget().statements;
const ids = await store.universe({ ref: 'US_CA_EQ', date: '2025-06-15' });
expect(ids).toEqual([-2_147_483_648, 0, 42, 2_147_483_647]);
expect(Object.is(ids[1], 0)).toBe(true);
expect(fake.runCalls).toEqual(expectedBudget);
expect(fake.calls.slice(0, 3).map((c) => c.kind)).toEqual(['run', 'run', 'run']);
expect(fake.calls[3]?.kind).toBe('query');
expect(fake.queryCalls[0]?.params).toEqual([
'USD',
'CAD',
'2025-06-05',
'2025-06-15',
'2025-06-15T23:59:59.999999Z',
'2025-06-15T23:59:59.999999Z',
]);
// Second call must not re-run budget SET statements and returns [] on empty result.
const empty = await store.universe({ ref: 'US_EQ', date: '2025-06-15' });
expect(empty).toEqual([]);
expect(fake.runCalls).toHaveLength(3);
expect(fake.queryCalls).toHaveLength(2);
});
it('throws MarketDataStoreValidationError on malformed, out-of-INT32, duplicate, or unsorted executor rows', async () => {
const badResults: unknown[] = [
'not-an-array',
[null],
[{}],
[{ listing_id: 1.5 }],
[{ listing_id: Number.NaN }],
[{ listing_id: '10' }],
[{ listing_id: null }],
[{ listing_id: -2_147_483_649 }],
[{ listing_id: 2_147_483_648 }],
[{ listing_id: 10 }, { listing_id: 10 }],
[{ listing_id: 20 }, { listing_id: 10 }],
];
for (const rawResult of badResults) {
const fake = createRecordingExecutor({
onQuery: () => rawResult as readonly TableRow[],
});
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
});
await expect(store.universe({ ref: 'US_EQ', date: '2025-06-15' })).rejects.toBeInstanceOf(
MarketDataStoreValidationError
);
}
});
});
describe('planFundamentalsAsOfQuery & createDuckDbMarketDataStore().fundamentalsAsOf()', () => {
const EXPECTED_GLOB = `${CURATED_ROOT}/fundamentals_pit/year=*/part.parquet`;
it('exports the exact 9 allow-listed FUNDAMENTALS_PIT_VALUE_FIELDS and plans parameterized Hive Parquet SQL', () => {
expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toEqual([
'revenue',
'net_income',
'operating_cash_flow',
'total_assets',
'total_equity',
'shares_outstanding',
'ttm_revenue',
'ttm_net_income',
'ttm_operating_cash_flow',
]);
const nonTtm = planFundamentalsAsOfQuery(
{
listingIds: [202, 101, 202],
fields: ['net_income', 'revenue', 'net_income'],
asOf: '2025-06-15',
},
DEFAULT_CTX
);
expect(nonTtm.sql).toBe(
'WITH latest AS (SELECT 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, f.net_income, f.revenue ' +
'FROM read_parquet(?, hive_partitioning = true) AS f ' +
'WHERE f.listing_id IN (?, ?) 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 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, s.net_income, s.revenue ' +
'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'
);
expect(nonTtm.params).toEqual([
EXPECTED_GLOB,
202,
101,
'2025-06-15T23:59:59.999999Z',
true,
]);
expect(nonTtm.fenced).toEqual({
fromMs: Date.UTC(2025, 5, 15, 0, 0, 0, 0),
toMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999),
asOfMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999),
scope: 'vault_fenced',
clampedTo: false,
clampedAsOf: false,
});
expect(nonTtm.sql).not.toContain(CURATED_ROOT);
expect(nonTtm.sql).not.toContain('2025-06-15');
expect(nonTtm.sql).not.toContain('ttm_period_end');
expect(nonTtm.sql).not.toContain('ttm_currency');
expect(nonTtm.sql).not.toContain('ttm_has_estimated_lag');
const withTtm = planFundamentalsAsOfQuery(
{
listingIds: [101],
fields: ['revenue', 'ttm_revenue', 'ttm_operating_cash_flow', 'revenue', 'ttm_revenue'],
asOf: '2025-06-15T14:30:00.123456+02:00',
allowEstimatedLag: false,
},
DEFAULT_CTX
);
expect(withTtm.sql).toBe(
'WITH latest AS (SELECT 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, f.revenue, f.ttm_revenue, f.ttm_operating_cash_flow, f.ttm_period_end, f.ttm_currency, f.ttm_has_estimated_lag ' +
'FROM read_parquet(?, hive_partitioning = true) AS f ' +
'WHERE f.listing_id IN (?) 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 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, s.revenue, ' +
'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_revenue ELSE NULL END AS ttm_revenue, ' +
'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_operating_cash_flow ELSE NULL END AS ttm_operating_cash_flow, ' +
'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 ' +
'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'
);
expect(withTtm.params).toEqual([
EXPECTED_GLOB,
101,
'2025-06-15T12:30:00.123456Z',
false,
]);
expect(withTtm.fenced.asOfMs).toBe(Date.UTC(2025, 5, 15, 12, 30, 0, 123));
expect(withTtm.fenced.clampedAsOf).toBe(false);
});
it('clamps asOf at or after vaultCutoffTs to vaultCutoffTs * 1000 - 1 micros even when vaultOperatorAuthorized is true', () => {
const authorizedCtx: DuckDbPlanContext = {
...DEFAULT_CTX,
vaultOperatorAuthorized: true,
};
for (const clampedAsOf of [
'2026-05-28',
'2026-05-28T00:00:00.000Z',
'2026-05-28T00:00:00.000001Z',
'2026-09-01T15:00:00Z',
]) {
const planned = planFundamentalsAsOfQuery(
{ listingIds: [1], fields: ['revenue'], asOf: clampedAsOf },
authorizedCtx
);
expect(planned.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]);
expect(planned.fenced).toEqual({
fromMs: CUTOFF_MS - 1,
toMs: CUTOFF_MS - 1,
asOfMs: CUTOFF_MS - 1,
scope: 'vault_fenced',
clampedTo: true,
clampedAsOf: true,
});
}
// Mid-day cutoff with a date-only asOf on the cutoff date clamps cleanly to 1 microsecond before cutoff.
const midDayCutoffMs = Date.UTC(2026, 4, 28, 12, 0, 0, 0);
const midDayClamped = planFundamentalsAsOfQuery(
{ listingIds: [1], fields: ['revenue'], asOf: '2026-05-28' },
{ curatedRoot: CURATED_ROOT, vaultCutoffTs: midDayCutoffMs }
);
expect(midDayClamped.params).toEqual([EXPECTED_GLOB, 1, '2026-05-28T11:59:59.999999Z', true]);
expect(midDayClamped.fenced.clampedAsOf).toBe(true);
expect(midDayClamped.fenced.clampedTo).toBe(true);
expect(midDayClamped.fenced.asOfMs).toBe(midDayCutoffMs - 1);
// One microsecond before cutoff stays unclamped and preserves exact micros.
const preCutoffMicros = planFundamentalsAsOfQuery(
{ listingIds: [1], fields: ['revenue'], asOf: MAX_ALLOWED_ISO_MICROS },
DEFAULT_CTX
);
expect(preCutoffMicros.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]);
expect(preCutoffMicros.fenced.clampedAsOf).toBe(false);
});
it('validates fields allow-list, allowEstimatedLag, listingIds, and asOf with zero executor calls on invalid input', async () => {
const fake = createRecordingExecutor();
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
});
const invalidFieldsCases: unknown[] = [
[],
'revenue',
null,
undefined,
['unknown_field'],
['revenue', 'period_end'],
['toString'],
['revenue; DROP TABLE x'],
[123],
];
for (const badFields of invalidFieldsCases) {
let caught: unknown;
try {
await store.fundamentalsAsOf({
listingIds: [1],
fields: badFields as string[],
asOf: '2025-06-15',
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
expect((caught as MarketDataStoreValidationError).field).toBe('fields');
}
const invalidLagCases: unknown[] = [null, 1, 0, 'true', 'false', {}];
for (const badLag of invalidLagCases) {
let caught: unknown;
try {
await store.fundamentalsAsOf({
listingIds: [1],
fields: ['revenue'],
asOf: '2025-06-15',
allowEstimatedLag: badLag as boolean,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
expect((caught as MarketDataStoreValidationError).field).toBe('allowEstimatedLag');
}
const invalidAsOfCases: unknown[] = ['', 'not-a-date', '2024-02-30', '2025-06-15T12:00:00', null, undefined];
for (const badAsOf of invalidAsOfCases) {
let caught: unknown;
try {
await store.fundamentalsAsOf({
listingIds: [1],
fields: ['revenue'],
asOf: badAsOf as string,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
expect((caught as MarketDataStoreValidationError).field).toBe('asOf');
}
await expect(
store.fundamentalsAsOf({ listingIds: [], fields: ['revenue'], asOf: '2025-06-15' })
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
await expect(
store.fundamentalsAsOf(null as unknown as Parameters<typeof store.fundamentalsAsOf>[0])
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
expect(fake.calls).toHaveLength(0);
});
it('initializes DuckDB budget once and maps fundamentalsAsOf columns in exact projection order with strict scalar validation', async () => {
const t1 = Date.UTC(2024, 7, 1, 20, 0, 0, 0);
const t2 = Date.UTC(2024, 7, 15, 20, 0, 0, 0);
let callIndex = 0;
const fake = createRecordingExecutor({
onQuery: () => {
callIndex += 1;
if (callIndex === 1) {
return [
{
listing_id: 101,
effective_known_at: t1,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-06-30',
fiscal_period: 'Q2',
currency: 'USD',
period_known_at: t1,
total_assets: null,
revenue: 120.5,
},
];
}
return [
{
listing_id: 101,
effective_known_at: t2,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-06-30',
fiscal_period: 'Q2',
currency: 'USD',
period_known_at: t1,
revenue: 120.5,
ttm_revenue: 450.25,
ttm_period_end: '2024-06-30',
ttm_currency: 'USD',
ttm_has_estimated_lag: false,
},
];
},
});
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
});
const expectedBudget = resolveDuckDbConnectionBudget().statements;
const first = await store.fundamentalsAsOf({
listingIds: [101],
fields: ['total_assets', 'revenue', 'total_assets'],
asOf: '2024-08-05',
});
expect(first.columns).toEqual([
'listing_id',
'effective_known_at',
'known_at_source',
'has_estimated_lag',
'period_end',
'fiscal_period',
'currency',
'period_known_at',
'total_assets',
'revenue',
]);
expect(first.rows).toEqual([
{
listing_id: 101,
effective_known_at: t1,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-06-30',
fiscal_period: 'Q2',
currency: 'USD',
period_known_at: t1,
total_assets: null,
revenue: 120.5,
},
]);
expect(fake.runCalls).toEqual(expectedBudget);
const second = await store.fundamentalsAsOf({
listingIds: [101],
fields: ['revenue', 'ttm_revenue'],
asOf: '2024-08-20',
allowEstimatedLag: false,
});
expect(second.columns).toEqual([
'listing_id',
'effective_known_at',
'known_at_source',
'has_estimated_lag',
'period_end',
'fiscal_period',
'currency',
'period_known_at',
'revenue',
'ttm_revenue',
'ttm_period_end',
'ttm_currency',
'ttm_has_estimated_lag',
]);
expect(second.rows).toHaveLength(1);
expect(second.rows[0]?.ttm_revenue).toBe(450.25);
expect(second.rows[0]?.ttm_has_estimated_lag).toBe(false);
// Budget SET statements must not re-run on second query.
expect(fake.runCalls).toHaveLength(3);
expect(fake.queryCalls).toHaveLength(2);
// Rejects non-boolean has_estimated_lag from a misbehaving executor.
const badBoolFake = createRecordingExecutor({
onQuery: () => [
{
listing_id: 101,
effective_known_at: t1,
known_at_source: 'filing_date',
has_estimated_lag: 'false' as unknown as boolean,
period_end: '2024-06-30',
fiscal_period: 'Q2',
currency: 'USD',
period_known_at: t1,
revenue: 120.5,
},
],
});
const badStore = createDuckDbMarketDataStore({
executor: badBoolFake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
});
await expect(
badStore.fundamentalsAsOf({ listingIds: [101], fields: ['revenue'], asOf: '2024-08-05' })
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
});
});
describe('fundamentalsAsOf hostile request inputs', () => {
it('fails closed with zero executor calls for JSON-decoded object, symbol, and sparse field entries', async () => {
const fake = createRecordingExecutor();
const store = createDuckDbMarketDataStore({
executor: fake.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: CUTOFF_MS,
});
const hostileFields: unknown[] = [
JSON.parse('[{"toString": 1}]'),
[Object.create(null)],
[Symbol('revenue')],
// eslint-disable-next-line no-sparse-arrays
[, 'revenue'],
['REVENUE'],
[' revenue'],
];
for (const fields of hostileFields) {
await expect(
store.fundamentalsAsOf({ listingIds: [1], fields: fields as string[], asOf: '2025-06-15' })
).rejects.toThrow();
}
const hostileLag = JSON.parse('{"toString": 1}');
await expect(
store.fundamentalsAsOf({
listingIds: [1],
fields: ['revenue'],
asOf: '2025-06-15',
allowEstimatedLag: hostileLag as boolean,
})
).rejects.toThrow();
expect(fake.calls).toHaveLength(0);
expect(fake.runCalls).toHaveLength(0);
});
it('plans a request asOf with an offset that crosses the cutoff as a clamped bound', () => {
// 2026-05-28T01:00:00+02:00 === 2026-05-27T23:00:00Z, i.e. before the cutoff: not clamped.
const beforeCutoff = planFundamentalsAsOfQuery(
{ listingIds: [1], fields: ['revenue'], asOf: '2026-05-28T01:00:00+02:00' },
DEFAULT_CTX
);
expect(Date.parse(beforeCutoff.params[2] as string)).toBe(Date.UTC(2026, 4, 27, 23, 0, 0, 0));
expect(beforeCutoff.fenced.clampedAsOf).toBe(false);
// 2026-05-27T23:00:00-02:00 === 2026-05-28T01:00:00Z, i.e. after the cutoff: clamped.
const afterCutoff = planFundamentalsAsOfQuery(
{ listingIds: [1], fields: ['revenue'], asOf: '2026-05-27T23:00:00-02:00' },
DEFAULT_CTX
);
expect(afterCutoff.params[2]).toBe(MAX_ALLOWED_ISO_MICROS);
expect(afterCutoff.fenced.clampedAsOf).toBe(true);
});
});