import { describe, expect, test } from 'bun:test'; import type { ClosableDuckDbExecutor } from '@stock-bot/duckdb'; import { M2_INTRADAY_TABLE_NAMES, type ApplyM2IntradayDDLResult, type QuestDbPgExecutorConfig, type QuestDbPgExecutorHandle, type QuestDbPgQueryExecutor, } from '@stock-bot/questdb'; import type { BarBatch, BarRecord, MarketDataStore, TableRow } from '@stock-bot/research'; import type { ManagedMarketDataStore, ResearchCopilotHostConfig } from '@stock-bot/research/mcp'; import { MAX_COLD_READ_MS, MAX_WARM_READ_MS, MIN_ONE_YEAR_WINDOW_MS, type M2LoadReceipt, type VerifyM2QuantCliDeps, type VerifyM2QuantDdlOnlyReport, type VerifyM2QuantReport, runVerifyM2QuantCli, } from '../verify-m2-quant'; const NVDA_LISTING_ID = 101; const NEXM_LISTING_ID = 202; const OVERLAP_LISTING_ID = 303; const VAULT_CUTOFF_ISO = '2025-02-13T00:00:00Z'; const VAULT_CUTOFF_MS = Date.parse(VAULT_CUTOFF_ISO); const KNOWN_AT_US = (BigInt(Date.parse('2025-02-01T00:00:00Z')) * 1000n).toString(); const DEFAULT_RECEIPT_REL_PATH = 'receipts/m2-load-receipt.json'; const DEFAULT_RECEIPT_ABS_PATH = `/tmp/verify-m2-quant-test/${DEFAULT_RECEIPT_REL_PATH}`; const DEFAULT_RESEND_BASELINE_REL_PATH = 'receipts/m2-initial-report.json'; const DEFAULT_RESEND_BASELINE_ABS_PATH = `/tmp/verify-m2-quant-test/${DEFAULT_RESEND_BASELINE_REL_PATH}`; const EOD_PROBE_TS_ISO = '2024-06-10T19:59:00.000000Z'; const EOD_PROBE_TS_US = isoToMicros('2024-06-10T19:59:00Z'); const QM_PROBE_TS_ISO = '2025-06-20T19:59:00.000000Z'; const QM_PROBE_TS_US = isoToMicros('2025-06-20T19:59:00Z'); const FX_PROBE_TS_ISO = '2024-06-10T19:59:00.000000Z'; const FX_PROBE_TS_US = isoToMicros('2024-06-10T19:59:00Z'); const OVERLAP_PROBE_TS_ISO = '2024-07-02T15:00:00.000000Z'; const OVERLAP_PROBE_TS_US = isoToMicros('2024-07-02T15:00:00Z'); function createBufferStream(): { readonly write: (chunk: string) => boolean; readonly text: () => string; } { const chunks: string[] = []; return { write(chunk: string): boolean { chunks.push(chunk); return true; }, text(): string { return chunks.join(''); }, }; } function isoToMicros(iso: string): string { return (BigInt(Date.parse(iso)) * 1000n).toString(); } function baseArgs(overrides: Record = {}): string[] { const defaults: Record = { '--questdb-host': '10.0.0.51', '--questdb-pg-port': '8812', '--curated-root': '/mnt/data/stockbot/curated', '--vault-cutoff-ts': VAULT_CUTOFF_ISO, '--nvda-listing-id': String(NVDA_LISTING_ID), '--nexm-listing-id': String(NEXM_LISTING_ID), '--bench-listing-id': String(NVDA_LISTING_ID), '--bench-from': '2024-01-02T00:00:00Z', '--bench-to': '2025-01-02T00:00:00Z', '--bench-as-of': '2025-02-01T00:00:00Z', '--load-receipt': DEFAULT_RECEIPT_REL_PATH, '--warm-runs': '3', '--wal-settle-timeout-ms': '5000', }; const merged = { ...defaults, ...overrides }; const argv: string[] = []; for (const [flag, value] of Object.entries(merged)) { if (value === null) { continue; } argv.push(flag, value); } return argv; } function defaultLoadReceipt(): M2LoadReceipt { return { beforeWal: { bars_1m: { writerTxn: '100', sequencerTxn: '100' }, fx_1m: { writerTxn: '30', sequencerTxn: '30' }, bar_revisions: { writerTxn: '0', sequencerTxn: '0' }, }, shards: { bars_1m: { probes: [ { listingId: NVDA_LISTING_ID, tsUs: EOD_PROBE_TS_US, expectedClose: 121.79, expectedSource: 'eod', expectedKnownAtUs: KNOWN_AT_US, }, ], }, bars_1m_qm: { probes: [ { listingId: NEXM_LISTING_ID, tsUs: QM_PROBE_TS_US, expectedClose: 8.02, expectedSource: 'qm', expectedKnownAtUs: KNOWN_AT_US, }, ], }, fx_1m: { probes: [ { pair: 'USDCAD', tsUs: FX_PROBE_TS_US, expectedClose: 1.3765, expectedSource: 'eod', }, ], }, }, dedup: { eodSentRows: 500_500, qmSentRows: 25_000, overlapRows: 500, overlapWinnerSource: 'qm', overlapProbes: [ { listingId: OVERLAP_LISTING_ID, tsUs: OVERLAP_PROBE_TS_US, expectedClose: 4.25, expectedSource: 'qm', expectedKnownAtUs: KNOWN_AT_US, }, ], }, }; } function defaultBars1mProbeMap(): Map[]> { return new Map[]>([ [ `${NVDA_LISTING_ID}|${EOD_PROBE_TS_ISO}`, [ { listing_id: String(NVDA_LISTING_ID), ts_us: EOD_PROBE_TS_US, close: 121.79, source: 'eod', known_at_us: KNOWN_AT_US, }, ], ], [ `${NEXM_LISTING_ID}|${QM_PROBE_TS_ISO}`, [ { listing_id: String(NEXM_LISTING_ID), ts_us: QM_PROBE_TS_US, close: 8.02, source: 'qm', known_at_us: KNOWN_AT_US, }, ], ], [ `${OVERLAP_LISTING_ID}|${OVERLAP_PROBE_TS_ISO}`, [ { listing_id: String(OVERLAP_LISTING_ID), ts_us: OVERLAP_PROBE_TS_US, close: 4.25, source: 'qm', known_at_us: KNOWN_AT_US, }, ], ], ]); } function defaultFx1mProbeMap(): Map[]> { return new Map[]>([ [ `USDCAD|${FX_PROBE_TS_ISO}`, [ { pair: 'USDCAD', ts_us: FX_PROBE_TS_US, close: 1.3765, source: 'eod', }, ], ], ]); } interface MockFixtureOptions { readonly walSequence?: readonly (readonly Record[])[]; readonly bars1mSummaryRows?: readonly Record[]; readonly fx1mSummaryRows?: readonly Record[]; readonly bars1mProbeRows?: Map[]>; readonly fx1mProbeRows?: Map[]>; readonly nvda1mRows?: readonly Record[]; readonly nexm1mRows?: readonly Record[]; readonly nvda1dRows?: readonly TableRow[]; readonly nexm1dRows?: readonly TableRow[]; readonly benchBatchesByCall?: readonly (readonly BarRecord[])[]; readonly perfDurationsMs?: readonly number[]; readonly loadReceipt?: M2LoadReceipt; readonly rawFiles?: Record; readonly openPgError?: Error; readonly queryError?: Error; } function defaultWalRows(): readonly Record[] { return [ { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, { name: 'bars_1m', suspended: false, writerTxn: '120', sequencerTxn: '120' }, { name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' }, ]; } function defaultBars1mSummaryRows(): readonly Record[] { return [ { source: 'eod', row_count: '500000', min_close: 0.42, max_close: 1210.5, min_ts_us: isoToMicros('2024-01-02T14:30:00Z'), max_ts_us: isoToMicros('2025-06-23T20:00:00Z'), }, { source: 'qm', row_count: '25000', min_close: 0.15, max_close: 24.5, min_ts_us: isoToMicros('2024-05-01T13:30:00Z'), max_ts_us: isoToMicros('2025-06-23T20:00:00Z'), }, ]; } function defaultFx1mSummaryRows(): readonly Record[] { return [ { pair: 'USDCAD', source: 'eod', row_count: '380000', min_close: 1.31, max_close: 1.45, min_ts_us: isoToMicros('2024-01-02T00:00:00Z'), max_ts_us: isoToMicros('2025-01-31T23:59:00Z'), }, ]; } function defaultNvda1mRows(): readonly Record[] { return [ // Multiple RTH bars on 2024-06-07 (pre-split 10:1); latest ts (19:59 UTC = 15:59 ET) must win. { ts_us: isoToMicros('2024-06-07T14:30:00Z'), close: 1190.0 }, { ts_us: isoToMicros('2024-06-07T19:59:00Z'), close: 1208.88 }, // Ex-date 2024-06-10 (post 10:1 split) { ts_us: isoToMicros('2024-06-10T19:59:00Z'), close: 121.79 }, // Post-split 2024-06-11 { ts_us: isoToMicros('2024-06-11T19:59:00Z'), close: 120.91 }, ]; } function defaultNvda1dRows(): readonly TableRow[] { return [ { session_date: '2024-06-07', close: 1208.88 }, { session_date: '2024-06-10', close: 121.79 }, { session_date: '2024-06-11', close: 120.91 }, ]; } function defaultNexm1mRows(): readonly Record[] { return [ // Pre-split 2025-06-19 (before 1:20 reverse split) { ts_us: isoToMicros('2025-06-19T19:59:00Z'), close: 0.4 }, // Ex-date 2025-06-20 (after 1:20 reverse split) { ts_us: isoToMicros('2025-06-20T19:59:00Z'), close: 8.02 }, ]; } function defaultNexm1dRows(): readonly TableRow[] { return [ { session_date: '2025-06-19', close: 0.4 }, { session_date: '2025-06-20', close: 8.0 }, ]; } function defaultBenchBars(): readonly BarRecord[] { const knownAt = Date.parse('2025-02-01T00:00:00Z'); return [ { listingId: NVDA_LISTING_ID, ts: Date.parse('2024-01-02T14:30:00Z'), open: 492.0, high: 493.5, low: 491.5, close: 492.8, volume: 12_000, vwap: 492.5, knownAt, }, { listingId: NVDA_LISTING_ID, ts: Date.parse('2024-06-10T19:59:00Z'), open: 121.5, high: 121.9, low: 121.4, close: 121.79, volume: 45_000, vwap: 121.7, knownAt, }, ]; } function createHarness( argv: readonly string[], options: MockFixtureOptions = {} ): { readonly deps: VerifyM2QuantCliDeps; readonly stdout: ReturnType; readonly stderr: ReturnType; readonly state: { ddlCalls: number; pgClosed: boolean; duckClosed: boolean; storeClosed: boolean; writtenFiles: Map; openedPgConfigs: QuestDbPgExecutorConfig[]; openedStoreConfigs: ResearchCopilotHostConfig[]; walPollCount: number; events: string[]; }; } { const stdout = createBufferStream(); const stderr = createBufferStream(); const state = { ddlCalls: 0, pgClosed: false, duckClosed: false, storeClosed: false, writtenFiles: new Map(), openedPgConfigs: [] as QuestDbPgExecutorConfig[], openedStoreConfigs: [] as ResearchCopilotHostConfig[], walPollCount: 0, events: [] as string[], }; const walSeq = options.walSequence ?? [defaultWalRows()]; const bars1mSummary = options.bars1mSummaryRows ?? defaultBars1mSummaryRows(); const fx1mSummary = options.fx1mSummaryRows ?? defaultFx1mSummaryRows(); const bars1mProbes = options.bars1mProbeRows ?? defaultBars1mProbeMap(); const fx1mProbes = options.fx1mProbeRows ?? defaultFx1mProbeMap(); const nvda1m = options.nvda1mRows ?? defaultNvda1mRows(); const nexm1m = options.nexm1mRows ?? defaultNexm1mRows(); const nvda1d = options.nvda1dRows ?? defaultNvda1dRows(); const nexm1d = options.nexm1dRows ?? defaultNexm1dRows(); const files = new Map([ [DEFAULT_RECEIPT_ABS_PATH, JSON.stringify(options.loadReceipt ?? defaultLoadReceipt())], ]); if (options.rawFiles !== undefined) { for (const [k, v] of Object.entries(options.rawFiles)) { files.set(k, v); } } let nowClock = 1_000_000; let benchCallIdx = 0; const durations = options.perfDurationsMs ?? [180, 42, 38, 41, 39, 40]; let perfCursor = 0; let perfTime = 0; let expectEndRead = false; const perfNowMs = (): number => { if (!expectEndRead) { expectEndRead = true; return perfTime; } expectEndRead = false; const delta = durations[Math.min(perfCursor, durations.length - 1)] ?? 20; perfCursor += 1; perfTime += delta; return perfTime; }; const pgExecutor: QuestDbPgQueryExecutor = { async query(sql: string, params?: readonly unknown[]) { if (options.queryError !== undefined) { throw options.queryError; } if (sql.includes('FROM wal_tables()')) { state.events.push('pg:wal_tables'); const idx = Math.min(state.walPollCount, walSeq.length - 1); state.walPollCount += 1; return { rows: walSeq[idx] ?? [] }; } if (sql.includes('FROM bars_1m GROUP BY source')) { state.events.push('pg:bars_1m_summary'); return { rows: bars1mSummary }; } if (sql.includes('FROM fx_1m GROUP BY pair, source')) { state.events.push('pg:fx_1m_summary'); return { rows: fx1mSummary }; } if (sql.includes('FROM bars_1m WHERE listing_id = $1 AND ts = $2')) { const key = `${String(params?.[0] ?? '')}|${String(params?.[1] ?? '')}`; state.events.push(`pg:probe_bars_1m:${key}`); return { rows: bars1mProbes.get(key) ?? [] }; } if (sql.includes('FROM fx_1m WHERE pair = $1 AND ts = $2')) { const key = `${String(params?.[0] ?? '')}|${String(params?.[1] ?? '')}`; state.events.push(`pg:probe_fx_1m:${key}`); return { rows: fx1mProbes.get(key) ?? [] }; } if (sql.includes("session = 'RTH'")) { const listingId = String(params?.[0] ?? ''); state.events.push(`pg:split_rth:${listingId}`); if (listingId === String(NVDA_LISTING_ID)) { return { rows: nvda1m }; } if (listingId === String(NEXM_LISTING_ID)) { return { rows: nexm1m }; } return { rows: [] }; } throw new Error(`Unexpected QuestDB SQL in mock: ${sql}`); }, }; const duckExecutor: ClosableDuckDbExecutor = { async run(): Promise { return undefined; }, async query(sql: string, params: readonly unknown[]): Promise { if (sql.includes('read_parquet')) { const listingId = Number(params[0]); state.events.push(`duck:bars_1d:${listingId}`); if (listingId === NVDA_LISTING_ID) { return nvda1d; } if (listingId === NEXM_LISTING_ID) { return nexm1d; } return []; } throw new Error(`Unexpected DuckDB SQL in mock: ${sql}`); }, async close(): Promise { state.duckClosed = true; }, }; const mockStore: MarketDataStore = { async *bars(): AsyncIterable { state.events.push(benchCallIdx === 0 ? 'bench:cold' : `bench:warm#${benchCallIdx}`); const batches = options.benchBatchesByCall; const rows = batches !== undefined ? (batches[Math.min(benchCallIdx, batches.length - 1)] ?? []) : defaultBenchBars(); benchCallIdx += 1; if (rows.length > 0) { yield { rows }; } }, async crossSection() { throw new Error('unused'); }, async fundamentalsAsOf() { throw new Error('unused'); }, async events() { throw new Error('unused'); }, async shortsAsOf() { throw new Error('unused'); }, async macroAsOf() { throw new Error('unused'); }, async fx() { throw new Error('unused'); }, async universe() { throw new Error('unused'); }, }; const deps: VerifyM2QuantCliDeps = { argv, cwd: '/tmp/verify-m2-quant-test', stdout, stderr, async openQuestDbPgExecutor(config: QuestDbPgExecutorConfig): Promise { state.openedPgConfigs.push(config); if (options.openPgError !== undefined) { throw options.openPgError; } return { executor: pgExecutor, async close(): Promise { state.pgClosed = true; }, }; }, async applyM2IntradayDDL(): Promise { state.ddlCalls += 1; state.events.push('pg:ddl'); return { appliedTables: [...M2_INTRADAY_TABLE_NAMES], statements: ['CREATE TABLE IF NOT EXISTS bars_1m ...'], }; }, async createDuckDbExecutor(): Promise { return duckExecutor; }, async openResearchCopilotStore( config: ResearchCopilotHostConfig ): Promise { state.openedStoreConfigs.push(config); return { store: mockStore, async close(): Promise { state.storeClosed = true; }, }; }, async readTextFile(path: string): Promise { const content = files.get(path); if (content === undefined) { throw new Error(`ENOENT: no such mock file '${path}'`); } return content; }, async writeReportFile(path: string, content: string): Promise { state.writtenFiles.set(path, content); }, nowMs: () => nowClock, perfNowMs, sleepMs: async (ms: number) => { nowClock += ms; }, walPollIntervalMs: 1000, }; return { deps, stdout, stderr, state }; } function assertSingleLineError(stderrText: string): void { expect(stderrText.length).toBeGreaterThan(0); expect(stderrText.endsWith('\n')).toBe(true); expect(stderrText.slice(0, -1)).not.toContain('\n'); } describe('scripts/verify-m2-quant.ts', () => { test('prints usage and exits 0 on --help', async () => { const { deps, stdout, stderr } = createHarness(['--help']); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(0); expect(stdout.text()).toContain('Usage: bun run scripts/verify-m2-quant.ts'); expect(stdout.text()).toContain('--ddl-only'); expect(stdout.text()).toContain('--load-receipt'); expect(stdout.text()).toContain('--resend-baseline'); expect(stderr.text()).toBe(''); }); test('--ddl-only succeeds against an empty QuestDB instance without querying table contents', async () => { const emptyWal = [ { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, { name: 'bars_1m', suspended: false, writerTxn: '0', sequencerTxn: '0' }, { name: 'fx_1m', suspended: false, writerTxn: '0', sequencerTxn: '0' }, ]; const { deps, stdout, stderr, state } = createHarness( [ '--ddl-only', '--questdb-host', '10.0.0.51', '--questdb-pg-port', '8812', '--out', 'out/ddl-only.json', ], { walSequence: [emptyWal], bars1mSummaryRows: [], fx1mSummaryRows: [], } ); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(0); expect(stderr.text()).toBe(''); expect(state.ddlCalls).toBe(1); expect(state.pgClosed).toBe(true); expect(state.duckClosed).toBe(false); expect(state.storeClosed).toBe(false); expect(state.openedStoreConfigs).toHaveLength(0); expect(state.events).toEqual(['pg:ddl', 'pg:wal_tables']); expect(state.writtenFiles.size).toBe(1); const report = JSON.parse(stdout.text()) as VerifyM2QuantDdlOnlyReport; expect(report.ok).toBe(true); expect(report.mode).toBe('ddl_only'); expect(report.ddl).toEqual({ applied: true, appliedTables: [...M2_INTRADAY_TABLE_NAMES], }); expect(report.walTables).toHaveLength(3); }); test('--ddl-only fails closed if a WAL table is missing or suspended', async () => { const { deps, stdout, stderr } = createHarness( ['--ddl-only', '--questdb-host', '10.0.0.51', '--questdb-pg-port', '8812'], { walSequence: [ [ { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, { name: 'bars_1m', suspended: true, writerTxn: '0', sequencerTxn: '0' }, { name: 'fx_1m', suspended: false, writerTxn: '0', sequencerTxn: '0' }, ], ], } ); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(1); expect(stdout.text()).toBe(''); assertSingleLineError(stderr.text()); expect(stderr.text()).toContain('Suspended QuestDB WAL table'); }); test('measures cold 1y 1m benchmark read BEFORE any verifier query scans bars_1m', async () => { const { deps, stdout, stderr, state } = createHarness(baseArgs()); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(0); expect(stderr.text()).toBe(''); const coldIndex = state.events.indexOf('bench:cold'); const summaryIndex = state.events.indexOf('pg:bars_1m_summary'); const firstProbeIndex = state.events.findIndex(e => e.startsWith('pg:probe_bars_1m:')); const firstSplitIndex = state.events.findIndex(e => e.startsWith('pg:split_rth:')); expect(coldIndex).toBe(0); expect(summaryIndex).toBeGreaterThan(coldIndex); expect(firstProbeIndex).toBeGreaterThan(coldIndex); expect(firstSplitIndex).toBeGreaterThan(coldIndex); expect((JSON.parse(stdout.text()) as VerifyM2QuantReport).ok).toBe(true); }); test('passes end-to-end without --apply-ddl, records effective bounds and load verification, writes --out, and closes all handles', async () => { const argv = [...baseArgs(), '--out', 'out/m2-quant-verify.json']; const { deps, stdout, stderr, state } = createHarness(argv); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(0); expect(stderr.text()).toBe(''); expect(state.ddlCalls).toBe(0); expect(state.pgClosed).toBe(true); expect(state.duckClosed).toBe(true); expect(state.storeClosed).toBe(true); const report = JSON.parse(stdout.text()) as VerifyM2QuantReport; expect(report.ok).toBe(true); expect(report.mode).toBe('verify'); expect(report.ddl).toEqual({ applied: false, appliedTables: [] }); expect(report.walTables).toHaveLength(3); expect(report.bars1mSummary).toHaveLength(2); expect(report.fx1mSummary).toHaveLength(1); expect(report.loadVerification.walAdvancement).toHaveLength(2); expect(report.loadVerification.probesVerified).toHaveLength(4); expect(report.loadVerification.dedupAccounting.minExpectedEodRows).toBe(500_000); expect(report.loadVerification.dedupAccounting.minExpectedQmRows).toBe(25_000); expect(report.loadVerification.dedupAccounting.minExpectedTotalBars1mRows).toBe(525_000); expect(report.resendVerification).toBeUndefined(); expect(report.splitChecks).toHaveLength(2); expect(report.splitChecks[0]?.label).toBe('NVDA.US'); expect(report.splitChecks[0]?.preSplitCount).toBe(1); expect(report.splitChecks[0]?.exOrPostSplitCount).toBe(2); expect(report.splitChecks[0]?.maxRelDiff).toBeLessThanOrEqual(0.005); expect(report.splitChecks[1]?.label).toBe('NEXM.V'); expect(report.splitChecks[1]?.maxRelDiff).toBeCloseTo(0.0025, 6); expect(report.benchmark.rowCount).toBe(2); expect(report.benchmark.effectiveFrom).toBe('2024-01-02T00:00:00.000Z'); expect(report.benchmark.effectiveTo).toBe('2025-01-02T00:00:00.000Z'); expect(report.benchmark.effectiveAsOf).toBe('2025-02-01T00:00:00.000Z'); expect(report.benchmark.effectiveSpanMs).toBeGreaterThanOrEqual(MIN_ONE_YEAR_WINDOW_MS); expect(report.benchmark.clampedTo).toBe(false); expect(report.benchmark.clampedAsOf).toBe(false); expect(report.benchmark.coldMs).toBe(180); expect(report.benchmark.warmRuns).toEqual([42, 38, 41]); expect(report.benchmark.maxWarmMs).toBe(42); expect(report.benchmark.thresholds).toEqual({ maxColdMs: MAX_COLD_READ_MS, maxWarmMs: MAX_WARM_READ_MS, minWindowMs: MIN_ONE_YEAR_WINDOW_MS, }); expect(state.writtenFiles.size).toBe(1); }); test('invokes applyM2IntradayDDL when --apply-ddl is set without scanning bars_1m before cold read', async () => { const argv = [...baseArgs(), '--apply-ddl']; const { deps, stdout, stderr, state } = createHarness(argv); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(0); expect(stderr.text()).toBe(''); expect(state.ddlCalls).toBe(1); expect(state.events[0]).toBe('pg:ddl'); expect(state.events[1]).toBe('bench:cold'); const report = JSON.parse(stdout.text()) as VerifyM2QuantReport; expect(report.ddl).toEqual({ applied: true, appliedTables: [...M2_INTRADAY_TABLE_NAMES], }); }); test('fails closed when WAL did not advance past receipt beforeWal (stale table contents)', async () => { const staleReceipt: M2LoadReceipt = { ...defaultLoadReceipt(), beforeWal: { bars_1m: { writerTxn: '120', sequencerTxn: '120' }, fx_1m: { writerTxn: '30', sequencerTxn: '30' }, }, }; const { deps, stdout, stderr } = createHarness(baseArgs(), { loadReceipt: staleReceipt, }); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(1); expect(stdout.text()).toBe(''); assertSingleLineError(stderr.text()); expect(stderr.text()).toContain("WAL for 'bars_1m' did not advance"); }); test('fails closed when QM shard prefix is rejected even if older EOD and FX rows satisfy split and latency checks', async () => { // Missing 'qm' group in bars_1m summary const missingQmGroup = createHarness(baseArgs(), { bars1mSummaryRows: [defaultBars1mSummaryRows()[0]!], }); expect(await runVerifyM2QuantCli(missingQmGroup.deps)).toBe(1); expect(missingQmGroup.stdout.text()).toBe(''); expect(missingQmGroup.stderr.text()).toContain("missing required source='qm'"); // Older 'qm' group exists, but current QM probe key is absent const missingQmProbeMap = defaultBars1mProbeMap(); missingQmProbeMap.delete(`${NEXM_LISTING_ID}|${QM_PROBE_TS_ISO}`); const missingQmProbe = createHarness(baseArgs(), { bars1mProbeRows: missingQmProbeMap, }); expect(await runVerifyM2QuantCli(missingQmProbe.deps)).toBe(1); expect(missingQmProbe.stdout.text()).toBe(''); expect(missingQmProbe.stderr.text()).toContain('bars_1m_qm'); expect(missingQmProbe.stderr.text()).toContain('expected exactly 1 row, found 0'); }); test('fails closed on 0x10 close mismatch, dedup duplicate rows, or insufficient post-dedup row counts', async () => { // Corrupted 0x10 binary-double close value on fx_1m probe const badFxProbes = defaultFx1mProbeMap(); badFxProbes.set(`USDCAD|${FX_PROBE_TS_ISO}`, [ { pair: 'USDCAD', ts_us: FX_PROBE_TS_US, close: 1.9999, source: 'eod' }, ]); const badFx = createHarness(baseArgs(), { fx1mProbeRows: badFxProbes }); expect(await runVerifyM2QuantCli(badFx.deps)).toBe(1); expect(badFx.stderr.text()).toContain('0x10 close mismatch for fx_1m'); // Duplicate rows returned for an overlap dedup key const dupOverlapProbes = defaultBars1mProbeMap(); dupOverlapProbes.set(`${OVERLAP_LISTING_ID}|${OVERLAP_PROBE_TS_ISO}`, [ { listing_id: String(OVERLAP_LISTING_ID), ts_us: OVERLAP_PROBE_TS_US, close: 4.25, source: 'qm', known_at_us: KNOWN_AT_US, }, { listing_id: String(OVERLAP_LISTING_ID), ts_us: OVERLAP_PROBE_TS_US, close: 4.25, source: 'eod', known_at_us: KNOWN_AT_US, }, ]); const dupOverlap = createHarness(baseArgs(), { bars1mProbeRows: dupOverlapProbes }); expect(await runVerifyM2QuantCli(dupOverlap.deps)).toBe(1); expect(dupOverlap.stderr.text()).toContain('dedup_overlap'); expect(dupOverlap.stderr.text()).toContain('expected exactly 1 row, found 2'); // Insufficient retained EOD rows after accounting for overlap const underCountedEod = createHarness(baseArgs(), { bars1mSummaryRows: [ { ...defaultBars1mSummaryRows()[0]!, row_count: '499999' }, defaultBars1mSummaryRows()[1]!, ], }); expect(await runVerifyM2QuantCli(underCountedEod.deps)).toBe(1); expect(underCountedEod.stderr.text()).toContain('EOD/QM dedup accounting failed'); }); test('verifies idempotent resend against the same receipt and prior baseline, failing on unchanged WAL or row count drift', async () => { // 1. Run initial verification to produce the baseline report const initial = createHarness(baseArgs()); expect(await runVerifyM2QuantCli(initial.deps)).toBe(0); const initialReportJson = initial.stdout.text(); // 2. Resend with advanced WAL and identical row counts/summaries passes const resendOk = createHarness( baseArgs({ '--resend-baseline': DEFAULT_RESEND_BASELINE_REL_PATH }), { rawFiles: { [DEFAULT_RESEND_BASELINE_ABS_PATH]: initialReportJson }, walSequence: [ [ { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, { name: 'bars_1m', suspended: false, writerTxn: '240', sequencerTxn: '240' }, { name: 'fx_1m', suspended: false, writerTxn: '90', sequencerTxn: '90' }, ], ], } ); expect(await runVerifyM2QuantCli(resendOk.deps)).toBe(0); expect(resendOk.stderr.text()).toBe(''); const resendReport = JSON.parse(resendOk.stdout.text()) as VerifyM2QuantReport; expect(resendReport.resendVerification?.ok).toBe(true); expect(resendReport.resendVerification?.bars1mRowCountsUnchanged).toBe(true); expect(resendReport.resendVerification?.fx1mRowCountsUnchanged).toBe(true); // 3. Resend where WAL did not advance past prior baseline fails const resendStaleWal = createHarness( baseArgs({ '--resend-baseline': DEFAULT_RESEND_BASELINE_REL_PATH }), { rawFiles: { [DEFAULT_RESEND_BASELINE_ABS_PATH]: initialReportJson }, walSequence: [defaultWalRows()], } ); expect(await runVerifyM2QuantCli(resendStaleWal.deps)).toBe(1); expect(resendStaleWal.stderr.text()).toContain('Idempotent resend WAL check'); // 4. Resend where row count increased (non-idempotent duplicate rows) fails const resendRowDrift = createHarness( baseArgs({ '--resend-baseline': DEFAULT_RESEND_BASELINE_REL_PATH }), { rawFiles: { [DEFAULT_RESEND_BASELINE_ABS_PATH]: initialReportJson }, walSequence: [ [ { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, { name: 'bars_1m', suspended: false, writerTxn: '240', sequencerTxn: '240' }, { name: 'fx_1m', suspended: false, writerTxn: '90', sequencerTxn: '90' }, ], ], bars1mSummaryRows: [ { ...defaultBars1mSummaryRows()[0]!, row_count: '500001' }, defaultBars1mSummaryRows()[1]!, ], } ); expect(await runVerifyM2QuantCli(resendRowDrift.deps)).toBe(1); expect(resendRowDrift.stderr.text()).toContain('Idempotent resend failed: bars_1m summary diverged'); }); test('rejects short and Vault-truncated benchmark windows before querying', async () => { // 1-month requested window const shortWindow = createHarness( baseArgs({ '--bench-from': '2024-01-02T00:00:00Z', '--bench-to': '2024-02-02T00:00:00Z', }) ); expect(await runVerifyM2QuantCli(shortWindow.deps)).toBe(1); expect(shortWindow.stdout.text()).toBe(''); assertSingleLineError(shortWindow.stderr.text()); expect(shortWindow.stderr.text()).toContain('shorter than the required 1-year minimum'); expect(shortWindow.state.openedStoreConfigs).toHaveLength(0); expect(shortWindow.state.openedPgConfigs).toHaveLength(0); // 1-year requested window truncated below 1 year by Vault cutoff (2025-02-13T00:00:00Z) const vaultTruncated = createHarness( baseArgs({ '--bench-from': '2024-06-01T00:00:00Z', '--bench-to': '2025-06-01T00:00:00Z', }) ); expect(await runVerifyM2QuantCli(vaultTruncated.deps)).toBe(1); expect(vaultTruncated.stdout.text()).toBe(''); assertSingleLineError(vaultTruncated.stderr.text()); expect(vaultTruncated.stderr.text()).toContain('Vault cutoff'); expect(vaultTruncated.stderr.text()).toContain('truncating the effective benchmark window'); expect(vaultTruncated.state.openedStoreConfigs).toHaveLength(0); expect(vaultTruncated.state.openedPgConfigs).toHaveLength(0); }); test('polls wal_tables() until writerTxn catches up to sequencerTxn', async () => { const { deps, stdout, stderr, state } = createHarness(baseArgs(), { walSequence: [ [ { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, { name: 'bars_1m', suspended: false, writerTxn: '118', sequencerTxn: '120' }, { name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' }, ], defaultWalRows(), ], }); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(0); expect(stderr.text()).toBe(''); expect(state.walPollCount).toBe(2); expect((JSON.parse(stdout.text()) as VerifyM2QuantReport).ok).toBe(true); }); test('fails closed when a required table is missing from wal_tables()', async () => { const { deps, stdout, stderr } = createHarness(baseArgs(), { walSequence: [ [ { name: 'bars_1m', suspended: false, writerTxn: '120', sequencerTxn: '120' }, { name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' }, ], ], }); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(1); expect(stdout.text()).toBe(''); assertSingleLineError(stderr.text()); expect(stderr.text()).toContain('bar_revisions'); }); test('fails closed when any WAL table is suspended', async () => { const { deps, stdout, stderr } = createHarness(baseArgs(), { walSequence: [ [ { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, { name: 'bars_1m', suspended: true, writerTxn: '120', sequencerTxn: '120' }, { name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' }, ], ], }); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(1); expect(stdout.text()).toBe(''); assertSingleLineError(stderr.text()); expect(stderr.text()).toContain('Suspended QuestDB WAL table'); }); test('fails closed when WAL remains unsettled past --wal-settle-timeout-ms', async () => { const { deps, stdout, stderr } = createHarness( baseArgs({ '--wal-settle-timeout-ms': '2000' }), { walSequence: [ [ { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, { name: 'bars_1m', suspended: false, writerTxn: '110', sequencerTxn: '120' }, { name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' }, ], ], } ); const code = await runVerifyM2QuantCli(deps); expect(code).toBe(1); expect(stdout.text()).toBe(''); assertSingleLineError(stderr.text()); expect(stderr.text()).toContain('Timed out'); expect(stderr.text()).toContain('writerTxn=110 { const zeroBars = createHarness(baseArgs(), { bars1mSummaryRows: [] }); expect(await runVerifyM2QuantCli(zeroBars.deps)).toBe(1); expect(zeroBars.stdout.text()).toBe(''); expect(zeroBars.stderr.text()).toContain('bars_1m contains zero rows'); const zeroFx = createHarness(baseArgs(), { fx1mSummaryRows: [] }); expect(await runVerifyM2QuantCli(zeroFx.deps)).toBe(1); expect(zeroFx.stdout.text()).toBe(''); expect(zeroFx.stderr.text()).toContain('fx_1m contains zero rows'); const nanClose = createHarness(baseArgs(), { bars1mSummaryRows: [ { source: 'eod', row_count: '500000', min_close: Number.NaN, max_close: 120.5, min_ts_us: isoToMicros('2024-01-02T14:30:00Z'), max_ts_us: isoToMicros('2024-06-10T20:00:00Z'), }, ], }); expect(await runVerifyM2QuantCli(nanClose.deps)).toBe(1); expect(nanClose.stdout.text()).toBe(''); expect(nanClose.stderr.text()).toContain('Invalid finite numeric value'); const nonPositiveFxClose = createHarness(baseArgs(), { fx1mSummaryRows: [ { pair: 'USDCAD', source: 'eod', row_count: '100', min_close: 0, max_close: 1.4, min_ts_us: isoToMicros('2024-01-02T00:00:00Z'), max_ts_us: isoToMicros('2025-01-31T23:59:00Z'), }, ], }); expect(await runVerifyM2QuantCli(nonPositiveFxClose.deps)).toBe(1); expect(nonPositiveFxClose.stderr.text()).toContain('invalid close bounds'); }); test('enforces split-boundary 0.5% tolerance and pre/post-split session presence', async () => { // Exactly at 0.5% passes const atLimit = createHarness(baseArgs(), { nvda1mRows: [ { ts_us: isoToMicros('2024-06-07T19:59:00Z'), close: 1005.0 }, { ts_us: isoToMicros('2024-06-10T19:59:00Z'), close: 100.5 }, ], nvda1dRows: [ { session_date: '2024-06-07', close: 1000.0 }, { session_date: '2024-06-10', close: 100.0 }, ], }); expect(await runVerifyM2QuantCli(atLimit.deps)).toBe(0); // Above 0.5% fails const overLimit = createHarness(baseArgs(), { nvda1mRows: [ { ts_us: isoToMicros('2024-06-07T19:59:00Z'), close: 1005.1 }, { ts_us: isoToMicros('2024-06-10T19:59:00Z'), close: 100.0 }, ], nvda1dRows: [ { session_date: '2024-06-07', close: 1000.0 }, { session_date: '2024-06-10', close: 100.0 }, ], }); expect(await runVerifyM2QuantCli(overLimit.deps)).toBe(1); expect(overLimit.stderr.text()).toContain('NVDA.US split-boundary close mismatch'); // Missing pre-split session fails const missingPreSplit = createHarness(baseArgs(), { nexm1mRows: [{ ts_us: isoToMicros('2025-06-20T19:59:00Z'), close: 8.0 }], nexm1dRows: [{ session_date: '2025-06-20', close: 8.0 }], }); expect(await runVerifyM2QuantCli(missingPreSplit.deps)).toBe(1); expect(missingPreSplit.stderr.text()).toContain('>= 1 matched pre-split session'); // Missing ex-date/post-split session fails const missingPostSplit = createHarness(baseArgs(), { nexm1mRows: [{ ts_us: isoToMicros('2025-06-19T19:59:00Z'), close: 0.4 }], nexm1dRows: [{ session_date: '2025-06-19', close: 0.4 }], }); expect(await runVerifyM2QuantCli(missingPostSplit.deps)).toBe(1); expect(missingPostSplit.stderr.text()).toContain('>= 1 matched ex-date/post-split session'); }); test('enforces cold (< 1000 ms), warm (< 250 ms), non-empty, and digest equality benchmark checks', async () => { const slowCold = createHarness(baseArgs(), { perfDurationsMs: [1000, 40, 40, 40], }); expect(await runVerifyM2QuantCli(slowCold.deps)).toBe(1); expect(slowCold.stderr.text()).toContain('Cold 1y 1m PGWire read exceeded threshold'); const slowWarm = createHarness(baseArgs(), { perfDurationsMs: [200, 50, 250, 50], }); expect(await runVerifyM2QuantCli(slowWarm.deps)).toBe(1); expect(slowWarm.stderr.text()).toContain('Warm 1y 1m PGWire read #2 exceeded threshold'); const emptyBench = createHarness(baseArgs(), { benchBatchesByCall: [[]], }); expect(await runVerifyM2QuantCli(emptyBench.deps)).toBe(1); expect(emptyBench.stderr.text()).toContain('returned 0 rows'); const coldRows = defaultBenchBars(); const mutatedRows: BarRecord[] = [ coldRows[0]!, { ...coldRows[1]!, close: coldRows[1]!.close + 0.01 }, ]; const digestMismatch = createHarness(baseArgs(), { benchBatchesByCall: [coldRows, mutatedRows], }); expect(await runVerifyM2QuantCli(digestMismatch.deps)).toBe(1); expect(digestMismatch.stderr.text()).toContain('diverged from cold baseline'); }); test('blocks post-Vault benchmark queries, vault_evaluation_only scope, and leaked bar timestamps', async () => { const postVaultFrom = createHarness( baseArgs({ '--bench-from': VAULT_CUTOFF_ISO, '--bench-to': '2026-06-01T00:00:00Z' }) ); expect(await runVerifyM2QuantCli(postVaultFrom.deps)).toBe(1); expect(postVaultFrom.stderr.text()).toContain('Vault cutoff'); expect(postVaultFrom.state.openedStoreConfigs).toHaveLength(0); const unauthorizedScope = createHarness( baseArgs({ '--bench-scope': 'vault_evaluation_only' }) ); expect(await runVerifyM2QuantCli(unauthorizedScope.deps)).toBe(1); expect(unauthorizedScope.stderr.text()).toContain('operator authorization'); expect(unauthorizedScope.state.openedStoreConfigs).toHaveLength(0); const leakedBarTs = createHarness(baseArgs(), { benchBatchesByCall: [ [ { ...defaultBenchBars()[0]!, ts: VAULT_CUTOFF_MS, }, ], ], }); expect(await runVerifyM2QuantCli(leakedBarTs.deps)).toBe(1); expect(leakedBarTs.stderr.text()).toContain('post-Vault bar'); const futureKnownAt = createHarness(baseArgs(), { benchBatchesByCall: [ [ { ...defaultBenchBars()[0]!, knownAt: Date.parse('2025-02-02T00:00:00Z'), }, ], ], }); expect(await runVerifyM2QuantCli(futureKnownAt.deps)).toBe(1); expect(futureKnownAt.stderr.text()).toContain('future-known bar'); }); test('redacts QuestDB URL DSNs and passwords on stderr', async () => { const secretUrl = 'postgresql://qdb_user:s3cr3t%21Pass@10.0.0.51:8812/qdb?password=altSecret'; const urlHarness = createHarness( baseArgs({ '--questdb-host': null, '--questdb-pg-port': null, '--questdb-url': secretUrl, }), { openPgError: new Error( `Connection failed for ${secretUrl} (decoded s3cr3t!Pass / altSecret)\nstack line` ), } ); const urlCode = await runVerifyM2QuantCli(urlHarness.deps); expect(urlCode).toBe(1); expect(urlHarness.stdout.text()).toBe(''); assertSingleLineError(urlHarness.stderr.text()); expect(urlHarness.stderr.text()).not.toContain('s3cr3t!Pass'); expect(urlHarness.stderr.text()).not.toContain('s3cr3t%21Pass'); expect(urlHarness.stderr.text()).not.toContain('altSecret'); expect(urlHarness.stderr.text()).not.toContain('qdb_user:'); expect(urlHarness.stderr.text()).toContain('[REDACTED]'); const passHarness = createHarness( baseArgs({ '--questdb-password': 'MySuperSecretPassword!' }), { queryError: new Error('Auth error for MySuperSecretPassword! on 10.0.0.51'), } ); const passCode = await runVerifyM2QuantCli(passHarness.deps); expect(passCode).toBe(1); assertSingleLineError(passHarness.stderr.text()); expect(passHarness.stderr.text()).not.toContain('MySuperSecretPassword!'); expect(passHarness.stderr.text()).toContain('[REDACTED]'); }); test('rejects invalid CLI arguments fail-closed', async () => { const missingHost = createHarness( baseArgs({ '--questdb-host': null, '--questdb-pg-port': null }) ); expect(await runVerifyM2QuantCli(missingHost.deps)).toBe(1); assertSingleLineError(missingHost.stderr.text()); expect(missingHost.stderr.text()).toContain('Missing required QuestDB connection flags'); const missingReceipt = createHarness(baseArgs({ '--load-receipt': null })); expect(await runVerifyM2QuantCli(missingReceipt.deps)).toBe(1); assertSingleLineError(missingReceipt.stderr.text()); expect(missingReceipt.stderr.text()).toContain('Missing required flag --load-receipt'); const conflictingConn = createHarness( baseArgs({ '--questdb-url': 'postgres://user:s3cr3tP4ss@10.0.0.51:8812/qdb' }) ); expect(await runVerifyM2QuantCli(conflictingConn.deps)).toBe(1); assertSingleLineError(conflictingConn.stderr.text()); expect(conflictingConn.stderr.text()).not.toContain('s3cr3tP4ss'); const nonUtcCutoff = createHarness( baseArgs({ '--vault-cutoff-ts': '2025-02-13T00:00:00+02:00' }) ); expect(await runVerifyM2QuantCli(nonUtcCutoff.deps)).toBe(1); assertSingleLineError(nonUtcCutoff.stderr.text()); expect(nonUtcCutoff.stderr.text()).toContain('UTC timestamp ending in'); }); });