diff --git a/scripts/test/verify-m2-quant.test.ts b/scripts/test/verify-m2-quant.test.ts new file mode 100644 index 00000000..7cfc03eb --- /dev/null +++ b/scripts/test/verify-m2-quant.test.ts @@ -0,0 +1,754 @@ +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, + type VerifyM2QuantCliDeps, + type VerifyM2QuantReport, + runVerifyM2QuantCli, +} from '../verify-m2-quant'; + +const NVDA_LISTING_ID = 101; +const NEXM_LISTING_ID = 202; +const VAULT_CUTOFF_ISO = '2025-02-13T00:00:00Z'; +const VAULT_CUTOFF_MS = Date.parse(VAULT_CUTOFF_ISO); + +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 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', + '--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 isoToMicros(iso: string): string { + return (BigInt(Date.parse(iso)) * 1000n).toString(); +} + +interface MockFixtureOptions { + readonly walSequence?: readonly (readonly Record[])[]; + readonly bars1mSummaryRows?: readonly Record[]; + readonly fx1mSummaryRows?: readonly Record[]; + 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 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.40 }, + // 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.40 }, + { session_date: '2025-06-20', close: 8.00 }, + ]; +} + +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; + }; +} { + 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, + }; + + const walSeq = options.walSequence ?? [defaultWalRows()]; + const bars1mSummary = options.bars1mSummaryRows ?? defaultBars1mSummaryRows(); + const fx1mSummary = options.fx1mSummaryRows ?? defaultFx1mSummaryRows(); + const nvda1m = options.nvda1mRows ?? defaultNvda1mRows(); + const nexm1m = options.nexm1mRows ?? defaultNexm1mRows(); + const nvda1d = options.nvda1dRows ?? defaultNvda1dRows(); + const nexm1d = options.nexm1dRows ?? defaultNexm1dRows(); + + 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()')) { + 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')) { + return { rows: bars1mSummary }; + } + if (sql.includes('FROM fx_1m GROUP BY pair, source')) { + return { rows: fx1mSummary }; + } + if (sql.includes("session = 'RTH'")) { + const listingId = String(params?.[0] ?? ''); + 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]); + 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 { + 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; + 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 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(stderr.text()).toBe(''); + }); + + test('passes end-to-end without --apply-ddl, 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.ddl).toEqual({ applied: false, appliedTables: [] }); + expect(report.walTables).toHaveLength(3); + expect(report.bars1mSummary).toHaveLength(2); + expect(report.fx1mSummary).toHaveLength(1); + 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.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, + }); + expect(state.writtenFiles.size).toBe(1); + }); + + test('invokes applyM2IntradayDDL when --apply-ddl is set', 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); + + const report = JSON.parse(stdout.text()) as VerifyM2QuantReport; + expect(report.ddl).toEqual({ + applied: true, + appliedTables: [...M2_INTRADAY_TABLE_NAMES], + }); + }); + + 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: '10', sequencerTxn: '10' }, + { name: 'fx_1m', suspended: false, writerTxn: '10', sequencerTxn: '10' }, + ], + ], + }); + + 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: '10', sequencerTxn: '10' }, + { name: 'fx_1m', suspended: false, writerTxn: '10', sequencerTxn: '10' }, + ], + ], + }); + + 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: '10', sequencerTxn: '20' }, + { name: 'fx_1m', suspended: false, writerTxn: '5', sequencerTxn: '5' }, + ], + ], + } + ); + + 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=10 { + 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: '100', + 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': '2025-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 conflictingConn = createHarness( + baseArgs({ '--questdb-url': 'postgres://user:pass@10.0.0.51:8812/qdb' }) + ); + expect(await runVerifyM2QuantCli(conflictingConn.deps)).toBe(1); + assertSingleLineError(conflictingConn.stderr.text()); + expect(conflictingConn.stderr.text()).not.toContain('pass'); + + 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'); + }); +}); diff --git a/scripts/verify-m2-quant.ts b/scripts/verify-m2-quant.ts new file mode 100644 index 00000000..0738201a --- /dev/null +++ b/scripts/verify-m2-quant.ts @@ -0,0 +1,1303 @@ +/** + * 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`). + * + * 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. + */ + +import { createHash } from 'node:crypto'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { + type ClosableDuckDbExecutor, + type OpenResearchCopilotStoreOptions, + createNodeDuckDbExecutor, + openResearchCopilotStore, +} from '@stock-bot/duckdb'; +import { + type ApplyM2IntradayDDLResult, + M2_INTRADAY_TABLE_NAMES, + type M2IntradayTableName, + type QuestDbPgExecutorConfig, + type QuestDbPgExecutorHandle, + type QuestDbPgQueryExecutor, + applyM2IntradayDDL, + openQuestDbPgExecutor, +} from '@stock-bot/questdb'; +import { + type BarRecord, + type DataScope, + applyVaultFence, + collectBars, +} from '@stock-bot/research'; +import type { ManagedMarketDataStore, ResearchCopilotHostConfig } from '@stock-bot/research/mcp'; + +const INT32_MAX = 2_147_483_647; +const STRICT_POSITIVE_INT_RE = /^[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$/; +const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; +const URL_CREDENTIAL_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^:@/\s]+):([^@/\s]+)@/g; +const POSTGRES_URL_RE = /postgres(?:ql)?:\/\/[^\s'"]+/gi; + +export const DEFAULT_WARM_RUNS = 5; +export const DEFAULT_WAL_SETTLE_TIMEOUT_MS = 30_000; +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 interface SplitBoundaryCaseSpec { + readonly label: 'NVDA.US' | 'NEXM.V'; + readonly fromDate: string; + readonly toDate: string; + readonly exDate: string; + readonly ratio: string; +} + +export const M2_SPLIT_BOUNDARY_CASES: readonly SplitBoundaryCaseSpec[] = [ + { + label: 'NVDA.US', + fromDate: '2024-06-06', + toDate: '2024-06-12', + exDate: '2024-06-10', + ratio: '10:1', + }, + { + label: 'NEXM.V', + fromDate: '2025-06-17', + toDate: '2025-06-23', + exDate: '2025-06-20', + ratio: '1:20', + }, +] as const; + +const NY_DATE_FORMATTER = new Intl.DateTimeFormat('en-CA', { + timeZone: 'America/New_York', + year: 'numeric', + month: '2-digit', + day: '2-digit', +}); + +export interface VerifyM2QuantStream { + write(chunk: string): boolean; +} + +export interface ParseVerifyM2QuantArgsOptions { + readonly cwd?: string; +} + +export interface ParsedVerifyM2QuantRun { + readonly kind: 'run'; + readonly questdb: QuestDbPgExecutorConfig; + readonly curatedRoot: string; + readonly vaultCutoffIso: string; + readonly vaultCutoffTs: number; + readonly nvdaListingId: number; + readonly nexmListingId: number; + readonly benchListingId: number; + readonly benchFrom: string; + readonly benchTo: string; + readonly benchAsOf: string; + readonly benchScope: DataScope; + readonly applyDdl: boolean; + readonly warmRuns: number; + readonly walSettleTimeoutMs: number; + readonly outPath?: string; +} + +export interface ParsedVerifyM2QuantHelp { + readonly kind: 'help'; +} + +export type ParsedVerifyM2QuantArgs = ParsedVerifyM2QuantRun | ParsedVerifyM2QuantHelp; + +export interface VerifyM2QuantCliDeps { + readonly argv?: readonly string[]; + readonly cwd?: string; + readonly stdout?: VerifyM2QuantStream; + readonly stderr?: VerifyM2QuantStream; + readonly openQuestDbPgExecutor?: ( + config: QuestDbPgExecutorConfig + ) => Promise; + readonly applyM2IntradayDDL?: ( + client: QuestDbPgQueryExecutor + ) => Promise; + readonly createDuckDbExecutor?: () => Promise; + readonly openResearchCopilotStore?: ( + config: ResearchCopilotHostConfig, + options?: OpenResearchCopilotStoreOptions + ) => Promise; + readonly writeReportFile?: (path: string, content: string) => Promise; + readonly nowMs?: () => number; + readonly perfNowMs?: () => number; + readonly sleepMs?: (ms: number) => Promise; + readonly walPollIntervalMs?: number; +} + +export interface WalTableStatusRow { + readonly name: M2IntradayTableName; + readonly suspended: boolean; + readonly writerTxn: string; + readonly sequencerTxn: string; +} + +export interface Bars1mSourceSummaryRow { + readonly source: string; + readonly rowCount: number; + readonly minClose: number; + readonly maxClose: number; + readonly minTsUs: string; + readonly maxTsUs: string; +} + +export interface Fx1mPairSourceSummaryRow { + readonly pair: string; + readonly source: string; + readonly rowCount: number; + readonly minClose: number; + readonly maxClose: number; + readonly minTsUs: string; + readonly maxTsUs: string; +} + +export interface SplitBoundarySessionComparison { + readonly sessionDate: string; + readonly phase: 'pre_split' | 'ex_or_post_split'; + readonly close1m: number; + readonly close1d: number; + readonly relDiff: number; +} + +export interface SplitBoundaryCheckResult { + readonly label: 'NVDA.US' | 'NEXM.V'; + readonly listingId: number; + readonly fromDate: string; + readonly toDate: string; + readonly exDate: string; + readonly ratio: string; + readonly preSplitCount: number; + readonly exOrPostSplitCount: number; + readonly maxRelDiff: number; + readonly sessions: readonly SplitBoundarySessionComparison[]; +} + +export interface IntradayBenchmarkResult { + readonly listingId: number; + readonly from: string; + readonly to: string; + readonly asOf: string; + readonly scope: DataScope; + readonly rowCount: number; + readonly digest: string; + readonly coldMs: number; + readonly warmRuns: readonly number[]; + readonly minWarmMs: number; + readonly medianWarmMs: number; + readonly maxWarmMs: number; + readonly thresholds: { + readonly maxColdMs: number; + readonly maxWarmMs: number; + }; +} + +export interface VerifyM2QuantReport { + readonly ok: true; + readonly target: { + readonly questdb: string; + readonly curatedRoot: string; + readonly vaultCutoffTs: string; + }; + readonly ddl: { + readonly applied: boolean; + readonly appliedTables: readonly M2IntradayTableName[]; + }; + readonly walTables: readonly WalTableStatusRow[]; + readonly bars1mSummary: readonly Bars1mSourceSummaryRow[]; + readonly fx1mSummary: readonly Fx1mPairSourceSummaryRow[]; + readonly splitChecks: readonly SplitBoundaryCheckResult[]; + readonly benchmark: IntradayBenchmarkResult; +} + +export class VerifyM2QuantError extends Error { + constructor(message: string) { + super(message); + this.name = 'VerifyM2QuantError'; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export const VERIFY_M2_QUANT_USAGE = [ + 'Usage: bun run scripts/verify-m2-quant.ts [options]', + '', + 'Required options:', + ' --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', + ' --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-as-of Benchmark point-in-time as-of bound', + '', + 'Optional options:', + ' --questdb-database QuestDB PGWire database name (host/port mode)', + ' --questdb-user QuestDB PGWire user (host/port mode)', + ' --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', + ` --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', + ' -h, --help Show this help message', + '', +].join('\n'); + +const VALUE_FLAGS = new Set([ + '--questdb-url', + '--questdb-host', + '--questdb-pg-port', + '--questdb-database', + '--questdb-user', + '--questdb-password', + '--questdb-ssl', + '--curated-root', + '--vault-cutoff-ts', + '--nvda-listing-id', + '--nexm-listing-id', + '--bench-listing-id', + '--bench-from', + '--bench-to', + '--bench-as-of', + '--bench-scope', + '--warm-runs', + '--wal-settle-timeout-ms', + '--out', +]); + +const BOOLEAN_FLAGS = new Set(['--apply-ddl']); +const SECRET_FLAGS = new Set(['--questdb-url', '--questdb-password']); + +function sanitizeSingleLine(message: string): string { + return message.replace(/\r?\n/g, ' ').trim(); +} + +function addRawAndDecodedNeedle(needles: Set, raw: string): void { + if (raw.length === 0) { + return; + } + needles.add(raw); + try { + const decoded = decodeURIComponent(raw); + if (decoded.length > 0) { + needles.add(decoded); + } + } catch { + // Malformed percent-encoding: raw value is already registered. + } +} + +function collectArgvSecretNeedles(argv: readonly string[]): Set { + const needles = new Set(); + for (let i = 0; i < argv.length; i += 1) { + const token = argv[i] as string; + const eqIndex = token.indexOf('='); + let flag: string; + let rawValue: string | undefined; + if (eqIndex !== -1) { + flag = token.slice(0, eqIndex); + rawValue = token.slice(eqIndex + 1); + } else { + flag = token; + if (SECRET_FLAGS.has(flag) && i + 1 < argv.length) { + rawValue = argv[i + 1]; + } + } + if (SECRET_FLAGS.has(flag) && rawValue !== undefined && rawValue.length > 0) { + addRawAndDecodedNeedle(needles, rawValue); + if (flag === '--questdb-url') { + try { + const parsed = new URL(rawValue); + if (parsed.href.length > 0) { + needles.add(parsed.href); + } + addRawAndDecodedNeedle(needles, parsed.password); + for (const [k, v] of parsed.searchParams.entries()) { + if (k.toLowerCase() === 'password' && v.length > 0) { + addRawAndDecodedNeedle(needles, v); + } + } + } catch { + // Non-URL string: raw string already registered. + } + } + } + } + return needles; +} + +export function redactSecrets(message: string, needles: Iterable): string { + let out = message; + const sorted = Array.from(new Set(needles)) + .filter(n => n.length > 0) + .sort((a, b) => b.length - a.length); + for (const needle of sorted) { + out = out.split(needle).join('[REDACTED]'); + } + out = out.replace(POSTGRES_URL_RE, '[REDACTED_DSN]'); + out = out.replace(URL_CREDENTIAL_RE, '$1[REDACTED]:[REDACTED]@'); + return out; +} + +function validateRawTokenValue(flag: string, rawValue: string): string { + if (rawValue.length === 0 || rawValue.trim().length === 0) { + throw new VerifyM2QuantError(`Flag '${flag}' requires a non-empty value.`); + } + if (rawValue.includes('\0')) { + throw new VerifyM2QuantError(`Flag '${flag}' value must not contain NUL bytes.`); + } + if (!SECRET_FLAGS.has(flag) && rawValue.startsWith('-')) { + throw new VerifyM2QuantError( + `Flag '${flag}' value must not start with '-' (received '${rawValue}').` + ); + } + return rawValue; +} + +function parsePositiveIntFlag(flag: string, rawValue: string, maxValue?: number): number { + const validated = validateRawTokenValue(flag, rawValue); + if (!STRICT_POSITIVE_INT_RE.test(validated)) { + throw new VerifyM2QuantError( + `Flag '${flag}' must be a positive integer (received '${validated}').` + ); + } + const parsed = Number(validated); + if (!Number.isSafeInteger(parsed) || parsed <= 0 || (maxValue !== undefined && parsed > maxValue)) { + throw new VerifyM2QuantError( + `Flag '${flag}' is out of allowed range (received '${validated}').` + ); + } + return parsed; +} + +function parseBooleanFlagValue(flag: string, rawValue: string): boolean { + const normalized = validateRawTokenValue(flag, rawValue).trim().toLowerCase(); + if (normalized === 'true') { + return true; + } + if (normalized === 'false') { + return false; + } + throw new VerifyM2QuantError( + `Flag '${flag}' must be 'true' or 'false' (received '${rawValue}').` + ); +} + +function parseStrictUtcIsoZ(flag: string, rawValue: string): number { + const validated = validateRawTokenValue(flag, rawValue); + const match = STRICT_UTC_INSTANT_RE.exec(validated); + if (match === null) { + throw new VerifyM2QuantError( + `Flag '${flag}' must be a strict ISO-8601 UTC timestamp ending in 'Z' (received '${validated}').` + ); + } + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const hours = Number(match[4]); + const minutes = Number(match[5]); + const seconds = Number(match[6]); + const frac = match[7] !== undefined ? Number(match[7].padEnd(3, '0')) : 0; + const epochMs = Date.UTC(year, month - 1, day, hours, minutes, seconds, frac); + const check = new Date(epochMs); + if ( + !Number.isSafeInteger(epochMs) || + check.getUTCFullYear() !== year || + check.getUTCMonth() !== month - 1 || + check.getUTCDate() !== day || + check.getUTCHours() !== hours || + check.getUTCMinutes() !== minutes || + check.getUTCSeconds() !== seconds || + check.getUTCMilliseconds() !== frac + ) { + throw new VerifyM2QuantError( + `Flag '${flag}' contains an invalid UTC calendar instant (received '${validated}').` + ); + } + return epochMs; +} + +function assertSafeDuckDbPath(rawPath: string, flag: string): string { + for (let i = 0; i < rawPath.length; i += 1) { + const code = rawPath.charCodeAt(i); + if (code <= 0x1f || code === 0x7f || code === 0x27 || code === 0x3b) { + throw new VerifyM2QuantError( + `Flag '${flag}' contains characters disallowed in DuckDB Parquet paths.` + ); + } + } + return rawPath.replace(/\/+$/, '') || '/'; +} + +export function parseVerifyM2QuantArgs( + argv: readonly string[], + options?: ParseVerifyM2QuantArgsOptions +): ParsedVerifyM2QuantArgs { + const baseCwd = options?.cwd ?? process.cwd(); + const seenValues = new Map(); + const seenBooleans = new Set(); + + for (let i = 0; i < argv.length; i += 1) { + const token = argv[i] as string; + if (token === '--help' || token === '-h') { + return { kind: 'help' }; + } + if (token === '--') { + throw new VerifyM2QuantError('Unexpected positional argument separator "--".'); + } + if (!token.startsWith('-')) { + throw new VerifyM2QuantError(`Unexpected positional argument '${token}'.`); + } + + const eqIndex = token.indexOf('='); + if (eqIndex !== -1) { + const flag = token.slice(0, eqIndex); + const rawValue = token.slice(eqIndex + 1); + if (BOOLEAN_FLAGS.has(flag)) { + throw new VerifyM2QuantError(`Flag '${flag}' does not accept a value.`); + } + if (!VALUE_FLAGS.has(flag)) { + throw new VerifyM2QuantError(`Unknown flag '${flag}'.`); + } + if (seenValues.has(flag)) { + throw new VerifyM2QuantError(`Duplicate flag '${flag}'.`); + } + seenValues.set(flag, validateRawTokenValue(flag, rawValue)); + continue; + } + + if (BOOLEAN_FLAGS.has(token)) { + if (seenBooleans.has(token)) { + throw new VerifyM2QuantError(`Duplicate flag '${token}'.`); + } + seenBooleans.add(token); + continue; + } + + if (!VALUE_FLAGS.has(token)) { + throw new VerifyM2QuantError(`Unknown flag '${token}'.`); + } + if (seenValues.has(token)) { + throw new VerifyM2QuantError(`Duplicate flag '${token}'.`); + } + if (i + 1 >= argv.length) { + throw new VerifyM2QuantError(`Flag '${token}' requires a value.`); + } + i += 1; + seenValues.set(token, validateRawTokenValue(token, argv[i] as string)); + } + + const rawUrl = seenValues.get('--questdb-url'); + const rawHost = seenValues.get('--questdb-host'); + const rawPort = seenValues.get('--questdb-pg-port'); + const rawDb = seenValues.get('--questdb-database'); + const rawUser = seenValues.get('--questdb-user'); + const rawPassword = seenValues.get('--questdb-password'); + const rawSsl = seenValues.get('--questdb-ssl'); + const ssl = rawSsl !== undefined ? parseBooleanFlagValue('--questdb-ssl', rawSsl) : undefined; + + let questdb: QuestDbPgExecutorConfig; + if (rawUrl !== undefined) { + if ( + rawHost !== undefined || + rawPort !== undefined || + rawDb !== undefined || + rawUser !== undefined || + rawPassword !== undefined + ) { + throw new VerifyM2QuantError( + 'Cannot combine --questdb-url with --questdb-host/--questdb-pg-port/--questdb-database/--questdb-user/--questdb-password.' + ); + } + questdb = { + url: rawUrl, + ...(ssl !== undefined ? { ssl } : {}), + }; + } else { + if (rawHost === undefined || rawPort === undefined) { + throw new VerifyM2QuantError( + 'Missing required QuestDB connection flags: provide --questdb-url or both --questdb-host and --questdb-pg-port.' + ); + } + const port = parsePositiveIntFlag('--questdb-pg-port', rawPort, 65_535); + questdb = { + host: rawHost, + port, + ...(rawDb !== undefined ? { database: rawDb } : {}), + ...(rawUser !== undefined ? { user: rawUser } : {}), + ...(rawPassword !== undefined ? { password: rawPassword } : {}), + ...(ssl !== undefined ? { ssl } : {}), + }; + } + + const requireFlag = (flag: string): string => { + const val = seenValues.get(flag); + if (val === undefined) { + throw new VerifyM2QuantError(`Missing required flag ${flag}.`); + } + return val; + }; + + const curatedRoot = assertSafeDuckDbPath( + resolve(baseCwd, requireFlag('--curated-root')), + '--curated-root' + ); + const vaultCutoffIso = requireFlag('--vault-cutoff-ts'); + const vaultCutoffTs = parseStrictUtcIsoZ('--vault-cutoff-ts', vaultCutoffIso); + + const nvdaListingId = parsePositiveIntFlag( + '--nvda-listing-id', + requireFlag('--nvda-listing-id'), + INT32_MAX + ); + const nexmListingId = parsePositiveIntFlag( + '--nexm-listing-id', + requireFlag('--nexm-listing-id'), + INT32_MAX + ); + const benchListingId = parsePositiveIntFlag( + '--bench-listing-id', + requireFlag('--bench-listing-id'), + INT32_MAX + ); + + const benchFrom = requireFlag('--bench-from'); + const benchTo = requireFlag('--bench-to'); + const benchAsOf = requireFlag('--bench-as-of'); + + const rawBenchScope = seenValues.get('--bench-scope'); + let benchScope: DataScope = 'vault_fenced'; + if (rawBenchScope !== undefined) { + if (rawBenchScope !== 'vault_fenced' && rawBenchScope !== 'vault_evaluation_only') { + throw new VerifyM2QuantError( + `Flag '--bench-scope' must be 'vault_fenced' or 'vault_evaluation_only' (received '${rawBenchScope}').` + ); + } + benchScope = rawBenchScope; + } + + const rawWarmRuns = seenValues.get('--warm-runs'); + 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, + curatedRoot, + vaultCutoffIso, + vaultCutoffTs, + nvdaListingId, + nexmListingId, + benchListingId, + benchFrom, + benchTo, + benchAsOf, + benchScope, + applyDdl: seenBooleans.has('--apply-ddl'), + warmRuns, + walSettleTimeoutMs, + ...(outPath !== undefined ? { outPath } : {}), + }; +} + +function parseBigIntCell(value: unknown, field: string): bigint { + if (typeof value === 'bigint') { + return value; + } + if (typeof value === 'number' && Number.isSafeInteger(value)) { + return BigInt(value); + } + if (typeof value === 'string' && STRICT_SIGNED_INT_RE.test(value.trim())) { + return BigInt(value.trim()); + } + throw new VerifyM2QuantError(`Invalid integer value for '${field}': ${String(value)}.`); +} + +function parseFiniteNumberCell(value: unknown, field: string): number { + if (typeof value === 'number' && Number.isFinite(value)) { + return Object.is(value, -0) ? 0 : value; + } + if (typeof value === 'string' && value.trim().length > 0) { + const parsed = Number(value.trim()); + if (Number.isFinite(parsed)) { + return Object.is(parsed, -0) ? 0 : parsed; + } + } + throw new VerifyM2QuantError(`Invalid finite numeric value for '${field}': ${String(value)}.`); +} + +function parseBooleanCell(value: unknown, field: string): boolean { + if (typeof value === 'boolean') { + return value; + } + if (typeof value === 'string') { + const lower = value.trim().toLowerCase(); + if (lower === 'true' || lower === 't') { + return true; + } + if (lower === 'false' || lower === 'f') { + return false; + } + } + throw new VerifyM2QuantError(`Invalid boolean value for '${field}': ${String(value)}.`); +} + +function parseRequiredStringCell(value: unknown, field: string): string { + if (typeof value === 'string' && value.trim().length > 0) { + return value.trim(); + } + throw new VerifyM2QuantError(`Invalid string value for '${field}': ${String(value)}.`); +} + +function formatNySessionDateFromMicros(tsUs: bigint): string { + const epochMs = Number(tsUs / 1000n); + if (!Number.isSafeInteger(epochMs)) { + throw new VerifyM2QuantError(`Out-of-range QuestDB timestamp micros: ${tsUs.toString()}.`); + } + const formatted = NY_DATE_FORMATTER.format(new Date(epochMs)); + if (!DATE_ONLY_RE.test(formatted)) { + throw new VerifyM2QuantError(`Unexpected America/New_York session date format: '${formatted}'.`); + } + return formatted; +} + +function addUtcDays(isoDate: string, deltaDays: number): string { + const parts = isoDate.split('-').map(Number); + const year = parts[0] as number; + const month = parts[1] as number; + const day = parts[2] as number; + const ms = Date.UTC(year, month - 1, day + deltaDays); + return new Date(ms).toISOString().slice(0, 10); +} + +function computeBarsDigest(bars: readonly BarRecord[]): string { + const hash = createHash('sha256'); + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i] as BarRecord; + hash.update( + `${bar.listingId},${bar.ts},${bar.open},${bar.high},${bar.low},${bar.close},${bar.volume},${bar.vwap ?? ''},${bar.knownAt}\n` + ); + } + return hash.digest('hex'); +} + +function computeMedian(values: readonly number[]): number { + const sorted = [...values].sort((a, b) => a - b); + const mid = Math.floor(sorted.length / 2); + if (sorted.length % 2 === 1) { + return sorted[mid] as number; + } + return ((sorted[mid - 1] as number) + (sorted[mid] as number)) / 2; +} + +function describeSafeQuestDbTarget(config: QuestDbPgExecutorConfig): string { + if (config.url !== undefined) { + try { + const parsed = new URL(config.url); + const port = parsed.port || '8812'; + return `${parsed.hostname}:${port}`; + } catch { + return '[redacted-url]'; + } + } + return `${config.host ?? 'localhost'}:${config.port ?? 8812}`; +} + +async function waitForHealthyWalTables( + executor: QuestDbPgQueryExecutor, + timeoutMs: number, + pollIntervalMs: number, + nowMs: () => number, + sleepMs: (ms: number) => Promise +): Promise { + const deadline = nowMs() + timeoutMs; + const sql = + "SELECT name, suspended, writerTxn, sequencerTxn FROM wal_tables() WHERE name IN ('bars_1m', 'fx_1m', 'bar_revisions') ORDER BY name"; + + while (true) { + const res = await executor.query(sql); + const byName = new Map< + M2IntradayTableName, + { suspended: boolean; writerTxn: bigint; sequencerTxn: bigint } + >(); + + for (const row of res.rows) { + const name = parseRequiredStringCell(row.name, 'wal_tables.name'); + if (!(M2_INTRADAY_TABLE_NAMES as readonly string[]).includes(name)) { + continue; + } + const suspended = parseBooleanCell(row.suspended, `${name}.suspended`); + const writerTxn = parseBigIntCell( + row.writerTxn ?? row.writertxn, + `${name}.writerTxn` + ); + const sequencerTxn = parseBigIntCell( + row.sequencerTxn ?? row.sequencertxn, + `${name}.sequencerTxn` + ); + byName.set(name as M2IntradayTableName, { suspended, writerTxn, sequencerTxn }); + } + + const missing = M2_INTRADAY_TABLE_NAMES.filter(name => !byName.has(name)); + if (missing.length > 0) { + throw new VerifyM2QuantError( + `Missing required M2 WAL tables in wal_tables(): ${missing.join(', ')}.` + ); + } + + const suspendedTables = M2_INTRADAY_TABLE_NAMES.filter( + name => byName.get(name)?.suspended === true + ); + if (suspendedTables.length > 0) { + throw new VerifyM2QuantError( + `Suspended QuestDB WAL table(s) detected: ${suspendedTables.join(', ')}.` + ); + } + + const unsettled = M2_INTRADAY_TABLE_NAMES.filter(name => { + const status = byName.get(name)!; + return status.writerTxn < status.sequencerTxn; + }); + + if (unsettled.length === 0) { + return M2_INTRADAY_TABLE_NAMES.map(name => { + const status = byName.get(name)!; + return { + name, + suspended: status.suspended, + writerTxn: status.writerTxn.toString(), + sequencerTxn: status.sequencerTxn.toString(), + }; + }); + } + + if (nowMs() >= deadline) { + const details = unsettled + .map(name => { + const status = byName.get(name)!; + return `${name}(writerTxn=${status.writerTxn.toString()} { + const sql = + 'SELECT source, count() AS row_count, min(close) AS min_close, max(close) AS max_close, ' + + 'CAST(min(ts) AS LONG) AS min_ts_us, CAST(max(ts) AS LONG) AS max_ts_us ' + + 'FROM bars_1m GROUP BY source ORDER BY source'; + const res = await executor.query(sql); + if (res.rows.length === 0) { + throw new VerifyM2QuantError('QuestDB bars_1m contains zero rows.'); + } + + const out: Bars1mSourceSummaryRow[] = []; + let totalRows = 0; + for (const row of res.rows) { + const source = parseRequiredStringCell(row.source, 'bars_1m.source'); + const rowCount = Number(parseBigIntCell(row.row_count, `bars_1m[${source}].row_count`)); + if (!Number.isSafeInteger(rowCount) || rowCount <= 0) { + throw new VerifyM2QuantError(`QuestDB bars_1m source '${source}' has non-positive row_count: ${rowCount}.`); + } + const minClose = parseFiniteNumberCell(row.min_close, `bars_1m[${source}].min_close`); + const maxClose = parseFiniteNumberCell(row.max_close, `bars_1m[${source}].max_close`); + if (minClose <= 0 || maxClose <= 0 || minClose > maxClose) { + throw new VerifyM2QuantError( + `QuestDB bars_1m source '${source}' has invalid close bounds [${minClose}, ${maxClose}].` + ); + } + const minTsUs = parseBigIntCell(row.min_ts_us, `bars_1m[${source}].min_ts_us`); + const maxTsUs = parseBigIntCell(row.max_ts_us, `bars_1m[${source}].max_ts_us`); + if (minTsUs > maxTsUs) { + throw new VerifyM2QuantError( + `QuestDB bars_1m source '${source}' has inverted timestamp range [${minTsUs.toString()}, ${maxTsUs.toString()}].` + ); + } + totalRows += rowCount; + out.push({ + source, + rowCount, + minClose, + maxClose, + minTsUs: minTsUs.toString(), + maxTsUs: maxTsUs.toString(), + }); + } + + if (totalRows <= 0) { + throw new VerifyM2QuantError('QuestDB bars_1m total row count is zero.'); + } + + return out; +} + +async function verifyFx1mCommits( + executor: QuestDbPgQueryExecutor +): Promise { + const sql = + 'SELECT pair, source, count() AS row_count, min(close) AS min_close, max(close) AS max_close, ' + + 'CAST(min(ts) AS LONG) AS min_ts_us, CAST(max(ts) AS LONG) AS max_ts_us ' + + 'FROM fx_1m GROUP BY pair, source ORDER BY pair, source'; + const res = await executor.query(sql); + if (res.rows.length === 0) { + throw new VerifyM2QuantError('QuestDB fx_1m contains zero rows.'); + } + + const out: Fx1mPairSourceSummaryRow[] = []; + let totalRows = 0; + for (const row of res.rows) { + const pair = parseRequiredStringCell(row.pair, 'fx_1m.pair'); + const source = parseRequiredStringCell(row.source, 'fx_1m.source'); + const rowCount = Number(parseBigIntCell(row.row_count, `fx_1m[${pair}/${source}].row_count`)); + if (!Number.isSafeInteger(rowCount) || rowCount <= 0) { + throw new VerifyM2QuantError( + `QuestDB fx_1m group '${pair}/${source}' has non-positive row_count: ${rowCount}.` + ); + } + const minClose = parseFiniteNumberCell(row.min_close, `fx_1m[${pair}/${source}].min_close`); + const maxClose = parseFiniteNumberCell(row.max_close, `fx_1m[${pair}/${source}].max_close`); + if (minClose <= 0 || maxClose <= 0 || minClose > maxClose) { + throw new VerifyM2QuantError( + `QuestDB fx_1m group '${pair}/${source}' has invalid close bounds [${minClose}, ${maxClose}].` + ); + } + const minTsUs = parseBigIntCell(row.min_ts_us, `fx_1m[${pair}/${source}].min_ts_us`); + const maxTsUs = parseBigIntCell(row.max_ts_us, `fx_1m[${pair}/${source}].max_ts_us`); + if (minTsUs > maxTsUs) { + throw new VerifyM2QuantError( + `QuestDB fx_1m group '${pair}/${source}' has inverted timestamp range [${minTsUs.toString()}, ${maxTsUs.toString()}].` + ); + } + totalRows += rowCount; + out.push({ + pair, + source, + rowCount, + minClose, + maxClose, + minTsUs: minTsUs.toString(), + maxTsUs: maxTsUs.toString(), + }); + } + + if (totalRows <= 0) { + throw new VerifyM2QuantError('QuestDB fx_1m total row count is zero.'); + } + + return out; +} + +async function verifySplitBoundaryCase( + spec: SplitBoundaryCaseSpec, + listingId: number, + questExecutor: QuestDbPgQueryExecutor, + duckExecutor: ClosableDuckDbExecutor, + curatedRoot: string +): Promise { + const fromUtcIso = `${spec.fromDate}T00:00:00.000Z`; + const toUtcIso = `${addUtcDays(spec.toDate, 1)}T05:00:00.000Z`; + + const qdbSql = + "SELECT CAST(ts AS LONG) AS ts_us, close FROM bars_1m WHERE listing_id = $1 AND session = 'RTH' AND ts >= $2 AND ts <= $3 ORDER BY ts ASC"; + const qdbRes = await questExecutor.query(qdbSql, [String(listingId), fromUtcIso, toUtcIso]); + + const latestClose1mByDate = new Map(); + for (const row of qdbRes.rows) { + const tsUs = parseBigIntCell(row.ts_us, `${spec.label}.bars_1m.ts_us`); + const close = parseFiniteNumberCell(row.close, `${spec.label}.bars_1m.close`); + if (close <= 0) { + throw new VerifyM2QuantError( + `${spec.label} bars_1m returned non-positive close (${close}) at ts_us=${tsUs.toString()}.` + ); + } + const nyDate = formatNySessionDateFromMicros(tsUs); + if (nyDate < spec.fromDate || nyDate > spec.toDate) { + continue; + } + const prev = latestClose1mByDate.get(nyDate); + if (prev === undefined || tsUs >= prev.tsUs) { + latestClose1mByDate.set(nyDate, { tsUs, close }); + } + } + + const bars1dPath = `${curatedRoot}/bars_1d/year=*/part.parquet`; + const duckSql = + 'SELECT CAST(session_date AS VARCHAR) AS session_date, close ' + + `FROM read_parquet('${bars1dPath}', hive_partitioning = true) ` + + 'WHERE listing_id = ? AND session_date >= CAST(? AS DATE) AND session_date <= CAST(? AS DATE) ' + + 'ORDER BY session_date ASC'; + const duckRows = await duckExecutor.query(duckSql, [listingId, spec.fromDate, spec.toDate]); + + const close1dByDate = new Map(); + for (const row of duckRows) { + const sessionDate = parseRequiredStringCell(row.session_date, `${spec.label}.bars_1d.session_date`); + const close = parseFiniteNumberCell(row.close, `${spec.label}.bars_1d.close`); + if (close <= 0) { + throw new VerifyM2QuantError( + `${spec.label} bars_1d returned non-positive close (${close}) on ${sessionDate}.` + ); + } + close1dByDate.set(sessionDate, close); + } + + const matchedDates = Array.from(latestClose1mByDate.keys()) + .filter(date => close1dByDate.has(date)) + .sort(); + + const sessions: SplitBoundarySessionComparison[] = []; + let preSplitCount = 0; + let exOrPostSplitCount = 0; + let maxRelDiff = 0; + + for (const sessionDate of matchedDates) { + const close1m = latestClose1mByDate.get(sessionDate)!.close; + const close1d = close1dByDate.get(sessionDate)!; + const relDiff = Math.abs(close1m - close1d) / close1d; + const phase: 'pre_split' | 'ex_or_post_split' = + sessionDate < spec.exDate ? 'pre_split' : 'ex_or_post_split'; + if (phase === 'pre_split') { + preSplitCount += 1; + } else { + exOrPostSplitCount += 1; + } + if (relDiff > maxRelDiff) { + maxRelDiff = relDiff; + } + if (relDiff > MAX_SPLIT_CLOSE_REL_DIFF) { + throw new VerifyM2QuantError( + `${spec.label} split-boundary close mismatch on ${sessionDate}: bars_1m=${close1m}, bars_1d=${close1d}, relDiff=${(relDiff * 100).toFixed(4)}% > ${(MAX_SPLIT_CLOSE_REL_DIFF * 100).toFixed(2)}%.` + ); + } + sessions.push({ sessionDate, phase, close1m, close1d, relDiff }); + } + + if (preSplitCount < 1) { + throw new VerifyM2QuantError( + `${spec.label} split-boundary check requires >= 1 matched pre-split session before ${spec.exDate} (found ${preSplitCount}).` + ); + } + if (exOrPostSplitCount < 1) { + throw new VerifyM2QuantError( + `${spec.label} split-boundary check requires >= 1 matched ex-date/post-split session on/after ${spec.exDate} (found ${exOrPostSplitCount}).` + ); + } + + return { + label: spec.label, + listingId, + fromDate: spec.fromDate, + toDate: spec.toDate, + exDate: spec.exDate, + ratio: spec.ratio, + preSplitCount, + exOrPostSplitCount, + maxRelDiff, + sessions, + }; +} + +async function runIntradayLatencyBenchmark( + parsed: ParsedVerifyM2QuantRun, + openStore: ( + config: ResearchCopilotHostConfig, + options?: OpenResearchCopilotStoreOptions + ) => Promise, + perfNowMs: () => number +): Promise { + // Pre-validate Vault fence with vaultOperatorAuthorized: false so violations + // fail closed deterministically even before opening a store handle. + const fence = applyVaultFence( + { + from: parsed.benchFrom, + to: parsed.benchTo, + asOf: parsed.benchAsOf, + scope: parsed.benchScope, + }, + { + vaultCutoffTs: parsed.vaultCutoffTs, + vaultOperatorAuthorized: false, + } + ); + + const hostConfig: ResearchCopilotHostConfig = { + postgresUrl: 'postgres://unused@127.0.0.1:5433/unused', + curatedRoot: parsed.curatedRoot, + vaultCutoffTs: parsed.vaultCutoffTs, + principalId: 'agent:00000000-0000-4000-8000-000000000000', + libraryRoot: parsed.curatedRoot, + referenceListingIds: { US: parsed.benchListingId }, + questdb: parsed.questdb, + }; + + const handle = await openStore(hostConfig); + try { + const query = { + listingIds: [parsed.benchListingId], + timeframe: '1m' as const, + from: parsed.benchFrom, + to: parsed.benchTo, + adjustment: 'raw' as const, + asOf: parsed.benchAsOf, + scope: parsed.benchScope, + }; + + const verifyBars = (bars: readonly BarRecord[], runLabel: string): string => { + if (bars.length === 0) { + throw new VerifyM2QuantError( + `Intraday 1m benchmark (${runLabel}) returned 0 rows for listing ${parsed.benchListingId}.` + ); + } + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i] as BarRecord; + if (bar.ts >= parsed.vaultCutoffTs) { + throw new VerifyM2QuantError( + `Intraday 1m benchmark (${runLabel}) returned post-Vault bar ts=${bar.ts} >= vaultCutoffTs=${parsed.vaultCutoffTs}.` + ); + } + if (bar.knownAt > fence.asOfMs) { + throw new VerifyM2QuantError( + `Intraday 1m benchmark (${runLabel}) returned future-known bar knownAt=${bar.knownAt} > asOfMs=${fence.asOfMs}.` + ); + } + } + return computeBarsDigest(bars); + }; + + const coldStart = perfNowMs(); + const coldBars = await collectBars(handle.store.bars(query)); + const coldMs = perfNowMs() - coldStart; + const coldDigest = verifyBars(coldBars, 'cold'); + + if (!(coldMs < MAX_COLD_READ_MS)) { + throw new VerifyM2QuantError( + `Cold 1y 1m PGWire read exceeded threshold: ${coldMs.toFixed(2)}ms >= ${MAX_COLD_READ_MS}ms.` + ); + } + + const warmRuns: number[] = []; + for (let runIdx = 0; runIdx < parsed.warmRuns; runIdx += 1) { + const warmStart = perfNowMs(); + const warmBars = await collectBars(handle.store.bars(query)); + const warmMs = perfNowMs() - warmStart; + const warmDigest = verifyBars(warmBars, `warm#${runIdx + 1}`); + + if (warmBars.length !== coldBars.length || warmDigest !== coldDigest) { + throw new VerifyM2QuantError( + `Warm 1y 1m PGWire read #${runIdx + 1} diverged from cold baseline (rows ${warmBars.length} vs ${coldBars.length}, digest ${warmDigest} vs ${coldDigest}).` + ); + } + if (!(warmMs < MAX_WARM_READ_MS)) { + throw new VerifyM2QuantError( + `Warm 1y 1m PGWire read #${runIdx + 1} exceeded threshold: ${warmMs.toFixed(2)}ms >= ${MAX_WARM_READ_MS}ms.` + ); + } + warmRuns.push(warmMs); + } + + const minWarmMs = Math.min(...warmRuns); + const maxWarmMs = Math.max(...warmRuns); + const medianWarmMs = computeMedian(warmRuns); + + return { + listingId: parsed.benchListingId, + from: parsed.benchFrom, + to: parsed.benchTo, + asOf: parsed.benchAsOf, + scope: parsed.benchScope, + rowCount: coldBars.length, + digest: coldDigest, + coldMs, + warmRuns, + minWarmMs, + medianWarmMs, + maxWarmMs, + thresholds: { + maxColdMs: MAX_COLD_READ_MS, + maxWarmMs: MAX_WARM_READ_MS, + }, + }; + } finally { + await handle.close(); + } +} + +async function defaultWriteReportFile(path: string, content: string): Promise { + await mkdir(dirname(path), { recursive: true }); + await writeFile(path, content, 'utf8'); +} + +function defaultSleepMs(ms: number): Promise { + return new Promise(resolveSleep => { + setTimeout(resolveSleep, ms); + }); +} + +/** + * Runs the QuestDB/DuckDB M2 verification CLI with injectable I/O, executors, + * store factory, and clocks for deterministic offline testing. + */ +export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Promise { + const argv = deps.argv ?? process.argv.slice(2); + const stdout = deps.stdout ?? process.stdout; + const stderr = deps.stderr ?? process.stderr; + const secretNeedles = collectArgvSecretNeedles(argv); + + const writeRedactedError = (prefix: string, err: unknown): void => { + const raw = err instanceof Error ? err.message : String(err); + const safe = sanitizeSingleLine(redactSecrets(raw, secretNeedles)); + stderr.write(`${prefix}: ${safe}\n`); + }; + + let parsed: ParsedVerifyM2QuantArgs; + try { + parsed = parseVerifyM2QuantArgs(argv, { + ...(deps.cwd !== undefined ? { cwd: deps.cwd } : {}), + }); + } catch (err: unknown) { + writeRedactedError('Invalid arguments', err); + return 1; + } + + if (parsed.kind === 'help') { + stdout.write(VERIFY_M2_QUANT_USAGE); + return 0; + } + + const openPg = deps.openQuestDbPgExecutor ?? openQuestDbPgExecutor; + const applyDdlFn = deps.applyM2IntradayDDL ?? applyM2IntradayDDL; + const createDuck = deps.createDuckDbExecutor ?? (() => createNodeDuckDbExecutor()); + const openStore = deps.openResearchCopilotStore ?? openResearchCopilotStore; + const writeReportFile = deps.writeReportFile ?? defaultWriteReportFile; + const nowMs = deps.nowMs ?? Date.now; + const perfNowMs = deps.perfNowMs ?? (() => performance.now()); + const sleepMs = deps.sleepMs ?? defaultSleepMs; + const walPollIntervalMs = deps.walPollIntervalMs ?? DEFAULT_WAL_POLL_INTERVAL_MS; + + try { + let ddlResult: { readonly applied: boolean; readonly appliedTables: readonly M2IntradayTableName[] } = + { applied: false, appliedTables: [] }; + let walTables: readonly WalTableStatusRow[]; + let bars1mSummary: readonly Bars1mSourceSummaryRow[]; + let fx1mSummary: readonly Fx1mPairSourceSummaryRow[]; + 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, + walPollIntervalMs, + nowMs, + sleepMs + ); + bars1mSummary = await verifyBars1mCommits(pgHandle.executor); + fx1mSummary = await verifyFx1mCommits(pgHandle.executor); + + const duckExecutor = await createDuck(); + try { + const listingIdByLabel: Record<'NVDA.US' | 'NEXM.V', number> = { + 'NVDA.US': parsed.nvdaListingId, + 'NEXM.V': parsed.nexmListingId, + }; + for (const spec of M2_SPLIT_BOUNDARY_CASES) { + splitChecks.push( + await verifySplitBoundaryCase( + spec, + listingIdByLabel[spec.label], + pgHandle.executor, + duckExecutor, + parsed.curatedRoot + ) + ); + } + } finally { + await duckExecutor.close(); + } + } finally { + await pgHandle.close(); + } + + const benchmark = await runIntradayLatencyBenchmark(parsed, openStore, perfNowMs); + + const report: VerifyM2QuantReport = { + ok: true, + target: { + questdb: describeSafeQuestDbTarget(parsed.questdb), + curatedRoot: parsed.curatedRoot, + vaultCutoffTs: parsed.vaultCutoffIso, + }, + ddl: ddlResult, + walTables, + bars1mSummary, + fx1mSummary, + splitChecks, + benchmark, + }; + + const json = `${JSON.stringify(report, null, 2)}\n`; + if (parsed.outPath !== undefined) { + await writeReportFile(parsed.outPath, json); + } + stdout.write(`${JSON.stringify(report)}\n`); + return 0; + } catch (err: unknown) { + writeRedactedError('M2 quant verification failed', err); + return 1; + } +} + +if (import.meta.main) { + process.exitCode = await runVerifyM2QuantCli(); +}