T-215: M2.5 — Execute host/quant M2 preflight, observed split-boundary & latency checks, and desktop Claude Code EC-1 sign-off

This commit is contained in:
Studio 2026-12-05 22:02:21 -05:00
parent 51165adfeb
commit 87ae19e5f9
2 changed files with 922 additions and 195 deletions

View file

@ -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`: `<name>==\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, string | null> = {}): string[] {
const defaults: Record<string, string | null> = {
'--questdb-host': '10.0.0.51',
@ -90,41 +230,45 @@ function baseArgs(overrides: Record<string, string | null> = {}): 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<string, readonly Record<string, unknown>[]> {
return new Map<string, readonly Record<string, unknown>[]>([
[
@ -156,7 +324,7 @@ function defaultBars1mProbeMap(): Map<string, readonly Record<string, unknown>[]
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<string, readonly Record<string, unknown>[]
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<string, readonly Record<string, unknown>[]
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<string, readonly Record<string, unknown>[]>
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<string, unknown>[])[];
readonly bars1mSummaryRows?: readonly Record<string, unknown>[];
readonly fx1mSummaryRows?: readonly Record<string, unknown>[];
readonly bars1mDigestRows?: readonly Record<string, unknown>[];
readonly fx1mDigestRows?: readonly Record<string, unknown>[];
readonly bars1mProbeRows?: Map<string, readonly Record<string, unknown>[]>;
readonly fx1mProbeRows?: Map<string, readonly Record<string, unknown>[]>;
readonly nvda1mRows?: readonly Record<string, unknown>[];
@ -233,7 +403,7 @@ function defaultWalRows(): readonly Record<string, unknown>[] {
function defaultBars1mSummaryRows(): readonly Record<string, unknown>[] {
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<string, unknown>[] {
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<string, unknown>[] {
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<string, unknown>[] {
];
}
function defaultBars1mDigestRows(): readonly Record<string, unknown>[] {
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<string, unknown>[] {
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<string, unknown>[] {
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,