stock-bot/scripts/test/verify-m2-quant.test.ts

1662 lines
59 KiB
TypeScript

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