import { describe, expect, it } from 'bun:test'; import { applyVaultFence, computeVaultCutoffTs, DEFAULT_DUCKDB_MEMORY_LIMIT, DEFAULT_DUCKDB_TEMP_DIRECTORY, DEFAULT_DUCKDB_THREADS, MarketDataStoreValidationError, resolveDuckDbConnectionBudget, VaultHoldoutFenceError, VaultScopeNotAuthorizedError, } from '@stock-bot/research'; import { applyVaultFence as subpathApplyVaultFence, computeVaultCutoffTs as subpathComputeVaultCutoffTs, resolveDuckDbConnectionBudget as subpathResolveDuckDbConnectionBudget, } from '@stock-bot/research/market-data-store'; function createSeededRng(seed: number): () => number { let state = seed >>> 0; return () => { state = (state + 0x6d2b79f5) >>> 0; let t = Math.imul(state ^ (state >>> 15), 1 | state); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; }; } function formatUtcDateOnly(epochMs: number): string { return new Date(epochMs).toISOString().slice(0, 10); } describe('market-data-store exports', () => { it('exposes identical runtime functions from package root and subpath', () => { expect(computeVaultCutoffTs).toBe(subpathComputeVaultCutoffTs); expect(applyVaultFence).toBe(subpathApplyVaultFence); expect(resolveDuckDbConnectionBudget).toBe(subpathResolveDuckDbConnectionBudget); }); }); describe('computeVaultCutoffTs', () => { it('subtracts 6 calendar months in UTC for standard dates', () => { expect(computeVaultCutoffTs('2026-11-28T00:00:00Z')).toBe(Date.UTC(2026, 4, 28, 0, 0, 0, 0)); expect(computeVaultCutoffTs('2026-11-28')).toBe(Date.UTC(2026, 4, 28, 0, 0, 0, 0)); }); it('clamps month-end dates to the last day of the target month, including leap years', () => { expect(computeVaultCutoffTs('2026-08-31')).toBe(Date.UTC(2026, 1, 28, 0, 0, 0, 0)); expect(computeVaultCutoffTs('2024-08-31')).toBe(Date.UTC(2024, 1, 29, 0, 0, 0, 0)); expect(computeVaultCutoffTs('2026-10-31')).toBe(Date.UTC(2026, 3, 30, 0, 0, 0, 0)); }); it('crosses year boundaries correctly', () => { expect(computeVaultCutoffTs('2026-01-15')).toBe(Date.UTC(2025, 6, 15, 0, 0, 0, 0)); expect(computeVaultCutoffTs('2026-06-30')).toBe(Date.UTC(2025, 11, 30, 0, 0, 0, 0)); }); it('preserves exact UTC time-of-day across month-end clamping', () => { expect(computeVaultCutoffTs('2026-08-31T14:35:22.789Z')).toBe( Date.UTC(2026, 1, 28, 14, 35, 22, 789) ); }); it('accepts integer epoch-ms numbers and valid Date instances', () => { const inputMs = Date.UTC(2026, 10, 28, 13, 45, 59, 123); const expectedMs = Date.UTC(2026, 4, 28, 13, 45, 59, 123); expect(computeVaultCutoffTs(inputMs)).toBe(expectedMs); expect(computeVaultCutoffTs(new Date(inputMs))).toBe(expectedMs); }); it('rejects invalid, non-finite, non-integer, and naive inputs with MarketDataStoreValidationError', () => { const invalidInputs: Array = [ Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, Date.UTC(2026, 4, 28) + 0.5, '', 'not-a-date', '2026-02-29', '2026-05-01T12:00:00', new Date('invalid'), ]; for (const input of invalidInputs) { expect(() => computeVaultCutoffTs(input)).toThrow(MarketDataStoreValidationError); } }); }); describe('applyVaultFence', () => { const cutoffMs = Date.UTC(2026, 4, 28, 0, 0, 0, 0); it('defaults omitted scope to vault_fenced and passes fully pre-cutoff queries unclamped', () => { const result = applyVaultFence( { from: '2025-01-01T00:00:00Z', to: '2026-05-27T23:59:59.999Z', asOf: '2026-05-27T23:59:59.999Z', }, { vaultCutoffTs: cutoffMs } ); expect(result).toEqual({ fromMs: Date.UTC(2025, 0, 1, 0, 0, 0, 0), toMs: cutoffMs - 1, asOfMs: cutoffMs - 1, scope: 'vault_fenced', clampedTo: false, clampedAsOf: false, }); }); it('throws VaultHoldoutFenceError when from >= cutoff (strictly greater or equal)', () => { for (const from of ['2026-05-28T00:00:00Z', '2026-05-28', '2026-06-01T00:00:00Z']) { let caught: unknown; try { applyVaultFence({ from, to: '2026-07-01T00:00:00Z' }, { vaultCutoffTs: cutoffMs }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(VaultHoldoutFenceError); const fenceErr = caught as VaultHoldoutFenceError; expect(fenceErr.from).toBe(from); expect(fenceErr.vaultCutoffTs).toBe(cutoffMs); expect(fenceErr.fromMs).toBeGreaterThanOrEqual(cutoffMs); } }); it('clamps to >= cutoff and asOf >= cutoff to cutoffMs - 1', () => { const atCutoff = applyVaultFence( { from: '2026-01-01T00:00:00Z', to: '2026-05-28T00:00:00Z', asOf: '2026-05-28T00:00:00Z', }, { vaultCutoffTs: cutoffMs } ); expect(atCutoff.toMs).toBe(cutoffMs - 1); expect(atCutoff.asOfMs).toBe(cutoffMs - 1); expect(atCutoff.clampedTo).toBe(true); expect(atCutoff.clampedAsOf).toBe(true); const pastCutoff = applyVaultFence( { from: '2026-01-01', to: '2026-11-28', asOf: '2026-11-28', }, { vaultCutoffTs: cutoffMs } ); expect(pastCutoff.toMs).toBe(cutoffMs - 1); expect(pastCutoff.asOfMs).toBe(cutoffMs - 1); expect(pastCutoff.clampedTo).toBe(true); expect(pastCutoff.clampedAsOf).toBe(true); }); it('defaults omitted asOf in vault_fenced scope to cutoffMs - 1 with clampedAsOf=false', () => { const result = applyVaultFence( { from: '2026-01-01', to: '2026-03-01', }, { vaultCutoffTs: cutoffMs } ); expect(result.asOfMs).toBe(cutoffMs - 1); expect(result.clampedTo).toBe(false); expect(result.clampedAsOf).toBe(false); }); it('fails closed on vault_evaluation_only unless vaultOperatorAuthorized is true', () => { expect(() => applyVaultFence( { from: '2026-05-28', to: '2026-11-28', scope: 'vault_evaluation_only', }, { vaultCutoffTs: cutoffMs } ) ).toThrow(VaultScopeNotAuthorizedError); expect(() => applyVaultFence( { from: '2026-05-28', to: '2026-11-28', scope: 'vault_evaluation_only', }, { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: false } ) ).toThrow(VaultScopeNotAuthorizedError); const authorized = applyVaultFence( { from: '2026-05-28', to: '2026-11-28', scope: 'vault_evaluation_only', }, { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: true } ); expect(authorized).toEqual({ fromMs: Date.UTC(2026, 4, 28, 0, 0, 0, 0), toMs: Date.UTC(2026, 10, 28, 23, 59, 59, 999), asOfMs: Date.UTC(2026, 10, 28, 23, 59, 59, 999), scope: 'vault_evaluation_only', clampedTo: false, clampedAsOf: false, }); }); it('expands date-only from to 00:00:00.000Z and date-only to/asOf to 23:59:59.999Z', () => { const result = applyVaultFence( { from: '2026-03-10', to: '2026-03-10', asOf: '2026-03-10', }, { vaultCutoffTs: cutoffMs } ); expect(result.fromMs).toBe(Date.UTC(2026, 2, 10, 0, 0, 0, 0)); expect(result.toMs).toBe(Date.UTC(2026, 2, 10, 23, 59, 59, 999)); expect(result.asOfMs).toBe(Date.UTC(2026, 2, 10, 23, 59, 59, 999)); }); it('normalizes explicit UTC offsets and truncates sub-millisecond fractions to integer ms', () => { const result = applyVaultFence( { from: '2026-03-10T08:00:00.987654-04:00', to: '2026-03-10T18:30:00.1+05:30', }, { vaultCutoffTs: cutoffMs } ); expect(result.fromMs).toBe(Date.UTC(2026, 2, 10, 12, 0, 0, 987)); expect(result.toMs).toBe(Date.UTC(2026, 2, 10, 13, 0, 0, 100)); }); it('rejects unknown scope, malformed timestamps, from > to, and non-finite cutoffs', () => { expect(() => applyVaultFence( { from: '2026-01-01', to: '2026-02-01', scope: 'unrestricted' as never, }, { vaultCutoffTs: cutoffMs } ) ).toThrow(MarketDataStoreValidationError); const invalidQueries = [ { from: 'bad-date', to: '2026-02-01' }, { from: '2026-01-01', to: 'bad-date' }, { from: '2026-01-01', to: '2026-02-01', asOf: 'bad-date' }, { from: '2026-01-01', to: '2026-02-01', asOf: '' }, { from: '2026-01-01T00:00:00', to: '2026-02-01' }, { from: '2026-02-30', to: '2026-03-01' }, { from: '2026-04-01', to: '2026-03-01' }, { from: '2026-09-01', to: '2026-08-01' }, ]; for (const q of invalidQueries) { expect(() => applyVaultFence(q, { vaultCutoffTs: cutoffMs })).toThrow( MarketDataStoreValidationError ); } for (const badCutoff of [ Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, cutoffMs + 0.25, ]) { expect(() => applyVaultFence({ from: '2026-01-01', to: '2026-02-01' }, { vaultCutoffTs: badCutoff }) ).toThrow(MarketDataStoreValidationError); } }); it('produces identical epoch-ms results under TZ=America/Toronto and TZ=UTC', () => { const previousTz = process.env.TZ; try { process.env.TZ = 'UTC'; const utcCutoff = computeVaultCutoffTs('2026-08-31T23:30:00.500Z'); const utcFenced = applyVaultFence( { from: '2026-01-01', to: '2026-03-15', asOf: '2026-02-28' }, { vaultCutoffTs: utcCutoff } ); process.env.TZ = 'America/Toronto'; const torontoCutoff = computeVaultCutoffTs('2026-08-31T23:30:00.500Z'); const torontoFenced = applyVaultFence( { from: '2026-01-01', to: '2026-03-15', asOf: '2026-02-28' }, { vaultCutoffTs: torontoCutoff } ); expect(torontoCutoff).toBe(utcCutoff); expect(torontoFenced).toEqual(utcFenced); } finally { if (previousTz === undefined) { delete process.env.TZ; } else { process.env.TZ = previousTz; } } }); it('enforces fromMs <= toMs < cutoffMs and asOfMs < cutoffMs across 1,500 seeded random cases', () => { const rng = createSeededRng(0x5eed1234); const baseMs = Date.UTC(2020, 0, 1, 0, 0, 0, 0); const spanMs = 8 * 365 * 86_400_000; let passedCount = 0; let fenceErrorCount = 0; let validationErrorCount = 0; for (let i = 0; i < 1_500; i += 1) { const randCutoff = baseMs + Math.floor(rng() * spanMs); const bucket = i % 5; const offsetFrom = bucket === 0 ? -Math.floor(rng() * 180 * 86_400_000) - 1 : bucket === 1 ? 0 : Math.floor((rng() - 0.5) * 360 * 86_400_000); const offsetTo = Math.floor((rng() - 0.3) * 360 * 86_400_000); const rawFromMs = randCutoff + offsetFrom; const rawToMs = randCutoff + offsetTo; const useDateOnlyFrom = rng() < 0.35; const useDateOnlyTo = rng() < 0.35; const fromStr = useDateOnlyFrom ? formatUtcDateOnly(rawFromMs) : new Date(rawFromMs).toISOString(); const toStr = useDateOnlyTo ? formatUtcDateOnly(rawToMs) : new Date(rawToMs).toISOString(); const asOfMode = i % 4; let asOfStr: string | undefined; if (asOfMode === 1) { const rawAsOfMs = randCutoff + Math.floor((rng() - 0.5) * 360 * 86_400_000); asOfStr = new Date(rawAsOfMs).toISOString(); } else if (asOfMode === 2) { const rawAsOfMs = randCutoff + Math.floor((rng() - 0.5) * 360 * 86_400_000); asOfStr = formatUtcDateOnly(rawAsOfMs); } else if (asOfMode === 3) { asOfStr = new Date(randCutoff).toISOString(); } try { const fenced = applyVaultFence( { from: fromStr, to: toStr, asOf: asOfStr }, { vaultCutoffTs: randCutoff } ); expect(fenced.scope).toBe('vault_fenced'); expect(fenced.fromMs).toBeLessThanOrEqual(fenced.toMs); expect(fenced.toMs).toBeLessThan(randCutoff); expect(fenced.asOfMs).toBeLessThan(randCutoff); passedCount += 1; } catch (err) { if (err instanceof VaultHoldoutFenceError) { expect(err.fromMs).toBeGreaterThanOrEqual(randCutoff); fenceErrorCount += 1; } else if (err instanceof MarketDataStoreValidationError) { validationErrorCount += 1; } else { throw err; } } } expect(passedCount).toBeGreaterThan(200); expect(fenceErrorCount).toBeGreaterThan(200); expect(validationErrorCount).toBeGreaterThan(100); }); }); describe('resolveDuckDbConnectionBudget', () => { it('returns the exact default budget and SET statements when env is empty', () => { const budget = resolveDuckDbConnectionBudget({}); expect(budget).toEqual({ memoryLimit: DEFAULT_DUCKDB_MEMORY_LIMIT, threads: DEFAULT_DUCKDB_THREADS, tempDirectory: DEFAULT_DUCKDB_TEMP_DIRECTORY, statements: [ "SET memory_limit = '6GB';", 'SET threads = 4;', "SET temp_directory = '/mnt/data/stockbot/tmp/duckdb';", ], }); }); it('applies valid environment overrides including decimal sizes and boundary thread counts', () => { const localDev = resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB', STOCKBOT_DUCKDB_THREADS: '2', STOCKBOT_DUCKDB_TEMP_DIRECTORY: '/tmp/duckdb', }); expect(localDev.statements).toEqual([ "SET memory_limit = '2GB';", 'SET threads = 2;', "SET temp_directory = '/tmp/duckdb';", ]); const decimalMin = resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_MEMORY_LIMIT: '1.5GiB', STOCKBOT_DUCKDB_THREADS: '1', STOCKBOT_DUCKDB_TEMP_DIRECTORY: '/var/tmp/stockbot-duckdb', }); expect(decimalMin.memoryLimit).toBe('1.5GiB'); expect(decimalMin.threads).toBe(1); const maxThreads = resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MiB', STOCKBOT_DUCKDB_THREADS: '64', }); expect(maxThreads.memoryLimit).toBe('512MiB'); expect(maxThreads.threads).toBe(64); }); it('rejects malformed memory limits, out-of-range threads, and unsafe temp paths', () => { const badMemoryLimits = ['0GB', '0.0GiB', '2gb', '2TB', '2 GB', '', "2GB'; DROP TABLE t;--"]; for (const value of badMemoryLimits) { expect(() => resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_MEMORY_LIMIT: value })).toThrow( MarketDataStoreValidationError ); } const badThreads = ['0', '65', '-1', '2.5', '04', 'abc', '']; for (const value of badThreads) { expect(() => resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_THREADS: value })).toThrow( MarketDataStoreValidationError ); } const badTempDirs = [ 'relative/path', './tmp', '', "/tmp/a'b", '/tmp/a;b', '/tmp/a\nb', '/tmp/a\rb', '/tmp/a\0b', ]; for (const value of badTempDirs) { expect(() => resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_TEMP_DIRECTORY: value }) ).toThrow(MarketDataStoreValidationError); } }); });