diff --git a/scripts/test/verify-m2-quant.test.ts b/scripts/test/verify-m2-quant.test.ts index b728bbe9..1aaf8114 100644 --- a/scripts/test/verify-m2-quant.test.ts +++ b/scripts/test/verify-m2-quant.test.ts @@ -12,15 +12,34 @@ import type { ManagedMarketDataStore, ResearchCopilotHostConfig } from '@stock-b 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; @@ -38,6 +57,10 @@ function createBufferStream(): { }; } +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', @@ -50,6 +73,7 @@ function baseArgs(overrides: Record = {}): string[] { '--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', }; @@ -64,20 +88,136 @@ function baseArgs(overrides: Record = {}): string[] { return argv; } -function isoToMicros(iso: string): string { - return (BigInt(Date.parse(iso)) * 1000n).toString(); +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; } @@ -148,7 +288,7 @@ function defaultNvda1dRows(): readonly TableRow[] { 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.40 }, + { 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 }, ]; @@ -156,8 +296,8 @@ function defaultNexm1mRows(): readonly Record[] { function defaultNexm1dRows(): readonly TableRow[] { return [ - { session_date: '2025-06-19', close: 0.40 }, - { session_date: '2025-06-20', close: 8.00 }, + { session_date: '2025-06-19', close: 0.4 }, + { session_date: '2025-06-20', close: 8.0 }, ]; } @@ -205,6 +345,7 @@ function createHarness( openedPgConfigs: QuestDbPgExecutorConfig[]; openedStoreConfigs: ResearchCopilotHostConfig[]; walPollCount: number; + events: string[]; }; } { const stdout = createBufferStream(); @@ -218,16 +359,28 @@ function createHarness( 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]; @@ -253,18 +406,32 @@ function createHarness( 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 }; } @@ -284,6 +451,7 @@ function createHarness( 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; } @@ -301,6 +469,7 @@ function createHarness( const mockStore: MarketDataStore = { async *bars(): AsyncIterable { + state.events.push(benchCallIdx === 0 ? 'bench:cold' : `bench:warm#${benchCallIdx}`); const batches = options.benchBatchesByCall; const rows = batches !== undefined @@ -353,6 +522,7 @@ function createHarness( }, 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 ...'], @@ -372,6 +542,13 @@ function createHarness( }, }; }, + 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); }, @@ -398,10 +575,97 @@ describe('scripts/verify-m2-quant.ts', () => { 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('passes end-to-end without --apply-ddl, writes --out, and closes all handles', async () => { + 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); @@ -415,10 +679,17 @@ describe('scripts/verify-m2-quant.ts', () => { 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); @@ -427,17 +698,24 @@ describe('scripts/verify-m2-quant.ts', () => { 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', async () => { + 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); @@ -445,6 +723,8 @@ describe('scripts/verify-m2-quant.ts', () => { 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({ @@ -453,6 +733,181 @@ describe('scripts/verify-m2-quant.ts', () => { }); }); + 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: [ @@ -476,8 +931,8 @@ describe('scripts/verify-m2-quant.ts', () => { const { deps, stdout, stderr } = createHarness(baseArgs(), { walSequence: [ [ - { name: 'bars_1m', suspended: false, writerTxn: '10', sequencerTxn: '10' }, - { name: 'fx_1m', suspended: false, writerTxn: '10', sequencerTxn: '10' }, + { name: 'bars_1m', suspended: false, writerTxn: '120', sequencerTxn: '120' }, + { name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' }, ], ], }); @@ -494,8 +949,8 @@ describe('scripts/verify-m2-quant.ts', () => { walSequence: [ [ { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, - { name: 'bars_1m', suspended: true, writerTxn: '10', sequencerTxn: '10' }, - { name: 'fx_1m', suspended: false, writerTxn: '10', sequencerTxn: '10' }, + { name: 'bars_1m', suspended: true, writerTxn: '120', sequencerTxn: '120' }, + { name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' }, ], ], }); @@ -514,8 +969,8 @@ describe('scripts/verify-m2-quant.ts', () => { walSequence: [ [ { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, - { name: 'bars_1m', suspended: false, writerTxn: '10', sequencerTxn: '20' }, - { name: 'fx_1m', suspended: false, writerTxn: '5', sequencerTxn: '5' }, + { name: 'bars_1m', suspended: false, writerTxn: '110', sequencerTxn: '120' }, + { name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' }, ], ], } @@ -526,7 +981,7 @@ describe('scripts/verify-m2-quant.ts', () => { expect(stdout.text()).toBe(''); assertSingleLineError(stderr.text()); expect(stderr.text()).toContain('Timed out'); - expect(stderr.text()).toContain('writerTxn=10 { @@ -544,7 +999,7 @@ describe('scripts/verify-m2-quant.ts', () => { bars1mSummaryRows: [ { source: 'eod', - row_count: '100', + row_count: '500000', min_close: Number.NaN, max_close: 120.5, min_ts_us: isoToMicros('2024-01-02T14:30:00Z'), @@ -651,7 +1106,7 @@ describe('scripts/verify-m2-quant.ts', () => { 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': '2025-06-01T00:00:00Z' }) + 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'); @@ -737,6 +1192,11 @@ describe('scripts/verify-m2-quant.ts', () => { 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' }) ); diff --git a/scripts/verify-m2-quant.ts b/scripts/verify-m2-quant.ts index 76587e2c..0d017c47 100644 --- a/scripts/verify-m2-quant.ts +++ b/scripts/verify-m2-quant.ts @@ -1,27 +1,34 @@ /** * Deterministic QuestDB 10.2.0 / DuckDB M2 verification CLI for `quant` (`10.0.0.51`). * - * Verifies Milestone M2 Exit Criterion 3 fail-closed: - * 1. Optional opt-in `applyM2IntradayDDL` (`--apply-ddl`). - * 2. `wal_tables()` health (`bars_1m`, `fx_1m`, `bar_revisions` present, - * `suspended = false`, `writerTxn >= sequencerTxn`) and non-zero finite - * `0x10` binary-double commits on `bars_1m` and `fx_1m`. - * 3. Observed split-boundary close agreement (`<= 0.5%`) between QuestDB - * `bars_1m` (`session = 'RTH'`, latest `ts` per `America/New_York` session - * date) and retained raw `bars_1d/year=/part.parquet` across `NVDA.US` - * (`2024-06-06..2024-06-12`, ex-date `2024-06-10`, `10:1`) and `NEXM.V` - * (`2025-06-17..2025-06-23`, ex-date `2025-06-20`, `1:20`). - * 4. 1-year single-listing `1m` PGWire latency benchmark (`< 1000 ms` cold, - * `< 250 ms` warm across `--warm-runs`, `rowCount > 0`, identical bar - * digests across runs, Vault-fenced with `vaultOperatorAuthorized: false`). + * Modes: + * - `--ddl-only`: Opt-in setup mode for fresh/empty QuestDB instances. Executes + * `applyM2IntradayDDL`, verifies `wal_tables()` health (`bars_1m`, `fx_1m`, + * `bar_revisions` present, `suspended = false`, `writerTxn >= sequencerTxn`), + * and exits 0 without querying table contents. + * - Full verification mode (default): Verifies Milestone M2 Exit Criterion 3 fail-closed: + * 1. Validates the Vault-fenced 1-year benchmark window (`>= 365` days after Vault + * clamping with `vaultOperatorAuthorized: false`) and measures the 1-year + * single-listing `1m` PGWire cold read (`< 1000 ms`) and warm reads (`< 250 ms`) + * BEFORE any verifier query scans `bars_1m`. + * 2. Verifies `wal_tables()` health, before-and-after WAL advancement against + * `--load-receipt`, non-zero finite `0x10` binary-double commits across all three + * shard prefixes (`bars_1m`, `bars_1m_qm`, `fx_1m`), exact expected key/close + * probes, EOD/QM deduplication accounting, and optional idempotent resend + * verification (`--resend-baseline`). + * 3. Verifies observed split-boundary close agreement (`<= 0.5%`) between QuestDB + * `bars_1m` (`session = 'RTH'`, latest `ts` per `America/New_York` session + * date) and retained raw `bars_1d/year=/part.parquet` across `NVDA.US` + * (`2024-06-06..2024-06-12`, ex-date `2024-06-10`, `10:1`) and `NEXM.V` + * (`2025-06-17..2025-06-23`, ex-date `2025-06-20`, `1:20`). * - * Fail-closed: any validation, WAL, split-boundary, Vault-fence, or latency - * failure writes a single redacted error line to stderr with zero stdout bytes - * and exits with code 1. + * Fail-closed: any validation, WAL, load-receipt, resend, split-boundary, Vault-fence, + * or latency failure writes a single redacted error line to stderr with zero stdout + * bytes and exits with code 1. */ import { createHash } from 'node:crypto'; -import { mkdir, writeFile } from 'node:fs/promises'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { dirname, resolve } from 'node:path'; import type { ClosableDuckDbExecutor, @@ -40,6 +47,7 @@ import { import { type BarRecord, type DataScope, + type FencedTimeRange, applyVaultFence, collectBars, } from '@stock-bot/research'; @@ -47,6 +55,7 @@ import type { ManagedMarketDataStore, ResearchCopilotHostConfig } from '@stock-b const INT32_MAX = 2_147_483_647; const STRICT_POSITIVE_INT_RE = /^[1-9]\d*$/; +const STRICT_NON_NEGATIVE_INT_RE = /^(?:0|[1-9]\d*)$/; const STRICT_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/; const STRICT_UTC_INSTANT_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/; @@ -60,6 +69,10 @@ export const DEFAULT_WAL_POLL_INTERVAL_MS = 250; export const MAX_SPLIT_CLOSE_REL_DIFF = 0.005; export const MAX_COLD_READ_MS = 1_000; export const MAX_WARM_READ_MS = 250; +export const MIN_ONE_YEAR_WINDOW_MS = 365 * 24 * 60 * 60 * 1000; +export const DEFAULT_PROBE_CLOSE_TOLERANCE = 1e-9; +export const REQUIRED_SHARD_PREFIXES = ['bars_1m', 'bars_1m_qm', 'fx_1m'] as const; +export type RequiredShardPrefix = (typeof REQUIRED_SHARD_PREFIXES)[number]; export interface SplitBoundaryCaseSpec { readonly label: 'NVDA.US' | 'NEXM.V'; @@ -114,17 +127,29 @@ export interface ParsedVerifyM2QuantRun { readonly benchTo: string; readonly benchAsOf: string; readonly benchScope: DataScope; + readonly loadReceiptPath: string; + readonly resendBaselinePath?: string; readonly applyDdl: boolean; readonly warmRuns: number; readonly walSettleTimeoutMs: number; readonly outPath?: string; } +export interface ParsedVerifyM2QuantDdlOnly { + readonly kind: 'ddl_only'; + readonly questdb: QuestDbPgExecutorConfig; + readonly walSettleTimeoutMs: number; + readonly outPath?: string; +} + export interface ParsedVerifyM2QuantHelp { readonly kind: 'help'; } -export type ParsedVerifyM2QuantArgs = ParsedVerifyM2QuantRun | ParsedVerifyM2QuantHelp; +export type ParsedVerifyM2QuantArgs = + | ParsedVerifyM2QuantRun + | ParsedVerifyM2QuantDdlOnly + | ParsedVerifyM2QuantHelp; export interface VerifyM2QuantCliDeps { readonly argv?: readonly string[]; @@ -142,6 +167,7 @@ export interface VerifyM2QuantCliDeps { config: ResearchCopilotHostConfig, options?: OpenResearchCopilotStoreOptions ) => Promise; + readonly readTextFile?: (path: string) => Promise; readonly writeReportFile?: (path: string, content: string) => Promise; readonly nowMs?: () => number; readonly perfNowMs?: () => number; @@ -149,6 +175,100 @@ export interface VerifyM2QuantCliDeps { readonly walPollIntervalMs?: number; } +export interface WalTxnPair { + readonly writerTxn: string; + readonly sequencerTxn: string; +} + +export interface LoadReceiptWalSnapshot { + readonly bars_1m: WalTxnPair; + readonly fx_1m: WalTxnPair; + readonly bar_revisions?: WalTxnPair; +} + +export interface Bars1mProbeExpectation { + readonly listingId: number; + readonly tsUs: string; + readonly expectedClose: number; + readonly expectedSource: 'eod' | 'qm'; + readonly expectedKnownAtUs?: string; + readonly closeTolerance?: number; +} + +export interface Fx1mProbeExpectation { + readonly pair: string; + readonly tsUs: string; + readonly expectedClose: number; + readonly expectedSource: string; + readonly closeTolerance?: number; +} + +export interface LoadReceiptDedupExpectation { + readonly eodSentRows: number; + readonly qmSentRows: number; + readonly overlapRows: number; + readonly overlapWinnerSource: 'eod' | 'qm'; + readonly overlapProbes?: readonly Bars1mProbeExpectation[]; +} + +export interface M2LoadReceipt { + readonly beforeWal: LoadReceiptWalSnapshot; + readonly shards: { + readonly bars_1m: { + readonly probes: readonly Bars1mProbeExpectation[]; + }; + readonly bars_1m_qm: { + readonly probes: readonly Bars1mProbeExpectation[]; + }; + readonly fx_1m: { + readonly probes: readonly Fx1mProbeExpectation[]; + }; + }; + readonly dedup: LoadReceiptDedupExpectation; +} + +export interface WalAdvancementEntry { + readonly table: 'bars_1m' | 'fx_1m'; + readonly beforeWriterTxn: string; + readonly afterWriterTxn: string; + readonly beforeSequencerTxn: string; + readonly afterSequencerTxn: string; +} + +export interface ProbeCheckResult { + readonly shardPrefix: RequiredShardPrefix | 'dedup_overlap'; + readonly key: string; + readonly expectedSource: string; + readonly actualSource: string; + readonly expectedClose: number; + readonly actualClose: number; + readonly absDiff: number; +} + +export interface LoadReceiptVerificationResult { + readonly walAdvancement: readonly WalAdvancementEntry[]; + readonly dedupAccounting: { + readonly eodSentRows: number; + readonly qmSentRows: number; + readonly overlapRows: number; + readonly overlapWinnerSource: 'eod' | 'qm'; + readonly minExpectedEodRows: number; + readonly minExpectedQmRows: number; + readonly minExpectedTotalBars1mRows: number; + readonly observedEodRows: number; + readonly observedQmRows: number; + readonly observedTotalBars1mRows: number; + }; + readonly probesVerified: readonly ProbeCheckResult[]; +} + +export interface ResendVerificationResult { + readonly ok: true; + readonly walAdvancement: readonly WalAdvancementEntry[]; + readonly bars1mRowCountsUnchanged: true; + readonly fx1mRowCountsUnchanged: true; +} + export interface WalTableStatusRow { readonly name: M2IntradayTableName; readonly suspended: boolean; @@ -201,6 +321,12 @@ export interface IntradayBenchmarkResult { readonly from: string; readonly to: string; readonly asOf: string; + readonly effectiveFrom: string; + readonly effectiveTo: string; + readonly effectiveAsOf: string; + readonly effectiveSpanMs: number; + readonly clampedTo: boolean; + readonly clampedAsOf: boolean; readonly scope: DataScope; readonly rowCount: number; readonly digest: string; @@ -212,11 +338,26 @@ export interface IntradayBenchmarkResult { readonly thresholds: { readonly maxColdMs: number; readonly maxWarmMs: number; + readonly minWindowMs: number; }; } +export interface VerifyM2QuantDdlOnlyReport { + readonly ok: true; + readonly mode: 'ddl_only'; + readonly target: { + readonly questdb: string; + }; + readonly ddl: { + readonly applied: true; + readonly appliedTables: readonly M2IntradayTableName[]; + }; + readonly walTables: readonly WalTableStatusRow[]; +} + export interface VerifyM2QuantReport { readonly ok: true; + readonly mode: 'verify'; readonly target: { readonly questdb: string; readonly curatedRoot: string; @@ -229,6 +370,8 @@ export interface VerifyM2QuantReport { readonly walTables: readonly WalTableStatusRow[]; readonly bars1mSummary: readonly Bars1mSourceSummaryRow[]; readonly fx1mSummary: readonly Fx1mPairSourceSummaryRow[]; + readonly loadVerification: LoadReceiptVerificationResult; + readonly resendVerification?: ResendVerificationResult; readonly splitChecks: readonly SplitBoundaryCheckResult[]; readonly benchmark: IntradayBenchmarkResult; } @@ -244,18 +387,25 @@ export class VerifyM2QuantError extends Error { export const VERIFY_M2_QUANT_USAGE = [ 'Usage: bun run scripts/verify-m2-quant.ts [options]', '', - 'Required options:', + 'Modes:', + ' --ddl-only Apply M2 intraday DDL on a fresh/empty QuestDB instance,', + ' verify wal_tables() health, and exit 0 (requires only QuestDB', + ' connection flags, optional --wal-settle-timeout-ms and --out)', + '', + 'Required options (full verification mode):', ' --questdb-url QuestDB PGWire URL (mutually exclusive with --questdb-host/--questdb-pg-port)', ' --questdb-host QuestDB PGWire host (requires --questdb-pg-port)', ' --questdb-pg-port QuestDB PGWire port (requires --questdb-host)', - ' --curated-root Curated Parquet root containing bars_1d/year=*/part.parquet', + ' --curated-root Curated Parquet root containing bars_1d/year=/part.parquet', ' --vault-cutoff-ts Authoritative Vault cutoff ISO-8601 UTC timestamp ending in Z', ' --nvda-listing-id Permanent listing_id for NVDA.US', ' --nexm-listing-id Permanent listing_id for NEXM.V', ' --bench-listing-id Permanent listing_id for 1y 1m PGWire latency benchmark', ' --bench-from Benchmark window start (must be < --vault-cutoff-ts)', - ' --bench-to Benchmark window end', + ' --bench-to Benchmark window end (effective fenced span must be >= 365 days)', ' --bench-as-of Benchmark point-in-time as-of bound', + ' --load-receipt JSON load receipt with beforeWal, per-prefix (bars_1m, bars_1m_qm,', + ' fx_1m) expected keys/closes, and EOD/QM dedup expectations', '', 'Optional options:', ' --questdb-database QuestDB PGWire database name (host/port mode)', @@ -263,7 +413,8 @@ export const VERIFY_M2_QUANT_USAGE = [ ' --questdb-password QuestDB PGWire password (host/port mode)', ' --questdb-ssl Explicit TLS flag', ' --bench-scope DataScope for benchmark (default: vault_fenced)', - ' --apply-ddl Execute applyM2IntradayDDL before checks', + ' --resend-baseline Prior VerifyM2QuantReport JSON to verify idempotent resend against', + ' --apply-ddl Execute applyM2IntradayDDL before checks (full mode)', ` --warm-runs Number of warm 1y 1m benchmark reads (default: ${DEFAULT_WARM_RUNS})`, ` --wal-settle-timeout-ms WAL settle polling timeout in ms (default: ${DEFAULT_WAL_SETTLE_TIMEOUT_MS})`, ' --out Optional JSON output file path', @@ -288,12 +439,14 @@ const VALUE_FLAGS = new Set([ '--bench-to', '--bench-as-of', '--bench-scope', + '--load-receipt', + '--resend-baseline', '--warm-runs', '--wal-settle-timeout-ms', '--out', ]); -const BOOLEAN_FLAGS = new Set(['--apply-ddl']); +const BOOLEAN_FLAGS = new Set(['--apply-ddl', '--ddl-only']); const SECRET_FLAGS = new Set(['--questdb-url', '--questdb-password']); function sanitizeSingleLine(message: string): string { @@ -558,6 +711,24 @@ export function parseVerifyM2QuantArgs( }; } + const rawWalTimeout = seenValues.get('--wal-settle-timeout-ms'); + const walSettleTimeoutMs = + rawWalTimeout !== undefined + ? parsePositiveIntFlag('--wal-settle-timeout-ms', rawWalTimeout) + : DEFAULT_WAL_SETTLE_TIMEOUT_MS; + + const rawOut = seenValues.get('--out'); + const outPath = rawOut !== undefined ? resolve(baseCwd, rawOut) : undefined; + + if (seenBooleans.has('--ddl-only')) { + return { + kind: 'ddl_only', + questdb, + walSettleTimeoutMs, + ...(outPath !== undefined ? { outPath } : {}), + }; + } + const requireFlag = (flag: string): string => { const val = seenValues.get(flag); if (val === undefined) { @@ -592,6 +763,10 @@ export function parseVerifyM2QuantArgs( const benchFrom = requireFlag('--bench-from'); const benchTo = requireFlag('--bench-to'); const benchAsOf = requireFlag('--bench-as-of'); + const loadReceiptPath = resolve(baseCwd, requireFlag('--load-receipt')); + const rawResendBaseline = seenValues.get('--resend-baseline'); + const resendBaselinePath = + rawResendBaseline !== undefined ? resolve(baseCwd, rawResendBaseline) : undefined; const rawBenchScope = seenValues.get('--bench-scope'); let benchScope: DataScope = 'vault_fenced'; @@ -608,15 +783,6 @@ export function parseVerifyM2QuantArgs( const warmRuns = rawWarmRuns !== undefined ? parsePositiveIntFlag('--warm-runs', rawWarmRuns) : DEFAULT_WARM_RUNS; - const rawWalTimeout = seenValues.get('--wal-settle-timeout-ms'); - const walSettleTimeoutMs = - rawWalTimeout !== undefined - ? parsePositiveIntFlag('--wal-settle-timeout-ms', rawWalTimeout) - : DEFAULT_WAL_SETTLE_TIMEOUT_MS; - - const rawOut = seenValues.get('--out'); - const outPath = rawOut !== undefined ? resolve(baseCwd, rawOut) : undefined; - return { kind: 'run', questdb, @@ -630,6 +796,8 @@ export function parseVerifyM2QuantArgs( benchTo, benchAsOf, benchScope, + loadReceiptPath, + ...(resendBaselinePath !== undefined ? { resendBaselinePath } : {}), applyDdl: seenBooleans.has('--apply-ddl'), warmRuns, walSettleTimeoutMs, @@ -1041,16 +1209,603 @@ async function verifySplitBoundaryCase( }; } -async function runIntradayLatencyBenchmark( - parsed: ParsedVerifyM2QuantRun, - openStore: ( - config: ResearchCopilotHostConfig, - options?: OpenResearchCopilotStoreOptions - ) => Promise, - perfNowMs: () => number -): Promise { +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function parseNonNegativeBigIntString(value: unknown, field: string): bigint { + if (typeof value === 'string' && STRICT_NON_NEGATIVE_INT_RE.test(value.trim())) { + return BigInt(value.trim()); + } + if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) { + return BigInt(value); + } + throw new VerifyM2QuantError(`Invalid non-negative integer for '${field}': ${String(value)}.`); +} + +function parsePositiveSafeInt(value: unknown, field: string, maxValue?: number): number { + if ( + typeof value === 'number' && + Number.isSafeInteger(value) && + value > 0 && + (maxValue === undefined || value <= maxValue) + ) { + return value; + } + throw new VerifyM2QuantError(`Invalid positive integer for '${field}': ${String(value)}.`); +} + +function parseNonNegativeSafeInt(value: unknown, field: string): number { + if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) { + return value; + } + throw new VerifyM2QuantError(`Invalid non-negative integer for '${field}': ${String(value)}.`); +} + +function formatUtcIsoMicros(tsUs: bigint): string { + const floorMs = tsUs >= 0n ? tsUs / 1000n : (tsUs - 999n) / 1000n; + const subMsMicros = Number(tsUs - floorMs * 1000n); + const epochMs = Number(floorMs); + if (!Number.isSafeInteger(epochMs)) { + throw new VerifyM2QuantError(`Out-of-range QuestDB timestamp micros: ${tsUs.toString()}.`); + } + const isoMs = new Date(epochMs).toISOString(); + return `${isoMs.slice(0, -1)}${String(subMsMicros).padStart(3, '0')}Z`; +} + +function parseWalTxnPair(value: unknown, field: string): WalTxnPair { + if (!isPlainObject(value)) { + throw new VerifyM2QuantError(`Expected object for '${field}'.`); + } + const writerTxn = parseNonNegativeBigIntString(value.writerTxn, `${field}.writerTxn`); + const sequencerTxn = parseNonNegativeBigIntString(value.sequencerTxn, `${field}.sequencerTxn`); + return { + writerTxn: writerTxn.toString(), + sequencerTxn: sequencerTxn.toString(), + }; +} + +function parseBars1mProbe( + value: unknown, + field: string, + requiredSource: 'eod' | 'qm' +): Bars1mProbeExpectation { + if (!isPlainObject(value)) { + throw new VerifyM2QuantError(`Expected probe object for '${field}'.`); + } + const listingId = parsePositiveSafeInt(value.listingId, `${field}.listingId`, INT32_MAX); + const tsUs = parseBigIntCell(value.tsUs, `${field}.tsUs`); + const expectedClose = parseFiniteNumberCell(value.expectedClose, `${field}.expectedClose`); + if (expectedClose <= 0) { + throw new VerifyM2QuantError(`${field}.expectedClose must be positive.`); + } + const expectedSource = parseRequiredStringCell(value.expectedSource, `${field}.expectedSource`); + if (expectedSource !== requiredSource) { + throw new VerifyM2QuantError( + `${field}.expectedSource must be '${requiredSource}' (received '${expectedSource}').` + ); + } + let expectedKnownAtUs: string | undefined; + if (value.expectedKnownAtUs !== undefined) { + expectedKnownAtUs = parseBigIntCell( + value.expectedKnownAtUs, + `${field}.expectedKnownAtUs` + ).toString(); + } + let closeTolerance: number | undefined; + if (value.closeTolerance !== undefined) { + closeTolerance = parseFiniteNumberCell(value.closeTolerance, `${field}.closeTolerance`); + if (closeTolerance < 0) { + throw new VerifyM2QuantError(`${field}.closeTolerance must be >= 0.`); + } + } + return { + listingId, + tsUs: tsUs.toString(), + expectedClose, + expectedSource, + ...(expectedKnownAtUs !== undefined ? { expectedKnownAtUs } : {}), + ...(closeTolerance !== undefined ? { closeTolerance } : {}), + }; +} + +function parseFx1mProbe(value: unknown, field: string): Fx1mProbeExpectation { + if (!isPlainObject(value)) { + throw new VerifyM2QuantError(`Expected probe object for '${field}'.`); + } + const pair = parseRequiredStringCell(value.pair, `${field}.pair`); + const tsUs = parseBigIntCell(value.tsUs, `${field}.tsUs`); + const expectedClose = parseFiniteNumberCell(value.expectedClose, `${field}.expectedClose`); + if (expectedClose <= 0) { + throw new VerifyM2QuantError(`${field}.expectedClose must be positive.`); + } + const expectedSource = parseRequiredStringCell(value.expectedSource, `${field}.expectedSource`); + let closeTolerance: number | undefined; + if (value.closeTolerance !== undefined) { + closeTolerance = parseFiniteNumberCell(value.closeTolerance, `${field}.closeTolerance`); + if (closeTolerance < 0) { + throw new VerifyM2QuantError(`${field}.closeTolerance must be >= 0.`); + } + } + return { + pair, + tsUs: tsUs.toString(), + expectedClose, + expectedSource, + ...(closeTolerance !== undefined ? { closeTolerance } : {}), + }; +} + +export function parseLoadReceiptJson(rawJson: string): M2LoadReceipt { + let parsed: unknown; + try { + parsed = JSON.parse(rawJson); + } catch (err: unknown) { + const detail = err instanceof Error ? err.message : String(err); + throw new VerifyM2QuantError(`Failed to parse --load-receipt JSON: ${detail}`); + } + if (!isPlainObject(parsed)) { + throw new VerifyM2QuantError('Load receipt JSON must be a top-level object.'); + } + + if (!isPlainObject(parsed.beforeWal)) { + throw new VerifyM2QuantError('Load receipt missing required object "beforeWal".'); + } + const beforeWal: LoadReceiptWalSnapshot = { + bars_1m: parseWalTxnPair(parsed.beforeWal.bars_1m, 'beforeWal.bars_1m'), + fx_1m: parseWalTxnPair(parsed.beforeWal.fx_1m, 'beforeWal.fx_1m'), + ...(parsed.beforeWal.bar_revisions !== undefined + ? { + bar_revisions: parseWalTxnPair( + parsed.beforeWal.bar_revisions, + 'beforeWal.bar_revisions' + ), + } + : {}), + }; + + if (!isPlainObject(parsed.shards)) { + throw new VerifyM2QuantError('Load receipt missing required object "shards".'); + } + const parseShardProbesRaw = (prefix: RequiredShardPrefix): readonly unknown[] => { + const entry = (parsed.shards as Record)[prefix]; + if (!isPlainObject(entry) || !Array.isArray(entry.probes) || entry.probes.length === 0) { + throw new VerifyM2QuantError( + `Load receipt shards.${prefix}.probes must be a non-empty array.` + ); + } + return entry.probes; + }; + + const bars1mProbes = parseShardProbesRaw('bars_1m').map((p, idx) => + parseBars1mProbe(p, `shards.bars_1m.probes[${idx}]`, 'eod') + ); + const bars1mQmProbes = parseShardProbesRaw('bars_1m_qm').map((p, idx) => + parseBars1mProbe(p, `shards.bars_1m_qm.probes[${idx}]`, 'qm') + ); + const fx1mProbes = parseShardProbesRaw('fx_1m').map((p, idx) => + parseFx1mProbe(p, `shards.fx_1m.probes[${idx}]`) + ); + + if (!isPlainObject(parsed.dedup)) { + throw new VerifyM2QuantError('Load receipt missing required object "dedup".'); + } + const eodSentRows = parsePositiveSafeInt(parsed.dedup.eodSentRows, 'dedup.eodSentRows'); + const qmSentRows = parsePositiveSafeInt(parsed.dedup.qmSentRows, 'dedup.qmSentRows'); + const overlapRows = parseNonNegativeSafeInt(parsed.dedup.overlapRows, 'dedup.overlapRows'); + if (overlapRows > Math.min(eodSentRows, qmSentRows)) { + throw new VerifyM2QuantError( + `Load receipt dedup.overlapRows (${overlapRows}) exceeds min(eodSentRows=${eodSentRows}, qmSentRows=${qmSentRows}).` + ); + } + const overlapWinnerSourceRaw = parseRequiredStringCell( + parsed.dedup.overlapWinnerSource, + 'dedup.overlapWinnerSource' + ); + if (overlapWinnerSourceRaw !== 'eod' && overlapWinnerSourceRaw !== 'qm') { + throw new VerifyM2QuantError( + `Load receipt dedup.overlapWinnerSource must be 'eod' or 'qm' (received '${overlapWinnerSourceRaw}').` + ); + } + const overlapWinnerSource: 'eod' | 'qm' = overlapWinnerSourceRaw; + + let overlapProbes: readonly Bars1mProbeExpectation[] | undefined; + if (parsed.dedup.overlapProbes !== undefined) { + if (!Array.isArray(parsed.dedup.overlapProbes)) { + throw new VerifyM2QuantError('Load receipt dedup.overlapProbes must be an array.'); + } + overlapProbes = parsed.dedup.overlapProbes.map((p, idx) => + parseBars1mProbe(p, `dedup.overlapProbes[${idx}]`, overlapWinnerSource) + ); + } + + return { + beforeWal, + shards: { + bars_1m: { probes: bars1mProbes }, + bars_1m_qm: { probes: bars1mQmProbes }, + fx_1m: { probes: fx1mProbes }, + }, + dedup: { + eodSentRows, + qmSentRows, + overlapRows, + overlapWinnerSource, + ...(overlapProbes !== undefined ? { overlapProbes } : {}), + }, + }; +} + +interface ParsedResendBaseline { + readonly walTables: ReadonlyMap; + readonly bars1mSummary: readonly Bars1mSourceSummaryRow[]; + readonly fx1mSummary: readonly Fx1mPairSourceSummaryRow[]; +} + +function parseResendBaselineJson(rawJson: string): ParsedResendBaseline { + let parsed: unknown; + try { + parsed = JSON.parse(rawJson); + } catch (err: unknown) { + const detail = err instanceof Error ? err.message : String(err); + throw new VerifyM2QuantError(`Failed to parse --resend-baseline JSON: ${detail}`); + } + if (!isPlainObject(parsed) || parsed.ok !== true) { + throw new VerifyM2QuantError('Resend baseline JSON must be a passing VerifyM2QuantReport (ok: true).'); + } + if (!Array.isArray(parsed.walTables) || parsed.walTables.length === 0) { + throw new VerifyM2QuantError('Resend baseline missing required non-empty "walTables" array.'); + } + const walMap = new Map(); + for (let i = 0; i < parsed.walTables.length; i += 1) { + const entry = parsed.walTables[i]; + if (!isPlainObject(entry)) { + throw new VerifyM2QuantError(`Resend baseline walTables[${i}] must be an object.`); + } + const name = parseRequiredStringCell(entry.name, `resendBaseline.walTables[${i}].name`); + if (!(M2_INTRADAY_TABLE_NAMES as readonly string[]).includes(name)) { + continue; + } + walMap.set( + name as M2IntradayTableName, + parseWalTxnPair(entry, `resendBaseline.walTables[${i}]`) + ); + } + for (const required of ['bars_1m', 'fx_1m'] as const) { + if (!walMap.has(required)) { + throw new VerifyM2QuantError(`Resend baseline walTables missing required table '${required}'.`); + } + } + + if (!Array.isArray(parsed.bars1mSummary) || parsed.bars1mSummary.length === 0) { + throw new VerifyM2QuantError('Resend baseline missing required non-empty "bars1mSummary" array.'); + } + const bars1mSummary: Bars1mSourceSummaryRow[] = parsed.bars1mSummary.map((entry, idx) => { + if (!isPlainObject(entry)) { + throw new VerifyM2QuantError(`Resend baseline bars1mSummary[${idx}] must be an object.`); + } + return { + source: parseRequiredStringCell(entry.source, `resendBaseline.bars1mSummary[${idx}].source`), + rowCount: parsePositiveSafeInt(entry.rowCount, `resendBaseline.bars1mSummary[${idx}].rowCount`), + minClose: parseFiniteNumberCell(entry.minClose, `resendBaseline.bars1mSummary[${idx}].minClose`), + maxClose: parseFiniteNumberCell(entry.maxClose, `resendBaseline.bars1mSummary[${idx}].maxClose`), + minTsUs: parseBigIntCell(entry.minTsUs, `resendBaseline.bars1mSummary[${idx}].minTsUs`).toString(), + maxTsUs: parseBigIntCell(entry.maxTsUs, `resendBaseline.bars1mSummary[${idx}].maxTsUs`).toString(), + }; + }); + + if (!Array.isArray(parsed.fx1mSummary) || parsed.fx1mSummary.length === 0) { + throw new VerifyM2QuantError('Resend baseline missing required non-empty "fx1mSummary" array.'); + } + const fx1mSummary: Fx1mPairSourceSummaryRow[] = parsed.fx1mSummary.map((entry, idx) => { + if (!isPlainObject(entry)) { + throw new VerifyM2QuantError(`Resend baseline fx1mSummary[${idx}] must be an object.`); + } + return { + pair: parseRequiredStringCell(entry.pair, `resendBaseline.fx1mSummary[${idx}].pair`), + source: parseRequiredStringCell(entry.source, `resendBaseline.fx1mSummary[${idx}].source`), + rowCount: parsePositiveSafeInt(entry.rowCount, `resendBaseline.fx1mSummary[${idx}].rowCount`), + minClose: parseFiniteNumberCell(entry.minClose, `resendBaseline.fx1mSummary[${idx}].minClose`), + maxClose: parseFiniteNumberCell(entry.maxClose, `resendBaseline.fx1mSummary[${idx}].maxClose`), + minTsUs: parseBigIntCell(entry.minTsUs, `resendBaseline.fx1mSummary[${idx}].minTsUs`).toString(), + maxTsUs: parseBigIntCell(entry.maxTsUs, `resendBaseline.fx1mSummary[${idx}].maxTsUs`).toString(), + }; + }); + + return { walTables: walMap, bars1mSummary, fx1mSummary }; +} + +function verifyWalAdvancement( + beforeMap: Readonly>, + afterTables: readonly WalTableStatusRow[], + contextLabel: string +): readonly WalAdvancementEntry[] { + const afterByName = new Map( + afterTables.map(row => [row.name, row]) + ); + const results: WalAdvancementEntry[] = []; + for (const table of ['bars_1m', 'fx_1m'] as const) { + const before = beforeMap[table]; + const after = afterByName.get(table); + if (after === undefined) { + throw new VerifyM2QuantError(`${contextLabel}: missing table '${table}' in settled wal_tables().`); + } + const beforeWriter = BigInt(before.writerTxn); + const afterWriter = BigInt(after.writerTxn); + const beforeSeq = BigInt(before.sequencerTxn); + const afterSeq = BigInt(after.sequencerTxn); + if (afterWriter <= beforeWriter || afterSeq <= beforeSeq) { + throw new VerifyM2QuantError( + `${contextLabel}: WAL for '${table}' did not advance (before writerTxn=${before.writerTxn}/sequencerTxn=${before.sequencerTxn}, after writerTxn=${after.writerTxn}/sequencerTxn=${after.sequencerTxn}).` + ); + } + results.push({ + table, + beforeWriterTxn: before.writerTxn, + afterWriterTxn: after.writerTxn, + beforeSequencerTxn: before.sequencerTxn, + afterSequencerTxn: after.sequencerTxn, + }); + } + return results; +} + +async function verifyBars1mProbe( + executor: QuestDbPgQueryExecutor, + shardPrefix: 'bars_1m' | 'bars_1m_qm' | 'dedup_overlap', + probe: Bars1mProbeExpectation +): Promise { + const tsIso = formatUtcIsoMicros(BigInt(probe.tsUs)); + const sql = + 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, close, source, CAST(known_at AS LONG) AS known_at_us ' + + 'FROM bars_1m WHERE listing_id = $1 AND ts = $2'; + const res = await executor.query(sql, [String(probe.listingId), tsIso]); + const key = `listing_id=${probe.listingId},ts_us=${probe.tsUs}`; + if (res.rows.length !== 1) { + throw new VerifyM2QuantError( + `Load receipt probe failed for ${shardPrefix} (${key}): expected exactly 1 row, found ${res.rows.length}.` + ); + } + const row = res.rows[0]!; + const actualSource = parseRequiredStringCell(row.source, `${shardPrefix}[${key}].source`); + if (actualSource !== probe.expectedSource) { + throw new VerifyM2QuantError( + `Load receipt probe source mismatch for ${shardPrefix} (${key}): expected '${probe.expectedSource}', found '${actualSource}'.` + ); + } + const actualClose = parseFiniteNumberCell(row.close, `${shardPrefix}[${key}].close`); + const tolerance = probe.closeTolerance ?? DEFAULT_PROBE_CLOSE_TOLERANCE; + const absDiff = Math.abs(actualClose - probe.expectedClose); + if (absDiff > tolerance) { + throw new VerifyM2QuantError( + `Load receipt probe 0x10 close mismatch for ${shardPrefix} (${key}): expected ${probe.expectedClose}, found ${actualClose} (absDiff=${absDiff} > tolerance=${tolerance}).` + ); + } + if (probe.expectedKnownAtUs !== undefined) { + const actualKnownAtUs = parseBigIntCell( + row.known_at_us, + `${shardPrefix}[${key}].known_at_us` + ).toString(); + if (actualKnownAtUs !== probe.expectedKnownAtUs) { + throw new VerifyM2QuantError( + `Load receipt probe known_at mismatch for ${shardPrefix} (${key}): expected ${probe.expectedKnownAtUs}, found ${actualKnownAtUs}.` + ); + } + } + return { + shardPrefix, + key, + expectedSource: probe.expectedSource, + actualSource, + expectedClose: probe.expectedClose, + actualClose, + absDiff, + }; +} + +async function verifyFx1mProbe( + executor: QuestDbPgQueryExecutor, + probe: Fx1mProbeExpectation +): Promise { + const tsIso = formatUtcIsoMicros(BigInt(probe.tsUs)); + const sql = + 'SELECT pair, CAST(ts AS LONG) AS ts_us, close, source FROM fx_1m WHERE pair = $1 AND ts = $2'; + const res = await executor.query(sql, [probe.pair, tsIso]); + const key = `pair=${probe.pair},ts_us=${probe.tsUs}`; + if (res.rows.length !== 1) { + throw new VerifyM2QuantError( + `Load receipt probe failed for fx_1m (${key}): expected exactly 1 row, found ${res.rows.length}.` + ); + } + const row = res.rows[0]!; + const actualSource = parseRequiredStringCell(row.source, `fx_1m[${key}].source`); + if (actualSource !== probe.expectedSource) { + throw new VerifyM2QuantError( + `Load receipt probe source mismatch for fx_1m (${key}): expected '${probe.expectedSource}', found '${actualSource}'.` + ); + } + const actualClose = parseFiniteNumberCell(row.close, `fx_1m[${key}].close`); + const tolerance = probe.closeTolerance ?? DEFAULT_PROBE_CLOSE_TOLERANCE; + const absDiff = Math.abs(actualClose - probe.expectedClose); + if (absDiff > tolerance) { + throw new VerifyM2QuantError( + `Load receipt probe 0x10 close mismatch for fx_1m (${key}): expected ${probe.expectedClose}, found ${actualClose} (absDiff=${absDiff} > tolerance=${tolerance}).` + ); + } + return { + shardPrefix: 'fx_1m', + key, + expectedSource: probe.expectedSource, + actualSource, + expectedClose: probe.expectedClose, + actualClose, + absDiff, + }; +} + +async function verifyLoadReceipt( + executor: QuestDbPgQueryExecutor, + receipt: M2LoadReceipt, + walTables: readonly WalTableStatusRow[], + bars1mSummary: readonly Bars1mSourceSummaryRow[], + fx1mSummary: readonly Fx1mPairSourceSummaryRow[] +): Promise { + const walAdvancement = verifyWalAdvancement( + { bars_1m: receipt.beforeWal.bars_1m, fx_1m: receipt.beforeWal.fx_1m }, + walTables, + 'Load receipt WAL check' + ); + + const bySource = new Map( + bars1mSummary.map(row => [row.source, row]) + ); + const eodGroup = bySource.get('eod'); + const qmGroup = bySource.get('qm'); + if (eodGroup === undefined) { + throw new VerifyM2QuantError( + "Load receipt verification failed: QuestDB bars_1m is missing required source='eod' group (bars_1m shard prefix)." + ); + } + if (qmGroup === undefined) { + throw new VerifyM2QuantError( + "Load receipt verification failed: QuestDB bars_1m is missing required source='qm' group (bars_1m_qm shard prefix)." + ); + } + if (fx1mSummary.length === 0) { + throw new VerifyM2QuantError( + 'Load receipt verification failed: QuestDB fx_1m is missing committed rows (fx_1m shard prefix).' + ); + } + + const { eodSentRows, qmSentRows, overlapRows, overlapWinnerSource } = receipt.dedup; + const minExpectedEodRows = + overlapWinnerSource === 'qm' ? eodSentRows - overlapRows : eodSentRows; + const minExpectedQmRows = + overlapWinnerSource === 'eod' ? qmSentRows - overlapRows : qmSentRows; + const minExpectedTotalBars1mRows = eodSentRows + qmSentRows - overlapRows; + const observedTotalBars1mRows = eodGroup.rowCount + qmGroup.rowCount; + + if (eodGroup.rowCount < minExpectedEodRows) { + throw new VerifyM2QuantError( + `EOD/QM dedup accounting failed: observed bars_1m source='eod' rowCount=${eodGroup.rowCount} < expected minimum ${minExpectedEodRows}.` + ); + } + if (qmGroup.rowCount < minExpectedQmRows) { + throw new VerifyM2QuantError( + `EOD/QM dedup accounting failed: observed bars_1m source='qm' rowCount=${qmGroup.rowCount} < expected minimum ${minExpectedQmRows}.` + ); + } + if (observedTotalBars1mRows < minExpectedTotalBars1mRows) { + throw new VerifyM2QuantError( + `EOD/QM dedup accounting failed: observed combined bars_1m rowCount=${observedTotalBars1mRows} < expected post-dedup minimum ${minExpectedTotalBars1mRows}.` + ); + } + + const probesVerified: ProbeCheckResult[] = []; + for (const probe of receipt.shards.bars_1m.probes) { + probesVerified.push(await verifyBars1mProbe(executor, 'bars_1m', probe)); + } + for (const probe of receipt.shards.bars_1m_qm.probes) { + probesVerified.push(await verifyBars1mProbe(executor, 'bars_1m_qm', probe)); + } + for (const probe of receipt.shards.fx_1m.probes) { + probesVerified.push(await verifyFx1mProbe(executor, probe)); + } + if (receipt.dedup.overlapProbes !== undefined) { + for (const probe of receipt.dedup.overlapProbes) { + probesVerified.push(await verifyBars1mProbe(executor, 'dedup_overlap', probe)); + } + } + + return { + walAdvancement, + dedupAccounting: { + eodSentRows, + qmSentRows, + overlapRows, + overlapWinnerSource, + minExpectedEodRows, + minExpectedQmRows, + minExpectedTotalBars1mRows, + observedEodRows: eodGroup.rowCount, + observedQmRows: qmGroup.rowCount, + observedTotalBars1mRows, + }, + probesVerified, + }; +} + +function verifyIdempotentResend( + baseline: ParsedResendBaseline, + walTables: readonly WalTableStatusRow[], + bars1mSummary: readonly Bars1mSourceSummaryRow[], + fx1mSummary: readonly Fx1mPairSourceSummaryRow[] +): ResendVerificationResult { + const walAdvancement = verifyWalAdvancement( + { + bars_1m: baseline.walTables.get('bars_1m')!, + fx_1m: baseline.walTables.get('fx_1m')!, + }, + walTables, + 'Idempotent resend WAL check' + ); + + if (bars1mSummary.length !== baseline.bars1mSummary.length) { + throw new VerifyM2QuantError( + `Idempotent resend failed: bars_1m source group count changed (${baseline.bars1mSummary.length} -> ${bars1mSummary.length}).` + ); + } + for (let i = 0; i < bars1mSummary.length; i += 1) { + const cur = bars1mSummary[i]!; + const prev = baseline.bars1mSummary[i]!; + if ( + cur.source !== prev.source || + cur.rowCount !== prev.rowCount || + cur.minClose !== prev.minClose || + cur.maxClose !== prev.maxClose || + cur.minTsUs !== prev.minTsUs || + cur.maxTsUs !== prev.maxTsUs + ) { + throw new VerifyM2QuantError( + `Idempotent resend failed: bars_1m summary diverged for source '${cur.source}' (rows ${prev.rowCount} -> ${cur.rowCount}, close [${prev.minClose},${prev.maxClose}] -> [${cur.minClose},${cur.maxClose}]).` + ); + } + } + + if (fx1mSummary.length !== baseline.fx1mSummary.length) { + throw new VerifyM2QuantError( + `Idempotent resend failed: fx_1m group count changed (${baseline.fx1mSummary.length} -> ${fx1mSummary.length}).` + ); + } + for (let i = 0; i < fx1mSummary.length; i += 1) { + const cur = fx1mSummary[i]!; + const prev = baseline.fx1mSummary[i]!; + if ( + cur.pair !== prev.pair || + cur.source !== prev.source || + cur.rowCount !== prev.rowCount || + cur.minClose !== prev.minClose || + cur.maxClose !== prev.maxClose || + cur.minTsUs !== prev.minTsUs || + cur.maxTsUs !== prev.maxTsUs + ) { + throw new VerifyM2QuantError( + `Idempotent resend failed: fx_1m summary diverged for '${cur.pair}/${cur.source}' (rows ${prev.rowCount} -> ${cur.rowCount}, close [${prev.minClose},${prev.maxClose}] -> [${cur.minClose},${cur.maxClose}]).` + ); + } + } + + return { + ok: true, + walAdvancement, + bars1mRowCountsUnchanged: true, + fx1mRowCountsUnchanged: true, + }; +} + +function validateBenchmarkFence(parsed: ParsedVerifyM2QuantRun): FencedTimeRange { // Pre-validate Vault fence with vaultOperatorAuthorized: false so violations - // fail closed deterministically even before opening a store handle. + // fail closed deterministically before opening any QuestDB or store handle. const fence = applyVaultFence( { from: parsed.benchFrom, @@ -1064,6 +1819,31 @@ async function runIntradayLatencyBenchmark( } ); + const effectiveSpanMs = fence.toMs - fence.fromMs + 1; + if (effectiveSpanMs < MIN_ONE_YEAR_WINDOW_MS) { + const effectiveFromIso = new Date(fence.fromMs).toISOString(); + const effectiveToIso = new Date(fence.toMs).toISOString(); + const effectiveDays = (effectiveSpanMs / 86_400_000).toFixed(2); + const reason = fence.clampedTo + ? `Vault cutoff (${parsed.vaultCutoffIso}) clamped --bench-to (${parsed.benchTo}) to ${effectiveToIso}, truncating the effective benchmark window` + : `Requested benchmark window (${parsed.benchFrom}..${parsed.benchTo}) is shorter than the required 1-year minimum`; + throw new VerifyM2QuantError( + `${reason}: effective fenced interval [${effectiveFromIso}, ${effectiveToIso}] covers ${effectiveDays} days (< 365 days required for 1-year benchmark).` + ); + } + + return fence; +} + +async function runIntradayLatencyBenchmark( + parsed: ParsedVerifyM2QuantRun, + fence: FencedTimeRange, + openStore: ( + config: ResearchCopilotHostConfig, + options?: OpenResearchCopilotStoreOptions + ) => Promise, + perfNowMs: () => number +): Promise { const hostConfig: ResearchCopilotHostConfig = { postgresUrl: 'postgres://unused@127.0.0.1:5433/unused', curatedRoot: parsed.curatedRoot, @@ -1148,6 +1928,12 @@ async function runIntradayLatencyBenchmark( from: parsed.benchFrom, to: parsed.benchTo, asOf: parsed.benchAsOf, + effectiveFrom: new Date(fence.fromMs).toISOString(), + effectiveTo: new Date(fence.toMs).toISOString(), + effectiveAsOf: new Date(fence.asOfMs).toISOString(), + effectiveSpanMs: fence.toMs - fence.fromMs + 1, + clampedTo: fence.clampedTo, + clampedAsOf: fence.clampedAsOf, scope: parsed.benchScope, rowCount: coldBars.length, digest: coldDigest, @@ -1159,6 +1945,7 @@ async function runIntradayLatencyBenchmark( thresholds: { maxColdMs: MAX_COLD_READ_MS, maxWarmMs: MAX_WARM_READ_MS, + minWindowMs: MIN_ONE_YEAR_WINDOW_MS, }, }; } finally { @@ -1166,6 +1953,10 @@ async function runIntradayLatencyBenchmark( } } +async function defaultReadTextFile(path: string): Promise { + return readFile(path, 'utf8'); +} + async function defaultWriteReportFile(path: string, content: string): Promise { await mkdir(dirname(path), { recursive: true }); await writeFile(path, content, 'utf8'); @@ -1225,6 +2016,7 @@ export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Prom const applyDdlFn = deps.applyM2IntradayDDL ?? applyM2IntradayDDL; const createDuck = deps.createDuckDbExecutor ?? defaultCreateDuckDbExecutor; const openStore = deps.openResearchCopilotStore ?? defaultOpenResearchCopilotStore; + const readTextFile = deps.readTextFile ?? defaultReadTextFile; const writeReportFile = deps.writeReportFile ?? defaultWriteReportFile; const nowMs = deps.nowMs ?? Date.now; const perfNowMs = deps.perfNowMs ?? (() => performance.now()); @@ -1232,20 +2024,82 @@ export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Prom const walPollIntervalMs = deps.walPollIntervalMs ?? DEFAULT_WAL_POLL_INTERVAL_MS; try { - let ddlResult: { readonly applied: boolean; readonly appliedTables: readonly M2IntradayTableName[] } = - { applied: false, appliedTables: [] }; + if (parsed.kind === 'ddl_only') { + const pgHandle = await openPg(parsed.questdb); + let appliedTables: readonly M2IntradayTableName[]; + let walTables: readonly WalTableStatusRow[]; + try { + const applied = await applyDdlFn(pgHandle.executor); + appliedTables = applied.appliedTables; + walTables = await waitForHealthyWalTables( + pgHandle.executor, + parsed.walSettleTimeoutMs, + walPollIntervalMs, + nowMs, + sleepMs + ); + } finally { + await pgHandle.close(); + } + + const ddlReport: VerifyM2QuantDdlOnlyReport = { + ok: true, + mode: 'ddl_only', + target: { + questdb: describeSafeQuestDbTarget(parsed.questdb), + }, + ddl: { + applied: true, + appliedTables, + }, + walTables, + }; + const json = `${JSON.stringify(ddlReport, null, 2)}\n`; + if (parsed.outPath !== undefined) { + await writeReportFile(parsed.outPath, json); + } + stdout.write(`${JSON.stringify(ddlReport)}\n`); + return 0; + } + + const receiptRaw = await readTextFile(parsed.loadReceiptPath); + const receipt = parseLoadReceiptJson(receiptRaw); + const resendBaseline = + parsed.resendBaselinePath !== undefined + ? parseResendBaselineJson(await readTextFile(parsed.resendBaselinePath)) + : undefined; + + // Validate Vault fence and 1-year effective window before any DB/store I/O. + const fence = validateBenchmarkFence(parsed); + + let ddlResult: { + readonly applied: boolean; + readonly appliedTables: readonly M2IntradayTableName[]; + } = { applied: false, appliedTables: [] }; + + if (parsed.applyDdl) { + const ddlPgHandle = await openPg(parsed.questdb); + try { + const applied = await applyDdlFn(ddlPgHandle.executor); + ddlResult = { applied: true, appliedTables: applied.appliedTables }; + } finally { + await ddlPgHandle.close(); + } + } + + // Measure the cold 1-year 1m benchmark read BEFORE any verifier query scans bars_1m + // so QuestDB and OS page caches are not pre-warmed after restart. + const benchmark = await runIntradayLatencyBenchmark(parsed, fence, openStore, perfNowMs); + let walTables: readonly WalTableStatusRow[]; let bars1mSummary: readonly Bars1mSourceSummaryRow[]; let fx1mSummary: readonly Fx1mPairSourceSummaryRow[]; + let loadVerification: LoadReceiptVerificationResult; + let resendVerification: ResendVerificationResult | undefined; const splitChecks: SplitBoundaryCheckResult[] = []; const pgHandle = await openPg(parsed.questdb); try { - if (parsed.applyDdl) { - const applied = await applyDdlFn(pgHandle.executor); - ddlResult = { applied: true, appliedTables: applied.appliedTables }; - } - walTables = await waitForHealthyWalTables( pgHandle.executor, parsed.walSettleTimeoutMs, @@ -1255,6 +2109,21 @@ export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Prom ); bars1mSummary = await verifyBars1mCommits(pgHandle.executor); fx1mSummary = await verifyFx1mCommits(pgHandle.executor); + loadVerification = await verifyLoadReceipt( + pgHandle.executor, + receipt, + walTables, + bars1mSummary, + fx1mSummary + ); + if (resendBaseline !== undefined) { + resendVerification = verifyIdempotentResend( + resendBaseline, + walTables, + bars1mSummary, + fx1mSummary + ); + } const duckExecutor = await createDuck(); try { @@ -1280,10 +2149,9 @@ export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Prom await pgHandle.close(); } - const benchmark = await runIntradayLatencyBenchmark(parsed, openStore, perfNowMs); - const report: VerifyM2QuantReport = { ok: true, + mode: 'verify', target: { questdb: describeSafeQuestDbTarget(parsed.questdb), curatedRoot: parsed.curatedRoot, @@ -1293,6 +2161,8 @@ export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Prom walTables, bars1mSummary, fx1mSummary, + loadVerification, + ...(resendVerification !== undefined ? { resendVerification } : {}), splitChecks, benchmark, };