420 lines
15 KiB
TypeScript
420 lines
15 KiB
TypeScript
import { describe, expect, it } from 'bun:test';
|
|
import {
|
|
createDuckDbMarketDataStore,
|
|
MarketDataStoreValidationError,
|
|
planBars1dQuery,
|
|
planUniverseQuery,
|
|
resolveDuckDbConnectionBudget,
|
|
UNIVERSE_REFS,
|
|
VaultHoldoutFenceError,
|
|
type DuckDbExecutor,
|
|
type DuckDbParam,
|
|
type DuckDbPlanContext,
|
|
type TableRow,
|
|
} from '@stock-bot/research';
|
|
|
|
// QA edge cases for T-122 (`universe` planner + adapter) not pinned by the primary suite.
|
|
|
|
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 DAY_MS = 86_400_000;
|
|
|
|
interface Recorder {
|
|
readonly executor: DuckDbExecutor;
|
|
readonly log: Array<{ kind: 'run' | 'query'; sql: string; params?: readonly DuckDbParam[] }>;
|
|
}
|
|
|
|
function recorder(
|
|
onQuery: (
|
|
sql: string,
|
|
params: readonly DuckDbParam[]
|
|
) => Promise<readonly TableRow[]> | readonly TableRow[] = () => [],
|
|
onRun: (sql: string) => Promise<void> | void = () => {}
|
|
): Recorder {
|
|
const log: Recorder['log'] = [];
|
|
return {
|
|
log,
|
|
executor: {
|
|
async run(sql) {
|
|
log.push({ kind: 'run', sql });
|
|
await onRun(sql);
|
|
},
|
|
async query(sql, params) {
|
|
log.push({ kind: 'query', sql, params: [...params] });
|
|
return onQuery(sql, params);
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
function mulberry32(seed: number): () => number {
|
|
let a = seed >>> 0;
|
|
return () => {
|
|
a = (a + 0x6d2b79f5) >>> 0;
|
|
let t = a;
|
|
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
|
};
|
|
}
|
|
|
|
function isoDate(ms: number): string {
|
|
return new Date(ms).toISOString().slice(0, 10);
|
|
}
|
|
|
|
interface FixtureBar {
|
|
readonly listing_id: number;
|
|
readonly currency: 'USD' | 'CAD';
|
|
readonly session_date: string;
|
|
readonly ts: string; // microsecond UTC ISO, same format the planner binds
|
|
readonly known_at: string;
|
|
}
|
|
|
|
function bar(
|
|
listingId: number,
|
|
currency: 'USD' | 'CAD',
|
|
sessionDate: string,
|
|
knownAt?: string
|
|
): FixtureBar {
|
|
return {
|
|
listing_id: listingId,
|
|
currency,
|
|
session_date: sessionDate,
|
|
ts: `${sessionDate}T20:00:00.000000Z`,
|
|
known_at: knownAt ?? `${sessionDate}T22:00:00.000000Z`,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* In-memory evaluator for the planned universe SQL: applies the bound predicates
|
|
* positionally (currency list, session_date bounds, ts bound, known_at bound) to a
|
|
* fixture `bars_1d` table and returns DISTINCT listing_id ASC, the way DuckDB would.
|
|
* Fixed-width ISO strings compare chronologically, matching DuckDB's typed compare.
|
|
*/
|
|
function evaluatingExecutor(bars: readonly FixtureBar[]): Recorder {
|
|
return recorder((sql, params) => {
|
|
const inMatch = /b\.currency IN \(([?, ]+)\)/.exec(sql);
|
|
const currencyCount = inMatch === null ? 1 : (inMatch[1] ?? '').split('?').length - 1;
|
|
expect(sql).toContain(
|
|
currencyCount === 1 && inMatch === null ? 'b.currency = ?' : 'b.currency IN ('
|
|
);
|
|
const currencies = params.slice(0, currencyCount) as string[];
|
|
const [lo, hi, tsMax, knownMax] = params.slice(currencyCount) as string[];
|
|
expect(params).toHaveLength(currencyCount + 4);
|
|
const ids = new Set<number>();
|
|
for (const b of bars) {
|
|
if (
|
|
currencies.includes(b.currency) &&
|
|
b.session_date >= (lo as string) &&
|
|
b.session_date <= (hi as string) &&
|
|
b.ts <= (tsMax as string) &&
|
|
b.known_at <= (knownMax as string)
|
|
) {
|
|
ids.add(b.listing_id);
|
|
}
|
|
}
|
|
return [...ids].sort((a, b) => a - b).map(listing_id => ({ listing_id }));
|
|
});
|
|
}
|
|
|
|
describe('T-122 QA: survivorship-free, no-look-ahead semantics over a fixture bars_1d table', () => {
|
|
const BARS: FixtureBar[] = [
|
|
// 101: US listing delisted after 2025-03-10.
|
|
bar(101, 'USD', '2025-03-03'),
|
|
bar(101, 'USD', '2025-03-10'),
|
|
// 102: US IPO on 2025-03-14 (future relative to 2025-03-12).
|
|
bar(102, 'USD', '2025-03-14'),
|
|
bar(102, 'USD', '2025-03-17'),
|
|
// 201: CAD TSX line trading throughout.
|
|
bar(201, 'CAD', '2025-03-05'),
|
|
bar(201, 'CAD', '2025-03-12'),
|
|
bar(201, 'CAD', '2025-03-19'),
|
|
// 202: USD-quoted TSX line (provisional rule -> US_EQ).
|
|
bar(202, 'USD', '2025-03-11'),
|
|
// 301: only bar on 2025-03-12 was published (known_at) the next morning.
|
|
bar(301, 'USD', '2025-03-12', '2025-03-13T09:30:00.000000Z'),
|
|
// 302: bar known exactly at the last microsecond of 2025-03-12 -> included.
|
|
bar(302, 'CAD', '2025-03-12', '2025-03-12T23:59:59.999999Z'),
|
|
// 401: last bar exactly 7 days before 2025-03-12 (inclusive lower bound).
|
|
bar(401, 'USD', '2025-03-05'),
|
|
// 402: last bar 8 days before 2025-03-12 (outside default window).
|
|
bar(402, 'CAD', '2025-03-04'),
|
|
];
|
|
|
|
it('includes a delisted listing only while it traded and never includes a not-yet-listed IPO', async () => {
|
|
const fx = evaluatingExecutor(BARS);
|
|
const store = createDuckDbMarketDataStore({
|
|
executor: fx.executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: CUTOFF_MS,
|
|
});
|
|
|
|
expect(await store.universe({ ref: 'US_EQ', date: '2025-03-12' })).toEqual([101, 202, 401]);
|
|
// 101 last traded 2025-03-10; window for 2025-03-17 is [03-10, 03-17] -> still included on the edge.
|
|
expect(await store.universe({ ref: 'US_EQ', date: '2025-03-17' })).toEqual([
|
|
101, 102, 202, 301,
|
|
]);
|
|
// One day later 101 drops out (delisted), 102 remains.
|
|
expect(await store.universe({ ref: 'US_EQ', date: '2025-03-18' })).toEqual([102, 202, 301]);
|
|
});
|
|
|
|
it('excludes bars published after the end of date (known_at fence) and includes the last-microsecond publication', async () => {
|
|
const fx = evaluatingExecutor(BARS);
|
|
const store = createDuckDbMarketDataStore({
|
|
executor: fx.executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: CUTOFF_MS,
|
|
});
|
|
|
|
const us = await store.universe({ ref: 'US_EQ', date: '2025-03-12' });
|
|
expect(us).not.toContain(301);
|
|
// Next day the restated bar is known -> 301 is active.
|
|
expect(await store.universe({ ref: 'US_EQ', date: '2025-03-13' })).toContain(301);
|
|
|
|
expect(await store.universe({ ref: 'CA_EQ', date: '2025-03-12' })).toEqual([201, 302]);
|
|
});
|
|
|
|
it('applies the provisional bar-currency membership rule and an inclusive 7-day lower bound', async () => {
|
|
const fx = evaluatingExecutor(BARS);
|
|
const store = createDuckDbMarketDataStore({
|
|
executor: fx.executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: CUTOFF_MS,
|
|
});
|
|
|
|
const ca = await store.universe({ ref: 'CA_EQ', date: '2025-03-12' });
|
|
const us = await store.universe({ ref: 'US_EQ', date: '2025-03-12' });
|
|
const both = await store.universe({ ref: 'US_CA_EQ', date: '2025-03-12' });
|
|
|
|
expect(us).toContain(202); // USD-quoted TSX line lands in US_EQ
|
|
expect(ca).not.toContain(202);
|
|
expect(us).toContain(401); // exactly date - 7 days
|
|
expect(ca).not.toContain(402); // date - 8 days
|
|
expect(both).toEqual([...new Set([...us, ...ca])].sort((a, b) => a - b));
|
|
|
|
// A wider custom lookback picks up the 8-day-old listing and nothing else changes.
|
|
const wide = createDuckDbMarketDataStore({
|
|
executor: evaluatingExecutor(BARS).executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: CUTOFF_MS,
|
|
universeLookbackDays: 8,
|
|
});
|
|
expect(await wide.universe({ ref: 'CA_EQ', date: '2025-03-12' })).toEqual([201, 302, 402]);
|
|
});
|
|
});
|
|
|
|
describe('T-122 QA: store/planner parity and adapter error paths', () => {
|
|
it('sends exactly the planUniverseQuery SQL and params for default and custom store lookbacks', async () => {
|
|
for (const lookback of [undefined, 1, 30]) {
|
|
const rec = recorder();
|
|
const store = createDuckDbMarketDataStore({
|
|
executor: rec.executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: CUTOFF_MS,
|
|
...(lookback === undefined ? {} : { universeLookbackDays: lookback }),
|
|
});
|
|
for (const ref of UNIVERSE_REFS) {
|
|
await store.universe({ ref, date: '2025-11-03' });
|
|
const expected = planUniverseQuery(
|
|
{ ref, date: '2025-11-03' },
|
|
lookback === undefined ? CTX : { ...CTX, universeLookbackDays: lookback }
|
|
);
|
|
const last = rec.log[rec.log.length - 1];
|
|
expect(last?.kind).toBe('query');
|
|
expect(last?.sql).toBe(expected.sql);
|
|
expect(last?.params).toEqual(expected.params);
|
|
}
|
|
}
|
|
});
|
|
|
|
it('runs the budget SET statements once and before any query under concurrent first universe calls', async () => {
|
|
const env = { STOCKBOT_DUCKDB_THREADS: '3', STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB' };
|
|
const rec = recorder(
|
|
() => [{ listing_id: 1 }],
|
|
() => new Promise<void>(resolve => setTimeout(resolve, 0))
|
|
);
|
|
const store = createDuckDbMarketDataStore({
|
|
executor: rec.executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: CUTOFF_MS,
|
|
env,
|
|
});
|
|
|
|
const results = await Promise.all([
|
|
store.universe({ ref: 'US_EQ', date: '2025-06-02' }),
|
|
store.universe({ ref: 'CA_EQ', date: '2025-06-02' }),
|
|
store.universe({ ref: 'US_CA_EQ', date: '2025-06-02' }),
|
|
]);
|
|
|
|
expect(results).toEqual([[1], [1], [1]]);
|
|
expect(rec.log.map(e => e.kind)).toEqual(['run', 'run', 'run', 'query', 'query', 'query']);
|
|
expect(rec.log.slice(0, 3).map(e => e.sql)).toEqual([
|
|
...resolveDuckDbConnectionBudget(env).statements,
|
|
]);
|
|
});
|
|
|
|
it('propagates executor query errors unchanged and retries budget init after a failed SET', async () => {
|
|
const boom = new Error('duckdb io error');
|
|
const failingQuery = recorder(() => Promise.reject(boom));
|
|
const s1 = createDuckDbMarketDataStore({
|
|
executor: failingQuery.executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: CUTOFF_MS,
|
|
});
|
|
await expect(s1.universe({ ref: 'US_EQ', date: '2025-06-02' })).rejects.toBe(boom);
|
|
|
|
let failFirstRun = true;
|
|
const flakyRun = recorder(
|
|
() => [{ listing_id: 7 }],
|
|
() => {
|
|
if (failFirstRun) {
|
|
failFirstRun = false;
|
|
throw new Error('SET failed');
|
|
}
|
|
}
|
|
);
|
|
const s2 = createDuckDbMarketDataStore({
|
|
executor: flakyRun.executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: CUTOFF_MS,
|
|
});
|
|
await expect(s2.universe({ ref: 'US_EQ', date: '2025-06-02' })).rejects.toThrow('SET failed');
|
|
expect(flakyRun.log.some(e => e.kind === 'query')).toBe(false);
|
|
expect(await s2.universe({ ref: 'US_EQ', date: '2025-06-02' })).toEqual([7]);
|
|
});
|
|
|
|
it('returns a fresh array per call and does not mutate the caller query object', async () => {
|
|
const rows: TableRow[] = [{ listing_id: 3 }, { listing_id: 9 }];
|
|
const rec = recorder(() => rows);
|
|
const store = createDuckDbMarketDataStore({
|
|
executor: rec.executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: CUTOFF_MS,
|
|
});
|
|
const q = Object.freeze({ ref: 'US_CA_EQ', date: '2025-06-02' });
|
|
|
|
const first = await store.universe(q);
|
|
first.push(99);
|
|
const second = await store.universe(q);
|
|
|
|
expect(second).toEqual([3, 9]);
|
|
expect(q).toEqual({ ref: 'US_CA_EQ', date: '2025-06-02' });
|
|
expect(rows).toEqual([{ listing_id: 3 }, { listing_id: 9 }]);
|
|
});
|
|
|
|
it('rejects a store-level universeLookbackDays at construction without touching the executor', () => {
|
|
const rec = recorder();
|
|
expect(() =>
|
|
createDuckDbMarketDataStore({
|
|
executor: rec.executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: CUTOFF_MS,
|
|
universeLookbackDays: -7,
|
|
})
|
|
).toThrow(MarketDataStoreValidationError);
|
|
expect(rec.log).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
describe('T-122 QA: seeded fence and lookback invariants', () => {
|
|
it('holds lookback arithmetic and Vault bounds across 600 seeded (date, lookback, ref, cutoff) cases', async () => {
|
|
const rng = mulberry32(20261129);
|
|
const baseMs = Date.UTC(2004, 0, 1);
|
|
let fencedCount = 0;
|
|
let plannedCount = 0;
|
|
|
|
for (let i = 0; i < 600; i += 1) {
|
|
// Cutoff anywhere in 2020..2027, sometimes mid-day.
|
|
const cutoffDayMs = Date.UTC(2020, 0, 1) + Math.floor(rng() * 8 * 365) * DAY_MS;
|
|
const cutoffMs = rng() < 0.5 ? cutoffDayMs : cutoffDayMs + Math.floor(rng() * DAY_MS);
|
|
const dateMs = baseMs + Math.floor(rng() * 24 * 365) * DAY_MS;
|
|
const date = isoDate(dateMs);
|
|
const lookback = 1 + Math.floor(rng() * 400);
|
|
const ref = UNIVERSE_REFS[Math.floor(rng() * UNIVERSE_REFS.length)] ?? 'US_EQ';
|
|
const ctx: DuckDbPlanContext = {
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: cutoffMs,
|
|
universeLookbackDays: lookback,
|
|
};
|
|
|
|
if (dateMs >= cutoffMs) {
|
|
fencedCount += 1;
|
|
expect(() => planUniverseQuery({ ref, date }, ctx)).toThrow(VaultHoldoutFenceError);
|
|
// Same class bars uses for a vault_fenced range starting on that date.
|
|
expect(() =>
|
|
planBars1dQuery(
|
|
{ listingIds: [1], timeframe: '1d', from: date, to: date, adjustment: 'raw' },
|
|
ctx
|
|
)
|
|
).toThrow(VaultHoldoutFenceError);
|
|
const rec = recorder();
|
|
const store = createDuckDbMarketDataStore({
|
|
executor: rec.executor,
|
|
curatedRoot: ROOT,
|
|
vaultCutoffTs: cutoffMs,
|
|
});
|
|
await expect(store.universe({ ref, date })).rejects.toBeInstanceOf(VaultHoldoutFenceError);
|
|
expect(rec.log).toHaveLength(0);
|
|
continue;
|
|
}
|
|
|
|
plannedCount += 1;
|
|
const planned = planUniverseQuery({ ref, date }, ctx);
|
|
const n = ref === 'US_CA_EQ' ? 2 : 1;
|
|
expect(planned.params).toHaveLength(n + 4);
|
|
const [lo, hi, tsMax, knownMax] = planned.params.slice(n) as string[];
|
|
expect(lo).toBe(isoDate(dateMs - lookback * DAY_MS));
|
|
expect(hi).toBe(date);
|
|
const endOfDateMs = dateMs + DAY_MS - 1;
|
|
const expectedUpperMs = Math.min(endOfDateMs, cutoffMs - 1);
|
|
expect(Date.parse(tsMax as string)).toBe(expectedUpperMs);
|
|
expect(tsMax).toBe(knownMax);
|
|
expect(Date.parse(tsMax as string)).toBeLessThan(cutoffMs);
|
|
// Never reads past the end of `date`.
|
|
expect((tsMax as string).slice(0, 10)).toBe(date);
|
|
expect(planned.fenced.clampedTo).toBe(endOfDateMs >= cutoffMs);
|
|
expect(planned.sql).not.toContain(date);
|
|
expect(planned.sql).not.toContain(lo as string);
|
|
}
|
|
|
|
// Both branches must actually be exercised by the seed.
|
|
expect(fencedCount).toBeGreaterThan(50);
|
|
expect(plannedCount).toBeGreaterThan(50);
|
|
});
|
|
|
|
it('clamps to the first microsecond window when the cutoff is 1 ms after midnight of date', () => {
|
|
const cutoff = Date.UTC(2025, 2, 12, 0, 0, 0, 1);
|
|
const planned = planUniverseQuery(
|
|
{ ref: 'US_EQ', date: '2025-03-12' },
|
|
{ curatedRoot: ROOT, vaultCutoffTs: cutoff }
|
|
);
|
|
expect(planned.params).toEqual([
|
|
'USD',
|
|
'2025-03-05',
|
|
'2025-03-12',
|
|
'2025-03-12T00:00:00.000999Z',
|
|
'2025-03-12T00:00:00.000999Z',
|
|
]);
|
|
expect(planned.fenced.clampedTo).toBe(true);
|
|
expect(planned.fenced.clampedAsOf).toBe(true);
|
|
});
|
|
|
|
it('produces identical SQL and params under TZ=UTC and TZ=America/Toronto', () => {
|
|
const prev = process.env.TZ;
|
|
try {
|
|
process.env.TZ = 'UTC';
|
|
const a = planUniverseQuery({ ref: 'US_CA_EQ', date: '2025-03-09' }, CTX); // DST switch in Toronto
|
|
process.env.TZ = 'America/Toronto';
|
|
const b = planUniverseQuery({ ref: 'US_CA_EQ', date: '2025-03-09' }, CTX);
|
|
expect(b).toEqual(a);
|
|
expect(a.params[2]).toBe('2025-03-02');
|
|
} finally {
|
|
if (prev === undefined) {
|
|
delete process.env.TZ;
|
|
} else {
|
|
process.env.TZ = prev;
|
|
}
|
|
}
|
|
});
|
|
});
|