From 87ae19e5f955c55b3ad411d3380c7e673a2ac533 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 5 Dec 2026 22:02:21 -0500 Subject: [PATCH] =?UTF-8?q?T-215:=20M2.5=20=E2=80=94=20Execute=20host/quan?= =?UTF-8?q?t=20M2=20preflight,=20observed=20split-boundary=20&=20latency?= =?UTF-8?q?=20checks,=20and=20desktop=20Claude=20Code=20EC-1=20sign-off?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/test/verify-m2-quant.test.ts | 526 +++++++++++++++++++++--- scripts/verify-m2-quant.ts | 591 +++++++++++++++++++++------ 2 files changed, 922 insertions(+), 195 deletions(-) diff --git a/scripts/test/verify-m2-quant.test.ts b/scripts/test/verify-m2-quant.test.ts index 1aaf8114..cb97a036 100644 --- a/scripts/test/verify-m2-quant.test.ts +++ b/scripts/test/verify-m2-quant.test.ts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto'; import { describe, expect, test } from 'bun:test'; import type { ClosableDuckDbExecutor } from '@stock-bot/duckdb'; import { @@ -10,6 +11,9 @@ import { import type { BarBatch, BarRecord, MarketDataStore, TableRow } from '@stock-bot/research'; import type { ManagedMarketDataStore, ResearchCopilotHostConfig } from '@stock-bot/research/mcp'; import { + BARS_1M_SOURCE_EOD, + BARS_1M_SOURCE_QM, + FX_1M_SOURCE_EOD, MAX_COLD_READ_MS, MAX_WARM_READ_MS, MIN_ONE_YEAR_WINDOW_MS, @@ -61,6 +65,142 @@ function isoToMicros(iso: string): string { return (BigInt(Date.parse(iso)) * 1000n).toString(); } +/** + * Encodes a binary `0x10` IEEE-754 double field matching `tools/curate-etl/src/ilp.rs` + * (`write_binary_f64`: `==\x10<8-byte LE f64>`). + */ +function encodeIlpBinaryDouble(name: string, value: number): Buffer { + const prefix = Buffer.from(`${name}==`, 'utf8'); + const typeTag = Buffer.from([0x10]); + const f64 = Buffer.alloc(8); + f64.writeDoubleLE(value, 0); + return Buffer.concat([prefix, typeTag, f64]); +} + +/** + * Encodes a canonical `bars_1m` ILP v2 line matching `tools/curate-etl/src/ilp.rs::encode_bar_1m` + * using the ETL's canonical source labels (`eod_unadj` / `qm_raw`). + */ +function encodeCanonicalIlpBar1mLine(row: { + readonly listingId: number; + readonly session: 'PRE' | 'RTH' | 'POST'; + readonly source: typeof BARS_1M_SOURCE_EOD | typeof BARS_1M_SOURCE_QM; + readonly open: number; + readonly high: number; + readonly low: number; + readonly close: number; + readonly volume: number; + readonly knownAtUs: string; + readonly tsUs: string; +}): Buffer { + const header = Buffer.from( + `bars_1m,listing_id=${row.listingId},session=${row.session},source=${row.source} `, + 'utf8' + ); + const comma = Buffer.from(',', 'utf8'); + const tail = Buffer.from(`,known_at=${row.knownAtUs}t ${row.tsUs}t\n`, 'utf8'); + return Buffer.concat([ + header, + encodeIlpBinaryDouble('open', row.open), + comma, + encodeIlpBinaryDouble('high', row.high), + comma, + encodeIlpBinaryDouble('low', row.low), + comma, + encodeIlpBinaryDouble('close', row.close), + comma, + encodeIlpBinaryDouble('volume', row.volume), + tail, + ]); +} + +/** + * Encodes a canonical `fx_1m` ILP v2 line matching `tools/curate-etl/src/ilp.rs::encode_fx_1m` + * using `curate_fx_1m.rs`'s canonical source label (`eod`). + */ +function encodeCanonicalIlpFx1mLine(row: { + readonly pair: string; + readonly source: typeof FX_1M_SOURCE_EOD; + readonly open: number; + readonly high: number; + readonly low: number; + readonly close: number; + readonly tsUs: string; +}): Buffer { + const header = Buffer.from(`fx_1m,pair=${row.pair},source=${row.source} `, 'utf8'); + const comma = Buffer.from(',', 'utf8'); + const tail = Buffer.from(` ${row.tsUs}t\n`, 'utf8'); + return Buffer.concat([ + header, + encodeIlpBinaryDouble('open', row.open), + comma, + encodeIlpBinaryDouble('high', row.high), + comma, + encodeIlpBinaryDouble('low', row.low), + comma, + encodeIlpBinaryDouble('close', row.close), + tail, + ]); +} + +function sha256Buf(buf: Buffer): string { + return createHash('sha256').update(buf).digest('hex'); +} + +const EOD_SHARD_BYTES = encodeCanonicalIlpBar1mLine({ + listingId: NVDA_LISTING_ID, + session: 'RTH', + source: BARS_1M_SOURCE_EOD, + open: 121.5, + high: 121.9, + low: 121.4, + close: 121.79, + volume: 45_000, + knownAtUs: KNOWN_AT_US, + tsUs: EOD_PROBE_TS_US, +}); + +const QM_SHARD_BYTES = Buffer.concat([ + encodeCanonicalIlpBar1mLine({ + listingId: NEXM_LISTING_ID, + session: 'RTH', + source: BARS_1M_SOURCE_QM, + open: 7.98, + high: 8.05, + low: 7.95, + close: 8.02, + volume: 12_500, + knownAtUs: KNOWN_AT_US, + tsUs: QM_PROBE_TS_US, + }), + encodeCanonicalIlpBar1mLine({ + listingId: OVERLAP_LISTING_ID, + session: 'RTH', + source: BARS_1M_SOURCE_QM, + open: 4.2, + high: 4.3, + low: 4.18, + close: 4.25, + volume: 8_000, + knownAtUs: KNOWN_AT_US, + tsUs: OVERLAP_PROBE_TS_US, + }), +]); + +const FX_SHARD_BYTES = encodeCanonicalIlpFx1mLine({ + pair: 'USDCAD', + source: FX_1M_SOURCE_EOD, + open: 1.376, + high: 1.377, + low: 1.3755, + close: 1.3765, + tsUs: FX_PROBE_TS_US, +}); + +const EOD_SHARD_SHA256 = sha256Buf(EOD_SHARD_BYTES); +const QM_SHARD_SHA256 = sha256Buf(QM_SHARD_BYTES); +const FX_SHARD_SHA256 = sha256Buf(FX_SHARD_BYTES); + function baseArgs(overrides: Record = {}): string[] { const defaults: Record = { '--questdb-host': '10.0.0.51', @@ -90,41 +230,45 @@ function baseArgs(overrides: Record = {}): string[] { 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: { + shardSha256: [EOD_SHARD_SHA256], + beforeWal: { writerTxn: '100', sequencerTxn: '100' }, + afterWal: { writerTxn: '112', sequencerTxn: '112' }, probes: [ { listingId: NVDA_LISTING_ID, tsUs: EOD_PROBE_TS_US, expectedClose: 121.79, - expectedSource: 'eod', + expectedSource: BARS_1M_SOURCE_EOD, expectedKnownAtUs: KNOWN_AT_US, }, ], }, bars_1m_qm: { + shardSha256: [QM_SHARD_SHA256], + beforeWal: { writerTxn: '112', sequencerTxn: '112' }, + afterWal: { writerTxn: '120', sequencerTxn: '120' }, probes: [ { listingId: NEXM_LISTING_ID, tsUs: QM_PROBE_TS_US, expectedClose: 8.02, - expectedSource: 'qm', + expectedSource: BARS_1M_SOURCE_QM, expectedKnownAtUs: KNOWN_AT_US, }, ], }, fx_1m: { + shardSha256: [FX_SHARD_SHA256], + beforeWal: { writerTxn: '30', sequencerTxn: '30' }, + afterWal: { writerTxn: '45', sequencerTxn: '45' }, probes: [ { pair: 'USDCAD', tsUs: FX_PROBE_TS_US, expectedClose: 1.3765, - expectedSource: 'eod', + expectedSource: FX_1M_SOURCE_EOD, }, ], }, @@ -133,13 +277,13 @@ function defaultLoadReceipt(): M2LoadReceipt { eodSentRows: 500_500, qmSentRows: 25_000, overlapRows: 500, - overlapWinnerSource: 'qm', + overlapWinnerSource: BARS_1M_SOURCE_QM, overlapProbes: [ { listingId: OVERLAP_LISTING_ID, tsUs: OVERLAP_PROBE_TS_US, expectedClose: 4.25, - expectedSource: 'qm', + expectedSource: BARS_1M_SOURCE_QM, expectedKnownAtUs: KNOWN_AT_US, }, ], @@ -147,6 +291,30 @@ function defaultLoadReceipt(): M2LoadReceipt { }; } +function defaultResendLoadReceipt(): M2LoadReceipt { + const base = defaultLoadReceipt(); + return { + ...base, + shards: { + bars_1m: { + ...base.shards.bars_1m, + beforeWal: { writerTxn: '120', sequencerTxn: '120' }, + afterWal: { writerTxn: '180', sequencerTxn: '180' }, + }, + bars_1m_qm: { + ...base.shards.bars_1m_qm, + beforeWal: { writerTxn: '180', sequencerTxn: '180' }, + afterWal: { writerTxn: '240', sequencerTxn: '240' }, + }, + fx_1m: { + ...base.shards.fx_1m, + beforeWal: { writerTxn: '45', sequencerTxn: '45' }, + afterWal: { writerTxn: '90', sequencerTxn: '90' }, + }, + }, + }; +} + function defaultBars1mProbeMap(): Map[]> { return new Map[]>([ [ @@ -156,7 +324,7 @@ function defaultBars1mProbeMap(): Map[] listing_id: String(NVDA_LISTING_ID), ts_us: EOD_PROBE_TS_US, close: 121.79, - source: 'eod', + source: BARS_1M_SOURCE_EOD, known_at_us: KNOWN_AT_US, }, ], @@ -168,7 +336,7 @@ function defaultBars1mProbeMap(): Map[] listing_id: String(NEXM_LISTING_ID), ts_us: QM_PROBE_TS_US, close: 8.02, - source: 'qm', + source: BARS_1M_SOURCE_QM, known_at_us: KNOWN_AT_US, }, ], @@ -180,7 +348,7 @@ function defaultBars1mProbeMap(): Map[] listing_id: String(OVERLAP_LISTING_ID), ts_us: OVERLAP_PROBE_TS_US, close: 4.25, - source: 'qm', + source: BARS_1M_SOURCE_QM, known_at_us: KNOWN_AT_US, }, ], @@ -197,7 +365,7 @@ function defaultFx1mProbeMap(): Map[]> pair: 'USDCAD', ts_us: FX_PROBE_TS_US, close: 1.3765, - source: 'eod', + source: FX_1M_SOURCE_EOD, }, ], ], @@ -208,6 +376,8 @@ interface MockFixtureOptions { readonly walSequence?: readonly (readonly Record[])[]; readonly bars1mSummaryRows?: readonly Record[]; readonly fx1mSummaryRows?: readonly Record[]; + readonly bars1mDigestRows?: readonly Record[]; + readonly fx1mDigestRows?: readonly Record[]; readonly bars1mProbeRows?: Map[]>; readonly fx1mProbeRows?: Map[]>; readonly nvda1mRows?: readonly Record[]; @@ -233,7 +403,7 @@ function defaultWalRows(): readonly Record[] { function defaultBars1mSummaryRows(): readonly Record[] { return [ { - source: 'eod', + source: BARS_1M_SOURCE_EOD, row_count: '500000', min_close: 0.42, max_close: 1210.5, @@ -241,7 +411,7 @@ function defaultBars1mSummaryRows(): readonly Record[] { max_ts_us: isoToMicros('2025-06-23T20:00:00Z'), }, { - source: 'qm', + source: BARS_1M_SOURCE_QM, row_count: '25000', min_close: 0.15, max_close: 24.5, @@ -255,7 +425,7 @@ function defaultFx1mSummaryRows(): readonly Record[] { return [ { pair: 'USDCAD', - source: 'eod', + source: FX_1M_SOURCE_EOD, row_count: '380000', min_close: 1.31, max_close: 1.45, @@ -265,6 +435,61 @@ function defaultFx1mSummaryRows(): readonly Record[] { ]; } +function defaultBars1mDigestRows(): readonly Record[] { + return [ + { + source: BARS_1M_SOURCE_EOD, + utc_day: '19884', + row_count: '500000', + sum_open: 60_500_000.0, + sum_high: 60_750_000.0, + sum_low: 60_250_000.0, + sum_close: 60_600_000.0, + sum_volume: 9_500_000_000.0, + sum_close_sq: 7_345_000_000.0, + 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: BARS_1M_SOURCE_QM, + utc_day: '20259', + row_count: '25000', + sum_open: 150_000.0, + sum_high: 152_000.0, + sum_low: 148_000.0, + sum_close: 150_500.0, + sum_volume: 300_000_000.0, + sum_close_sq: 906_010.0, + 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 defaultFx1mDigestRows(): readonly Record[] { + return [ + { + pair: 'USDCAD', + source: FX_1M_SOURCE_EOD, + utc_day: '19884', + row_count: '380000', + sum_open: 522_500.0, + sum_high: 522_800.0, + sum_low: 522_200.0, + sum_close: 522_600.0, + sum_close_sq: 718_712.5, + 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. @@ -365,6 +590,8 @@ function createHarness( const walSeq = options.walSequence ?? [defaultWalRows()]; const bars1mSummary = options.bars1mSummaryRows ?? defaultBars1mSummaryRows(); const fx1mSummary = options.fx1mSummaryRows ?? defaultFx1mSummaryRows(); + const bars1mDigest = options.bars1mDigestRows ?? defaultBars1mDigestRows(); + const fx1mDigest = options.fx1mDigestRows ?? defaultFx1mDigestRows(); const bars1mProbes = options.bars1mProbeRows ?? defaultBars1mProbeMap(); const fx1mProbes = options.fx1mProbeRows ?? defaultFx1mProbeMap(); const nvda1m = options.nvda1mRows ?? defaultNvda1mRows(); @@ -419,6 +646,14 @@ function createHarness( state.events.push('pg:fx_1m_summary'); return { rows: fx1mSummary }; } + if (sql.includes('FROM bars_1m) GROUP BY source, utc_day')) { + state.events.push('pg:digest_bars_1m'); + return { rows: bars1mDigest }; + } + if (sql.includes('FROM fx_1m) GROUP BY pair, source, utc_day')) { + state.events.push('pg:digest_fx_1m'); + return { rows: fx1mDigest }; + } 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}`); @@ -646,26 +881,63 @@ describe('scripts/verify-m2-quant.ts', () => { 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()); + test('settles wal_tables() for expected load txns BEFORE benchmark, and keeps all bar/FX scans AFTER cold read', async () => { + const { deps, stdout, stderr, state } = createHarness(baseArgs(), { + walSequence: [ + [ + { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, + { name: 'bars_1m', suspended: false, writerTxn: '115', 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); + const lastWalIndex = state.events.lastIndexOf('pg:wal_tables'); const coldIndex = state.events.indexOf('bench:cold'); const summaryIndex = state.events.indexOf('pg:bars_1m_summary'); + const fxSummaryIndex = state.events.indexOf('pg:fx_1m_summary'); + const barsDigestIndex = state.events.indexOf('pg:digest_bars_1m'); + const fxDigestIndex = state.events.indexOf('pg:digest_fx_1m'); 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(lastWalIndex).toBe(1); + expect(coldIndex).toBe(2); expect(summaryIndex).toBeGreaterThan(coldIndex); + expect(fxSummaryIndex).toBeGreaterThan(coldIndex); + expect(barsDigestIndex).toBeGreaterThan(coldIndex); + expect(fxDigestIndex).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 () => { + test('fails closed before starting benchmark when QuestDB sequencerTxn is behind expected load receipt', async () => { + const { deps, stdout, stderr, state } = createHarness(baseArgs(), { + walSequence: [ + [ + { name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' }, + { name: 'bars_1m', suspended: false, writerTxn: '112', sequencerTxn: '112' }, + { name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' }, + ], + ], + }); + + const code = await runVerifyM2QuantCli(deps); + expect(code).toBe(1); + expect(stdout.text()).toBe(''); + assertSingleLineError(stderr.text()); + expect(stderr.text()).toContain("WAL for 'bars_1m' sequencerTxn=112 is behind expected load receipt"); + expect(state.openedStoreConfigs).toHaveLength(0); + }); + + test('passes end-to-end without --apply-ddl, records canonical sources, shard hashes, content digests, and closes all handles', async () => { const argv = [...baseArgs(), '--out', 'out/m2-quant-verify.json']; const { deps, stdout, stderr, state } = createHarness(argv); @@ -683,8 +955,16 @@ describe('scripts/verify-m2-quant.ts', () => { expect(report.ddl).toEqual({ applied: false, appliedTables: [] }); expect(report.walTables).toHaveLength(3); expect(report.bars1mSummary).toHaveLength(2); + expect(report.bars1mSummary.map(r => r.source)).toEqual([BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM]); expect(report.fx1mSummary).toHaveLength(1); - expect(report.loadVerification.walAdvancement).toHaveLength(2); + expect(report.bars1mContentDigest).toMatch(/^[0-9a-f]{64}$/); + expect(report.fx1mContentDigest).toMatch(/^[0-9a-f]{64}$/); + expect(report.loadVerification.walAdvancement).toHaveLength(3); + expect(report.loadVerification.shardHashes).toEqual({ + bars_1m: [EOD_SHARD_SHA256], + bars_1m_qm: [QM_SHARD_SHA256], + fx_1m: [FX_SHARD_SHA256], + }); expect(report.loadVerification.probesVerified).toHaveLength(4); expect(report.loadVerification.dedupAccounting.minExpectedEodRows).toBe(500_000); expect(report.loadVerification.dedupAccounting.minExpectedQmRows).toBe(25_000); @@ -715,7 +995,7 @@ describe('scripts/verify-m2-quant.ts', () => { expect(state.writtenFiles.size).toBe(1); }); - test('invokes applyM2IntradayDDL when --apply-ddl is set without scanning bars_1m before cold read', async () => { + test('invokes applyM2IntradayDDL and settles WAL 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); @@ -724,7 +1004,8 @@ describe('scripts/verify-m2-quant.ts', () => { expect(stderr.text()).toBe(''); expect(state.ddlCalls).toBe(1); expect(state.events[0]).toBe('pg:ddl'); - expect(state.events[1]).toBe('bench:cold'); + expect(state.events[1]).toBe('pg:wal_tables'); + expect(state.events[2]).toBe('bench:cold'); const report = JSON.parse(stdout.text()) as VerifyM2QuantReport; expect(report.ddl).toEqual({ @@ -733,35 +1014,82 @@ 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, + test('rejects non-canonical legacy bars_1m source labels (eod/qm) in load receipts', async () => { + const legacyReceiptRaw = JSON.stringify(defaultLoadReceipt()) + .replaceAll(BARS_1M_SOURCE_EOD, 'eod') + .replaceAll(BARS_1M_SOURCE_QM, 'qm'); + const { deps, stdout, stderr, state } = createHarness(baseArgs(), { + rawFiles: { [DEFAULT_RECEIPT_ABS_PATH]: legacyReceiptRaw }, }); 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"); + expect(stderr.text()).toContain(`must be '${BARS_1M_SOURCE_EOD}'`); + expect(state.openedPgConfigs).toHaveLength(0); + expect(state.openedStoreConfigs).toHaveLength(0); }); - 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 + test('fails closed when current QM send fails even if matching QM rows already exist and EOD/FX advanced WAL', async () => { + // Regression: EOD advanced bars_1m (100->112) and FX advanced fx_1m (30->45), + // and QuestDB already contains matching qm_raw rows from an earlier run, + // but the current bars_1m_qm send failed so its WAL did not advance (112->112). + const base = defaultLoadReceipt(); + const failedQmReceipt: M2LoadReceipt = { + ...base, + shards: { + ...base.shards, + bars_1m_qm: { + ...base.shards.bars_1m_qm, + beforeWal: { writerTxn: '112', sequencerTxn: '112' }, + afterWal: { writerTxn: '112', sequencerTxn: '112' }, + }, + }, + }; + const failedQm = createHarness(baseArgs(), { + loadReceipt: failedQmReceipt, + }); + expect(await runVerifyM2QuantCli(failedQm.deps)).toBe(1); + expect(failedQm.stdout.text()).toBe(''); + assertSingleLineError(failedQm.stderr.text()); + expect(failedQm.stderr.text()).toContain("WAL for shard prefix 'bars_1m_qm' did not advance"); + + // Overlapping bars_1m and bars_1m_qm WAL windows cannot share the same WAL advancement + const overlappingWalReceipt: M2LoadReceipt = { + ...base, + shards: { + ...base.shards, + bars_1m: { + ...base.shards.bars_1m, + beforeWal: { writerTxn: '100', sequencerTxn: '100' }, + afterWal: { writerTxn: '120', sequencerTxn: '120' }, + }, + bars_1m_qm: { + ...base.shards.bars_1m_qm, + beforeWal: { writerTxn: '100', sequencerTxn: '100' }, + afterWal: { writerTxn: '120', sequencerTxn: '120' }, + }, + }, + }; + const overlapping = createHarness(baseArgs(), { + loadReceipt: overlappingWalReceipt, + }); + expect(await runVerifyM2QuantCli(overlapping.deps)).toBe(1); + expect(overlapping.stdout.text()).toBe(''); + expect(overlapping.stderr.text()).toContain('overlapping WAL windows'); + }); + + test('fails closed when QM shard prefix is missing from bars_1m or probe key is absent', async () => { + // Missing 'qm_raw' 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'"); + expect(missingQmGroup.stderr.text()).toContain(`missing required source='${BARS_1M_SOURCE_QM}'`); - // Older 'qm' group exists, but current QM probe key is absent + // Older 'qm_raw' 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(), { @@ -777,7 +1105,7 @@ describe('scripts/verify-m2-quant.ts', () => { // 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' }, + { pair: 'USDCAD', ts_us: FX_PROBE_TS_US, close: 1.9999, source: FX_1M_SOURCE_EOD }, ]); const badFx = createHarness(baseArgs(), { fx1mProbeRows: badFxProbes }); expect(await runVerifyM2QuantCli(badFx.deps)).toBe(1); @@ -790,14 +1118,14 @@ describe('scripts/verify-m2-quant.ts', () => { listing_id: String(OVERLAP_LISTING_ID), ts_us: OVERLAP_PROBE_TS_US, close: 4.25, - source: 'qm', + source: BARS_1M_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', + source: BARS_1M_SOURCE_EOD, known_at_us: KNOWN_AT_US, }, ]); @@ -817,37 +1145,42 @@ describe('scripts/verify-m2-quant.ts', () => { 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 () => { + test('verifies idempotent resend bound to shard hashes and retained row digests, catching interior unprobed close edits', 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 resendWal = [ + { 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' }, + ]; + + // 2. Resend with same shard hashes, advanced per-prefix WAL, and identical summaries/digests passes const resendOk = createHarness( baseArgs({ '--resend-baseline': DEFAULT_RESEND_BASELINE_REL_PATH }), { + loadReceipt: defaultResendLoadReceipt(), 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' }, - ], - ], + walSequence: [resendWal], } ); 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?.shardHashesMatched).toBe(true); expect(resendReport.resendVerification?.bars1mRowCountsUnchanged).toBe(true); expect(resendReport.resendVerification?.fx1mRowCountsUnchanged).toBe(true); + expect(resendReport.resendVerification?.bars1mContentDigestMatched).toBe(true); + expect(resendReport.resendVerification?.fx1mContentDigestMatched).toBe(true); - // 3. Resend where WAL did not advance past prior baseline fails + // 3. Resend where receipt WAL predates prior baseline fails const resendStaleWal = createHarness( baseArgs({ '--resend-baseline': DEFAULT_RESEND_BASELINE_REL_PATH }), { + loadReceipt: defaultLoadReceipt(), rawFiles: { [DEFAULT_RESEND_BASELINE_ABS_PATH]: initialReportJson }, walSequence: [defaultWalRows()], } @@ -855,18 +1188,89 @@ describe('scripts/verify-m2-quant.ts', () => { 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 + // 4. Resend with a regenerated FX shard (different shard SHA-256) fails + const regeneratedFxBytes = encodeCanonicalIlpFx1mLine({ + pair: 'USDCAD', + source: FX_1M_SOURCE_EOD, + open: 1.376, + high: 1.377, + low: 1.3755, + close: 1.3766, + tsUs: FX_PROBE_TS_US, + }); + const regeneratedReceipt: M2LoadReceipt = { + ...defaultResendLoadReceipt(), + shards: { + ...defaultResendLoadReceipt().shards, + fx_1m: { + ...defaultResendLoadReceipt().shards.fx_1m, + shardSha256: [sha256Buf(regeneratedFxBytes)], + }, + }, + }; + const resendHashDrift = createHarness( + baseArgs({ '--resend-baseline': DEFAULT_RESEND_BASELINE_REL_PATH }), + { + loadReceipt: regeneratedReceipt, + rawFiles: { [DEFAULT_RESEND_BASELINE_ABS_PATH]: initialReportJson }, + walSequence: [resendWal], + } + ); + expect(await runVerifyM2QuantCli(resendHashDrift.deps)).toBe(1); + expect(resendHashDrift.stderr.text()).toContain("shard SHA-256 diverged for 'fx_1m'"); + + // 5. Regression: unprobed interior FX close edited without moving row_count, min_close, + // max_close, min_ts_us, or max_ts_us — caught by retained row content digest! + const mutatedFxDigestRows = defaultFx1mDigestRows().map(row => ({ + ...row, + sum_close: Number(row.sum_close) + 0.0025, + sum_close_sq: Number(row.sum_close_sq) + 0.0068, + })); + const resendInteriorFxDrift = createHarness( + baseArgs({ '--resend-baseline': DEFAULT_RESEND_BASELINE_REL_PATH }), + { + loadReceipt: defaultResendLoadReceipt(), + rawFiles: { [DEFAULT_RESEND_BASELINE_ABS_PATH]: initialReportJson }, + walSequence: [resendWal], + fx1mDigestRows: mutatedFxDigestRows, + } + ); + expect(await runVerifyM2QuantCli(resendInteriorFxDrift.deps)).toBe(1); + expect(resendInteriorFxDrift.stderr.text()).toContain( + 'Idempotent resend failed: fx_1m retained row content digest diverged' + ); + + // 6. Unprobed interior bars_1m close edited without moving extrema — caught by content digest! + const mutatedBarsDigestRows = defaultBars1mDigestRows().map((row, idx) => + idx === 0 + ? { + ...row, + sum_close: Number(row.sum_close) + 0.5, + sum_close_sq: Number(row.sum_close_sq) + 120.0, + } + : row + ); + const resendInteriorBarsDrift = createHarness( + baseArgs({ '--resend-baseline': DEFAULT_RESEND_BASELINE_REL_PATH }), + { + loadReceipt: defaultResendLoadReceipt(), + rawFiles: { [DEFAULT_RESEND_BASELINE_ABS_PATH]: initialReportJson }, + walSequence: [resendWal], + bars1mDigestRows: mutatedBarsDigestRows, + } + ); + expect(await runVerifyM2QuantCli(resendInteriorBarsDrift.deps)).toBe(1); + expect(resendInteriorBarsDrift.stderr.text()).toContain( + 'Idempotent resend failed: bars_1m retained row content digest diverged' + ); + + // 7. Resend where row count increased (non-idempotent duplicate rows) fails const resendRowDrift = createHarness( baseArgs({ '--resend-baseline': DEFAULT_RESEND_BASELINE_REL_PATH }), { + loadReceipt: defaultResendLoadReceipt(), 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' }, - ], - ], + walSequence: [resendWal], bars1mSummaryRows: [ { ...defaultBars1mSummaryRows()[0]!, row_count: '500001' }, defaultBars1mSummaryRows()[1]!, @@ -998,7 +1402,7 @@ describe('scripts/verify-m2-quant.ts', () => { const nanClose = createHarness(baseArgs(), { bars1mSummaryRows: [ { - source: 'eod', + source: BARS_1M_SOURCE_EOD, row_count: '500000', min_close: Number.NaN, max_close: 120.5, diff --git a/scripts/verify-m2-quant.ts b/scripts/verify-m2-quant.ts index 0d017c47..f0e7c81f 100644 --- a/scripts/verify-m2-quant.ts +++ b/scripts/verify-m2-quant.ts @@ -7,16 +7,23 @@ * `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 + * 1. Validates the load receipt (canonical ETL sources `eod_unadj`, `qm_raw`, `eod`; + * shard SHA-256 hashes; independent settled before/after WAL windows per shard + * prefix `bars_1m`, `bars_1m_qm`, `fx_1m`), optional resend baseline, and the + * Vault-fenced 1-year benchmark window (`>= 365` days after Vault clamping with + * `vaultOperatorAuthorized: false`) before any DB or store I/O. + * 2. Polls `wal_tables()` (metadata only, zero bar-table scans) until `bars_1m`, + * `fx_1m`, and `bar_revisions` are healthy, settled (`writerTxn >= sequencerTxn`), + * and have applied all expected load-receipt transactions BEFORE starting the + * timed benchmark. + * 3. Measures the 1-year single-listing `1m` PGWire cold read (`< 1000 ms`) and warm + * reads (`< 250 ms`) BEFORE any verifier query scans `bars_1m` or `fx_1m`. + * 4. Verifies non-zero finite `0x10` binary-double commits across all three shard + * prefixes (`bars_1m`, `bars_1m_qm`, `fx_1m`), exact shard-derived key/close + * probes, EOD/QM deduplication accounting, stable retained-row content digests, + * and optional idempotent resend verification (`--resend-baseline`, bound to shard + * hashes and retained-row content digests). + * 5. 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` @@ -60,6 +67,7 @@ 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 SHA256_HEX_RE = /^[0-9a-f]{64}$/; const URL_CREDENTIAL_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^:@/\s]+):([^@/\s]+)@/g; const POSTGRES_URL_RE = /postgres(?:ql)?:\/\/[^\s'"]+/gi; @@ -71,6 +79,10 @@ 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 BARS_1M_SOURCE_EOD = 'eod_unadj' as const; +export const BARS_1M_SOURCE_QM = 'qm_raw' as const; +export const FX_1M_SOURCE_EOD = 'eod' as const; +export type Bars1mSource = typeof BARS_1M_SOURCE_EOD | typeof BARS_1M_SOURCE_QM; export const REQUIRED_SHARD_PREFIXES = ['bars_1m', 'bars_1m_qm', 'fx_1m'] as const; export type RequiredShardPrefix = (typeof REQUIRED_SHARD_PREFIXES)[number]; @@ -180,17 +192,11 @@ export interface WalTxnPair { 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 expectedSource: Bars1mSource; readonly expectedKnownAtUs?: string; readonly closeTolerance?: number; } @@ -199,40 +205,49 @@ export interface Fx1mProbeExpectation { readonly pair: string; readonly tsUs: string; readonly expectedClose: number; - readonly expectedSource: string; + readonly expectedSource: typeof FX_1M_SOURCE_EOD; readonly closeTolerance?: number; } +export interface ShardPrefixLoadReceipt { + readonly shardSha256: readonly string[]; + readonly beforeWal: WalTxnPair; + readonly afterWal: WalTxnPair; + readonly probes: readonly TProbe[]; +} + export interface LoadReceiptDedupExpectation { readonly eodSentRows: number; readonly qmSentRows: number; readonly overlapRows: number; - readonly overlapWinnerSource: 'eod' | 'qm'; + readonly overlapWinnerSource: Bars1mSource; 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 bars_1m: ShardPrefixLoadReceipt; + readonly bars_1m_qm: ShardPrefixLoadReceipt; + readonly fx_1m: ShardPrefixLoadReceipt; }; readonly dedup: LoadReceiptDedupExpectation; } -export interface WalAdvancementEntry { +export interface PrefixWalAdvancementEntry { + readonly shardPrefix: RequiredShardPrefix; readonly table: 'bars_1m' | 'fx_1m'; readonly beforeWriterTxn: string; readonly afterWriterTxn: string; readonly beforeSequencerTxn: string; readonly afterSequencerTxn: string; + readonly liveWriterTxn: string; + readonly liveSequencerTxn: string; +} + +export interface ShardHashesByPrefix { + readonly bars_1m: readonly string[]; + readonly bars_1m_qm: readonly string[]; + readonly fx_1m: readonly string[]; } export interface ProbeCheckResult { @@ -246,12 +261,13 @@ export interface ProbeCheckResult { } export interface LoadReceiptVerificationResult { - readonly walAdvancement: readonly WalAdvancementEntry[]; + readonly walAdvancement: readonly PrefixWalAdvancementEntry[]; + readonly shardHashes: ShardHashesByPrefix; readonly dedupAccounting: { readonly eodSentRows: number; readonly qmSentRows: number; readonly overlapRows: number; - readonly overlapWinnerSource: 'eod' | 'qm'; + readonly overlapWinnerSource: Bars1mSource; readonly minExpectedEodRows: number; readonly minExpectedQmRows: number; readonly minExpectedTotalBars1mRows: number; @@ -264,9 +280,12 @@ export interface LoadReceiptVerificationResult { export interface ResendVerificationResult { readonly ok: true; - readonly walAdvancement: readonly WalAdvancementEntry[]; + readonly walAdvancement: readonly PrefixWalAdvancementEntry[]; + readonly shardHashesMatched: true; readonly bars1mRowCountsUnchanged: true; readonly fx1mRowCountsUnchanged: true; + readonly bars1mContentDigestMatched: true; + readonly fx1mContentDigestMatched: true; } export interface WalTableStatusRow { @@ -370,6 +389,8 @@ export interface VerifyM2QuantReport { readonly walTables: readonly WalTableStatusRow[]; readonly bars1mSummary: readonly Bars1mSourceSummaryRow[]; readonly fx1mSummary: readonly Fx1mPairSourceSummaryRow[]; + readonly bars1mContentDigest: string; + readonly fx1mContentDigest: string; readonly loadVerification: LoadReceiptVerificationResult; readonly resendVerification?: ResendVerificationResult; readonly splitChecks: readonly SplitBoundaryCheckResult[]; @@ -404,8 +425,9 @@ export const VERIFY_M2_QUANT_USAGE = [ ' --bench-from Benchmark window start (must be < --vault-cutoff-ts)', ' --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', + ' --load-receipt JSON load receipt with per-prefix (bars_1m, bars_1m_qm, fx_1m)', + ' shard SHA-256 hashes, settled beforeWal/afterWal, expected keys/closes,', + ' and EOD/QM dedup expectations', '', 'Optional options:', ' --questdb-database QuestDB PGWire database name (host/port mode)', @@ -908,12 +930,18 @@ function describeSafeQuestDbTarget(config: QuestDbPgExecutorConfig): string { return `${config.host ?? 'localhost'}:${config.port ?? 8812}`; } +interface RequiredMinWalByTable { + readonly bars_1m: WalTxnPair; + readonly fx_1m: WalTxnPair; +} + async function waitForHealthyWalTables( executor: QuestDbPgQueryExecutor, timeoutMs: number, pollIntervalMs: number, nowMs: () => number, - sleepMs: (ms: number) => Promise + sleepMs: (ms: number) => Promise, + requiredMinWal?: RequiredMinWalByTable ): Promise { const deadline = nowMs() + timeoutMs; const sql = @@ -959,9 +987,30 @@ async function waitForHealthyWalTables( ); } + if (requiredMinWal !== undefined) { + for (const table of ['bars_1m', 'fx_1m'] as const) { + const status = byName.get(table)!; + const minReqSeq = BigInt(requiredMinWal[table].sequencerTxn); + if (status.sequencerTxn < minReqSeq) { + throw new VerifyM2QuantError( + `QuestDB WAL for '${table}' sequencerTxn=${status.sequencerTxn.toString()} is behind expected load receipt sequencerTxn=${minReqSeq.toString()}.` + ); + } + } + } + const unsettled = M2_INTRADAY_TABLE_NAMES.filter(name => { const status = byName.get(name)!; - return status.writerTxn < status.sequencerTxn; + if (status.writerTxn < status.sequencerTxn) { + return true; + } + if (requiredMinWal !== undefined && (name === 'bars_1m' || name === 'fx_1m')) { + const minReqWriter = BigInt(requiredMinWal[name].writerTxn); + if (status.writerTxn < minReqWriter) { + return true; + } + } + return false; }); if (unsettled.length === 0) { @@ -980,7 +1029,11 @@ async function waitForHealthyWalTables( const details = unsettled .map(name => { const status = byName.get(name)!; - return `${name}(writerTxn=${status.writerTxn.toString()} parseSha256Hex(entry, `${field}[${idx}]`)); +} + function parseWalTxnPair(value: unknown, field: string): WalTxnPair { if (!isPlainObject(value)) { throw new VerifyM2QuantError(`Expected object for '${field}'.`); @@ -1265,10 +1335,18 @@ function parseWalTxnPair(value: unknown, field: string): WalTxnPair { }; } +function assertSettledWalPair(pair: WalTxnPair, field: string): void { + if (BigInt(pair.writerTxn) < BigInt(pair.sequencerTxn)) { + throw new VerifyM2QuantError( + `Unsettled WAL snapshot for '${field}' (writerTxn=${pair.writerTxn} < sequencerTxn=${pair.sequencerTxn}).` + ); + } +} + function parseBars1mProbe( value: unknown, field: string, - requiredSource: 'eod' | 'qm' + requiredSource: Bars1mSource ): Bars1mProbeExpectation { if (!isPlainObject(value)) { throw new VerifyM2QuantError(`Expected probe object for '${field}'.`); @@ -1320,6 +1398,11 @@ function parseFx1mProbe(value: unknown, field: string): Fx1mProbeExpectation { throw new VerifyM2QuantError(`${field}.expectedClose must be positive.`); } const expectedSource = parseRequiredStringCell(value.expectedSource, `${field}.expectedSource`); + if (expectedSource !== FX_1M_SOURCE_EOD) { + throw new VerifyM2QuantError( + `${field}.expectedSource must be '${FX_1M_SOURCE_EOD}' (received '${expectedSource}').` + ); + } let closeTolerance: number | undefined; if (value.closeTolerance !== undefined) { closeTolerance = parseFiniteNumberCell(value.closeTolerance, `${field}.closeTolerance`); @@ -1336,6 +1419,37 @@ function parseFx1mProbe(value: unknown, field: string): Fx1mProbeExpectation { }; } +function parseShardPrefixEntry( + shardsObj: Record, + prefix: RequiredShardPrefix, + parseProbe: (entry: unknown, field: string) => TProbe +): ShardPrefixLoadReceipt { + const entry = shardsObj[prefix]; + if (!isPlainObject(entry)) { + throw new VerifyM2QuantError(`Load receipt missing required object "shards.${prefix}".`); + } + const shardSha256 = parseSha256List(entry.shardSha256, `shards.${prefix}.shardSha256`); + const beforeWal = parseWalTxnPair(entry.beforeWal, `shards.${prefix}.beforeWal`); + const afterWal = parseWalTxnPair(entry.afterWal, `shards.${prefix}.afterWal`); + assertSettledWalPair(beforeWal, `shards.${prefix}.beforeWal`); + assertSettledWalPair(afterWal, `shards.${prefix}.afterWal`); + if ( + BigInt(afterWal.writerTxn) <= BigInt(beforeWal.writerTxn) || + BigInt(afterWal.sequencerTxn) <= BigInt(beforeWal.sequencerTxn) + ) { + throw new VerifyM2QuantError( + `Load receipt WAL for shard prefix '${prefix}' did not advance (before writerTxn=${beforeWal.writerTxn}/sequencerTxn=${beforeWal.sequencerTxn}, after writerTxn=${afterWal.writerTxn}/sequencerTxn=${afterWal.sequencerTxn}).` + ); + } + if (!Array.isArray(entry.probes) || entry.probes.length === 0) { + throw new VerifyM2QuantError( + `Load receipt shards.${prefix}.probes must be a non-empty array.` + ); + } + const probes = entry.probes.map((p, idx) => parseProbe(p, `shards.${prefix}.probes[${idx}]`)); + return { shardSha256, beforeWal, afterWal, probes }; +} + export function parseLoadReceiptJson(rawJson: string): M2LoadReceipt { let parsed: unknown; try { @@ -1348,44 +1462,36 @@ export function parseLoadReceiptJson(rawJson: string): M2LoadReceipt { 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 shardsObj = parsed.shards as Record; + const bars1mShard = parseShardPrefixEntry(shardsObj, 'bars_1m', (p, f) => + parseBars1mProbe(p, f, BARS_1M_SOURCE_EOD) + ); + const bars1mQmShard = parseShardPrefixEntry(shardsObj, 'bars_1m_qm', (p, f) => + parseBars1mProbe(p, f, BARS_1M_SOURCE_QM) + ); + const fx1mShard = parseShardPrefixEntry(shardsObj, 'fx_1m', (p, f) => parseFx1mProbe(p, f)); - 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}]`) - ); + // Both bars_1m and bars_1m_qm write to the QuestDB bars_1m table; require disjoint + // settled WAL windows so EOD advancement can never mask a failed/rejected QM send. + const eodBeforeW = BigInt(bars1mShard.beforeWal.writerTxn); + const eodBeforeS = BigInt(bars1mShard.beforeWal.sequencerTxn); + const eodAfterW = BigInt(bars1mShard.afterWal.writerTxn); + const eodAfterS = BigInt(bars1mShard.afterWal.sequencerTxn); + const qmBeforeW = BigInt(bars1mQmShard.beforeWal.writerTxn); + const qmBeforeS = BigInt(bars1mQmShard.beforeWal.sequencerTxn); + const qmAfterW = BigInt(bars1mQmShard.afterWal.writerTxn); + const qmAfterS = BigInt(bars1mQmShard.afterWal.sequencerTxn); + + const eodBeforeQm = qmBeforeW >= eodAfterW && qmBeforeS >= eodAfterS; + const qmBeforeEod = eodBeforeW >= qmAfterW && eodBeforeS >= qmAfterS; + if (!eodBeforeQm && !qmBeforeEod) { + throw new VerifyM2QuantError( + `Load receipt shards.bars_1m [${bars1mShard.beforeWal.writerTxn}..${bars1mShard.afterWal.writerTxn}] and shards.bars_1m_qm [${bars1mQmShard.beforeWal.writerTxn}..${bars1mQmShard.afterWal.writerTxn}] have overlapping WAL windows; send and capture each prefix separately.` + ); + } if (!isPlainObject(parsed.dedup)) { throw new VerifyM2QuantError('Load receipt missing required object "dedup".'); @@ -1402,12 +1508,15 @@ export function parseLoadReceiptJson(rawJson: string): M2LoadReceipt { parsed.dedup.overlapWinnerSource, 'dedup.overlapWinnerSource' ); - if (overlapWinnerSourceRaw !== 'eod' && overlapWinnerSourceRaw !== 'qm') { + if ( + overlapWinnerSourceRaw !== BARS_1M_SOURCE_EOD && + overlapWinnerSourceRaw !== BARS_1M_SOURCE_QM + ) { throw new VerifyM2QuantError( - `Load receipt dedup.overlapWinnerSource must be 'eod' or 'qm' (received '${overlapWinnerSourceRaw}').` + `Load receipt dedup.overlapWinnerSource must be '${BARS_1M_SOURCE_EOD}' or '${BARS_1M_SOURCE_QM}' (received '${overlapWinnerSourceRaw}').` ); } - const overlapWinnerSource: 'eod' | 'qm' = overlapWinnerSourceRaw; + const overlapWinnerSource: Bars1mSource = overlapWinnerSourceRaw; let overlapProbes: readonly Bars1mProbeExpectation[] | undefined; if (parsed.dedup.overlapProbes !== undefined) { @@ -1420,11 +1529,10 @@ export function parseLoadReceiptJson(rawJson: string): M2LoadReceipt { } return { - beforeWal, shards: { - bars_1m: { probes: bars1mProbes }, - bars_1m_qm: { probes: bars1mQmProbes }, - fx_1m: { probes: fx1mProbes }, + bars_1m: bars1mShard, + bars_1m_qm: bars1mQmShard, + fx_1m: fx1mShard, }, dedup: { eodSentRows, @@ -1436,10 +1544,27 @@ export function parseLoadReceiptJson(rawJson: string): M2LoadReceipt { }; } +function getRequiredMinWalFromReceipt(receipt: M2LoadReceipt): RequiredMinWalByTable { + const eodAfterW = BigInt(receipt.shards.bars_1m.afterWal.writerTxn); + const eodAfterS = BigInt(receipt.shards.bars_1m.afterWal.sequencerTxn); + const qmAfterW = BigInt(receipt.shards.bars_1m_qm.afterWal.writerTxn); + const qmAfterS = BigInt(receipt.shards.bars_1m_qm.afterWal.sequencerTxn); + return { + bars_1m: { + writerTxn: (eodAfterW >= qmAfterW ? eodAfterW : qmAfterW).toString(), + sequencerTxn: (eodAfterS >= qmAfterS ? eodAfterS : qmAfterS).toString(), + }, + fx_1m: receipt.shards.fx_1m.afterWal, + }; +} + interface ParsedResendBaseline { readonly walTables: ReadonlyMap; readonly bars1mSummary: readonly Bars1mSourceSummaryRow[]; readonly fx1mSummary: readonly Fx1mPairSourceSummaryRow[]; + readonly shardHashes: ShardHashesByPrefix; + readonly bars1mContentDigest: string; + readonly fx1mContentDigest: string; } function parseResendBaselineJson(rawJson: string): ParsedResendBaseline { @@ -1512,44 +1637,181 @@ function parseResendBaselineJson(rawJson: string): ParsedResendBaseline { }; }); - return { walTables: walMap, bars1mSummary, fx1mSummary }; + if (!isPlainObject(parsed.loadVerification) || !isPlainObject(parsed.loadVerification.shardHashes)) { + throw new VerifyM2QuantError( + 'Resend baseline missing required "loadVerification.shardHashes" object.' + ); + } + const rawHashes = parsed.loadVerification.shardHashes as Record; + const shardHashes: ShardHashesByPrefix = { + bars_1m: parseSha256List(rawHashes.bars_1m, 'resendBaseline.loadVerification.shardHashes.bars_1m'), + bars_1m_qm: parseSha256List( + rawHashes.bars_1m_qm, + 'resendBaseline.loadVerification.shardHashes.bars_1m_qm' + ), + fx_1m: parseSha256List(rawHashes.fx_1m, 'resendBaseline.loadVerification.shardHashes.fx_1m'), + }; + + const bars1mContentDigest = parseSha256Hex( + parsed.bars1mContentDigest, + 'resendBaseline.bars1mContentDigest' + ); + const fx1mContentDigest = parseSha256Hex( + parsed.fx1mContentDigest, + 'resendBaseline.fx1mContentDigest' + ); + + return { + walTables: walMap, + bars1mSummary, + fx1mSummary, + shardHashes, + bars1mContentDigest, + fx1mContentDigest, + }; } -function verifyWalAdvancement( - beforeMap: Readonly>, - afterTables: readonly WalTableStatusRow[], - contextLabel: string -): readonly WalAdvancementEntry[] { - const afterByName = new Map( - afterTables.map(row => [row.name, row]) +function verifyPerPrefixWalAdvancement( + receipt: M2LoadReceipt, + liveWalTables: readonly WalTableStatusRow[], + baselineWal?: ReadonlyMap, + contextLabel = 'Load receipt WAL check' +): readonly PrefixWalAdvancementEntry[] { + const liveByName = new Map( + liveWalTables.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) { + const prefixSpecs: readonly { readonly prefix: RequiredShardPrefix; readonly table: 'bars_1m' | 'fx_1m' }[] = [ + { prefix: 'bars_1m', table: 'bars_1m' }, + { prefix: 'bars_1m_qm', table: 'bars_1m' }, + { prefix: 'fx_1m', table: 'fx_1m' }, + ]; + + const results: PrefixWalAdvancementEntry[] = []; + for (const { prefix, table } of prefixSpecs) { + const shard = receipt.shards[prefix]; + const live = liveByName.get(table); + if (live === 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); + const beforeWriter = BigInt(shard.beforeWal.writerTxn); + const afterWriter = BigInt(shard.afterWal.writerTxn); + const beforeSeq = BigInt(shard.beforeWal.sequencerTxn); + const afterSeq = BigInt(shard.afterWal.sequencerTxn); + const liveWriter = BigInt(live.writerTxn); + const liveSeq = BigInt(live.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}).` + `${contextLabel}: WAL for shard prefix '${prefix}' (${table}) did not advance.` ); } + if (liveWriter < afterWriter || liveSeq < afterSeq) { + throw new VerifyM2QuantError( + `${contextLabel}: live QuestDB WAL for '${table}' (writerTxn=${live.writerTxn}/sequencerTxn=${live.sequencerTxn}) is behind shard prefix '${prefix}' afterWal (writerTxn=${shard.afterWal.writerTxn}/sequencerTxn=${shard.afterWal.sequencerTxn}).` + ); + } + if (baselineWal !== undefined) { + const base = baselineWal.get(table)!; + const baseWriter = BigInt(base.writerTxn); + const baseSeq = BigInt(base.sequencerTxn); + if (beforeWriter < baseWriter || beforeSeq < baseSeq) { + throw new VerifyM2QuantError( + `${contextLabel}: shard prefix '${prefix}' beforeWal (writerTxn=${shard.beforeWal.writerTxn}/sequencerTxn=${shard.beforeWal.sequencerTxn}) predates resend baseline WAL (writerTxn=${base.writerTxn}/sequencerTxn=${base.sequencerTxn}).` + ); + } + if (liveWriter <= baseWriter || liveSeq <= baseSeq) { + throw new VerifyM2QuantError( + `${contextLabel}: live QuestDB WAL for '${table}' did not advance past resend baseline (baseline writerTxn=${base.writerTxn}/sequencerTxn=${base.sequencerTxn}, live writerTxn=${live.writerTxn}/sequencerTxn=${live.sequencerTxn}).` + ); + } + } + results.push({ + shardPrefix: prefix, table, - beforeWriterTxn: before.writerTxn, - afterWriterTxn: after.writerTxn, - beforeSequencerTxn: before.sequencerTxn, - afterSequencerTxn: after.sequencerTxn, + beforeWriterTxn: shard.beforeWal.writerTxn, + afterWriterTxn: shard.afterWal.writerTxn, + beforeSequencerTxn: shard.beforeWal.sequencerTxn, + afterSequencerTxn: shard.afterWal.sequencerTxn, + liveWriterTxn: live.writerTxn, + liveSequencerTxn: live.sequencerTxn, }); } return results; } +async function computeBars1mContentDigest(executor: QuestDbPgQueryExecutor): Promise { + const sql = + 'SELECT source, utc_day, count() AS row_count, ' + + 'sum(open) AS sum_open, sum(high) AS sum_high, sum(low) AS sum_low, ' + + 'sum(close) AS sum_close, sum(volume) AS sum_volume, sum(close_sq) AS sum_close_sq, ' + + '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 (SELECT source, CAST(ts AS LONG) / 86400000000 AS utc_day, ' + + 'open, high, low, close, volume, close * close AS close_sq, ts FROM bars_1m) ' + + 'GROUP BY source, utc_day ORDER BY source, utc_day'; + const res = await executor.query(sql); + if (res.rows.length === 0) { + throw new VerifyM2QuantError('QuestDB bars_1m content digest query returned zero buckets.'); + } + const hash = createHash('sha256'); + for (const row of res.rows) { + const source = parseRequiredStringCell(row.source, 'bars_1m_digest.source'); + const utcDay = parseBigIntCell(row.utc_day, 'bars_1m_digest.utc_day'); + const rowCount = parseBigIntCell(row.row_count, 'bars_1m_digest.row_count'); + const sumOpen = parseFiniteNumberCell(row.sum_open, 'bars_1m_digest.sum_open'); + const sumHigh = parseFiniteNumberCell(row.sum_high, 'bars_1m_digest.sum_high'); + const sumLow = parseFiniteNumberCell(row.sum_low, 'bars_1m_digest.sum_low'); + const sumClose = parseFiniteNumberCell(row.sum_close, 'bars_1m_digest.sum_close'); + const sumVolume = parseFiniteNumberCell(row.sum_volume, 'bars_1m_digest.sum_volume'); + const sumCloseSq = parseFiniteNumberCell(row.sum_close_sq, 'bars_1m_digest.sum_close_sq'); + const minClose = parseFiniteNumberCell(row.min_close, 'bars_1m_digest.min_close'); + const maxClose = parseFiniteNumberCell(row.max_close, 'bars_1m_digest.max_close'); + const minTsUs = parseBigIntCell(row.min_ts_us, 'bars_1m_digest.min_ts_us'); + const maxTsUs = parseBigIntCell(row.max_ts_us, 'bars_1m_digest.max_ts_us'); + hash.update( + `${source}|${utcDay.toString()}|${rowCount.toString()}|${sumOpen}|${sumHigh}|${sumLow}|${sumClose}|${sumVolume}|${sumCloseSq}|${minClose}|${maxClose}|${minTsUs.toString()}|${maxTsUs.toString()}\n` + ); + } + return hash.digest('hex'); +} + +async function computeFx1mContentDigest(executor: QuestDbPgQueryExecutor): Promise { + const sql = + 'SELECT pair, source, utc_day, count() AS row_count, ' + + 'sum(open) AS sum_open, sum(high) AS sum_high, sum(low) AS sum_low, ' + + 'sum(close) AS sum_close, sum(close_sq) AS sum_close_sq, ' + + '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 (SELECT pair, source, CAST(ts AS LONG) / 86400000000 AS utc_day, ' + + 'open, high, low, close, close * close AS close_sq, ts FROM fx_1m) ' + + 'GROUP BY pair, source, utc_day ORDER BY pair, source, utc_day'; + const res = await executor.query(sql); + if (res.rows.length === 0) { + throw new VerifyM2QuantError('QuestDB fx_1m content digest query returned zero buckets.'); + } + const hash = createHash('sha256'); + for (const row of res.rows) { + const pair = parseRequiredStringCell(row.pair, 'fx_1m_digest.pair'); + const source = parseRequiredStringCell(row.source, 'fx_1m_digest.source'); + const utcDay = parseBigIntCell(row.utc_day, 'fx_1m_digest.utc_day'); + const rowCount = parseBigIntCell(row.row_count, 'fx_1m_digest.row_count'); + const sumOpen = parseFiniteNumberCell(row.sum_open, 'fx_1m_digest.sum_open'); + const sumHigh = parseFiniteNumberCell(row.sum_high, 'fx_1m_digest.sum_high'); + const sumLow = parseFiniteNumberCell(row.sum_low, 'fx_1m_digest.sum_low'); + const sumClose = parseFiniteNumberCell(row.sum_close, 'fx_1m_digest.sum_close'); + const sumCloseSq = parseFiniteNumberCell(row.sum_close_sq, 'fx_1m_digest.sum_close_sq'); + const minClose = parseFiniteNumberCell(row.min_close, 'fx_1m_digest.min_close'); + const maxClose = parseFiniteNumberCell(row.max_close, 'fx_1m_digest.max_close'); + const minTsUs = parseBigIntCell(row.min_ts_us, 'fx_1m_digest.min_ts_us'); + const maxTsUs = parseBigIntCell(row.max_ts_us, 'fx_1m_digest.max_ts_us'); + hash.update( + `${pair}|${source}|${utcDay.toString()}|${rowCount.toString()}|${sumOpen}|${sumHigh}|${sumLow}|${sumClose}|${sumCloseSq}|${minClose}|${maxClose}|${minTsUs.toString()}|${maxTsUs.toString()}\n` + ); + } + return hash.digest('hex'); +} + async function verifyBars1mProbe( executor: QuestDbPgQueryExecutor, shardPrefix: 'bars_1m' | 'bars_1m_qm' | 'dedup_overlap', @@ -1650,25 +1912,26 @@ async function verifyLoadReceipt( bars1mSummary: readonly Bars1mSourceSummaryRow[], fx1mSummary: readonly Fx1mPairSourceSummaryRow[] ): Promise { - const walAdvancement = verifyWalAdvancement( - { bars_1m: receipt.beforeWal.bars_1m, fx_1m: receipt.beforeWal.fx_1m }, + const walAdvancement = verifyPerPrefixWalAdvancement( + receipt, walTables, + undefined, 'Load receipt WAL check' ); const bySource = new Map( bars1mSummary.map(row => [row.source, row]) ); - const eodGroup = bySource.get('eod'); - const qmGroup = bySource.get('qm'); + const eodGroup = bySource.get(BARS_1M_SOURCE_EOD); + const qmGroup = bySource.get(BARS_1M_SOURCE_QM); if (eodGroup === undefined) { throw new VerifyM2QuantError( - "Load receipt verification failed: QuestDB bars_1m is missing required source='eod' group (bars_1m shard prefix)." + `Load receipt verification failed: QuestDB bars_1m is missing required source='${BARS_1M_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)." + `Load receipt verification failed: QuestDB bars_1m is missing required source='${BARS_1M_SOURCE_QM}' group (bars_1m_qm shard prefix).` ); } if (fx1mSummary.length === 0) { @@ -1679,20 +1942,20 @@ async function verifyLoadReceipt( const { eodSentRows, qmSentRows, overlapRows, overlapWinnerSource } = receipt.dedup; const minExpectedEodRows = - overlapWinnerSource === 'qm' ? eodSentRows - overlapRows : eodSentRows; + overlapWinnerSource === BARS_1M_SOURCE_QM ? eodSentRows - overlapRows : eodSentRows; const minExpectedQmRows = - overlapWinnerSource === 'eod' ? qmSentRows - overlapRows : qmSentRows; + overlapWinnerSource === BARS_1M_SOURCE_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}.` + `EOD/QM dedup accounting failed: observed bars_1m source='${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}.` + `EOD/QM dedup accounting failed: observed bars_1m source='${BARS_1M_SOURCE_QM}' rowCount=${qmGroup.rowCount} < expected minimum ${minExpectedQmRows}.` ); } if (observedTotalBars1mRows < minExpectedTotalBars1mRows) { @@ -1719,6 +1982,11 @@ async function verifyLoadReceipt( return { walAdvancement, + shardHashes: { + bars_1m: receipt.shards.bars_1m.shardSha256, + bars_1m_qm: receipt.shards.bars_1m_qm.shardSha256, + fx_1m: receipt.shards.fx_1m.shardSha256, + }, dedupAccounting: { eodSentRows, qmSentRows, @@ -1735,18 +2003,46 @@ async function verifyLoadReceipt( }; } +function assertShardHashesMatch( + prefix: RequiredShardPrefix, + baselineHashes: readonly string[], + currentHashes: readonly string[] +): void { + if (baselineHashes.length !== currentHashes.length) { + throw new VerifyM2QuantError( + `Idempotent resend failed: shard hash count diverged for '${prefix}' (${baselineHashes.length} -> ${currentHashes.length}).` + ); + } + for (let i = 0; i < baselineHashes.length; i += 1) { + if (baselineHashes[i] !== currentHashes[i]) { + throw new VerifyM2QuantError( + `Idempotent resend failed: shard SHA-256 diverged for '${prefix}'[${i}] (${baselineHashes[i]} -> ${currentHashes[i]}).` + ); + } + } +} + function verifyIdempotentResend( baseline: ParsedResendBaseline, + receipt: M2LoadReceipt, walTables: readonly WalTableStatusRow[], bars1mSummary: readonly Bars1mSourceSummaryRow[], - fx1mSummary: readonly Fx1mPairSourceSummaryRow[] + fx1mSummary: readonly Fx1mPairSourceSummaryRow[], + bars1mContentDigest: string, + fx1mContentDigest: string ): ResendVerificationResult { - const walAdvancement = verifyWalAdvancement( - { - bars_1m: baseline.walTables.get('bars_1m')!, - fx_1m: baseline.walTables.get('fx_1m')!, - }, + for (const prefix of REQUIRED_SHARD_PREFIXES) { + assertShardHashesMatch( + prefix, + baseline.shardHashes[prefix], + receipt.shards[prefix].shardSha256 + ); + } + + const walAdvancement = verifyPerPrefixWalAdvancement( + receipt, walTables, + baseline.walTables, 'Idempotent resend WAL check' ); @@ -1795,11 +2091,25 @@ function verifyIdempotentResend( } } + if (bars1mContentDigest !== baseline.bars1mContentDigest) { + throw new VerifyM2QuantError( + `Idempotent resend failed: bars_1m retained row content digest diverged (${baseline.bars1mContentDigest} -> ${bars1mContentDigest}).` + ); + } + if (fx1mContentDigest !== baseline.fx1mContentDigest) { + throw new VerifyM2QuantError( + `Idempotent resend failed: fx_1m retained row content digest diverged (${baseline.fx1mContentDigest} -> ${fx1mContentDigest}).` + ); + } + return { ok: true, walAdvancement, + shardHashesMatched: true, bars1mRowCountsUnchanged: true, fx1mRowCountsUnchanged: true, + bars1mContentDigestMatched: true, + fx1mContentDigestMatched: true, }; } @@ -2071,42 +2381,48 @@ export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Prom // Validate Vault fence and 1-year effective window before any DB/store I/O. const fence = validateBenchmarkFence(parsed); + const requiredMinWal = getRequiredMinWalFromReceipt(receipt); let ddlResult: { readonly applied: boolean; readonly appliedTables: readonly M2IntradayTableName[]; } = { applied: false, appliedTables: [] }; + let walTables: readonly WalTableStatusRow[]; - if (parsed.applyDdl) { - const ddlPgHandle = await openPg(parsed.questdb); - try { - const applied = await applyDdlFn(ddlPgHandle.executor); + // Poll wal_tables() (metadata only, zero bar-table scans) and confirm all expected + // load transactions are applied BEFORE starting the timed cold benchmark read. + const preBenchPgHandle = await openPg(parsed.questdb); + try { + if (parsed.applyDdl) { + const applied = await applyDdlFn(preBenchPgHandle.executor); ddlResult = { applied: true, appliedTables: applied.appliedTables }; - } finally { - await ddlPgHandle.close(); } + walTables = await waitForHealthyWalTables( + preBenchPgHandle.executor, + parsed.walSettleTimeoutMs, + walPollIntervalMs, + nowMs, + sleepMs, + requiredMinWal + ); + } finally { + await preBenchPgHandle.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. + // or fx_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 bars1mContentDigest: string; + let fx1mContentDigest: string; let loadVerification: LoadReceiptVerificationResult; let resendVerification: ResendVerificationResult | undefined; const splitChecks: SplitBoundaryCheckResult[] = []; const pgHandle = await openPg(parsed.questdb); try { - walTables = await waitForHealthyWalTables( - pgHandle.executor, - parsed.walSettleTimeoutMs, - walPollIntervalMs, - nowMs, - sleepMs - ); bars1mSummary = await verifyBars1mCommits(pgHandle.executor); fx1mSummary = await verifyFx1mCommits(pgHandle.executor); loadVerification = await verifyLoadReceipt( @@ -2116,12 +2432,17 @@ export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Prom bars1mSummary, fx1mSummary ); + bars1mContentDigest = await computeBars1mContentDigest(pgHandle.executor); + fx1mContentDigest = await computeFx1mContentDigest(pgHandle.executor); if (resendBaseline !== undefined) { resendVerification = verifyIdempotentResend( resendBaseline, + receipt, walTables, bars1mSummary, - fx1mSummary + fx1mSummary, + bars1mContentDigest, + fx1mContentDigest ); } @@ -2161,6 +2482,8 @@ export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Prom walTables, bars1mSummary, fx1mSummary, + bars1mContentDigest, + fx1mContentDigest, loadVerification, ...(resendVerification !== undefined ? { resendVerification } : {}), splitChecks,