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

2184 lines
76 KiB
TypeScript

/**
* Deterministic QuestDB 10.2.0 / DuckDB M2 verification CLI for `quant` (`10.0.0.51`).
*
* Modes:
* - `--ddl-only`: Opt-in setup mode for fresh/empty QuestDB instances. Executes
* `applyM2IntradayDDL`, verifies `wal_tables()` health (`bars_1m`, `fx_1m`,
* `bar_revisions` present, `suspended = false`, `writerTxn >= sequencerTxn`),
* and exits 0 without querying table contents.
* - Full verification mode (default): Verifies Milestone M2 Exit Criterion 3 fail-closed:
* 1. Validates the Vault-fenced 1-year benchmark window (`>= 365` days after Vault
* clamping with `vaultOperatorAuthorized: false`) and measures the 1-year
* single-listing `1m` PGWire cold read (`< 1000 ms`) and warm reads (`< 250 ms`)
* BEFORE any verifier query scans `bars_1m`.
* 2. Verifies `wal_tables()` health, before-and-after WAL advancement against
* `--load-receipt`, non-zero finite `0x10` binary-double commits across all three
* shard prefixes (`bars_1m`, `bars_1m_qm`, `fx_1m`), exact expected key/close
* probes, EOD/QM deduplication accounting, and optional idempotent resend
* verification (`--resend-baseline`).
* 3. Verifies observed split-boundary close agreement (`<= 0.5%`) between QuestDB
* `bars_1m` (`session = 'RTH'`, latest `ts` per `America/New_York` session
* date) and retained raw `bars_1d/year=<YYYY>/part.parquet` across `NVDA.US`
* (`2024-06-06..2024-06-12`, ex-date `2024-06-10`, `10:1`) and `NEXM.V`
* (`2025-06-17..2025-06-23`, ex-date `2025-06-20`, `1:20`).
*
* Fail-closed: any validation, WAL, load-receipt, resend, split-boundary, Vault-fence,
* or latency failure writes a single redacted error line to stderr with zero stdout
* bytes and exits with code 1.
*/
import { createHash } from 'node:crypto';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import type {
ClosableDuckDbExecutor,
OpenResearchCopilotStoreOptions,
} from '@stock-bot/duckdb';
import {
type ApplyM2IntradayDDLResult,
M2_INTRADAY_TABLE_NAMES,
type M2IntradayTableName,
type QuestDbPgExecutorConfig,
type QuestDbPgExecutorHandle,
type QuestDbPgQueryExecutor,
applyM2IntradayDDL,
openQuestDbPgExecutor,
} from '@stock-bot/questdb';
import {
type BarRecord,
type DataScope,
type FencedTimeRange,
applyVaultFence,
collectBars,
} from '@stock-bot/research';
import type { ManagedMarketDataStore, ResearchCopilotHostConfig } from '@stock-bot/research/mcp';
const INT32_MAX = 2_147_483_647;
const STRICT_POSITIVE_INT_RE = /^[1-9]\d*$/;
const STRICT_NON_NEGATIVE_INT_RE = /^(?:0|[1-9]\d*)$/;
const STRICT_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/;
const STRICT_UTC_INSTANT_RE =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/;
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
const URL_CREDENTIAL_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^:@/\s]+):([^@/\s]+)@/g;
const POSTGRES_URL_RE = /postgres(?:ql)?:\/\/[^\s'"]+/gi;
export const DEFAULT_WARM_RUNS = 5;
export const DEFAULT_WAL_SETTLE_TIMEOUT_MS = 30_000;
export const DEFAULT_WAL_POLL_INTERVAL_MS = 250;
export const MAX_SPLIT_CLOSE_REL_DIFF = 0.005;
export const MAX_COLD_READ_MS = 1_000;
export const MAX_WARM_READ_MS = 250;
export const MIN_ONE_YEAR_WINDOW_MS = 365 * 24 * 60 * 60 * 1000;
export const DEFAULT_PROBE_CLOSE_TOLERANCE = 1e-9;
export const REQUIRED_SHARD_PREFIXES = ['bars_1m', 'bars_1m_qm', 'fx_1m'] as const;
export type RequiredShardPrefix = (typeof REQUIRED_SHARD_PREFIXES)[number];
export interface SplitBoundaryCaseSpec {
readonly label: 'NVDA.US' | 'NEXM.V';
readonly fromDate: string;
readonly toDate: string;
readonly exDate: string;
readonly ratio: string;
}
export const M2_SPLIT_BOUNDARY_CASES: readonly SplitBoundaryCaseSpec[] = [
{
label: 'NVDA.US',
fromDate: '2024-06-06',
toDate: '2024-06-12',
exDate: '2024-06-10',
ratio: '10:1',
},
{
label: 'NEXM.V',
fromDate: '2025-06-17',
toDate: '2025-06-23',
exDate: '2025-06-20',
ratio: '1:20',
},
] as const;
const NY_DATE_FORMATTER = new Intl.DateTimeFormat('en-CA', {
timeZone: 'America/New_York',
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
export interface VerifyM2QuantStream {
write(chunk: string): boolean;
}
export interface ParseVerifyM2QuantArgsOptions {
readonly cwd?: string;
}
export interface ParsedVerifyM2QuantRun {
readonly kind: 'run';
readonly questdb: QuestDbPgExecutorConfig;
readonly curatedRoot: string;
readonly vaultCutoffIso: string;
readonly vaultCutoffTs: number;
readonly nvdaListingId: number;
readonly nexmListingId: number;
readonly benchListingId: number;
readonly benchFrom: string;
readonly benchTo: string;
readonly benchAsOf: string;
readonly benchScope: DataScope;
readonly loadReceiptPath: string;
readonly resendBaselinePath?: string;
readonly applyDdl: boolean;
readonly warmRuns: number;
readonly walSettleTimeoutMs: number;
readonly outPath?: string;
}
export interface ParsedVerifyM2QuantDdlOnly {
readonly kind: 'ddl_only';
readonly questdb: QuestDbPgExecutorConfig;
readonly walSettleTimeoutMs: number;
readonly outPath?: string;
}
export interface ParsedVerifyM2QuantHelp {
readonly kind: 'help';
}
export type ParsedVerifyM2QuantArgs =
| ParsedVerifyM2QuantRun
| ParsedVerifyM2QuantDdlOnly
| ParsedVerifyM2QuantHelp;
export interface VerifyM2QuantCliDeps {
readonly argv?: readonly string[];
readonly cwd?: string;
readonly stdout?: VerifyM2QuantStream;
readonly stderr?: VerifyM2QuantStream;
readonly openQuestDbPgExecutor?: (
config: QuestDbPgExecutorConfig
) => Promise<QuestDbPgExecutorHandle>;
readonly applyM2IntradayDDL?: (
client: QuestDbPgQueryExecutor
) => Promise<ApplyM2IntradayDDLResult>;
readonly createDuckDbExecutor?: () => Promise<ClosableDuckDbExecutor>;
readonly openResearchCopilotStore?: (
config: ResearchCopilotHostConfig,
options?: OpenResearchCopilotStoreOptions
) => Promise<ManagedMarketDataStore>;
readonly readTextFile?: (path: string) => Promise<string>;
readonly writeReportFile?: (path: string, content: string) => Promise<void>;
readonly nowMs?: () => number;
readonly perfNowMs?: () => number;
readonly sleepMs?: (ms: number) => Promise<void>;
readonly walPollIntervalMs?: number;
}
export interface WalTxnPair {
readonly writerTxn: string;
readonly sequencerTxn: string;
}
export interface LoadReceiptWalSnapshot {
readonly bars_1m: WalTxnPair;
readonly fx_1m: WalTxnPair;
readonly bar_revisions?: WalTxnPair;
}
export interface Bars1mProbeExpectation {
readonly listingId: number;
readonly tsUs: string;
readonly expectedClose: number;
readonly expectedSource: 'eod' | 'qm';
readonly expectedKnownAtUs?: string;
readonly closeTolerance?: number;
}
export interface Fx1mProbeExpectation {
readonly pair: string;
readonly tsUs: string;
readonly expectedClose: number;
readonly expectedSource: string;
readonly closeTolerance?: number;
}
export interface LoadReceiptDedupExpectation {
readonly eodSentRows: number;
readonly qmSentRows: number;
readonly overlapRows: number;
readonly overlapWinnerSource: 'eod' | 'qm';
readonly overlapProbes?: readonly Bars1mProbeExpectation[];
}
export interface M2LoadReceipt {
readonly beforeWal: LoadReceiptWalSnapshot;
readonly shards: {
readonly bars_1m: {
readonly probes: readonly Bars1mProbeExpectation[];
};
readonly bars_1m_qm: {
readonly probes: readonly Bars1mProbeExpectation[];
};
readonly fx_1m: {
readonly probes: readonly Fx1mProbeExpectation[];
};
};
readonly dedup: LoadReceiptDedupExpectation;
}
export interface WalAdvancementEntry {
readonly table: 'bars_1m' | 'fx_1m';
readonly beforeWriterTxn: string;
readonly afterWriterTxn: string;
readonly beforeSequencerTxn: string;
readonly afterSequencerTxn: string;
}
export interface ProbeCheckResult {
readonly shardPrefix: RequiredShardPrefix | 'dedup_overlap';
readonly key: string;
readonly expectedSource: string;
readonly actualSource: string;
readonly expectedClose: number;
readonly actualClose: number;
readonly absDiff: number;
}
export interface LoadReceiptVerificationResult {
readonly walAdvancement: readonly WalAdvancementEntry[];
readonly dedupAccounting: {
readonly eodSentRows: number;
readonly qmSentRows: number;
readonly overlapRows: number;
readonly overlapWinnerSource: 'eod' | 'qm';
readonly minExpectedEodRows: number;
readonly minExpectedQmRows: number;
readonly minExpectedTotalBars1mRows: number;
readonly observedEodRows: number;
readonly observedQmRows: number;
readonly observedTotalBars1mRows: number;
};
readonly probesVerified: readonly ProbeCheckResult[];
}
export interface ResendVerificationResult {
readonly ok: true;
readonly walAdvancement: readonly WalAdvancementEntry[];
readonly bars1mRowCountsUnchanged: true;
readonly fx1mRowCountsUnchanged: true;
}
export interface WalTableStatusRow {
readonly name: M2IntradayTableName;
readonly suspended: boolean;
readonly writerTxn: string;
readonly sequencerTxn: string;
}
export interface Bars1mSourceSummaryRow {
readonly source: string;
readonly rowCount: number;
readonly minClose: number;
readonly maxClose: number;
readonly minTsUs: string;
readonly maxTsUs: string;
}
export interface Fx1mPairSourceSummaryRow {
readonly pair: string;
readonly source: string;
readonly rowCount: number;
readonly minClose: number;
readonly maxClose: number;
readonly minTsUs: string;
readonly maxTsUs: string;
}
export interface SplitBoundarySessionComparison {
readonly sessionDate: string;
readonly phase: 'pre_split' | 'ex_or_post_split';
readonly close1m: number;
readonly close1d: number;
readonly relDiff: number;
}
export interface SplitBoundaryCheckResult {
readonly label: 'NVDA.US' | 'NEXM.V';
readonly listingId: number;
readonly fromDate: string;
readonly toDate: string;
readonly exDate: string;
readonly ratio: string;
readonly preSplitCount: number;
readonly exOrPostSplitCount: number;
readonly maxRelDiff: number;
readonly sessions: readonly SplitBoundarySessionComparison[];
}
export interface IntradayBenchmarkResult {
readonly listingId: number;
readonly from: string;
readonly to: string;
readonly asOf: string;
readonly effectiveFrom: string;
readonly effectiveTo: string;
readonly effectiveAsOf: string;
readonly effectiveSpanMs: number;
readonly clampedTo: boolean;
readonly clampedAsOf: boolean;
readonly scope: DataScope;
readonly rowCount: number;
readonly digest: string;
readonly coldMs: number;
readonly warmRuns: readonly number[];
readonly minWarmMs: number;
readonly medianWarmMs: number;
readonly maxWarmMs: number;
readonly thresholds: {
readonly maxColdMs: number;
readonly maxWarmMs: number;
readonly minWindowMs: number;
};
}
export interface VerifyM2QuantDdlOnlyReport {
readonly ok: true;
readonly mode: 'ddl_only';
readonly target: {
readonly questdb: string;
};
readonly ddl: {
readonly applied: true;
readonly appliedTables: readonly M2IntradayTableName[];
};
readonly walTables: readonly WalTableStatusRow[];
}
export interface VerifyM2QuantReport {
readonly ok: true;
readonly mode: 'verify';
readonly target: {
readonly questdb: string;
readonly curatedRoot: string;
readonly vaultCutoffTs: string;
};
readonly ddl: {
readonly applied: boolean;
readonly appliedTables: readonly M2IntradayTableName[];
};
readonly walTables: readonly WalTableStatusRow[];
readonly bars1mSummary: readonly Bars1mSourceSummaryRow[];
readonly fx1mSummary: readonly Fx1mPairSourceSummaryRow[];
readonly loadVerification: LoadReceiptVerificationResult;
readonly resendVerification?: ResendVerificationResult;
readonly splitChecks: readonly SplitBoundaryCheckResult[];
readonly benchmark: IntradayBenchmarkResult;
}
export class VerifyM2QuantError extends Error {
constructor(message: string) {
super(message);
this.name = 'VerifyM2QuantError';
Object.setPrototypeOf(this, new.target.prototype);
}
}
export const VERIFY_M2_QUANT_USAGE = [
'Usage: bun run scripts/verify-m2-quant.ts [options]',
'',
'Modes:',
' --ddl-only Apply M2 intraday DDL on a fresh/empty QuestDB instance,',
' verify wal_tables() health, and exit 0 (requires only QuestDB',
' connection flags, optional --wal-settle-timeout-ms and --out)',
'',
'Required options (full verification mode):',
' --questdb-url <url> QuestDB PGWire URL (mutually exclusive with --questdb-host/--questdb-pg-port)',
' --questdb-host <host> QuestDB PGWire host (requires --questdb-pg-port)',
' --questdb-pg-port <port> QuestDB PGWire port (requires --questdb-host)',
' --curated-root <dir> Curated Parquet root containing bars_1d/year=<YYYY>/part.parquet',
' --vault-cutoff-ts <iso-utc-z> Authoritative Vault cutoff ISO-8601 UTC timestamp ending in Z',
' --nvda-listing-id <int32> Permanent listing_id for NVDA.US',
' --nexm-listing-id <int32> Permanent listing_id for NEXM.V',
' --bench-listing-id <int32> Permanent listing_id for 1y 1m PGWire latency benchmark',
' --bench-from <iso-or-date> Benchmark window start (must be < --vault-cutoff-ts)',
' --bench-to <iso-or-date> Benchmark window end (effective fenced span must be >= 365 days)',
' --bench-as-of <iso-or-date> Benchmark point-in-time as-of bound',
' --load-receipt <path> JSON load receipt with beforeWal, per-prefix (bars_1m, bars_1m_qm,',
' fx_1m) expected keys/closes, and EOD/QM dedup expectations',
'',
'Optional options:',
' --questdb-database <name> QuestDB PGWire database name (host/port mode)',
' --questdb-user <user> QuestDB PGWire user (host/port mode)',
' --questdb-password <pass> QuestDB PGWire password (host/port mode)',
' --questdb-ssl <true|false> Explicit TLS flag',
' --bench-scope <scope> DataScope for benchmark (default: vault_fenced)',
' --resend-baseline <path> Prior VerifyM2QuantReport JSON to verify idempotent resend against',
' --apply-ddl Execute applyM2IntradayDDL before checks (full mode)',
` --warm-runs <pos-int> Number of warm 1y 1m benchmark reads (default: ${DEFAULT_WARM_RUNS})`,
` --wal-settle-timeout-ms <pos-int> WAL settle polling timeout in ms (default: ${DEFAULT_WAL_SETTLE_TIMEOUT_MS})`,
' --out <path> Optional JSON output file path',
' -h, --help Show this help message',
'',
].join('\n');
const VALUE_FLAGS = new Set([
'--questdb-url',
'--questdb-host',
'--questdb-pg-port',
'--questdb-database',
'--questdb-user',
'--questdb-password',
'--questdb-ssl',
'--curated-root',
'--vault-cutoff-ts',
'--nvda-listing-id',
'--nexm-listing-id',
'--bench-listing-id',
'--bench-from',
'--bench-to',
'--bench-as-of',
'--bench-scope',
'--load-receipt',
'--resend-baseline',
'--warm-runs',
'--wal-settle-timeout-ms',
'--out',
]);
const BOOLEAN_FLAGS = new Set(['--apply-ddl', '--ddl-only']);
const SECRET_FLAGS = new Set(['--questdb-url', '--questdb-password']);
function sanitizeSingleLine(message: string): string {
return message.replace(/\r?\n/g, ' ').trim();
}
function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
if (raw.length === 0) {
return;
}
needles.add(raw);
try {
const decoded = decodeURIComponent(raw);
if (decoded.length > 0) {
needles.add(decoded);
}
} catch {
// Malformed percent-encoding: raw value is already registered.
}
}
function collectArgvSecretNeedles(argv: readonly string[]): Set<string> {
const needles = new Set<string>();
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i] as string;
const eqIndex = token.indexOf('=');
let flag: string;
let rawValue: string | undefined;
if (eqIndex !== -1) {
flag = token.slice(0, eqIndex);
rawValue = token.slice(eqIndex + 1);
} else {
flag = token;
if (SECRET_FLAGS.has(flag) && i + 1 < argv.length) {
rawValue = argv[i + 1];
}
}
if (SECRET_FLAGS.has(flag) && rawValue !== undefined && rawValue.length > 0) {
addRawAndDecodedNeedle(needles, rawValue);
if (flag === '--questdb-url') {
try {
const parsed = new URL(rawValue);
if (parsed.href.length > 0) {
needles.add(parsed.href);
}
addRawAndDecodedNeedle(needles, parsed.password);
for (const [k, v] of parsed.searchParams.entries()) {
if (k.toLowerCase() === 'password' && v.length > 0) {
addRawAndDecodedNeedle(needles, v);
}
}
} catch {
// Non-URL string: raw string already registered.
}
}
}
}
return needles;
}
export function redactSecrets(message: string, needles: Iterable<string>): string {
let out = message;
const sorted = Array.from(new Set(needles))
.filter(n => n.length > 0)
.sort((a, b) => b.length - a.length);
for (const needle of sorted) {
out = out.split(needle).join('[REDACTED]');
}
out = out.replace(POSTGRES_URL_RE, '[REDACTED_DSN]');
out = out.replace(URL_CREDENTIAL_RE, '$1[REDACTED]:[REDACTED]@');
return out;
}
function validateRawTokenValue(flag: string, rawValue: string): string {
if (rawValue.length === 0 || rawValue.trim().length === 0) {
throw new VerifyM2QuantError(`Flag '${flag}' requires a non-empty value.`);
}
if (rawValue.includes('\0')) {
throw new VerifyM2QuantError(`Flag '${flag}' value must not contain NUL bytes.`);
}
if (!SECRET_FLAGS.has(flag) && rawValue.startsWith('-')) {
throw new VerifyM2QuantError(
`Flag '${flag}' value must not start with '-' (received '${rawValue}').`
);
}
return rawValue;
}
function parsePositiveIntFlag(flag: string, rawValue: string, maxValue?: number): number {
const validated = validateRawTokenValue(flag, rawValue);
if (!STRICT_POSITIVE_INT_RE.test(validated)) {
throw new VerifyM2QuantError(
`Flag '${flag}' must be a positive integer (received '${validated}').`
);
}
const parsed = Number(validated);
if (!Number.isSafeInteger(parsed) || parsed <= 0 || (maxValue !== undefined && parsed > maxValue)) {
throw new VerifyM2QuantError(
`Flag '${flag}' is out of allowed range (received '${validated}').`
);
}
return parsed;
}
function parseBooleanFlagValue(flag: string, rawValue: string): boolean {
const normalized = validateRawTokenValue(flag, rawValue).trim().toLowerCase();
if (normalized === 'true') {
return true;
}
if (normalized === 'false') {
return false;
}
throw new VerifyM2QuantError(
`Flag '${flag}' must be 'true' or 'false' (received '${rawValue}').`
);
}
function parseStrictUtcIsoZ(flag: string, rawValue: string): number {
const validated = validateRawTokenValue(flag, rawValue);
const match = STRICT_UTC_INSTANT_RE.exec(validated);
if (match === null) {
throw new VerifyM2QuantError(
`Flag '${flag}' must be a strict ISO-8601 UTC timestamp ending in 'Z' (received '${validated}').`
);
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const hours = Number(match[4]);
const minutes = Number(match[5]);
const seconds = Number(match[6]);
const frac = match[7] !== undefined ? Number(match[7].padEnd(3, '0')) : 0;
const epochMs = Date.UTC(year, month - 1, day, hours, minutes, seconds, frac);
const check = new Date(epochMs);
if (
!Number.isSafeInteger(epochMs) ||
check.getUTCFullYear() !== year ||
check.getUTCMonth() !== month - 1 ||
check.getUTCDate() !== day ||
check.getUTCHours() !== hours ||
check.getUTCMinutes() !== minutes ||
check.getUTCSeconds() !== seconds ||
check.getUTCMilliseconds() !== frac
) {
throw new VerifyM2QuantError(
`Flag '${flag}' contains an invalid UTC calendar instant (received '${validated}').`
);
}
return epochMs;
}
function assertSafeDuckDbPath(rawPath: string, flag: string): string {
for (let i = 0; i < rawPath.length; i += 1) {
const code = rawPath.charCodeAt(i);
if (code <= 0x1f || code === 0x7f || code === 0x27 || code === 0x3b) {
throw new VerifyM2QuantError(
`Flag '${flag}' contains characters disallowed in DuckDB Parquet paths.`
);
}
}
return rawPath.replace(/\/+$/, '') || '/';
}
export function parseVerifyM2QuantArgs(
argv: readonly string[],
options?: ParseVerifyM2QuantArgsOptions
): ParsedVerifyM2QuantArgs {
const baseCwd = options?.cwd ?? process.cwd();
const seenValues = new Map<string, string>();
const seenBooleans = new Set<string>();
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i] as string;
if (token === '--help' || token === '-h') {
return { kind: 'help' };
}
if (token === '--') {
throw new VerifyM2QuantError('Unexpected positional argument separator "--".');
}
if (!token.startsWith('-')) {
throw new VerifyM2QuantError(`Unexpected positional argument '${token}'.`);
}
const eqIndex = token.indexOf('=');
if (eqIndex !== -1) {
const flag = token.slice(0, eqIndex);
const rawValue = token.slice(eqIndex + 1);
if (BOOLEAN_FLAGS.has(flag)) {
throw new VerifyM2QuantError(`Flag '${flag}' does not accept a value.`);
}
if (!VALUE_FLAGS.has(flag)) {
throw new VerifyM2QuantError(`Unknown flag '${flag}'.`);
}
if (seenValues.has(flag)) {
throw new VerifyM2QuantError(`Duplicate flag '${flag}'.`);
}
seenValues.set(flag, validateRawTokenValue(flag, rawValue));
continue;
}
if (BOOLEAN_FLAGS.has(token)) {
if (seenBooleans.has(token)) {
throw new VerifyM2QuantError(`Duplicate flag '${token}'.`);
}
seenBooleans.add(token);
continue;
}
if (!VALUE_FLAGS.has(token)) {
throw new VerifyM2QuantError(`Unknown flag '${token}'.`);
}
if (seenValues.has(token)) {
throw new VerifyM2QuantError(`Duplicate flag '${token}'.`);
}
if (i + 1 >= argv.length) {
throw new VerifyM2QuantError(`Flag '${token}' requires a value.`);
}
i += 1;
seenValues.set(token, validateRawTokenValue(token, argv[i] as string));
}
const rawUrl = seenValues.get('--questdb-url');
const rawHost = seenValues.get('--questdb-host');
const rawPort = seenValues.get('--questdb-pg-port');
const rawDb = seenValues.get('--questdb-database');
const rawUser = seenValues.get('--questdb-user');
const rawPassword = seenValues.get('--questdb-password');
const rawSsl = seenValues.get('--questdb-ssl');
const ssl = rawSsl !== undefined ? parseBooleanFlagValue('--questdb-ssl', rawSsl) : undefined;
let questdb: QuestDbPgExecutorConfig;
if (rawUrl !== undefined) {
if (
rawHost !== undefined ||
rawPort !== undefined ||
rawDb !== undefined ||
rawUser !== undefined ||
rawPassword !== undefined
) {
throw new VerifyM2QuantError(
'Cannot combine --questdb-url with --questdb-host/--questdb-pg-port/--questdb-database/--questdb-user/--questdb-password.'
);
}
questdb = {
url: rawUrl,
...(ssl !== undefined ? { ssl } : {}),
};
} else {
if (rawHost === undefined || rawPort === undefined) {
throw new VerifyM2QuantError(
'Missing required QuestDB connection flags: provide --questdb-url or both --questdb-host and --questdb-pg-port.'
);
}
const port = parsePositiveIntFlag('--questdb-pg-port', rawPort, 65_535);
questdb = {
host: rawHost,
port,
...(rawDb !== undefined ? { database: rawDb } : {}),
...(rawUser !== undefined ? { user: rawUser } : {}),
...(rawPassword !== undefined ? { password: rawPassword } : {}),
...(ssl !== undefined ? { ssl } : {}),
};
}
const rawWalTimeout = seenValues.get('--wal-settle-timeout-ms');
const walSettleTimeoutMs =
rawWalTimeout !== undefined
? parsePositiveIntFlag('--wal-settle-timeout-ms', rawWalTimeout)
: DEFAULT_WAL_SETTLE_TIMEOUT_MS;
const rawOut = seenValues.get('--out');
const outPath = rawOut !== undefined ? resolve(baseCwd, rawOut) : undefined;
if (seenBooleans.has('--ddl-only')) {
return {
kind: 'ddl_only',
questdb,
walSettleTimeoutMs,
...(outPath !== undefined ? { outPath } : {}),
};
}
const requireFlag = (flag: string): string => {
const val = seenValues.get(flag);
if (val === undefined) {
throw new VerifyM2QuantError(`Missing required flag ${flag}.`);
}
return val;
};
const curatedRoot = assertSafeDuckDbPath(
resolve(baseCwd, requireFlag('--curated-root')),
'--curated-root'
);
const vaultCutoffIso = requireFlag('--vault-cutoff-ts');
const vaultCutoffTs = parseStrictUtcIsoZ('--vault-cutoff-ts', vaultCutoffIso);
const nvdaListingId = parsePositiveIntFlag(
'--nvda-listing-id',
requireFlag('--nvda-listing-id'),
INT32_MAX
);
const nexmListingId = parsePositiveIntFlag(
'--nexm-listing-id',
requireFlag('--nexm-listing-id'),
INT32_MAX
);
const benchListingId = parsePositiveIntFlag(
'--bench-listing-id',
requireFlag('--bench-listing-id'),
INT32_MAX
);
const benchFrom = requireFlag('--bench-from');
const benchTo = requireFlag('--bench-to');
const benchAsOf = requireFlag('--bench-as-of');
const loadReceiptPath = resolve(baseCwd, requireFlag('--load-receipt'));
const rawResendBaseline = seenValues.get('--resend-baseline');
const resendBaselinePath =
rawResendBaseline !== undefined ? resolve(baseCwd, rawResendBaseline) : undefined;
const rawBenchScope = seenValues.get('--bench-scope');
let benchScope: DataScope = 'vault_fenced';
if (rawBenchScope !== undefined) {
if (rawBenchScope !== 'vault_fenced' && rawBenchScope !== 'vault_evaluation_only') {
throw new VerifyM2QuantError(
`Flag '--bench-scope' must be 'vault_fenced' or 'vault_evaluation_only' (received '${rawBenchScope}').`
);
}
benchScope = rawBenchScope;
}
const rawWarmRuns = seenValues.get('--warm-runs');
const warmRuns =
rawWarmRuns !== undefined ? parsePositiveIntFlag('--warm-runs', rawWarmRuns) : DEFAULT_WARM_RUNS;
return {
kind: 'run',
questdb,
curatedRoot,
vaultCutoffIso,
vaultCutoffTs,
nvdaListingId,
nexmListingId,
benchListingId,
benchFrom,
benchTo,
benchAsOf,
benchScope,
loadReceiptPath,
...(resendBaselinePath !== undefined ? { resendBaselinePath } : {}),
applyDdl: seenBooleans.has('--apply-ddl'),
warmRuns,
walSettleTimeoutMs,
...(outPath !== undefined ? { outPath } : {}),
};
}
function parseBigIntCell(value: unknown, field: string): bigint {
if (typeof value === 'bigint') {
return value;
}
if (typeof value === 'number' && Number.isSafeInteger(value)) {
return BigInt(value);
}
if (typeof value === 'string' && STRICT_SIGNED_INT_RE.test(value.trim())) {
return BigInt(value.trim());
}
throw new VerifyM2QuantError(`Invalid integer value for '${field}': ${String(value)}.`);
}
function parseFiniteNumberCell(value: unknown, field: string): number {
if (typeof value === 'number' && Number.isFinite(value)) {
return Object.is(value, -0) ? 0 : value;
}
if (typeof value === 'string' && value.trim().length > 0) {
const parsed = Number(value.trim());
if (Number.isFinite(parsed)) {
return Object.is(parsed, -0) ? 0 : parsed;
}
}
throw new VerifyM2QuantError(`Invalid finite numeric value for '${field}': ${String(value)}.`);
}
function parseBooleanCell(value: unknown, field: string): boolean {
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'string') {
const lower = value.trim().toLowerCase();
if (lower === 'true' || lower === 't') {
return true;
}
if (lower === 'false' || lower === 'f') {
return false;
}
}
throw new VerifyM2QuantError(`Invalid boolean value for '${field}': ${String(value)}.`);
}
function parseRequiredStringCell(value: unknown, field: string): string {
if (typeof value === 'string' && value.trim().length > 0) {
return value.trim();
}
throw new VerifyM2QuantError(`Invalid string value for '${field}': ${String(value)}.`);
}
function formatNySessionDateFromMicros(tsUs: bigint): string {
const epochMs = Number(tsUs / 1000n);
if (!Number.isSafeInteger(epochMs)) {
throw new VerifyM2QuantError(`Out-of-range QuestDB timestamp micros: ${tsUs.toString()}.`);
}
const formatted = NY_DATE_FORMATTER.format(new Date(epochMs));
if (!DATE_ONLY_RE.test(formatted)) {
throw new VerifyM2QuantError(`Unexpected America/New_York session date format: '${formatted}'.`);
}
return formatted;
}
function addUtcDays(isoDate: string, deltaDays: number): string {
const parts = isoDate.split('-').map(Number);
const year = parts[0] as number;
const month = parts[1] as number;
const day = parts[2] as number;
const ms = Date.UTC(year, month - 1, day + deltaDays);
return new Date(ms).toISOString().slice(0, 10);
}
function computeBarsDigest(bars: readonly BarRecord[]): string {
const hash = createHash('sha256');
for (let i = 0; i < bars.length; i += 1) {
const bar = bars[i] as BarRecord;
hash.update(
`${bar.listingId},${bar.ts},${bar.open},${bar.high},${bar.low},${bar.close},${bar.volume},${bar.vwap ?? ''},${bar.knownAt}\n`
);
}
return hash.digest('hex');
}
function computeMedian(values: readonly number[]): number {
const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 1) {
return sorted[mid] as number;
}
return ((sorted[mid - 1] as number) + (sorted[mid] as number)) / 2;
}
function describeSafeQuestDbTarget(config: QuestDbPgExecutorConfig): string {
if (config.url !== undefined) {
try {
const parsed = new URL(config.url);
const port = parsed.port || '8812';
return `${parsed.hostname}:${port}`;
} catch {
return '[redacted-url]';
}
}
return `${config.host ?? 'localhost'}:${config.port ?? 8812}`;
}
async function waitForHealthyWalTables(
executor: QuestDbPgQueryExecutor,
timeoutMs: number,
pollIntervalMs: number,
nowMs: () => number,
sleepMs: (ms: number) => Promise<void>
): Promise<readonly WalTableStatusRow[]> {
const deadline = nowMs() + timeoutMs;
const sql =
"SELECT name, suspended, writerTxn, sequencerTxn FROM wal_tables() WHERE name IN ('bars_1m', 'fx_1m', 'bar_revisions') ORDER BY name";
while (true) {
const res = await executor.query(sql);
const byName = new Map<
M2IntradayTableName,
{ suspended: boolean; writerTxn: bigint; sequencerTxn: bigint }
>();
for (const row of res.rows) {
const name = parseRequiredStringCell(row.name, 'wal_tables.name');
if (!(M2_INTRADAY_TABLE_NAMES as readonly string[]).includes(name)) {
continue;
}
const suspended = parseBooleanCell(row.suspended, `${name}.suspended`);
const writerTxn = parseBigIntCell(
row.writerTxn ?? row.writertxn,
`${name}.writerTxn`
);
const sequencerTxn = parseBigIntCell(
row.sequencerTxn ?? row.sequencertxn,
`${name}.sequencerTxn`
);
byName.set(name as M2IntradayTableName, { suspended, writerTxn, sequencerTxn });
}
const missing = M2_INTRADAY_TABLE_NAMES.filter(name => !byName.has(name));
if (missing.length > 0) {
throw new VerifyM2QuantError(
`Missing required M2 WAL tables in wal_tables(): ${missing.join(', ')}.`
);
}
const suspendedTables = M2_INTRADAY_TABLE_NAMES.filter(
name => byName.get(name)?.suspended === true
);
if (suspendedTables.length > 0) {
throw new VerifyM2QuantError(
`Suspended QuestDB WAL table(s) detected: ${suspendedTables.join(', ')}.`
);
}
const unsettled = M2_INTRADAY_TABLE_NAMES.filter(name => {
const status = byName.get(name)!;
return status.writerTxn < status.sequencerTxn;
});
if (unsettled.length === 0) {
return M2_INTRADAY_TABLE_NAMES.map(name => {
const status = byName.get(name)!;
return {
name,
suspended: status.suspended,
writerTxn: status.writerTxn.toString(),
sequencerTxn: status.sequencerTxn.toString(),
};
});
}
if (nowMs() >= deadline) {
const details = unsettled
.map(name => {
const status = byName.get(name)!;
return `${name}(writerTxn=${status.writerTxn.toString()}<sequencerTxn=${status.sequencerTxn.toString()})`;
})
.join(', ');
throw new VerifyM2QuantError(
`Timed out after ${timeoutMs}ms waiting for QuestDB WAL tables to settle: ${details}.`
);
}
await sleepMs(pollIntervalMs);
}
}
async function verifyBars1mCommits(
executor: QuestDbPgQueryExecutor
): Promise<readonly Bars1mSourceSummaryRow[]> {
const sql =
'SELECT source, count() AS row_count, min(close) AS min_close, max(close) AS max_close, ' +
'CAST(min(ts) AS LONG) AS min_ts_us, CAST(max(ts) AS LONG) AS max_ts_us ' +
'FROM bars_1m GROUP BY source ORDER BY source';
const res = await executor.query(sql);
if (res.rows.length === 0) {
throw new VerifyM2QuantError('QuestDB bars_1m contains zero rows.');
}
const out: Bars1mSourceSummaryRow[] = [];
let totalRows = 0;
for (const row of res.rows) {
const source = parseRequiredStringCell(row.source, 'bars_1m.source');
const rowCount = Number(parseBigIntCell(row.row_count, `bars_1m[${source}].row_count`));
if (!Number.isSafeInteger(rowCount) || rowCount <= 0) {
throw new VerifyM2QuantError(`QuestDB bars_1m source '${source}' has non-positive row_count: ${rowCount}.`);
}
const minClose = parseFiniteNumberCell(row.min_close, `bars_1m[${source}].min_close`);
const maxClose = parseFiniteNumberCell(row.max_close, `bars_1m[${source}].max_close`);
if (minClose <= 0 || maxClose <= 0 || minClose > maxClose) {
throw new VerifyM2QuantError(
`QuestDB bars_1m source '${source}' has invalid close bounds [${minClose}, ${maxClose}].`
);
}
const minTsUs = parseBigIntCell(row.min_ts_us, `bars_1m[${source}].min_ts_us`);
const maxTsUs = parseBigIntCell(row.max_ts_us, `bars_1m[${source}].max_ts_us`);
if (minTsUs > maxTsUs) {
throw new VerifyM2QuantError(
`QuestDB bars_1m source '${source}' has inverted timestamp range [${minTsUs.toString()}, ${maxTsUs.toString()}].`
);
}
totalRows += rowCount;
out.push({
source,
rowCount,
minClose,
maxClose,
minTsUs: minTsUs.toString(),
maxTsUs: maxTsUs.toString(),
});
}
if (totalRows <= 0) {
throw new VerifyM2QuantError('QuestDB bars_1m total row count is zero.');
}
return out;
}
async function verifyFx1mCommits(
executor: QuestDbPgQueryExecutor
): Promise<readonly Fx1mPairSourceSummaryRow[]> {
const sql =
'SELECT pair, source, count() AS row_count, min(close) AS min_close, max(close) AS max_close, ' +
'CAST(min(ts) AS LONG) AS min_ts_us, CAST(max(ts) AS LONG) AS max_ts_us ' +
'FROM fx_1m GROUP BY pair, source ORDER BY pair, source';
const res = await executor.query(sql);
if (res.rows.length === 0) {
throw new VerifyM2QuantError('QuestDB fx_1m contains zero rows.');
}
const out: Fx1mPairSourceSummaryRow[] = [];
let totalRows = 0;
for (const row of res.rows) {
const pair = parseRequiredStringCell(row.pair, 'fx_1m.pair');
const source = parseRequiredStringCell(row.source, 'fx_1m.source');
const rowCount = Number(parseBigIntCell(row.row_count, `fx_1m[${pair}/${source}].row_count`));
if (!Number.isSafeInteger(rowCount) || rowCount <= 0) {
throw new VerifyM2QuantError(
`QuestDB fx_1m group '${pair}/${source}' has non-positive row_count: ${rowCount}.`
);
}
const minClose = parseFiniteNumberCell(row.min_close, `fx_1m[${pair}/${source}].min_close`);
const maxClose = parseFiniteNumberCell(row.max_close, `fx_1m[${pair}/${source}].max_close`);
if (minClose <= 0 || maxClose <= 0 || minClose > maxClose) {
throw new VerifyM2QuantError(
`QuestDB fx_1m group '${pair}/${source}' has invalid close bounds [${minClose}, ${maxClose}].`
);
}
const minTsUs = parseBigIntCell(row.min_ts_us, `fx_1m[${pair}/${source}].min_ts_us`);
const maxTsUs = parseBigIntCell(row.max_ts_us, `fx_1m[${pair}/${source}].max_ts_us`);
if (minTsUs > maxTsUs) {
throw new VerifyM2QuantError(
`QuestDB fx_1m group '${pair}/${source}' has inverted timestamp range [${minTsUs.toString()}, ${maxTsUs.toString()}].`
);
}
totalRows += rowCount;
out.push({
pair,
source,
rowCount,
minClose,
maxClose,
minTsUs: minTsUs.toString(),
maxTsUs: maxTsUs.toString(),
});
}
if (totalRows <= 0) {
throw new VerifyM2QuantError('QuestDB fx_1m total row count is zero.');
}
return out;
}
async function verifySplitBoundaryCase(
spec: SplitBoundaryCaseSpec,
listingId: number,
questExecutor: QuestDbPgQueryExecutor,
duckExecutor: ClosableDuckDbExecutor,
curatedRoot: string
): Promise<SplitBoundaryCheckResult> {
const fromUtcIso = `${spec.fromDate}T00:00:00.000Z`;
const toUtcIso = `${addUtcDays(spec.toDate, 1)}T05:00:00.000Z`;
const qdbSql =
"SELECT CAST(ts AS LONG) AS ts_us, close FROM bars_1m WHERE listing_id = $1 AND session = 'RTH' AND ts >= $2 AND ts <= $3 ORDER BY ts ASC";
const qdbRes = await questExecutor.query(qdbSql, [String(listingId), fromUtcIso, toUtcIso]);
const latestClose1mByDate = new Map<string, { tsUs: bigint; close: number }>();
for (const row of qdbRes.rows) {
const tsUs = parseBigIntCell(row.ts_us, `${spec.label}.bars_1m.ts_us`);
const close = parseFiniteNumberCell(row.close, `${spec.label}.bars_1m.close`);
if (close <= 0) {
throw new VerifyM2QuantError(
`${spec.label} bars_1m returned non-positive close (${close}) at ts_us=${tsUs.toString()}.`
);
}
const nyDate = formatNySessionDateFromMicros(tsUs);
if (nyDate < spec.fromDate || nyDate > spec.toDate) {
continue;
}
const prev = latestClose1mByDate.get(nyDate);
if (prev === undefined || tsUs >= prev.tsUs) {
latestClose1mByDate.set(nyDate, { tsUs, close });
}
}
const bars1dPath = `${curatedRoot}/bars_1d/year=*/part.parquet`;
const duckSql =
'SELECT CAST(session_date AS VARCHAR) AS session_date, close ' +
`FROM read_parquet('${bars1dPath}', hive_partitioning = true) ` +
'WHERE listing_id = ? AND session_date >= CAST(? AS DATE) AND session_date <= CAST(? AS DATE) ' +
'ORDER BY session_date ASC';
const duckRows = await duckExecutor.query(duckSql, [listingId, spec.fromDate, spec.toDate]);
const close1dByDate = new Map<string, number>();
for (const row of duckRows) {
const sessionDate = parseRequiredStringCell(row.session_date, `${spec.label}.bars_1d.session_date`);
const close = parseFiniteNumberCell(row.close, `${spec.label}.bars_1d.close`);
if (close <= 0) {
throw new VerifyM2QuantError(
`${spec.label} bars_1d returned non-positive close (${close}) on ${sessionDate}.`
);
}
close1dByDate.set(sessionDate, close);
}
const matchedDates = Array.from(latestClose1mByDate.keys())
.filter(date => close1dByDate.has(date))
.sort();
const sessions: SplitBoundarySessionComparison[] = [];
let preSplitCount = 0;
let exOrPostSplitCount = 0;
let maxRelDiff = 0;
for (const sessionDate of matchedDates) {
const close1m = latestClose1mByDate.get(sessionDate)!.close;
const close1d = close1dByDate.get(sessionDate)!;
const relDiff = Math.abs(close1m - close1d) / close1d;
const phase: 'pre_split' | 'ex_or_post_split' =
sessionDate < spec.exDate ? 'pre_split' : 'ex_or_post_split';
if (phase === 'pre_split') {
preSplitCount += 1;
} else {
exOrPostSplitCount += 1;
}
if (relDiff > maxRelDiff) {
maxRelDiff = relDiff;
}
if (relDiff > MAX_SPLIT_CLOSE_REL_DIFF) {
throw new VerifyM2QuantError(
`${spec.label} split-boundary close mismatch on ${sessionDate}: bars_1m=${close1m}, bars_1d=${close1d}, relDiff=${(relDiff * 100).toFixed(4)}% > ${(MAX_SPLIT_CLOSE_REL_DIFF * 100).toFixed(2)}%.`
);
}
sessions.push({ sessionDate, phase, close1m, close1d, relDiff });
}
if (preSplitCount < 1) {
throw new VerifyM2QuantError(
`${spec.label} split-boundary check requires >= 1 matched pre-split session before ${spec.exDate} (found ${preSplitCount}).`
);
}
if (exOrPostSplitCount < 1) {
throw new VerifyM2QuantError(
`${spec.label} split-boundary check requires >= 1 matched ex-date/post-split session on/after ${spec.exDate} (found ${exOrPostSplitCount}).`
);
}
return {
label: spec.label,
listingId,
fromDate: spec.fromDate,
toDate: spec.toDate,
exDate: spec.exDate,
ratio: spec.ratio,
preSplitCount,
exOrPostSplitCount,
maxRelDiff,
sessions,
};
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function parseNonNegativeBigIntString(value: unknown, field: string): bigint {
if (typeof value === 'string' && STRICT_NON_NEGATIVE_INT_RE.test(value.trim())) {
return BigInt(value.trim());
}
if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) {
return BigInt(value);
}
throw new VerifyM2QuantError(`Invalid non-negative integer for '${field}': ${String(value)}.`);
}
function parsePositiveSafeInt(value: unknown, field: string, maxValue?: number): number {
if (
typeof value === 'number' &&
Number.isSafeInteger(value) &&
value > 0 &&
(maxValue === undefined || value <= maxValue)
) {
return value;
}
throw new VerifyM2QuantError(`Invalid positive integer for '${field}': ${String(value)}.`);
}
function parseNonNegativeSafeInt(value: unknown, field: string): number {
if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) {
return value;
}
throw new VerifyM2QuantError(`Invalid non-negative integer for '${field}': ${String(value)}.`);
}
function formatUtcIsoMicros(tsUs: bigint): string {
const floorMs = tsUs >= 0n ? tsUs / 1000n : (tsUs - 999n) / 1000n;
const subMsMicros = Number(tsUs - floorMs * 1000n);
const epochMs = Number(floorMs);
if (!Number.isSafeInteger(epochMs)) {
throw new VerifyM2QuantError(`Out-of-range QuestDB timestamp micros: ${tsUs.toString()}.`);
}
const isoMs = new Date(epochMs).toISOString();
return `${isoMs.slice(0, -1)}${String(subMsMicros).padStart(3, '0')}Z`;
}
function parseWalTxnPair(value: unknown, field: string): WalTxnPair {
if (!isPlainObject(value)) {
throw new VerifyM2QuantError(`Expected object for '${field}'.`);
}
const writerTxn = parseNonNegativeBigIntString(value.writerTxn, `${field}.writerTxn`);
const sequencerTxn = parseNonNegativeBigIntString(value.sequencerTxn, `${field}.sequencerTxn`);
return {
writerTxn: writerTxn.toString(),
sequencerTxn: sequencerTxn.toString(),
};
}
function parseBars1mProbe(
value: unknown,
field: string,
requiredSource: 'eod' | 'qm'
): Bars1mProbeExpectation {
if (!isPlainObject(value)) {
throw new VerifyM2QuantError(`Expected probe object for '${field}'.`);
}
const listingId = parsePositiveSafeInt(value.listingId, `${field}.listingId`, INT32_MAX);
const tsUs = parseBigIntCell(value.tsUs, `${field}.tsUs`);
const expectedClose = parseFiniteNumberCell(value.expectedClose, `${field}.expectedClose`);
if (expectedClose <= 0) {
throw new VerifyM2QuantError(`${field}.expectedClose must be positive.`);
}
const expectedSource = parseRequiredStringCell(value.expectedSource, `${field}.expectedSource`);
if (expectedSource !== requiredSource) {
throw new VerifyM2QuantError(
`${field}.expectedSource must be '${requiredSource}' (received '${expectedSource}').`
);
}
let expectedKnownAtUs: string | undefined;
if (value.expectedKnownAtUs !== undefined) {
expectedKnownAtUs = parseBigIntCell(
value.expectedKnownAtUs,
`${field}.expectedKnownAtUs`
).toString();
}
let closeTolerance: number | undefined;
if (value.closeTolerance !== undefined) {
closeTolerance = parseFiniteNumberCell(value.closeTolerance, `${field}.closeTolerance`);
if (closeTolerance < 0) {
throw new VerifyM2QuantError(`${field}.closeTolerance must be >= 0.`);
}
}
return {
listingId,
tsUs: tsUs.toString(),
expectedClose,
expectedSource,
...(expectedKnownAtUs !== undefined ? { expectedKnownAtUs } : {}),
...(closeTolerance !== undefined ? { closeTolerance } : {}),
};
}
function parseFx1mProbe(value: unknown, field: string): Fx1mProbeExpectation {
if (!isPlainObject(value)) {
throw new VerifyM2QuantError(`Expected probe object for '${field}'.`);
}
const pair = parseRequiredStringCell(value.pair, `${field}.pair`);
const tsUs = parseBigIntCell(value.tsUs, `${field}.tsUs`);
const expectedClose = parseFiniteNumberCell(value.expectedClose, `${field}.expectedClose`);
if (expectedClose <= 0) {
throw new VerifyM2QuantError(`${field}.expectedClose must be positive.`);
}
const expectedSource = parseRequiredStringCell(value.expectedSource, `${field}.expectedSource`);
let closeTolerance: number | undefined;
if (value.closeTolerance !== undefined) {
closeTolerance = parseFiniteNumberCell(value.closeTolerance, `${field}.closeTolerance`);
if (closeTolerance < 0) {
throw new VerifyM2QuantError(`${field}.closeTolerance must be >= 0.`);
}
}
return {
pair,
tsUs: tsUs.toString(),
expectedClose,
expectedSource,
...(closeTolerance !== undefined ? { closeTolerance } : {}),
};
}
export function parseLoadReceiptJson(rawJson: string): M2LoadReceipt {
let parsed: unknown;
try {
parsed = JSON.parse(rawJson);
} catch (err: unknown) {
const detail = err instanceof Error ? err.message : String(err);
throw new VerifyM2QuantError(`Failed to parse --load-receipt JSON: ${detail}`);
}
if (!isPlainObject(parsed)) {
throw new VerifyM2QuantError('Load receipt JSON must be a top-level object.');
}
if (!isPlainObject(parsed.beforeWal)) {
throw new VerifyM2QuantError('Load receipt missing required object "beforeWal".');
}
const beforeWal: LoadReceiptWalSnapshot = {
bars_1m: parseWalTxnPair(parsed.beforeWal.bars_1m, 'beforeWal.bars_1m'),
fx_1m: parseWalTxnPair(parsed.beforeWal.fx_1m, 'beforeWal.fx_1m'),
...(parsed.beforeWal.bar_revisions !== undefined
? {
bar_revisions: parseWalTxnPair(
parsed.beforeWal.bar_revisions,
'beforeWal.bar_revisions'
),
}
: {}),
};
if (!isPlainObject(parsed.shards)) {
throw new VerifyM2QuantError('Load receipt missing required object "shards".');
}
const parseShardProbesRaw = (prefix: RequiredShardPrefix): readonly unknown[] => {
const entry = (parsed.shards as Record<string, unknown>)[prefix];
if (!isPlainObject(entry) || !Array.isArray(entry.probes) || entry.probes.length === 0) {
throw new VerifyM2QuantError(
`Load receipt shards.${prefix}.probes must be a non-empty array.`
);
}
return entry.probes;
};
const bars1mProbes = parseShardProbesRaw('bars_1m').map((p, idx) =>
parseBars1mProbe(p, `shards.bars_1m.probes[${idx}]`, 'eod')
);
const bars1mQmProbes = parseShardProbesRaw('bars_1m_qm').map((p, idx) =>
parseBars1mProbe(p, `shards.bars_1m_qm.probes[${idx}]`, 'qm')
);
const fx1mProbes = parseShardProbesRaw('fx_1m').map((p, idx) =>
parseFx1mProbe(p, `shards.fx_1m.probes[${idx}]`)
);
if (!isPlainObject(parsed.dedup)) {
throw new VerifyM2QuantError('Load receipt missing required object "dedup".');
}
const eodSentRows = parsePositiveSafeInt(parsed.dedup.eodSentRows, 'dedup.eodSentRows');
const qmSentRows = parsePositiveSafeInt(parsed.dedup.qmSentRows, 'dedup.qmSentRows');
const overlapRows = parseNonNegativeSafeInt(parsed.dedup.overlapRows, 'dedup.overlapRows');
if (overlapRows > Math.min(eodSentRows, qmSentRows)) {
throw new VerifyM2QuantError(
`Load receipt dedup.overlapRows (${overlapRows}) exceeds min(eodSentRows=${eodSentRows}, qmSentRows=${qmSentRows}).`
);
}
const overlapWinnerSourceRaw = parseRequiredStringCell(
parsed.dedup.overlapWinnerSource,
'dedup.overlapWinnerSource'
);
if (overlapWinnerSourceRaw !== 'eod' && overlapWinnerSourceRaw !== 'qm') {
throw new VerifyM2QuantError(
`Load receipt dedup.overlapWinnerSource must be 'eod' or 'qm' (received '${overlapWinnerSourceRaw}').`
);
}
const overlapWinnerSource: 'eod' | 'qm' = overlapWinnerSourceRaw;
let overlapProbes: readonly Bars1mProbeExpectation[] | undefined;
if (parsed.dedup.overlapProbes !== undefined) {
if (!Array.isArray(parsed.dedup.overlapProbes)) {
throw new VerifyM2QuantError('Load receipt dedup.overlapProbes must be an array.');
}
overlapProbes = parsed.dedup.overlapProbes.map((p, idx) =>
parseBars1mProbe(p, `dedup.overlapProbes[${idx}]`, overlapWinnerSource)
);
}
return {
beforeWal,
shards: {
bars_1m: { probes: bars1mProbes },
bars_1m_qm: { probes: bars1mQmProbes },
fx_1m: { probes: fx1mProbes },
},
dedup: {
eodSentRows,
qmSentRows,
overlapRows,
overlapWinnerSource,
...(overlapProbes !== undefined ? { overlapProbes } : {}),
},
};
}
interface ParsedResendBaseline {
readonly walTables: ReadonlyMap<M2IntradayTableName, WalTxnPair>;
readonly bars1mSummary: readonly Bars1mSourceSummaryRow[];
readonly fx1mSummary: readonly Fx1mPairSourceSummaryRow[];
}
function parseResendBaselineJson(rawJson: string): ParsedResendBaseline {
let parsed: unknown;
try {
parsed = JSON.parse(rawJson);
} catch (err: unknown) {
const detail = err instanceof Error ? err.message : String(err);
throw new VerifyM2QuantError(`Failed to parse --resend-baseline JSON: ${detail}`);
}
if (!isPlainObject(parsed) || parsed.ok !== true) {
throw new VerifyM2QuantError('Resend baseline JSON must be a passing VerifyM2QuantReport (ok: true).');
}
if (!Array.isArray(parsed.walTables) || parsed.walTables.length === 0) {
throw new VerifyM2QuantError('Resend baseline missing required non-empty "walTables" array.');
}
const walMap = new Map<M2IntradayTableName, WalTxnPair>();
for (let i = 0; i < parsed.walTables.length; i += 1) {
const entry = parsed.walTables[i];
if (!isPlainObject(entry)) {
throw new VerifyM2QuantError(`Resend baseline walTables[${i}] must be an object.`);
}
const name = parseRequiredStringCell(entry.name, `resendBaseline.walTables[${i}].name`);
if (!(M2_INTRADAY_TABLE_NAMES as readonly string[]).includes(name)) {
continue;
}
walMap.set(
name as M2IntradayTableName,
parseWalTxnPair(entry, `resendBaseline.walTables[${i}]`)
);
}
for (const required of ['bars_1m', 'fx_1m'] as const) {
if (!walMap.has(required)) {
throw new VerifyM2QuantError(`Resend baseline walTables missing required table '${required}'.`);
}
}
if (!Array.isArray(parsed.bars1mSummary) || parsed.bars1mSummary.length === 0) {
throw new VerifyM2QuantError('Resend baseline missing required non-empty "bars1mSummary" array.');
}
const bars1mSummary: Bars1mSourceSummaryRow[] = parsed.bars1mSummary.map((entry, idx) => {
if (!isPlainObject(entry)) {
throw new VerifyM2QuantError(`Resend baseline bars1mSummary[${idx}] must be an object.`);
}
return {
source: parseRequiredStringCell(entry.source, `resendBaseline.bars1mSummary[${idx}].source`),
rowCount: parsePositiveSafeInt(entry.rowCount, `resendBaseline.bars1mSummary[${idx}].rowCount`),
minClose: parseFiniteNumberCell(entry.minClose, `resendBaseline.bars1mSummary[${idx}].minClose`),
maxClose: parseFiniteNumberCell(entry.maxClose, `resendBaseline.bars1mSummary[${idx}].maxClose`),
minTsUs: parseBigIntCell(entry.minTsUs, `resendBaseline.bars1mSummary[${idx}].minTsUs`).toString(),
maxTsUs: parseBigIntCell(entry.maxTsUs, `resendBaseline.bars1mSummary[${idx}].maxTsUs`).toString(),
};
});
if (!Array.isArray(parsed.fx1mSummary) || parsed.fx1mSummary.length === 0) {
throw new VerifyM2QuantError('Resend baseline missing required non-empty "fx1mSummary" array.');
}
const fx1mSummary: Fx1mPairSourceSummaryRow[] = parsed.fx1mSummary.map((entry, idx) => {
if (!isPlainObject(entry)) {
throw new VerifyM2QuantError(`Resend baseline fx1mSummary[${idx}] must be an object.`);
}
return {
pair: parseRequiredStringCell(entry.pair, `resendBaseline.fx1mSummary[${idx}].pair`),
source: parseRequiredStringCell(entry.source, `resendBaseline.fx1mSummary[${idx}].source`),
rowCount: parsePositiveSafeInt(entry.rowCount, `resendBaseline.fx1mSummary[${idx}].rowCount`),
minClose: parseFiniteNumberCell(entry.minClose, `resendBaseline.fx1mSummary[${idx}].minClose`),
maxClose: parseFiniteNumberCell(entry.maxClose, `resendBaseline.fx1mSummary[${idx}].maxClose`),
minTsUs: parseBigIntCell(entry.minTsUs, `resendBaseline.fx1mSummary[${idx}].minTsUs`).toString(),
maxTsUs: parseBigIntCell(entry.maxTsUs, `resendBaseline.fx1mSummary[${idx}].maxTsUs`).toString(),
};
});
return { walTables: walMap, bars1mSummary, fx1mSummary };
}
function verifyWalAdvancement(
beforeMap: Readonly<Record<'bars_1m' | 'fx_1m', WalTxnPair>>,
afterTables: readonly WalTableStatusRow[],
contextLabel: string
): readonly WalAdvancementEntry[] {
const afterByName = new Map<M2IntradayTableName, WalTableStatusRow>(
afterTables.map(row => [row.name, row])
);
const results: WalAdvancementEntry[] = [];
for (const table of ['bars_1m', 'fx_1m'] as const) {
const before = beforeMap[table];
const after = afterByName.get(table);
if (after === undefined) {
throw new VerifyM2QuantError(`${contextLabel}: missing table '${table}' in settled wal_tables().`);
}
const beforeWriter = BigInt(before.writerTxn);
const afterWriter = BigInt(after.writerTxn);
const beforeSeq = BigInt(before.sequencerTxn);
const afterSeq = BigInt(after.sequencerTxn);
if (afterWriter <= beforeWriter || afterSeq <= beforeSeq) {
throw new VerifyM2QuantError(
`${contextLabel}: WAL for '${table}' did not advance (before writerTxn=${before.writerTxn}/sequencerTxn=${before.sequencerTxn}, after writerTxn=${after.writerTxn}/sequencerTxn=${after.sequencerTxn}).`
);
}
results.push({
table,
beforeWriterTxn: before.writerTxn,
afterWriterTxn: after.writerTxn,
beforeSequencerTxn: before.sequencerTxn,
afterSequencerTxn: after.sequencerTxn,
});
}
return results;
}
async function verifyBars1mProbe(
executor: QuestDbPgQueryExecutor,
shardPrefix: 'bars_1m' | 'bars_1m_qm' | 'dedup_overlap',
probe: Bars1mProbeExpectation
): Promise<ProbeCheckResult> {
const tsIso = formatUtcIsoMicros(BigInt(probe.tsUs));
const sql =
'SELECT listing_id, CAST(ts AS LONG) AS ts_us, close, source, CAST(known_at AS LONG) AS known_at_us ' +
'FROM bars_1m WHERE listing_id = $1 AND ts = $2';
const res = await executor.query(sql, [String(probe.listingId), tsIso]);
const key = `listing_id=${probe.listingId},ts_us=${probe.tsUs}`;
if (res.rows.length !== 1) {
throw new VerifyM2QuantError(
`Load receipt probe failed for ${shardPrefix} (${key}): expected exactly 1 row, found ${res.rows.length}.`
);
}
const row = res.rows[0]!;
const actualSource = parseRequiredStringCell(row.source, `${shardPrefix}[${key}].source`);
if (actualSource !== probe.expectedSource) {
throw new VerifyM2QuantError(
`Load receipt probe source mismatch for ${shardPrefix} (${key}): expected '${probe.expectedSource}', found '${actualSource}'.`
);
}
const actualClose = parseFiniteNumberCell(row.close, `${shardPrefix}[${key}].close`);
const tolerance = probe.closeTolerance ?? DEFAULT_PROBE_CLOSE_TOLERANCE;
const absDiff = Math.abs(actualClose - probe.expectedClose);
if (absDiff > tolerance) {
throw new VerifyM2QuantError(
`Load receipt probe 0x10 close mismatch for ${shardPrefix} (${key}): expected ${probe.expectedClose}, found ${actualClose} (absDiff=${absDiff} > tolerance=${tolerance}).`
);
}
if (probe.expectedKnownAtUs !== undefined) {
const actualKnownAtUs = parseBigIntCell(
row.known_at_us,
`${shardPrefix}[${key}].known_at_us`
).toString();
if (actualKnownAtUs !== probe.expectedKnownAtUs) {
throw new VerifyM2QuantError(
`Load receipt probe known_at mismatch for ${shardPrefix} (${key}): expected ${probe.expectedKnownAtUs}, found ${actualKnownAtUs}.`
);
}
}
return {
shardPrefix,
key,
expectedSource: probe.expectedSource,
actualSource,
expectedClose: probe.expectedClose,
actualClose,
absDiff,
};
}
async function verifyFx1mProbe(
executor: QuestDbPgQueryExecutor,
probe: Fx1mProbeExpectation
): Promise<ProbeCheckResult> {
const tsIso = formatUtcIsoMicros(BigInt(probe.tsUs));
const sql =
'SELECT pair, CAST(ts AS LONG) AS ts_us, close, source FROM fx_1m WHERE pair = $1 AND ts = $2';
const res = await executor.query(sql, [probe.pair, tsIso]);
const key = `pair=${probe.pair},ts_us=${probe.tsUs}`;
if (res.rows.length !== 1) {
throw new VerifyM2QuantError(
`Load receipt probe failed for fx_1m (${key}): expected exactly 1 row, found ${res.rows.length}.`
);
}
const row = res.rows[0]!;
const actualSource = parseRequiredStringCell(row.source, `fx_1m[${key}].source`);
if (actualSource !== probe.expectedSource) {
throw new VerifyM2QuantError(
`Load receipt probe source mismatch for fx_1m (${key}): expected '${probe.expectedSource}', found '${actualSource}'.`
);
}
const actualClose = parseFiniteNumberCell(row.close, `fx_1m[${key}].close`);
const tolerance = probe.closeTolerance ?? DEFAULT_PROBE_CLOSE_TOLERANCE;
const absDiff = Math.abs(actualClose - probe.expectedClose);
if (absDiff > tolerance) {
throw new VerifyM2QuantError(
`Load receipt probe 0x10 close mismatch for fx_1m (${key}): expected ${probe.expectedClose}, found ${actualClose} (absDiff=${absDiff} > tolerance=${tolerance}).`
);
}
return {
shardPrefix: 'fx_1m',
key,
expectedSource: probe.expectedSource,
actualSource,
expectedClose: probe.expectedClose,
actualClose,
absDiff,
};
}
async function verifyLoadReceipt(
executor: QuestDbPgQueryExecutor,
receipt: M2LoadReceipt,
walTables: readonly WalTableStatusRow[],
bars1mSummary: readonly Bars1mSourceSummaryRow[],
fx1mSummary: readonly Fx1mPairSourceSummaryRow[]
): Promise<LoadReceiptVerificationResult> {
const walAdvancement = verifyWalAdvancement(
{ bars_1m: receipt.beforeWal.bars_1m, fx_1m: receipt.beforeWal.fx_1m },
walTables,
'Load receipt WAL check'
);
const bySource = new Map<string, Bars1mSourceSummaryRow>(
bars1mSummary.map(row => [row.source, row])
);
const eodGroup = bySource.get('eod');
const qmGroup = bySource.get('qm');
if (eodGroup === undefined) {
throw new VerifyM2QuantError(
"Load receipt verification failed: QuestDB bars_1m is missing required source='eod' group (bars_1m shard prefix)."
);
}
if (qmGroup === undefined) {
throw new VerifyM2QuantError(
"Load receipt verification failed: QuestDB bars_1m is missing required source='qm' group (bars_1m_qm shard prefix)."
);
}
if (fx1mSummary.length === 0) {
throw new VerifyM2QuantError(
'Load receipt verification failed: QuestDB fx_1m is missing committed rows (fx_1m shard prefix).'
);
}
const { eodSentRows, qmSentRows, overlapRows, overlapWinnerSource } = receipt.dedup;
const minExpectedEodRows =
overlapWinnerSource === 'qm' ? eodSentRows - overlapRows : eodSentRows;
const minExpectedQmRows =
overlapWinnerSource === 'eod' ? qmSentRows - overlapRows : qmSentRows;
const minExpectedTotalBars1mRows = eodSentRows + qmSentRows - overlapRows;
const observedTotalBars1mRows = eodGroup.rowCount + qmGroup.rowCount;
if (eodGroup.rowCount < minExpectedEodRows) {
throw new VerifyM2QuantError(
`EOD/QM dedup accounting failed: observed bars_1m source='eod' rowCount=${eodGroup.rowCount} < expected minimum ${minExpectedEodRows}.`
);
}
if (qmGroup.rowCount < minExpectedQmRows) {
throw new VerifyM2QuantError(
`EOD/QM dedup accounting failed: observed bars_1m source='qm' rowCount=${qmGroup.rowCount} < expected minimum ${minExpectedQmRows}.`
);
}
if (observedTotalBars1mRows < minExpectedTotalBars1mRows) {
throw new VerifyM2QuantError(
`EOD/QM dedup accounting failed: observed combined bars_1m rowCount=${observedTotalBars1mRows} < expected post-dedup minimum ${minExpectedTotalBars1mRows}.`
);
}
const probesVerified: ProbeCheckResult[] = [];
for (const probe of receipt.shards.bars_1m.probes) {
probesVerified.push(await verifyBars1mProbe(executor, 'bars_1m', probe));
}
for (const probe of receipt.shards.bars_1m_qm.probes) {
probesVerified.push(await verifyBars1mProbe(executor, 'bars_1m_qm', probe));
}
for (const probe of receipt.shards.fx_1m.probes) {
probesVerified.push(await verifyFx1mProbe(executor, probe));
}
if (receipt.dedup.overlapProbes !== undefined) {
for (const probe of receipt.dedup.overlapProbes) {
probesVerified.push(await verifyBars1mProbe(executor, 'dedup_overlap', probe));
}
}
return {
walAdvancement,
dedupAccounting: {
eodSentRows,
qmSentRows,
overlapRows,
overlapWinnerSource,
minExpectedEodRows,
minExpectedQmRows,
minExpectedTotalBars1mRows,
observedEodRows: eodGroup.rowCount,
observedQmRows: qmGroup.rowCount,
observedTotalBars1mRows,
},
probesVerified,
};
}
function verifyIdempotentResend(
baseline: ParsedResendBaseline,
walTables: readonly WalTableStatusRow[],
bars1mSummary: readonly Bars1mSourceSummaryRow[],
fx1mSummary: readonly Fx1mPairSourceSummaryRow[]
): ResendVerificationResult {
const walAdvancement = verifyWalAdvancement(
{
bars_1m: baseline.walTables.get('bars_1m')!,
fx_1m: baseline.walTables.get('fx_1m')!,
},
walTables,
'Idempotent resend WAL check'
);
if (bars1mSummary.length !== baseline.bars1mSummary.length) {
throw new VerifyM2QuantError(
`Idempotent resend failed: bars_1m source group count changed (${baseline.bars1mSummary.length} -> ${bars1mSummary.length}).`
);
}
for (let i = 0; i < bars1mSummary.length; i += 1) {
const cur = bars1mSummary[i]!;
const prev = baseline.bars1mSummary[i]!;
if (
cur.source !== prev.source ||
cur.rowCount !== prev.rowCount ||
cur.minClose !== prev.minClose ||
cur.maxClose !== prev.maxClose ||
cur.minTsUs !== prev.minTsUs ||
cur.maxTsUs !== prev.maxTsUs
) {
throw new VerifyM2QuantError(
`Idempotent resend failed: bars_1m summary diverged for source '${cur.source}' (rows ${prev.rowCount} -> ${cur.rowCount}, close [${prev.minClose},${prev.maxClose}] -> [${cur.minClose},${cur.maxClose}]).`
);
}
}
if (fx1mSummary.length !== baseline.fx1mSummary.length) {
throw new VerifyM2QuantError(
`Idempotent resend failed: fx_1m group count changed (${baseline.fx1mSummary.length} -> ${fx1mSummary.length}).`
);
}
for (let i = 0; i < fx1mSummary.length; i += 1) {
const cur = fx1mSummary[i]!;
const prev = baseline.fx1mSummary[i]!;
if (
cur.pair !== prev.pair ||
cur.source !== prev.source ||
cur.rowCount !== prev.rowCount ||
cur.minClose !== prev.minClose ||
cur.maxClose !== prev.maxClose ||
cur.minTsUs !== prev.minTsUs ||
cur.maxTsUs !== prev.maxTsUs
) {
throw new VerifyM2QuantError(
`Idempotent resend failed: fx_1m summary diverged for '${cur.pair}/${cur.source}' (rows ${prev.rowCount} -> ${cur.rowCount}, close [${prev.minClose},${prev.maxClose}] -> [${cur.minClose},${cur.maxClose}]).`
);
}
}
return {
ok: true,
walAdvancement,
bars1mRowCountsUnchanged: true,
fx1mRowCountsUnchanged: true,
};
}
function validateBenchmarkFence(parsed: ParsedVerifyM2QuantRun): FencedTimeRange {
// Pre-validate Vault fence with vaultOperatorAuthorized: false so violations
// fail closed deterministically before opening any QuestDB or store handle.
const fence = applyVaultFence(
{
from: parsed.benchFrom,
to: parsed.benchTo,
asOf: parsed.benchAsOf,
scope: parsed.benchScope,
},
{
vaultCutoffTs: parsed.vaultCutoffTs,
vaultOperatorAuthorized: false,
}
);
const effectiveSpanMs = fence.toMs - fence.fromMs + 1;
if (effectiveSpanMs < MIN_ONE_YEAR_WINDOW_MS) {
const effectiveFromIso = new Date(fence.fromMs).toISOString();
const effectiveToIso = new Date(fence.toMs).toISOString();
const effectiveDays = (effectiveSpanMs / 86_400_000).toFixed(2);
const reason = fence.clampedTo
? `Vault cutoff (${parsed.vaultCutoffIso}) clamped --bench-to (${parsed.benchTo}) to ${effectiveToIso}, truncating the effective benchmark window`
: `Requested benchmark window (${parsed.benchFrom}..${parsed.benchTo}) is shorter than the required 1-year minimum`;
throw new VerifyM2QuantError(
`${reason}: effective fenced interval [${effectiveFromIso}, ${effectiveToIso}] covers ${effectiveDays} days (< 365 days required for 1-year benchmark).`
);
}
return fence;
}
async function runIntradayLatencyBenchmark(
parsed: ParsedVerifyM2QuantRun,
fence: FencedTimeRange,
openStore: (
config: ResearchCopilotHostConfig,
options?: OpenResearchCopilotStoreOptions
) => Promise<ManagedMarketDataStore>,
perfNowMs: () => number
): Promise<IntradayBenchmarkResult> {
const hostConfig: ResearchCopilotHostConfig = {
postgresUrl: 'postgres://unused@127.0.0.1:5433/unused',
curatedRoot: parsed.curatedRoot,
vaultCutoffTs: parsed.vaultCutoffTs,
principalId: 'agent:00000000-0000-4000-8000-000000000000',
libraryRoot: parsed.curatedRoot,
referenceListingIds: { XNYS: [parsed.benchListingId] },
questdb: parsed.questdb,
};
const handle = await openStore(hostConfig);
try {
const query = {
listingIds: [parsed.benchListingId],
timeframe: '1m' as const,
from: parsed.benchFrom,
to: parsed.benchTo,
adjustment: 'raw' as const,
asOf: parsed.benchAsOf,
scope: parsed.benchScope,
};
const verifyBars = (bars: readonly BarRecord[], runLabel: string): string => {
if (bars.length === 0) {
throw new VerifyM2QuantError(
`Intraday 1m benchmark (${runLabel}) returned 0 rows for listing ${parsed.benchListingId}.`
);
}
for (let i = 0; i < bars.length; i += 1) {
const bar = bars[i] as BarRecord;
if (bar.ts >= parsed.vaultCutoffTs) {
throw new VerifyM2QuantError(
`Intraday 1m benchmark (${runLabel}) returned post-Vault bar ts=${bar.ts} >= vaultCutoffTs=${parsed.vaultCutoffTs}.`
);
}
if (bar.knownAt > fence.asOfMs) {
throw new VerifyM2QuantError(
`Intraday 1m benchmark (${runLabel}) returned future-known bar knownAt=${bar.knownAt} > asOfMs=${fence.asOfMs}.`
);
}
}
return computeBarsDigest(bars);
};
const coldStart = perfNowMs();
const coldBars = await collectBars(handle.store.bars(query));
const coldMs = perfNowMs() - coldStart;
const coldDigest = verifyBars(coldBars, 'cold');
if (!(coldMs < MAX_COLD_READ_MS)) {
throw new VerifyM2QuantError(
`Cold 1y 1m PGWire read exceeded threshold: ${coldMs.toFixed(2)}ms >= ${MAX_COLD_READ_MS}ms.`
);
}
const warmRuns: number[] = [];
for (let runIdx = 0; runIdx < parsed.warmRuns; runIdx += 1) {
const warmStart = perfNowMs();
const warmBars = await collectBars(handle.store.bars(query));
const warmMs = perfNowMs() - warmStart;
const warmDigest = verifyBars(warmBars, `warm#${runIdx + 1}`);
if (warmBars.length !== coldBars.length || warmDigest !== coldDigest) {
throw new VerifyM2QuantError(
`Warm 1y 1m PGWire read #${runIdx + 1} diverged from cold baseline (rows ${warmBars.length} vs ${coldBars.length}, digest ${warmDigest} vs ${coldDigest}).`
);
}
if (!(warmMs < MAX_WARM_READ_MS)) {
throw new VerifyM2QuantError(
`Warm 1y 1m PGWire read #${runIdx + 1} exceeded threshold: ${warmMs.toFixed(2)}ms >= ${MAX_WARM_READ_MS}ms.`
);
}
warmRuns.push(warmMs);
}
const minWarmMs = Math.min(...warmRuns);
const maxWarmMs = Math.max(...warmRuns);
const medianWarmMs = computeMedian(warmRuns);
return {
listingId: parsed.benchListingId,
from: parsed.benchFrom,
to: parsed.benchTo,
asOf: parsed.benchAsOf,
effectiveFrom: new Date(fence.fromMs).toISOString(),
effectiveTo: new Date(fence.toMs).toISOString(),
effectiveAsOf: new Date(fence.asOfMs).toISOString(),
effectiveSpanMs: fence.toMs - fence.fromMs + 1,
clampedTo: fence.clampedTo,
clampedAsOf: fence.clampedAsOf,
scope: parsed.benchScope,
rowCount: coldBars.length,
digest: coldDigest,
coldMs,
warmRuns,
minWarmMs,
medianWarmMs,
maxWarmMs,
thresholds: {
maxColdMs: MAX_COLD_READ_MS,
maxWarmMs: MAX_WARM_READ_MS,
minWindowMs: MIN_ONE_YEAR_WINDOW_MS,
},
};
} finally {
await handle.close();
}
}
async function defaultReadTextFile(path: string): Promise<string> {
return readFile(path, 'utf8');
}
async function defaultWriteReportFile(path: string, content: string): Promise<void> {
await mkdir(dirname(path), { recursive: true });
await writeFile(path, content, 'utf8');
}
async function defaultCreateDuckDbExecutor(): Promise<ClosableDuckDbExecutor> {
const { createNodeDuckDbExecutor } = await import('@stock-bot/duckdb');
return createNodeDuckDbExecutor();
}
async function defaultOpenResearchCopilotStore(
config: ResearchCopilotHostConfig,
options?: OpenResearchCopilotStoreOptions
): Promise<ManagedMarketDataStore> {
const { openResearchCopilotStore } = await import('@stock-bot/duckdb');
return openResearchCopilotStore(config, options);
}
function defaultSleepMs(ms: number): Promise<void> {
return new Promise(resolveSleep => {
setTimeout(resolveSleep, ms);
});
}
/**
* Runs the QuestDB/DuckDB M2 verification CLI with injectable I/O, executors,
* store factory, and clocks for deterministic offline testing.
*/
export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Promise<number> {
const argv = deps.argv ?? process.argv.slice(2);
const stdout = deps.stdout ?? process.stdout;
const stderr = deps.stderr ?? process.stderr;
const secretNeedles = collectArgvSecretNeedles(argv);
const writeRedactedError = (prefix: string, err: unknown): void => {
const raw = err instanceof Error ? err.message : String(err);
const safe = sanitizeSingleLine(redactSecrets(raw, secretNeedles));
stderr.write(`${prefix}: ${safe}\n`);
};
let parsed: ParsedVerifyM2QuantArgs;
try {
parsed = parseVerifyM2QuantArgs(argv, {
...(deps.cwd !== undefined ? { cwd: deps.cwd } : {}),
});
} catch (err: unknown) {
writeRedactedError('Invalid arguments', err);
return 1;
}
if (parsed.kind === 'help') {
stdout.write(VERIFY_M2_QUANT_USAGE);
return 0;
}
const openPg = deps.openQuestDbPgExecutor ?? openQuestDbPgExecutor;
const applyDdlFn = deps.applyM2IntradayDDL ?? applyM2IntradayDDL;
const createDuck = deps.createDuckDbExecutor ?? defaultCreateDuckDbExecutor;
const openStore = deps.openResearchCopilotStore ?? defaultOpenResearchCopilotStore;
const readTextFile = deps.readTextFile ?? defaultReadTextFile;
const writeReportFile = deps.writeReportFile ?? defaultWriteReportFile;
const nowMs = deps.nowMs ?? Date.now;
const perfNowMs = deps.perfNowMs ?? (() => performance.now());
const sleepMs = deps.sleepMs ?? defaultSleepMs;
const walPollIntervalMs = deps.walPollIntervalMs ?? DEFAULT_WAL_POLL_INTERVAL_MS;
try {
if (parsed.kind === 'ddl_only') {
const pgHandle = await openPg(parsed.questdb);
let appliedTables: readonly M2IntradayTableName[];
let walTables: readonly WalTableStatusRow[];
try {
const applied = await applyDdlFn(pgHandle.executor);
appliedTables = applied.appliedTables;
walTables = await waitForHealthyWalTables(
pgHandle.executor,
parsed.walSettleTimeoutMs,
walPollIntervalMs,
nowMs,
sleepMs
);
} finally {
await pgHandle.close();
}
const ddlReport: VerifyM2QuantDdlOnlyReport = {
ok: true,
mode: 'ddl_only',
target: {
questdb: describeSafeQuestDbTarget(parsed.questdb),
},
ddl: {
applied: true,
appliedTables,
},
walTables,
};
const json = `${JSON.stringify(ddlReport, null, 2)}\n`;
if (parsed.outPath !== undefined) {
await writeReportFile(parsed.outPath, json);
}
stdout.write(`${JSON.stringify(ddlReport)}\n`);
return 0;
}
const receiptRaw = await readTextFile(parsed.loadReceiptPath);
const receipt = parseLoadReceiptJson(receiptRaw);
const resendBaseline =
parsed.resendBaselinePath !== undefined
? parseResendBaselineJson(await readTextFile(parsed.resendBaselinePath))
: undefined;
// Validate Vault fence and 1-year effective window before any DB/store I/O.
const fence = validateBenchmarkFence(parsed);
let ddlResult: {
readonly applied: boolean;
readonly appliedTables: readonly M2IntradayTableName[];
} = { applied: false, appliedTables: [] };
if (parsed.applyDdl) {
const ddlPgHandle = await openPg(parsed.questdb);
try {
const applied = await applyDdlFn(ddlPgHandle.executor);
ddlResult = { applied: true, appliedTables: applied.appliedTables };
} finally {
await ddlPgHandle.close();
}
}
// Measure the cold 1-year 1m benchmark read BEFORE any verifier query scans bars_1m
// so QuestDB and OS page caches are not pre-warmed after restart.
const benchmark = await runIntradayLatencyBenchmark(parsed, fence, openStore, perfNowMs);
let walTables: readonly WalTableStatusRow[];
let bars1mSummary: readonly Bars1mSourceSummaryRow[];
let fx1mSummary: readonly Fx1mPairSourceSummaryRow[];
let loadVerification: LoadReceiptVerificationResult;
let resendVerification: ResendVerificationResult | undefined;
const splitChecks: SplitBoundaryCheckResult[] = [];
const pgHandle = await openPg(parsed.questdb);
try {
walTables = await waitForHealthyWalTables(
pgHandle.executor,
parsed.walSettleTimeoutMs,
walPollIntervalMs,
nowMs,
sleepMs
);
bars1mSummary = await verifyBars1mCommits(pgHandle.executor);
fx1mSummary = await verifyFx1mCommits(pgHandle.executor);
loadVerification = await verifyLoadReceipt(
pgHandle.executor,
receipt,
walTables,
bars1mSummary,
fx1mSummary
);
if (resendBaseline !== undefined) {
resendVerification = verifyIdempotentResend(
resendBaseline,
walTables,
bars1mSummary,
fx1mSummary
);
}
const duckExecutor = await createDuck();
try {
const listingIdByLabel: Record<'NVDA.US' | 'NEXM.V', number> = {
'NVDA.US': parsed.nvdaListingId,
'NEXM.V': parsed.nexmListingId,
};
for (const spec of M2_SPLIT_BOUNDARY_CASES) {
splitChecks.push(
await verifySplitBoundaryCase(
spec,
listingIdByLabel[spec.label],
pgHandle.executor,
duckExecutor,
parsed.curatedRoot
)
);
}
} finally {
await duckExecutor.close();
}
} finally {
await pgHandle.close();
}
const report: VerifyM2QuantReport = {
ok: true,
mode: 'verify',
target: {
questdb: describeSafeQuestDbTarget(parsed.questdb),
curatedRoot: parsed.curatedRoot,
vaultCutoffTs: parsed.vaultCutoffIso,
},
ddl: ddlResult,
walTables,
bars1mSummary,
fx1mSummary,
loadVerification,
...(resendVerification !== undefined ? { resendVerification } : {}),
splitChecks,
benchmark,
};
const json = `${JSON.stringify(report, null, 2)}\n`;
if (parsed.outPath !== undefined) {
await writeReportFile(parsed.outPath, json);
}
stdout.write(`${JSON.stringify(report)}\n`);
return 0;
} catch (err: unknown) {
writeRedactedError('M2 quant verification failed', err);
return 1;
}
}
if (import.meta.main) {
process.exitCode = await runVerifyM2QuantCli();
}