T-119: tests
This commit is contained in:
parent
0a08a9962e
commit
bfcc1cf49f
1 changed files with 318 additions and 0 deletions
318
libs/research/test/market-data-store-duckdb.qa.test.ts
Normal file
318
libs/research/test/market-data-store-duckdb.qa.test.ts
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
AdjFactorsSnapshotError,
|
||||
type BarBatch,
|
||||
type DuckDbExecutor,
|
||||
type DuckDbParam,
|
||||
type DuckDbPlanContext,
|
||||
MarketDataStoreValidationError,
|
||||
type TableRow,
|
||||
VaultHoldoutFenceError,
|
||||
createDuckDbMarketDataStore,
|
||||
planBars1dQuery,
|
||||
planEventsQuery,
|
||||
planFx1dQuery,
|
||||
planShortsAsOfQuery,
|
||||
resolveDuckDbConnectionBudget,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
// QA edge cases for T-119 that the primary suite does not pin down.
|
||||
|
||||
const ROOT = '/data/curated';
|
||||
const CUTOFF_MS = Date.UTC(2026, 4, 28); // 2026-05-28T00:00:00.000Z
|
||||
const CTX: DuckDbPlanContext = { curatedRoot: ROOT, vaultCutoffTs: CUTOFF_MS };
|
||||
const BUDGET_ENV = { STOCKBOT_DUCKDB_THREADS: '3', STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB' };
|
||||
|
||||
interface Recorder {
|
||||
readonly executor: DuckDbExecutor;
|
||||
readonly log: Array<{ kind: 'run' | 'query'; sql: string; params?: readonly DuckDbParam[] }>;
|
||||
}
|
||||
|
||||
function recorder(
|
||||
onQuery: (sql: string, params: readonly DuckDbParam[]) => readonly TableRow[] = () => []
|
||||
): Recorder {
|
||||
const log: Recorder['log'] = [];
|
||||
return {
|
||||
log,
|
||||
executor: {
|
||||
async run(sql) {
|
||||
log.push({ kind: 'run', sql });
|
||||
},
|
||||
async query(sql, params) {
|
||||
log.push({ kind: 'query', sql, params: [...params] });
|
||||
return onQuery(sql, params);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fencedKv(asOfMicros: number | null, vaultCutoffMicros: number | null): TableRow[] {
|
||||
return [
|
||||
{ key: 'stock_bot.adj_factors.format_version', value: '1' },
|
||||
{ key: 'stock_bot.adj_factors.snapshot_kind', value: 'point_in_time_fenced' },
|
||||
{ key: 'stock_bot.adj_factors.as_of_micros', value: asOfMicros === null ? 'none' : String(asOfMicros) },
|
||||
{
|
||||
key: 'stock_bot.adj_factors.vault_cutoff_micros',
|
||||
value: vaultCutoffMicros === null ? 'none' : String(vaultCutoffMicros),
|
||||
},
|
||||
{ key: 'stock_bot.adj_factors.rows_written', value: '2' },
|
||||
{ key: 'stock_bot.adj_factors.snapshot_checksum', value: '0x0123456789abcdef' },
|
||||
];
|
||||
}
|
||||
|
||||
async function drain(it: AsyncIterable<BarBatch>): Promise<BarBatch[]> {
|
||||
const out: BarBatch[] = [];
|
||||
for await (const b of it) {
|
||||
out.push(b);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('T-119 QA: listingIds boundaries and caller-input immutability', () => {
|
||||
it('accepts exact INT32 bounds and binds them as numbers, never in SQL text', () => {
|
||||
const planned = planBars1dQuery(
|
||||
{
|
||||
listingIds: [-2_147_483_648, 2_147_483_647],
|
||||
timeframe: '1d',
|
||||
from: '2025-01-02',
|
||||
to: '2025-01-03',
|
||||
adjustment: 'raw',
|
||||
},
|
||||
CTX
|
||||
);
|
||||
|
||||
expect(planned.params.slice(0, 2)).toEqual([-2_147_483_648, 2_147_483_647]);
|
||||
expect(planned.sql).not.toContain('2147483647');
|
||||
expect(planned.sql).not.toContain('2147483648');
|
||||
expect(planned.sql).toContain('b.listing_id IN (?, ?)');
|
||||
});
|
||||
|
||||
it('deduplicates frozen listingIds and kinds (including -0 vs 0) without mutating caller arrays', () => {
|
||||
const listingIds = Object.freeze([7, 0, -0, 7, 9]);
|
||||
const kinds = Object.freeze(['filing', 'earnings', 'filing'] as const);
|
||||
|
||||
const planned = planEventsQuery(
|
||||
{ kinds: [...kinds], listingIds: listingIds as number[], from: '2025-01-02', to: '2025-01-03' },
|
||||
CTX
|
||||
);
|
||||
|
||||
expect(listingIds).toEqual([7, 0, -0, 7, 9]);
|
||||
expect(planned.sql).toContain('e.kind IN (?, ?) AND e.listing_id IN (?, ?, ?)');
|
||||
expect(planned.params.slice(0, 5)).toEqual(['filing', 'earnings', 7, 0, 9]);
|
||||
expect(Object.is(planned.params[3], 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-119 QA: timestamp precision and offsets', () => {
|
||||
it('preserves explicit microsecond from/to/asOf digits and normalises offsets to UTC', () => {
|
||||
const planned = planBars1dQuery(
|
||||
{
|
||||
listingIds: [1],
|
||||
timeframe: '1d',
|
||||
from: '2025-01-02T09:30:00.123456-05:00',
|
||||
to: '2025-01-03T16:00:00.654321-05:00',
|
||||
asOf: '2025-01-03T21:00:00.000001Z',
|
||||
adjustment: 'raw',
|
||||
},
|
||||
CTX
|
||||
);
|
||||
|
||||
expect(planned.params).toEqual([
|
||||
1,
|
||||
'2025-01-02T14:30:00.123456Z',
|
||||
'2025-01-03T21:00:00.654321Z',
|
||||
'2025-01-03T21:00:00.000001Z',
|
||||
]);
|
||||
});
|
||||
|
||||
it('binds a single-millisecond window with explicit micros ordered correctly and rejects inverted micros', () => {
|
||||
const ok = planEventsQuery(
|
||||
{
|
||||
kinds: ['filing'],
|
||||
from: '2025-01-02T10:00:00.000100Z',
|
||||
to: '2025-01-02T10:00:00.000900Z',
|
||||
},
|
||||
CTX
|
||||
);
|
||||
expect(ok.params.slice(1, 3)).toEqual(['2025-01-02T10:00:00.000100Z', '2025-01-02T10:00:00.000900Z']);
|
||||
|
||||
expect(() =>
|
||||
planEventsQuery(
|
||||
{ kinds: ['filing'], from: '2025-01-02T10:00:00.000900Z', to: '2025-01-02T10:00:00.000100Z' },
|
||||
CTX
|
||||
)
|
||||
).toThrow(MarketDataStoreValidationError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-119 QA: Vault bounds under a non-midnight cutoff', () => {
|
||||
// computeVaultCutoffTs preserves the time-of-day of the max ingested ts, so cutoffs need not be midnight.
|
||||
const cutoff = Date.UTC(2026, 4, 28, 14, 30, 0, 0);
|
||||
const ctx: DuckDbPlanContext = { curatedRoot: ROOT, vaultCutoffTs: cutoff };
|
||||
const cutoffMinusOneMicroIso = '2026-05-28T14:29:59.999999Z';
|
||||
|
||||
it('clamps bars/events/fx upper ts and known_at bounds to cutoff - 1µs', () => {
|
||||
const bars = planBars1dQuery(
|
||||
{ listingIds: [1], timeframe: '1d', from: '2026-05-01', to: '2026-12-31', asOf: '2027-01-01', adjustment: 'raw' },
|
||||
ctx
|
||||
);
|
||||
expect(bars.params.slice(-2)).toEqual([cutoffMinusOneMicroIso, cutoffMinusOneMicroIso]);
|
||||
|
||||
const events = planEventsQuery({ kinds: ['ceo_post'], from: '2026-05-01', to: '2026-05-28' }, ctx);
|
||||
expect(events.params.slice(-2)).toEqual([cutoffMinusOneMicroIso, cutoffMinusOneMicroIso]);
|
||||
|
||||
const fx = planFx1dQuery({ pair: 'USD.CAD', timeframe: '1d', from: '2026-05-01', to: '2026-06-30' }, ctx);
|
||||
expect(fx.params).toEqual(['USDCAD', '2026-05-01T00:00:00.000Z', cutoffMinusOneMicroIso, cutoffMinusOneMicroIso]);
|
||||
});
|
||||
|
||||
it('keeps shortsAsOf known_at strictly before the cutoff even when the report_date bound lands on the cutoff day', () => {
|
||||
const shorts = planShortsAsOfQuery({ listingIds: [5], from: '2026-05-01', to: '2026-09-01' }, ctx);
|
||||
|
||||
expect(shorts.params).toEqual([5, '2026-05-01', '2026-05-28', cutoffMinusOneMicroIso]);
|
||||
expect(shorts.fenced.toMs).toBe(cutoff - 1);
|
||||
expect(shorts.fenced.asOfMs).toBe(cutoff - 1);
|
||||
});
|
||||
|
||||
it('rejects from exactly at a non-midnight cutoff but accepts from one millisecond earlier', () => {
|
||||
expect(() =>
|
||||
planShortsAsOfQuery({ listingIds: [5], from: '2026-05-28T14:30:00Z', to: '2026-06-01' }, ctx)
|
||||
).toThrow(VaultHoldoutFenceError);
|
||||
const planned = planShortsAsOfQuery(
|
||||
{ listingIds: [5], from: '2026-05-28T14:29:59.999Z', to: '2026-06-01' },
|
||||
ctx
|
||||
);
|
||||
expect(planned.params.slice(1, 3)).toEqual(['2026-05-28', '2026-05-28']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-119 QA: adapter immutable-path flow and budget ordering', () => {
|
||||
const IMMUTABLE = '/data/snapshots/adj_factors_2026-05-27.parquet';
|
||||
|
||||
it('runs env-derived budget SETs, then the footer query, then the bars query bound to the immutable path', async () => {
|
||||
const asOfMicros = CUTOFF_MS * 1000 - 1;
|
||||
const rec = recorder((sql) => {
|
||||
if (sql.includes('parquet_kv_metadata')) {
|
||||
return fencedKv(asOfMicros, CUTOFF_MS * 1000);
|
||||
}
|
||||
return [
|
||||
{ listing_id: 42, ts: Date.UTC(2025, 0, 2, 21), open: 50, high: 51, low: 49, close: 50, volume: 2000, vwap: null, known_at: Date.UTC(2025, 0, 2, 22) },
|
||||
];
|
||||
});
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
immutableAdjFactorsPath: IMMUTABLE,
|
||||
env: BUDGET_ENV,
|
||||
});
|
||||
|
||||
const batches = await drain(
|
||||
store.bars({ listingIds: [42], timeframe: '1d', from: '2025-01-01', to: '2025-01-31', adjustment: 'split' })
|
||||
);
|
||||
|
||||
const budget = resolveDuckDbConnectionBudget(BUDGET_ENV).statements;
|
||||
expect(rec.log.map((c) => c.kind)).toEqual(['run', 'run', 'run', 'query', 'query']);
|
||||
expect(rec.log.slice(0, 3).map((c) => c.sql)).toEqual([...budget]);
|
||||
expect(rec.log[3]?.sql).toContain(`parquet_kv_metadata('${IMMUTABLE}')`);
|
||||
expect(rec.log[4]?.sql).toContain(`read_parquet('${IMMUTABLE}')`);
|
||||
expect(rec.log[4]?.sql).not.toContain(`${ROOT}/adj_factors/part.parquet`);
|
||||
expect(batches).toEqual([
|
||||
{
|
||||
rows: [
|
||||
{ listingId: 42, ts: Date.UTC(2025, 0, 2, 21), open: 50, high: 51, low: 49, close: 50, volume: 2000, vwap: null, knownAt: Date.UTC(2025, 0, 2, 22) },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('fails closed with incompatible_fence when the immutable snapshot fence differs from the query asOf, issuing no bars scan', async () => {
|
||||
const rec = recorder((sql) =>
|
||||
sql.includes('parquet_kv_metadata') ? fencedKv(Date.UTC(2025, 5, 30) * 1000, CUTOFF_MS * 1000) : []
|
||||
);
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
immutableAdjFactorsPath: IMMUTABLE,
|
||||
env: BUDGET_ENV,
|
||||
});
|
||||
|
||||
const err = await drain(
|
||||
store.bars({ listingIds: [42], timeframe: '1d', from: '2025-01-01', to: '2025-01-31', adjustment: 'total' })
|
||||
).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(AdjFactorsSnapshotError);
|
||||
expect((err as AdjFactorsSnapshotError).code).toBe('incompatible_fence');
|
||||
expect(rec.log.filter((c) => c.kind === 'query')).toHaveLength(1);
|
||||
expect(rec.log.some((c) => c.sql.includes('bars_1d'))).toBe(false);
|
||||
});
|
||||
|
||||
it('does not run budget SETs when the first call fails validation, then runs them once on the next valid call', async () => {
|
||||
const rec = recorder();
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
env: BUDGET_ENV,
|
||||
});
|
||||
|
||||
await expect(
|
||||
store.events({ kinds: ['filing'], listingIds: [1.5], from: '2025-01-01', to: '2025-01-02' })
|
||||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect(rec.log).toHaveLength(0);
|
||||
|
||||
await store.events({ kinds: ['filing'], from: '2025-01-01', to: '2025-01-02' });
|
||||
await store.fx({ pair: 'USD.CAD', timeframe: '1d', from: '2025-01-01', to: '2025-01-02' });
|
||||
expect(rec.log.map((c) => c.kind)).toEqual(['run', 'run', 'run', 'query', 'query']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-119 QA: pinned-artifact release failures', () => {
|
||||
it('propagates a release() failure after a successful scan and still releases exactly once', async () => {
|
||||
const asOfMicros = CUTOFF_MS * 1000 - 1;
|
||||
const rec = recorder((sql) => (sql.includes('parquet_kv_metadata') ? fencedKv(asOfMicros, CUTOFF_MS * 1000) : []));
|
||||
let releases = 0;
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
env: BUDGET_ENV,
|
||||
pinAdjFactorsArtifact: () => ({
|
||||
pinnedPath: '/proc/self/fd/17',
|
||||
release() {
|
||||
releases += 1;
|
||||
throw new Error('close failed');
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const err = await drain(
|
||||
store.bars({ listingIds: [42], timeframe: '1d', from: '2025-01-01', to: '2025-01-31', adjustment: 'split' })
|
||||
).catch((e: unknown) => e);
|
||||
|
||||
expect((err as Error).message).toBe('close failed');
|
||||
expect(releases).toBe(1);
|
||||
expect(rec.log.filter((c) => c.kind === 'query').map((c) => c.sql.includes('/proc/self/fd/17'))).toEqual([true, true]);
|
||||
});
|
||||
|
||||
it('never calls the pinner for an adjusted query that fails the Vault fence', async () => {
|
||||
const rec = recorder();
|
||||
let pins = 0;
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
env: BUDGET_ENV,
|
||||
pinAdjFactorsArtifact: () => {
|
||||
pins += 1;
|
||||
return { pinnedPath: '/proc/self/fd/17', release() {} };
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
drain(store.bars({ listingIds: [42], timeframe: '1d', from: '2026-05-28', to: '2026-06-30', adjustment: 'split' }))
|
||||
).rejects.toBeInstanceOf(VaultHoldoutFenceError);
|
||||
expect(pins).toBe(0);
|
||||
expect(rec.log).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue