T-79: tests

This commit is contained in:
Studio 2026-11-28 00:27:01 -05:00
parent be06a00ffe
commit 63b4c420c3
2 changed files with 571 additions and 0 deletions

View file

@ -0,0 +1,479 @@
import { describe, expect, it } from 'bun:test';
import {
applyVaultFence,
computeVaultCutoffTs,
MarketDataStoreValidationError,
resolveDuckDbConnectionBudget,
VaultHoldoutFenceError,
VaultScopeNotAuthorizedError,
type VaultFenceQuery,
} from '@stock-bot/research';
const DAY_MS = 86_400_000;
function createSeededRng(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
};
}
function captureError(fn: () => unknown): unknown {
try {
fn();
} catch (err) {
return err;
}
return undefined;
}
describe('computeVaultCutoffTs edge cases', () => {
it('clamps 31st to 30-day target months and wraps December/March correctly', () => {
expect(computeVaultCutoffTs('2026-03-31')).toBe(Date.UTC(2025, 8, 30));
expect(computeVaultCutoffTs('2026-12-31')).toBe(Date.UTC(2026, 5, 30));
expect(computeVaultCutoffTs('2026-07-31')).toBe(Date.UTC(2026, 0, 31));
});
it('applies Gregorian century leap rules (2000 leap, 2100 not)', () => {
expect(computeVaultCutoffTs('2000-08-30')).toBe(Date.UTC(2000, 1, 29));
expect(computeVaultCutoffTs('2100-08-31')).toBe(Date.UTC(2100, 1, 28));
});
it('normalizes offset input to UTC before subtracting months', () => {
// 2026-08-31T01:00+02:00 is 2026-08-30T23:00Z -> Feb has no 30th -> 2026-02-28T23:00Z.
expect(computeVaultCutoffTs('2026-08-31T01:00:00+02:00')).toBe(
Date.UTC(2026, 1, 28, 23, 0, 0, 0)
);
});
it('handles pre-1970 instants and the 0..99 two-digit-year range without offsetting to 19xx', () => {
expect(computeVaultCutoffTs('1969-12-31T12:00:00Z')).toBe(Date.UTC(1969, 5, 30, 12));
const expected = new Date(0);
expected.setUTCFullYear(49, 6, 15);
expected.setUTCHours(0, 0, 0, 0);
expect(computeVaultCutoffTs('0050-01-15')).toBe(expected.getTime());
});
it('throws the typed error when the result would fall outside the ECMAScript range', () => {
expect(() => computeVaultCutoffTs(-8_640_000_000_000_000)).toThrow(
MarketDataStoreValidationError
);
expect(() => computeVaultCutoffTs(8_640_000_000_000_001)).toThrow(
MarketDataStoreValidationError
);
});
it('rejects non-number/string/Date inputs at runtime', () => {
for (const bad of [null, undefined, {}, [], true] as unknown[]) {
expect(() => computeVaultCutoffTs(bad as number)).toThrow(MarketDataStoreValidationError);
}
});
it('carries the offending field name on validation errors', () => {
const err = captureError(() => computeVaultCutoffTs('nope'));
expect(err).toBeInstanceOf(MarketDataStoreValidationError);
expect(err).toBeInstanceOf(Error);
expect((err as MarketDataStoreValidationError).field).toBe('maxIngestedTs');
expect((err as MarketDataStoreValidationError).name).toBe('MarketDataStoreValidationError');
});
});
describe('applyVaultFence strict timestamp parsing', () => {
const cutoffMs = Date.UTC(2026, 4, 28);
const ctx = { vaultCutoffTs: cutoffMs };
it.each([
['lowercase z suffix', '2026-01-01T00:00:00z'],
['space separator', '2026-01-01 00:00:00Z'],
['hour 24', '2026-01-01T24:00:00Z'],
['leap second', '2026-01-01T23:59:60Z'],
['minute 60', '2026-01-01T00:60:00Z'],
['offset hour 24', '2026-01-01T00:00:00+24:00'],
['offset minute 60', '2026-01-01T00:00:00+05:60'],
['compact offset', '2026-01-01T00:00:00+0500'],
['missing seconds', '2026-01-01T00:00Z'],
['empty fraction', '2026-01-01T00:00:00.Z'],
['month 13', '2026-13-01'],
['month 00', '2026-00-10'],
['day 00', '2026-01-00'],
['1900-02-29 (not leap)', '1900-02-29'],
['expanded year', '+2026-01-01'],
['leading whitespace', ' 2026-01-01'],
['trailing whitespace', '2026-01-01 '],
['trailing newline', '2026-01-01\n'],
['epoch digits as string', '1767225600000'],
])('rejects %s in from', (_label, from) => {
const err = captureError(() => applyVaultFence({ from, to: '2026-02-01' }, ctx));
expect(err).toBeInstanceOf(MarketDataStoreValidationError);
expect((err as MarketDataStoreValidationError).field).toBe('from');
});
it('accepts 2000-02-29 and treats -00:00 / +00:00 as UTC', () => {
expect(
applyVaultFence({ from: '2000-02-29', to: '2000-02-29T12:00:00+00:00' }, ctx)
).toMatchObject({ fromMs: Date.UTC(2000, 1, 29), toMs: Date.UTC(2000, 1, 29, 12) });
expect(
applyVaultFence({ from: '2026-01-01T00:00:00-00:00', to: '2026-01-02' }, ctx).fromMs
).toBe(Date.UTC(2026, 0, 1));
});
it('rejects non-string timestamps passed through untyped callers', () => {
for (const bad of [123, null, {}] as unknown[]) {
const q = { from: bad, to: '2026-02-01' } as unknown as VaultFenceQuery;
expect(() => applyVaultFence(q, ctx)).toThrow(MarketDataStoreValidationError);
}
});
it('allows a zero-width range (from === to as instants)', () => {
const r = applyVaultFence({ from: '2026-01-01T10:00:00Z', to: '2026-01-01T10:00:00Z' }, ctx);
expect(r.fromMs).toBe(r.toMs);
});
});
describe('applyVaultFence boundary semantics', () => {
it('fences on the UTC instant, not the literal string, when offsets are used', () => {
const cutoffMs = Date.UTC(2026, 4, 28);
// 2026-05-27T23:00-01:00 === 2026-05-28T00:00Z === cutoff -> must be fenced.
const err = captureError(() =>
applyVaultFence(
{ from: '2026-05-27T23:00:00-01:00', to: '2026-06-01' },
{ vaultCutoffTs: cutoffMs }
)
);
expect(err).toBeInstanceOf(VaultHoldoutFenceError);
expect((err as VaultHoldoutFenceError).fromMs).toBe(cutoffMs);
// One millisecond earlier is allowed and to is clamped.
const ok = applyVaultFence(
{ from: '2026-05-27T22:59:59.999-01:00', to: '2026-06-01' },
{ vaultCutoffTs: cutoffMs }
);
expect(ok.fromMs).toBe(cutoffMs - 1);
expect(ok.toMs).toBe(cutoffMs - 1);
expect(ok.clampedTo).toBe(true);
});
it('does not clamp to/asOf at exactly cutoffMs - 1', () => {
const cutoffMs = Date.UTC(2026, 4, 28);
const r = applyVaultFence(
{ from: '2026-05-01', to: '2026-05-27', asOf: '2026-05-27T23:59:59.999Z' },
{ vaultCutoffTs: cutoffMs }
);
expect(r).toMatchObject({
toMs: cutoffMs - 1,
asOfMs: cutoffMs - 1,
clampedTo: false,
clampedAsOf: false,
});
});
it('allows a date-only from on the cutoff day when the cutoff has a non-midnight time', () => {
const cutoffMs = Date.UTC(2026, 4, 28, 12, 0, 0, 0);
const r = applyVaultFence(
{ from: '2026-05-28', to: '2026-05-28' },
{ vaultCutoffTs: cutoffMs }
);
expect(r.fromMs).toBe(Date.UTC(2026, 4, 28));
expect(r.toMs).toBe(cutoffMs - 1);
expect(r.clampedTo).toBe(true);
expect(r.asOfMs).toBe(cutoffMs - 1);
});
it('keeps an asOf earlier than from untouched (point-in-time look-back)', () => {
const cutoffMs = Date.UTC(2026, 4, 28);
const r = applyVaultFence(
{ from: '2026-03-01', to: '2026-04-01', asOf: '2026-01-15' },
{ vaultCutoffTs: cutoffMs }
);
expect(r.asOfMs).toBe(Date.UTC(2026, 0, 15, 23, 59, 59, 999));
expect(r.clampedAsOf).toBe(false);
});
it('still fences and clamps vault_fenced queries even when the operator flag is true', () => {
const cutoffMs = Date.UTC(2026, 4, 28);
const authCtx = { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: true };
expect(() => applyVaultFence({ from: '2026-06-01', to: '2026-07-01' }, authCtx)).toThrow(
VaultHoldoutFenceError
);
const r = applyVaultFence({ from: '2026-01-01', to: '2026-11-28' }, authCtx);
expect(r.toMs).toBe(cutoffMs - 1);
expect(r.asOfMs).toBe(cutoffMs - 1);
expect(r.scope).toBe('vault_fenced');
});
it('reports from > to as a validation error even when both bounds are inside the Vault', () => {
const err = captureError(() =>
applyVaultFence(
{ from: '2026-10-02', to: '2026-10-01' },
{ vaultCutoffTs: Date.UTC(2026, 4, 28) }
)
);
expect(err).toBeInstanceOf(MarketDataStoreValidationError);
expect(err).not.toBeInstanceOf(VaultHoldoutFenceError);
});
it('does not mutate the query or context objects', () => {
const query = Object.freeze({ from: '2026-01-01', to: '2026-11-28', asOf: '2026-11-28' });
const ctx = Object.freeze({ vaultCutoffTs: Date.UTC(2026, 4, 28) });
applyVaultFence(query, ctx);
expect(query).toEqual({ from: '2026-01-01', to: '2026-11-28', asOf: '2026-11-28' });
});
it('rejects the minimum representable cutoff since cutoff - 1 would be unrepresentable', () => {
expect(() =>
applyVaultFence(
{ from: '2026-01-01', to: '2026-02-01' },
{ vaultCutoffTs: -8_640_000_000_000_000 }
)
).toThrow(MarketDataStoreValidationError);
});
});
describe('applyVaultFence vault_evaluation_only authorization', () => {
const cutoffMs = Date.UTC(2026, 4, 28);
it('fails closed for truthy-but-not-true authorization values', () => {
for (const flag of [1, 'true', {}, 'yes'] as unknown[]) {
const ctx = { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: flag as boolean };
const err = captureError(() =>
applyVaultFence(
{ from: '2026-06-01', to: '2026-07-01', scope: 'vault_evaluation_only' },
ctx
)
);
expect(err).toBeInstanceOf(VaultScopeNotAuthorizedError);
expect((err as Error).name).toBe('VaultScopeNotAuthorizedError');
}
});
it('fails closed before parsing, so a bad timestamp never leaks past authorization', () => {
const err = captureError(() =>
applyVaultFence(
{ from: 'garbage', to: 'garbage', scope: 'vault_evaluation_only' },
{ vaultCutoffTs: cutoffMs }
)
);
expect(err).toBeInstanceOf(VaultScopeNotAuthorizedError);
});
it('still validates timestamps and ordering when authorized', () => {
const ctx = { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: true };
expect(() =>
applyVaultFence({ from: 'bad', to: '2026-07-01', scope: 'vault_evaluation_only' }, ctx)
).toThrow(MarketDataStoreValidationError);
expect(() =>
applyVaultFence({ from: '2026-08-01', to: '2026-07-01', scope: 'vault_evaluation_only' }, ctx)
).toThrow(MarketDataStoreValidationError);
});
it('keeps an explicit asOf past the cutoff unclamped when authorized', () => {
const r = applyVaultFence(
{
from: '2026-01-01',
to: '2026-11-01',
asOf: '2026-11-27T10:00:00Z',
scope: 'vault_evaluation_only',
},
{ vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: true }
);
expect(r).toEqual({
fromMs: Date.UTC(2026, 0, 1),
toMs: Date.UTC(2026, 10, 1, 23, 59, 59, 999),
asOfMs: Date.UTC(2026, 10, 27, 10),
scope: 'vault_evaluation_only',
clampedTo: false,
clampedAsOf: false,
});
});
});
describe('applyVaultFence seeded oracle (exact expected outcome per tuple)', () => {
// Independent oracle: each tuple is generated from integer epoch-ms, so the
// expected normalized bounds are computed directly instead of by re-parsing.
it('matches the oracle on 2,000 seeded tuples', () => {
const rng = createSeededRng(0x0a11_7e57);
const baseMs = Date.UTC(2019, 0, 1);
const spanMs = 9 * 365 * DAY_MS;
const counts = { ok: 0, fence: 0, order: 0, clampedTo: 0, clampedAsOf: 0 };
type Bound = { str: string; startMs: number; endMs: number };
const makeBound = (ms: number): Bound => {
if (rng() < 0.4) {
const dayStart = Math.floor(ms / DAY_MS) * DAY_MS;
return {
str: new Date(dayStart).toISOString().slice(0, 10),
startMs: dayStart,
endMs: dayStart + DAY_MS - 1,
};
}
if (rng() < 0.5) {
// Express the same instant with a non-UTC offset (+/- up to 14h, whole minutes).
const offsetMin = Math.floor((rng() - 0.5) * 2 * 14 * 60);
const local = new Date(ms + offsetMin * 60_000).toISOString().slice(0, 23);
const sign = offsetMin < 0 ? '-' : '+';
const abs = Math.abs(offsetMin);
const hh = String(Math.floor(abs / 60)).padStart(2, '0');
const mm = String(abs % 60).padStart(2, '0');
return { str: `${local}${sign}${hh}:${mm}`, startMs: ms, endMs: ms };
}
return { str: new Date(ms).toISOString(), startMs: ms, endMs: ms };
};
for (let i = 0; i < 2_000; i += 1) {
// Cutoffs include midnight-aligned values so date-only bounds hit it exactly.
const rawCutoff = baseMs + Math.floor(rng() * spanMs);
const cutoffMs = i % 3 === 0 ? Math.floor(rawCutoff / DAY_MS) * DAY_MS : rawCutoff;
const pick = (): number => {
const mode = Math.floor(rng() * 4);
if (mode === 0) {
return cutoffMs;
}
if (mode === 1) {
return cutoffMs - 1;
}
return cutoffMs + Math.floor((rng() - 0.55) * 300 * DAY_MS);
};
const from = makeBound(pick());
const to = makeBound(pick());
const asOf = i % 3 === 0 ? undefined : makeBound(pick());
const fromMs = from.startMs;
const toMs = to.endMs;
const act = () =>
applyVaultFence(
{ from: from.str, to: to.str, asOf: asOf?.str },
{ vaultCutoffTs: cutoffMs }
);
if (fromMs > toMs) {
expect(captureError(act)).toBeInstanceOf(MarketDataStoreValidationError);
counts.order += 1;
continue;
}
if (fromMs >= cutoffMs) {
const err = captureError(act);
expect(err).toBeInstanceOf(VaultHoldoutFenceError);
expect((err as VaultHoldoutFenceError).fromMs).toBe(fromMs);
counts.fence += 1;
continue;
}
const expectedClampedTo = toMs >= cutoffMs;
const expectedClampedAsOf = asOf !== undefined && asOf.endMs >= cutoffMs;
const expectedAsOfMs = asOf === undefined || expectedClampedAsOf ? cutoffMs - 1 : asOf.endMs;
expect(act()).toEqual({
fromMs,
toMs: expectedClampedTo ? cutoffMs - 1 : toMs,
asOfMs: expectedAsOfMs,
scope: 'vault_fenced',
clampedTo: expectedClampedTo,
clampedAsOf: expectedClampedAsOf,
});
counts.ok += 1;
counts.clampedTo += expectedClampedTo ? 1 : 0;
counts.clampedAsOf += expectedClampedAsOf ? 1 : 0;
}
// Coverage guard: every branch must be exercised by the seeded corpus.
expect(counts.ok).toBeGreaterThan(200);
expect(counts.fence).toBeGreaterThan(200);
expect(counts.order).toBeGreaterThan(100);
expect(counts.clampedTo).toBeGreaterThan(50);
expect(counts.clampedAsOf).toBeGreaterThan(50);
});
});
describe('resolveDuckDbConnectionBudget edge cases', () => {
it('treats explicitly undefined env entries as unset and uses defaults', () => {
const budget = resolveDuckDbConnectionBudget({
STOCKBOT_DUCKDB_MEMORY_LIMIT: undefined,
STOCKBOT_DUCKDB_THREADS: undefined,
STOCKBOT_DUCKDB_TEMP_DIRECTORY: undefined,
});
expect(budget.statements).toEqual([
"SET memory_limit = '6GB';",
'SET threads = 4;',
"SET temp_directory = '/mnt/data/stockbot/tmp/duckdb';",
]);
});
it('reads process.env when env is omitted', () => {
const keys = [
'STOCKBOT_DUCKDB_MEMORY_LIMIT',
'STOCKBOT_DUCKDB_THREADS',
'STOCKBOT_DUCKDB_TEMP_DIRECTORY',
] as const;
const saved = keys.map(k => process.env[k]);
try {
process.env.STOCKBOT_DUCKDB_MEMORY_LIMIT = '3GB';
process.env.STOCKBOT_DUCKDB_THREADS = '3';
process.env.STOCKBOT_DUCKDB_TEMP_DIRECTORY = '/var/tmp/qa-duckdb';
expect(resolveDuckDbConnectionBudget().statements).toEqual([
"SET memory_limit = '3GB';",
'SET threads = 3;',
"SET temp_directory = '/var/tmp/qa-duckdb';",
]);
process.env.STOCKBOT_DUCKDB_THREADS = '0';
expect(() => resolveDuckDbConnectionBudget()).toThrow(MarketDataStoreValidationError);
} finally {
keys.forEach((k, idx) => {
const prev = saved[idx];
if (prev === undefined) {
delete process.env[k];
} else {
process.env[k] = prev;
}
});
}
});
it.each(['.5GB', '1.GB', '1.5.5GB', ' 2GB', '2GB ', '2GB\n', '+2GB', '-2GB', '2KB', '2Gb', '2'])(
'rejects memory limit %p',
value => {
const err = captureError(() =>
resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_MEMORY_LIMIT: value })
);
expect(err).toBeInstanceOf(MarketDataStoreValidationError);
expect((err as MarketDataStoreValidationError).field).toBe('STOCKBOT_DUCKDB_MEMORY_LIMIT');
}
);
it.each([' 4', '4 ', '4\n', '+4', '1e1', '0x4', '999999999999999999999'])(
'rejects threads %p',
value => {
const err = captureError(() =>
resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_THREADS: value })
);
expect(err).toBeInstanceOf(MarketDataStoreValidationError);
expect((err as MarketDataStoreValidationError).field).toBe('STOCKBOT_DUCKDB_THREADS');
}
);
it.each(['/tmp/a\tb', '/tmp/a\x7fb', '/tmp/a\x1bb', "/tmp/x';SET threads = 64;--"])(
'rejects temp directory %p',
value => {
const err = captureError(() =>
resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_TEMP_DIRECTORY: value })
);
expect(err).toBeInstanceOf(MarketDataStoreValidationError);
expect((err as MarketDataStoreValidationError).field).toBe('STOCKBOT_DUCKDB_TEMP_DIRECTORY');
}
);
it('fails on any one invalid field instead of returning a partial budget', () => {
expect(() =>
resolveDuckDbConnectionBudget({
STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB',
STOCKBOT_DUCKDB_THREADS: '2',
STOCKBOT_DUCKDB_TEMP_DIRECTORY: 'tmp',
})
).toThrow(MarketDataStoreValidationError);
});
it('returns a fresh statements array per call', () => {
const a = resolveDuckDbConnectionBudget({});
a.statements.push('SET threads = 64;');
expect(resolveDuckDbConnectionBudget({}).statements).toHaveLength(3);
});
});

View file

@ -230,3 +230,95 @@ void _query;
void _ctx;
void _range;
void _budget;
// QA: exact parameter/return signatures for every §4 method. Assignability of
// the stub above cannot catch optionality drift (e.g. `crossSection.asOf`
// becoming required), so assert type identity against the documented shapes.
type ParamOf<K extends keyof MarketDataStore> = Parameters<MarketDataStore[K]>[0];
type ReturnOf<K extends keyof MarketDataStore> = ReturnType<MarketDataStore[K]>;
const _exactMethodKeys: AssertEqual<
keyof MarketDataStore,
| 'bars'
| 'crossSection'
| 'fundamentalsAsOf'
| 'events'
| 'shortsAsOf'
| 'macroAsOf'
| 'fx'
| 'universe'
> = true;
const _exactScope: AssertEqual<DataScope, 'vault_fenced' | 'vault_evaluation_only'> = true;
const _exactBarsParam: AssertEqual<
ParamOf<'bars'>,
{
listingIds: number[];
timeframe: '1m' | '5m' | '1h' | '1d';
from: string;
to: string;
adjustment: 'raw' | 'split' | 'total';
asOf?: string;
scope?: DataScope;
}
> = true;
const _exactBarsReturn: AssertEqual<ReturnOf<'bars'>, AsyncIterable<BarBatch>> = true;
const _exactCrossParam: AssertEqual<
ParamOf<'crossSection'>,
{ features: string[]; date: string; universe: UniverseRef; asOf?: string }
> = true;
const _exactCrossReturn: AssertEqual<ReturnOf<'crossSection'>, Promise<Table>> = true;
const _exactFundParam: AssertEqual<
ParamOf<'fundamentalsAsOf'>,
{ listingIds: number[]; fields: string[]; asOf: string; allowEstimatedLag?: boolean }
> = true;
const _exactFundReturn: AssertEqual<ReturnOf<'fundamentalsAsOf'>, Promise<Table>> = true;
const _exactEventsParam: AssertEqual<
ParamOf<'events'>,
{ kinds: EventKind[]; listingIds?: number[]; from: string; to: string; asOf?: string }
> = true;
const _exactEventsReturn: AssertEqual<ReturnOf<'events'>, Promise<Table>> = true;
const _exactShortsParam: AssertEqual<
ParamOf<'shortsAsOf'>,
{ listingIds: number[]; from: string; to: string; asOf?: string }
> = true;
const _exactShortsReturn: AssertEqual<ReturnOf<'shortsAsOf'>, Promise<Table>> = true;
const _exactMacroParam: AssertEqual<
ParamOf<'macroAsOf'>,
{ countries: string[]; indicators: string[]; from: string; to: string; asOf?: string }
> = true;
const _exactMacroReturn: AssertEqual<ReturnOf<'macroAsOf'>, Promise<Table>> = true;
const _exactFxParam: AssertEqual<
ParamOf<'fx'>,
{ pair: 'USD.CAD'; timeframe: '1m' | '1d'; from: string; to: string }
> = true;
const _exactFxReturn: AssertEqual<ReturnOf<'fx'>, Promise<Table>> = true;
const _exactUniverseParam: AssertEqual<
ParamOf<'universe'>,
{ ref: UniverseRef; date: string }
> = true;
const _exactUniverseReturn: AssertEqual<ReturnOf<'universe'>, Promise<number[]>> = true;
// Sanity: the helper must actually detect optionality drift.
const _detectsOptionalityDrift: AssertEqual<{ asOf?: string }, { asOf: string }> = false;
void [
_exactMethodKeys,
_exactScope,
_exactBarsParam,
_exactBarsReturn,
_exactCrossParam,
_exactCrossReturn,
_exactFundParam,
_exactFundReturn,
_exactEventsParam,
_exactEventsReturn,
_exactShortsParam,
_exactShortsReturn,
_exactMacroParam,
_exactMacroReturn,
_exactFxParam,
_exactFxReturn,
_exactUniverseParam,
_exactUniverseReturn,
_detectsOptionalityDrift,
];