/** * 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 load receipt (canonical ETL sources `eod_unadj`, `qm_raw`, `eod`; * shard SHA-256 hashes; independent settled before/after WAL windows per shard * prefix `bars_1m`, `bars_1m_qm`, `fx_1m`), optional resend baseline, and the * Vault-fenced 1-year benchmark window (`>= 365` days after Vault clamping with * `vaultOperatorAuthorized: false`) before any DB or store I/O. * 2. Polls `wal_tables()` (metadata only, zero bar-table scans) until `bars_1m`, * `fx_1m`, and `bar_revisions` are healthy, settled (`writerTxn >= sequencerTxn`), * and have applied all expected load-receipt transactions BEFORE starting the * timed benchmark. * 3. Measures the 1-year single-listing `1m` PGWire cold read (`< 1000 ms`) and warm * reads (`< 250 ms`) BEFORE any verifier query scans `bars_1m` or `fx_1m`. * 4. Verifies non-zero finite `0x10` binary-double commits across all three shard * prefixes (`bars_1m`, `bars_1m_qm`, `fx_1m`), exact shard-derived key/close * probes, EOD/QM deduplication accounting, stable retained-row content digests, * and optional idempotent resend verification (`--resend-baseline`, bound to shard * hashes and retained-row content digests). * 5. Verifies observed split-boundary close agreement (`<= 0.5%`) between QuestDB * `bars_1m` (`session = 'RTH'`, latest `ts` per `America/New_York` session * date) and retained raw `bars_1d/year=/part.parquet` across `NVDA.US` * (`2024-06-06..2024-06-12`, ex-date `2024-06-10`, `10:1`) and `NEXM.V` * (`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 SHA256_HEX_RE = /^[0-9a-f]{64}$/; const URL_CREDENTIAL_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^:@/\s]+):([^@/\s]+)@/g; const POSTGRES_URL_RE = /postgres(?:ql)?:\/\/[^\s'"]+/gi; 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 BARS_1M_SOURCE_EOD = 'eod_unadj' as const; export const BARS_1M_SOURCE_QM = 'qm_raw' as const; export const FX_1M_SOURCE_EOD = 'eod' as const; export type Bars1mSource = typeof BARS_1M_SOURCE_EOD | typeof BARS_1M_SOURCE_QM; export const REQUIRED_SHARD_PREFIXES = ['bars_1m', 'bars_1m_qm', 'fx_1m'] as const; export type RequiredShardPrefix = (typeof REQUIRED_SHARD_PREFIXES)[number]; 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; readonly applyM2IntradayDDL?: ( client: QuestDbPgQueryExecutor ) => Promise; readonly createDuckDbExecutor?: () => Promise; readonly openResearchCopilotStore?: ( config: ResearchCopilotHostConfig, options?: OpenResearchCopilotStoreOptions ) => Promise; readonly readTextFile?: (path: string) => Promise; readonly writeReportFile?: (path: string, content: string) => Promise; readonly nowMs?: () => number; readonly perfNowMs?: () => number; readonly sleepMs?: (ms: number) => Promise; readonly walPollIntervalMs?: number; } export interface WalTxnPair { readonly writerTxn: string; readonly sequencerTxn: string; } export interface Bars1mProbeExpectation { readonly listingId: number; readonly tsUs: string; readonly expectedClose: number; readonly expectedSource: Bars1mSource; readonly expectedKnownAtUs?: string; readonly closeTolerance?: number; } export interface Fx1mProbeExpectation { readonly pair: string; readonly tsUs: string; readonly expectedClose: number; readonly expectedSource: typeof FX_1M_SOURCE_EOD; readonly closeTolerance?: number; } export interface ShardPrefixLoadReceipt { readonly shardSha256: readonly string[]; readonly beforeWal: WalTxnPair; readonly afterWal: WalTxnPair; readonly probes: readonly TProbe[]; } export interface LoadReceiptDedupExpectation { readonly eodSentRows: number; readonly qmSentRows: number; readonly overlapRows: number; readonly overlapWinnerSource: Bars1mSource; readonly overlapProbes?: readonly Bars1mProbeExpectation[]; } export interface M2LoadReceipt { readonly shards: { readonly bars_1m: ShardPrefixLoadReceipt; readonly bars_1m_qm: ShardPrefixLoadReceipt; readonly fx_1m: ShardPrefixLoadReceipt; }; readonly dedup: LoadReceiptDedupExpectation; } export interface PrefixWalAdvancementEntry { readonly shardPrefix: RequiredShardPrefix; readonly table: 'bars_1m' | 'fx_1m'; readonly beforeWriterTxn: string; readonly afterWriterTxn: string; readonly beforeSequencerTxn: string; readonly afterSequencerTxn: string; readonly liveWriterTxn: string; readonly liveSequencerTxn: string; } export interface ShardHashesByPrefix { readonly bars_1m: readonly string[]; readonly bars_1m_qm: readonly string[]; readonly fx_1m: readonly string[]; } export interface ProbeCheckResult { 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 PrefixWalAdvancementEntry[]; readonly shardHashes: ShardHashesByPrefix; readonly dedupAccounting: { readonly eodSentRows: number; readonly qmSentRows: number; readonly overlapRows: number; readonly overlapWinnerSource: Bars1mSource; 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 PrefixWalAdvancementEntry[]; readonly shardHashesMatched: true; readonly bars1mRowCountsUnchanged: true; readonly fx1mRowCountsUnchanged: true; readonly bars1mContentDigestMatched: true; readonly fx1mContentDigestMatched: 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 bars1mContentDigest: string; readonly fx1mContentDigest: string; 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 QuestDB PGWire URL (mutually exclusive with --questdb-host/--questdb-pg-port)', ' --questdb-host QuestDB PGWire host (requires --questdb-pg-port)', ' --questdb-pg-port QuestDB PGWire port (requires --questdb-host)', ' --curated-root Curated Parquet root containing bars_1d/year=/part.parquet', ' --vault-cutoff-ts Authoritative Vault cutoff ISO-8601 UTC timestamp ending in Z', ' --nvda-listing-id Permanent listing_id for NVDA.US', ' --nexm-listing-id Permanent listing_id for NEXM.V', ' --bench-listing-id Permanent listing_id for 1y 1m PGWire latency benchmark', ' --bench-from Benchmark window start (must be < --vault-cutoff-ts)', ' --bench-to Benchmark window end (effective fenced span must be >= 365 days)', ' --bench-as-of Benchmark point-in-time as-of bound', ' --load-receipt JSON load receipt with per-prefix (bars_1m, bars_1m_qm, fx_1m)', ' shard SHA-256 hashes, settled beforeWal/afterWal, expected keys/closes,', ' and EOD/QM dedup expectations', '', 'Optional options:', ' --questdb-database QuestDB PGWire database name (host/port mode)', ' --questdb-user QuestDB PGWire user (host/port mode)', ' --questdb-password QuestDB PGWire password (host/port mode)', ' --questdb-ssl Explicit TLS flag', ' --bench-scope DataScope for benchmark (default: vault_fenced)', ' --resend-baseline Prior VerifyM2QuantReport JSON to verify idempotent resend against', ' --apply-ddl Execute applyM2IntradayDDL before checks (full mode)', ` --warm-runs Number of warm 1y 1m benchmark reads (default: ${DEFAULT_WARM_RUNS})`, ` --wal-settle-timeout-ms WAL settle polling timeout in ms (default: ${DEFAULT_WAL_SETTLE_TIMEOUT_MS})`, ' --out Optional JSON output file path', ' -h, --help Show this help message', '', ].join('\n'); const VALUE_FLAGS = new Set([ '--questdb-url', '--questdb-host', '--questdb-pg-port', '--questdb-database', '--questdb-user', '--questdb-password', '--questdb-ssl', '--curated-root', '--vault-cutoff-ts', '--nvda-listing-id', '--nexm-listing-id', '--bench-listing-id', '--bench-from', '--bench-to', '--bench-as-of', '--bench-scope', '--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, raw: string): void { if (raw.length === 0) { return; } needles.add(raw); try { const decoded = decodeURIComponent(raw); if (decoded.length > 0) { needles.add(decoded); } } catch { // Malformed percent-encoding: raw value is already registered. } } function collectArgvSecretNeedles(argv: readonly string[]): Set { const needles = new Set(); for (let i = 0; i < argv.length; i += 1) { const token = argv[i] as string; const eqIndex = token.indexOf('='); let flag: string; let rawValue: string | undefined; if (eqIndex !== -1) { flag = token.slice(0, eqIndex); rawValue = token.slice(eqIndex + 1); } else { flag = token; if (SECRET_FLAGS.has(flag) && i + 1 < argv.length) { rawValue = argv[i + 1]; } } if (SECRET_FLAGS.has(flag) && rawValue !== undefined && rawValue.length > 0) { addRawAndDecodedNeedle(needles, rawValue); if (flag === '--questdb-url') { try { const parsed = new URL(rawValue); if (parsed.href.length > 0) { needles.add(parsed.href); } addRawAndDecodedNeedle(needles, parsed.password); for (const [k, v] of parsed.searchParams.entries()) { if (k.toLowerCase() === 'password' && v.length > 0) { addRawAndDecodedNeedle(needles, v); } } } catch { // Non-URL string: raw string already registered. } } } } return needles; } export function redactSecrets(message: string, needles: Iterable): string { let out = message; const sorted = Array.from(new Set(needles)) .filter(n => n.length > 0) .sort((a, b) => b.length - a.length); for (const needle of sorted) { out = out.split(needle).join('[REDACTED]'); } out = out.replace(POSTGRES_URL_RE, '[REDACTED_DSN]'); out = out.replace(URL_CREDENTIAL_RE, '$1[REDACTED]:[REDACTED]@'); return out; } function validateRawTokenValue(flag: string, rawValue: string): string { if (rawValue.length === 0 || rawValue.trim().length === 0) { throw new VerifyM2QuantError(`Flag '${flag}' requires a non-empty value.`); } if (rawValue.includes('\0')) { throw new VerifyM2QuantError(`Flag '${flag}' value must not contain NUL bytes.`); } if (!SECRET_FLAGS.has(flag) && rawValue.startsWith('-')) { throw new VerifyM2QuantError( `Flag '${flag}' value must not start with '-' (received '${rawValue}').` ); } return rawValue; } function parsePositiveIntFlag(flag: string, rawValue: string, maxValue?: number): number { const validated = validateRawTokenValue(flag, rawValue); if (!STRICT_POSITIVE_INT_RE.test(validated)) { throw new VerifyM2QuantError( `Flag '${flag}' must be a positive integer (received '${validated}').` ); } const parsed = Number(validated); if (!Number.isSafeInteger(parsed) || parsed <= 0 || (maxValue !== undefined && parsed > maxValue)) { throw new VerifyM2QuantError( `Flag '${flag}' is out of allowed range (received '${validated}').` ); } return parsed; } function parseBooleanFlagValue(flag: string, rawValue: string): boolean { const normalized = validateRawTokenValue(flag, rawValue).trim().toLowerCase(); if (normalized === 'true') { return true; } if (normalized === 'false') { return false; } throw new VerifyM2QuantError( `Flag '${flag}' must be 'true' or 'false' (received '${rawValue}').` ); } function parseStrictUtcIsoZ(flag: string, rawValue: string): number { const validated = validateRawTokenValue(flag, rawValue); const match = STRICT_UTC_INSTANT_RE.exec(validated); if (match === null) { throw new VerifyM2QuantError( `Flag '${flag}' must be a strict ISO-8601 UTC timestamp ending in 'Z' (received '${validated}').` ); } const year = Number(match[1]); const month = Number(match[2]); const day = Number(match[3]); const hours = Number(match[4]); const minutes = Number(match[5]); const seconds = Number(match[6]); const frac = match[7] !== undefined ? Number(match[7].padEnd(3, '0')) : 0; const epochMs = Date.UTC(year, month - 1, day, hours, minutes, seconds, frac); const check = new Date(epochMs); if ( !Number.isSafeInteger(epochMs) || check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day || check.getUTCHours() !== hours || check.getUTCMinutes() !== minutes || check.getUTCSeconds() !== seconds || check.getUTCMilliseconds() !== frac ) { throw new VerifyM2QuantError( `Flag '${flag}' contains an invalid UTC calendar instant (received '${validated}').` ); } return epochMs; } function assertSafeDuckDbPath(rawPath: string, flag: string): string { for (let i = 0; i < rawPath.length; i += 1) { const code = rawPath.charCodeAt(i); if (code <= 0x1f || code === 0x7f || code === 0x27 || code === 0x3b) { throw new VerifyM2QuantError( `Flag '${flag}' contains characters disallowed in DuckDB Parquet paths.` ); } } return rawPath.replace(/\/+$/, '') || '/'; } export function parseVerifyM2QuantArgs( argv: readonly string[], options?: ParseVerifyM2QuantArgsOptions ): ParsedVerifyM2QuantArgs { const baseCwd = options?.cwd ?? process.cwd(); const seenValues = new Map(); const seenBooleans = new Set(); for (let i = 0; i < argv.length; i += 1) { const token = argv[i] as string; if (token === '--help' || token === '-h') { return { kind: 'help' }; } if (token === '--') { throw new VerifyM2QuantError('Unexpected positional argument separator "--".'); } if (!token.startsWith('-')) { throw new VerifyM2QuantError(`Unexpected positional argument '${token}'.`); } const eqIndex = token.indexOf('='); if (eqIndex !== -1) { const flag = token.slice(0, eqIndex); const rawValue = token.slice(eqIndex + 1); if (BOOLEAN_FLAGS.has(flag)) { throw new VerifyM2QuantError(`Flag '${flag}' does not accept a value.`); } if (!VALUE_FLAGS.has(flag)) { throw new VerifyM2QuantError(`Unknown flag '${flag}'.`); } if (seenValues.has(flag)) { throw new VerifyM2QuantError(`Duplicate flag '${flag}'.`); } seenValues.set(flag, validateRawTokenValue(flag, rawValue)); continue; } if (BOOLEAN_FLAGS.has(token)) { if (seenBooleans.has(token)) { throw new VerifyM2QuantError(`Duplicate flag '${token}'.`); } seenBooleans.add(token); continue; } if (!VALUE_FLAGS.has(token)) { throw new VerifyM2QuantError(`Unknown flag '${token}'.`); } if (seenValues.has(token)) { throw new VerifyM2QuantError(`Duplicate flag '${token}'.`); } if (i + 1 >= argv.length) { throw new VerifyM2QuantError(`Flag '${token}' requires a value.`); } i += 1; seenValues.set(token, validateRawTokenValue(token, argv[i] as string)); } const rawUrl = seenValues.get('--questdb-url'); const rawHost = seenValues.get('--questdb-host'); const rawPort = seenValues.get('--questdb-pg-port'); const rawDb = seenValues.get('--questdb-database'); const rawUser = seenValues.get('--questdb-user'); const rawPassword = seenValues.get('--questdb-password'); const rawSsl = seenValues.get('--questdb-ssl'); const ssl = rawSsl !== undefined ? parseBooleanFlagValue('--questdb-ssl', rawSsl) : undefined; let questdb: QuestDbPgExecutorConfig; if (rawUrl !== undefined) { if ( rawHost !== undefined || rawPort !== undefined || rawDb !== undefined || rawUser !== undefined || rawPassword !== undefined ) { throw new VerifyM2QuantError( 'Cannot combine --questdb-url with --questdb-host/--questdb-pg-port/--questdb-database/--questdb-user/--questdb-password.' ); } questdb = { url: rawUrl, ...(ssl !== undefined ? { ssl } : {}), }; } else { if (rawHost === undefined || rawPort === undefined) { throw new VerifyM2QuantError( 'Missing required QuestDB connection flags: provide --questdb-url or both --questdb-host and --questdb-pg-port.' ); } const port = parsePositiveIntFlag('--questdb-pg-port', rawPort, 65_535); questdb = { host: rawHost, port, ...(rawDb !== undefined ? { database: rawDb } : {}), ...(rawUser !== undefined ? { user: rawUser } : {}), ...(rawPassword !== undefined ? { password: rawPassword } : {}), ...(ssl !== undefined ? { ssl } : {}), }; } const 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}`; } interface RequiredMinWalByTable { readonly bars_1m: WalTxnPair; readonly fx_1m: WalTxnPair; } async function waitForHealthyWalTables( executor: QuestDbPgQueryExecutor, timeoutMs: number, pollIntervalMs: number, nowMs: () => number, sleepMs: (ms: number) => Promise, requiredMinWal?: RequiredMinWalByTable ): Promise { const deadline = nowMs() + timeoutMs; const sql = "SELECT name, suspended, writerTxn, sequencerTxn FROM wal_tables() WHERE name IN ('bars_1m', 'fx_1m', 'bar_revisions') ORDER BY name"; while (true) { const res = await executor.query(sql); const byName = new Map< M2IntradayTableName, { suspended: boolean; writerTxn: bigint; sequencerTxn: bigint } >(); for (const row of res.rows) { const name = parseRequiredStringCell(row.name, 'wal_tables.name'); if (!(M2_INTRADAY_TABLE_NAMES as readonly string[]).includes(name)) { continue; } const suspended = parseBooleanCell(row.suspended, `${name}.suspended`); const writerTxn = parseBigIntCell( row.writerTxn ?? row.writertxn, `${name}.writerTxn` ); const sequencerTxn = parseBigIntCell( row.sequencerTxn ?? row.sequencertxn, `${name}.sequencerTxn` ); byName.set(name as M2IntradayTableName, { suspended, writerTxn, sequencerTxn }); } const missing = M2_INTRADAY_TABLE_NAMES.filter(name => !byName.has(name)); if (missing.length > 0) { throw new VerifyM2QuantError( `Missing required M2 WAL tables in wal_tables(): ${missing.join(', ')}.` ); } const suspendedTables = M2_INTRADAY_TABLE_NAMES.filter( name => byName.get(name)?.suspended === true ); if (suspendedTables.length > 0) { throw new VerifyM2QuantError( `Suspended QuestDB WAL table(s) detected: ${suspendedTables.join(', ')}.` ); } if (requiredMinWal !== undefined) { for (const table of ['bars_1m', 'fx_1m'] as const) { const status = byName.get(table)!; const minReqSeq = BigInt(requiredMinWal[table].sequencerTxn); if (status.sequencerTxn < minReqSeq) { throw new VerifyM2QuantError( `QuestDB WAL for '${table}' sequencerTxn=${status.sequencerTxn.toString()} is behind expected load receipt sequencerTxn=${minReqSeq.toString()}.` ); } } } const unsettled = M2_INTRADAY_TABLE_NAMES.filter(name => { const status = byName.get(name)!; if (status.writerTxn < status.sequencerTxn) { return true; } if (requiredMinWal !== undefined && (name === 'bars_1m' || name === 'fx_1m')) { const minReqWriter = BigInt(requiredMinWal[name].writerTxn); if (status.writerTxn < minReqWriter) { return true; } } return false; }); if (unsettled.length === 0) { 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)!; const minReq = requiredMinWal !== undefined && (name === 'bars_1m' || name === 'fx_1m') ? `,requiredWriterTxn=${requiredMinWal[name].writerTxn}` : ''; return `${name}(writerTxn=${status.writerTxn.toString()} { const sql = 'SELECT source, count() AS row_count, min(close) AS min_close, max(close) AS max_close, ' + 'CAST(min(ts) AS LONG) AS min_ts_us, CAST(max(ts) AS LONG) AS max_ts_us ' + 'FROM bars_1m GROUP BY source ORDER BY source'; const res = await executor.query(sql); if (res.rows.length === 0) { throw new VerifyM2QuantError('QuestDB bars_1m contains zero rows.'); } const out: Bars1mSourceSummaryRow[] = []; let totalRows = 0; for (const row of res.rows) { const source = parseRequiredStringCell(row.source, 'bars_1m.source'); const rowCount = Number(parseBigIntCell(row.row_count, `bars_1m[${source}].row_count`)); if (!Number.isSafeInteger(rowCount) || rowCount <= 0) { throw new VerifyM2QuantError(`QuestDB bars_1m source '${source}' has non-positive row_count: ${rowCount}.`); } const minClose = parseFiniteNumberCell(row.min_close, `bars_1m[${source}].min_close`); const maxClose = parseFiniteNumberCell(row.max_close, `bars_1m[${source}].max_close`); if (minClose <= 0 || maxClose <= 0 || minClose > maxClose) { throw new VerifyM2QuantError( `QuestDB bars_1m source '${source}' has invalid close bounds [${minClose}, ${maxClose}].` ); } const minTsUs = parseBigIntCell(row.min_ts_us, `bars_1m[${source}].min_ts_us`); const maxTsUs = parseBigIntCell(row.max_ts_us, `bars_1m[${source}].max_ts_us`); if (minTsUs > maxTsUs) { throw new VerifyM2QuantError( `QuestDB bars_1m source '${source}' has inverted timestamp range [${minTsUs.toString()}, ${maxTsUs.toString()}].` ); } totalRows += rowCount; out.push({ source, rowCount, minClose, maxClose, minTsUs: minTsUs.toString(), maxTsUs: maxTsUs.toString(), }); } if (totalRows <= 0) { throw new VerifyM2QuantError('QuestDB bars_1m total row count is zero.'); } return out; } async function verifyFx1mCommits( executor: QuestDbPgQueryExecutor ): Promise { const sql = 'SELECT pair, source, count() AS row_count, min(close) AS min_close, max(close) AS max_close, ' + 'CAST(min(ts) AS LONG) AS min_ts_us, CAST(max(ts) AS LONG) AS max_ts_us ' + 'FROM fx_1m GROUP BY pair, source ORDER BY pair, source'; const res = await executor.query(sql); if (res.rows.length === 0) { throw new VerifyM2QuantError('QuestDB fx_1m contains zero rows.'); } const out: Fx1mPairSourceSummaryRow[] = []; let totalRows = 0; for (const row of res.rows) { const pair = parseRequiredStringCell(row.pair, 'fx_1m.pair'); const source = parseRequiredStringCell(row.source, 'fx_1m.source'); const rowCount = Number(parseBigIntCell(row.row_count, `fx_1m[${pair}/${source}].row_count`)); if (!Number.isSafeInteger(rowCount) || rowCount <= 0) { throw new VerifyM2QuantError( `QuestDB fx_1m group '${pair}/${source}' has non-positive row_count: ${rowCount}.` ); } const minClose = parseFiniteNumberCell(row.min_close, `fx_1m[${pair}/${source}].min_close`); const maxClose = parseFiniteNumberCell(row.max_close, `fx_1m[${pair}/${source}].max_close`); if (minClose <= 0 || maxClose <= 0 || minClose > maxClose) { throw new VerifyM2QuantError( `QuestDB fx_1m group '${pair}/${source}' has invalid close bounds [${minClose}, ${maxClose}].` ); } const minTsUs = parseBigIntCell(row.min_ts_us, `fx_1m[${pair}/${source}].min_ts_us`); const maxTsUs = parseBigIntCell(row.max_ts_us, `fx_1m[${pair}/${source}].max_ts_us`); if (minTsUs > maxTsUs) { throw new VerifyM2QuantError( `QuestDB fx_1m group '${pair}/${source}' has inverted timestamp range [${minTsUs.toString()}, ${maxTsUs.toString()}].` ); } totalRows += rowCount; out.push({ pair, source, rowCount, minClose, maxClose, minTsUs: minTsUs.toString(), maxTsUs: maxTsUs.toString(), }); } if (totalRows <= 0) { throw new VerifyM2QuantError('QuestDB fx_1m total row count is zero.'); } return out; } async function verifySplitBoundaryCase( spec: SplitBoundaryCaseSpec, listingId: number, questExecutor: QuestDbPgQueryExecutor, duckExecutor: ClosableDuckDbExecutor, curatedRoot: string ): Promise { const fromUtcIso = `${spec.fromDate}T00:00:00.000Z`; const toUtcIso = `${addUtcDays(spec.toDate, 1)}T05:00:00.000Z`; const qdbSql = "SELECT CAST(ts AS LONG) AS ts_us, close FROM bars_1m WHERE listing_id = $1 AND session = 'RTH' AND ts >= $2 AND ts <= $3 ORDER BY ts ASC"; const qdbRes = await questExecutor.query(qdbSql, [String(listingId), fromUtcIso, toUtcIso]); const latestClose1mByDate = new Map(); for (const row of qdbRes.rows) { const tsUs = parseBigIntCell(row.ts_us, `${spec.label}.bars_1m.ts_us`); const close = parseFiniteNumberCell(row.close, `${spec.label}.bars_1m.close`); if (close <= 0) { throw new VerifyM2QuantError( `${spec.label} bars_1m returned non-positive close (${close}) at ts_us=${tsUs.toString()}.` ); } const nyDate = formatNySessionDateFromMicros(tsUs); if (nyDate < spec.fromDate || nyDate > spec.toDate) { continue; } const prev = latestClose1mByDate.get(nyDate); if (prev === undefined || tsUs >= prev.tsUs) { latestClose1mByDate.set(nyDate, { tsUs, close }); } } const bars1dPath = `${curatedRoot}/bars_1d/year=*/part.parquet`; const duckSql = 'SELECT CAST(session_date AS VARCHAR) AS session_date, close ' + `FROM read_parquet('${bars1dPath}', hive_partitioning = true) ` + 'WHERE listing_id = ? AND session_date >= CAST(? AS DATE) AND session_date <= CAST(? AS DATE) ' + 'ORDER BY session_date ASC'; const duckRows = await duckExecutor.query(duckSql, [listingId, spec.fromDate, spec.toDate]); const close1dByDate = new Map(); for (const row of duckRows) { const sessionDate = parseRequiredStringCell(row.session_date, `${spec.label}.bars_1d.session_date`); const close = parseFiniteNumberCell(row.close, `${spec.label}.bars_1d.close`); if (close <= 0) { throw new VerifyM2QuantError( `${spec.label} bars_1d returned non-positive close (${close}) on ${sessionDate}.` ); } close1dByDate.set(sessionDate, close); } const matchedDates = Array.from(latestClose1mByDate.keys()) .filter(date => close1dByDate.has(date)) .sort(); const sessions: SplitBoundarySessionComparison[] = []; let preSplitCount = 0; let exOrPostSplitCount = 0; let maxRelDiff = 0; for (const sessionDate of matchedDates) { const close1m = latestClose1mByDate.get(sessionDate)!.close; const close1d = close1dByDate.get(sessionDate)!; const relDiff = Math.abs(close1m - close1d) / close1d; const phase: 'pre_split' | 'ex_or_post_split' = sessionDate < spec.exDate ? 'pre_split' : 'ex_or_post_split'; if (phase === 'pre_split') { preSplitCount += 1; } else { exOrPostSplitCount += 1; } if (relDiff > maxRelDiff) { maxRelDiff = relDiff; } if (relDiff > MAX_SPLIT_CLOSE_REL_DIFF) { throw new VerifyM2QuantError( `${spec.label} split-boundary close mismatch on ${sessionDate}: bars_1m=${close1m}, bars_1d=${close1d}, relDiff=${(relDiff * 100).toFixed(4)}% > ${(MAX_SPLIT_CLOSE_REL_DIFF * 100).toFixed(2)}%.` ); } sessions.push({ sessionDate, phase, close1m, close1d, relDiff }); } if (preSplitCount < 1) { throw new VerifyM2QuantError( `${spec.label} split-boundary check requires >= 1 matched pre-split session before ${spec.exDate} (found ${preSplitCount}).` ); } if (exOrPostSplitCount < 1) { throw new VerifyM2QuantError( `${spec.label} split-boundary check requires >= 1 matched ex-date/post-split session on/after ${spec.exDate} (found ${exOrPostSplitCount}).` ); } return { label: spec.label, listingId, fromDate: spec.fromDate, toDate: spec.toDate, exDate: spec.exDate, ratio: spec.ratio, preSplitCount, exOrPostSplitCount, maxRelDiff, sessions, }; } function isPlainObject(value: unknown): value is Record { 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 parseSha256Hex(value: unknown, field: string): string { const raw = parseRequiredStringCell(value, field).toLowerCase(); if (!SHA256_HEX_RE.test(raw)) { throw new VerifyM2QuantError( `Invalid SHA-256 hex digest for '${field}': expected 64 hex characters.` ); } return raw; } function parseSha256List(value: unknown, field: string): readonly string[] { if (!Array.isArray(value) || value.length === 0) { throw new VerifyM2QuantError(`Expected non-empty SHA-256 array for '${field}'.`); } return value.map((entry, idx) => parseSha256Hex(entry, `${field}[${idx}]`)); } 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 assertSettledWalPair(pair: WalTxnPair, field: string): void { if (BigInt(pair.writerTxn) < BigInt(pair.sequencerTxn)) { throw new VerifyM2QuantError( `Unsettled WAL snapshot for '${field}' (writerTxn=${pair.writerTxn} < sequencerTxn=${pair.sequencerTxn}).` ); } } function parseBars1mProbe( value: unknown, field: string, requiredSource: Bars1mSource ): 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`); if (expectedSource !== FX_1M_SOURCE_EOD) { throw new VerifyM2QuantError( `${field}.expectedSource must be '${FX_1M_SOURCE_EOD}' (received '${expectedSource}').` ); } let closeTolerance: number | undefined; if (value.closeTolerance !== undefined) { closeTolerance = parseFiniteNumberCell(value.closeTolerance, `${field}.closeTolerance`); if (closeTolerance < 0) { throw new VerifyM2QuantError(`${field}.closeTolerance must be >= 0.`); } } return { pair, tsUs: tsUs.toString(), expectedClose, expectedSource, ...(closeTolerance !== undefined ? { closeTolerance } : {}), }; } function parseShardPrefixEntry( shardsObj: Record, prefix: RequiredShardPrefix, parseProbe: (entry: unknown, field: string) => TProbe ): ShardPrefixLoadReceipt { const entry = shardsObj[prefix]; if (!isPlainObject(entry)) { throw new VerifyM2QuantError(`Load receipt missing required object "shards.${prefix}".`); } const shardSha256 = parseSha256List(entry.shardSha256, `shards.${prefix}.shardSha256`); const beforeWal = parseWalTxnPair(entry.beforeWal, `shards.${prefix}.beforeWal`); const afterWal = parseWalTxnPair(entry.afterWal, `shards.${prefix}.afterWal`); assertSettledWalPair(beforeWal, `shards.${prefix}.beforeWal`); assertSettledWalPair(afterWal, `shards.${prefix}.afterWal`); if ( BigInt(afterWal.writerTxn) <= BigInt(beforeWal.writerTxn) || BigInt(afterWal.sequencerTxn) <= BigInt(beforeWal.sequencerTxn) ) { throw new VerifyM2QuantError( `Load receipt WAL for shard prefix '${prefix}' did not advance (before writerTxn=${beforeWal.writerTxn}/sequencerTxn=${beforeWal.sequencerTxn}, after writerTxn=${afterWal.writerTxn}/sequencerTxn=${afterWal.sequencerTxn}).` ); } if (!Array.isArray(entry.probes) || entry.probes.length === 0) { throw new VerifyM2QuantError( `Load receipt shards.${prefix}.probes must be a non-empty array.` ); } const probes = entry.probes.map((p, idx) => parseProbe(p, `shards.${prefix}.probes[${idx}]`)); return { shardSha256, beforeWal, afterWal, probes }; } export function parseLoadReceiptJson(rawJson: string): M2LoadReceipt { let parsed: unknown; try { 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.shards)) { throw new VerifyM2QuantError('Load receipt missing required object "shards".'); } const shardsObj = parsed.shards as Record; const bars1mShard = parseShardPrefixEntry(shardsObj, 'bars_1m', (p, f) => parseBars1mProbe(p, f, BARS_1M_SOURCE_EOD) ); const bars1mQmShard = parseShardPrefixEntry(shardsObj, 'bars_1m_qm', (p, f) => parseBars1mProbe(p, f, BARS_1M_SOURCE_QM) ); const fx1mShard = parseShardPrefixEntry(shardsObj, 'fx_1m', (p, f) => parseFx1mProbe(p, f)); // Both bars_1m and bars_1m_qm write to the QuestDB bars_1m table; require disjoint // settled WAL windows so EOD advancement can never mask a failed/rejected QM send. const eodBeforeW = BigInt(bars1mShard.beforeWal.writerTxn); const eodBeforeS = BigInt(bars1mShard.beforeWal.sequencerTxn); const eodAfterW = BigInt(bars1mShard.afterWal.writerTxn); const eodAfterS = BigInt(bars1mShard.afterWal.sequencerTxn); const qmBeforeW = BigInt(bars1mQmShard.beforeWal.writerTxn); const qmBeforeS = BigInt(bars1mQmShard.beforeWal.sequencerTxn); const qmAfterW = BigInt(bars1mQmShard.afterWal.writerTxn); const qmAfterS = BigInt(bars1mQmShard.afterWal.sequencerTxn); const eodBeforeQm = qmBeforeW >= eodAfterW && qmBeforeS >= eodAfterS; const qmBeforeEod = eodBeforeW >= qmAfterW && eodBeforeS >= qmAfterS; if (!eodBeforeQm && !qmBeforeEod) { throw new VerifyM2QuantError( `Load receipt shards.bars_1m [${bars1mShard.beforeWal.writerTxn}..${bars1mShard.afterWal.writerTxn}] and shards.bars_1m_qm [${bars1mQmShard.beforeWal.writerTxn}..${bars1mQmShard.afterWal.writerTxn}] have overlapping WAL windows; send and capture each prefix separately.` ); } if (!isPlainObject(parsed.dedup)) { throw new VerifyM2QuantError('Load receipt missing required object "dedup".'); } 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 !== BARS_1M_SOURCE_EOD && overlapWinnerSourceRaw !== BARS_1M_SOURCE_QM ) { throw new VerifyM2QuantError( `Load receipt dedup.overlapWinnerSource must be '${BARS_1M_SOURCE_EOD}' or '${BARS_1M_SOURCE_QM}' (received '${overlapWinnerSourceRaw}').` ); } const overlapWinnerSource: Bars1mSource = 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 { shards: { bars_1m: bars1mShard, bars_1m_qm: bars1mQmShard, fx_1m: fx1mShard, }, dedup: { eodSentRows, qmSentRows, overlapRows, overlapWinnerSource, ...(overlapProbes !== undefined ? { overlapProbes } : {}), }, }; } function getRequiredMinWalFromReceipt(receipt: M2LoadReceipt): RequiredMinWalByTable { const eodAfterW = BigInt(receipt.shards.bars_1m.afterWal.writerTxn); const eodAfterS = BigInt(receipt.shards.bars_1m.afterWal.sequencerTxn); const qmAfterW = BigInt(receipt.shards.bars_1m_qm.afterWal.writerTxn); const qmAfterS = BigInt(receipt.shards.bars_1m_qm.afterWal.sequencerTxn); return { bars_1m: { writerTxn: (eodAfterW >= qmAfterW ? eodAfterW : qmAfterW).toString(), sequencerTxn: (eodAfterS >= qmAfterS ? eodAfterS : qmAfterS).toString(), }, fx_1m: receipt.shards.fx_1m.afterWal, }; } interface ParsedResendBaseline { readonly walTables: ReadonlyMap; readonly bars1mSummary: readonly Bars1mSourceSummaryRow[]; readonly fx1mSummary: readonly Fx1mPairSourceSummaryRow[]; readonly shardHashes: ShardHashesByPrefix; readonly bars1mContentDigest: string; readonly fx1mContentDigest: string; } function parseResendBaselineJson(rawJson: string): ParsedResendBaseline { 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(); 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(), }; }); if (!isPlainObject(parsed.loadVerification) || !isPlainObject(parsed.loadVerification.shardHashes)) { throw new VerifyM2QuantError( 'Resend baseline missing required "loadVerification.shardHashes" object.' ); } const rawHashes = parsed.loadVerification.shardHashes as Record; const shardHashes: ShardHashesByPrefix = { bars_1m: parseSha256List(rawHashes.bars_1m, 'resendBaseline.loadVerification.shardHashes.bars_1m'), bars_1m_qm: parseSha256List( rawHashes.bars_1m_qm, 'resendBaseline.loadVerification.shardHashes.bars_1m_qm' ), fx_1m: parseSha256List(rawHashes.fx_1m, 'resendBaseline.loadVerification.shardHashes.fx_1m'), }; const bars1mContentDigest = parseSha256Hex( parsed.bars1mContentDigest, 'resendBaseline.bars1mContentDigest' ); const fx1mContentDigest = parseSha256Hex( parsed.fx1mContentDigest, 'resendBaseline.fx1mContentDigest' ); return { walTables: walMap, bars1mSummary, fx1mSummary, shardHashes, bars1mContentDigest, fx1mContentDigest, }; } function verifyPerPrefixWalAdvancement( receipt: M2LoadReceipt, liveWalTables: readonly WalTableStatusRow[], baselineWal?: ReadonlyMap, contextLabel = 'Load receipt WAL check' ): readonly PrefixWalAdvancementEntry[] { const liveByName = new Map( liveWalTables.map(row => [row.name, row]) ); const prefixSpecs: readonly { readonly prefix: RequiredShardPrefix; readonly table: 'bars_1m' | 'fx_1m' }[] = [ { prefix: 'bars_1m', table: 'bars_1m' }, { prefix: 'bars_1m_qm', table: 'bars_1m' }, { prefix: 'fx_1m', table: 'fx_1m' }, ]; const results: PrefixWalAdvancementEntry[] = []; for (const { prefix, table } of prefixSpecs) { const shard = receipt.shards[prefix]; const live = liveByName.get(table); if (live === undefined) { throw new VerifyM2QuantError(`${contextLabel}: missing table '${table}' in settled wal_tables().`); } const beforeWriter = BigInt(shard.beforeWal.writerTxn); const afterWriter = BigInt(shard.afterWal.writerTxn); const beforeSeq = BigInt(shard.beforeWal.sequencerTxn); const afterSeq = BigInt(shard.afterWal.sequencerTxn); const liveWriter = BigInt(live.writerTxn); const liveSeq = BigInt(live.sequencerTxn); if (afterWriter <= beforeWriter || afterSeq <= beforeSeq) { throw new VerifyM2QuantError( `${contextLabel}: WAL for shard prefix '${prefix}' (${table}) did not advance.` ); } if (liveWriter < afterWriter || liveSeq < afterSeq) { throw new VerifyM2QuantError( `${contextLabel}: live QuestDB WAL for '${table}' (writerTxn=${live.writerTxn}/sequencerTxn=${live.sequencerTxn}) is behind shard prefix '${prefix}' afterWal (writerTxn=${shard.afterWal.writerTxn}/sequencerTxn=${shard.afterWal.sequencerTxn}).` ); } if (baselineWal !== undefined) { const base = baselineWal.get(table)!; const baseWriter = BigInt(base.writerTxn); const baseSeq = BigInt(base.sequencerTxn); if (beforeWriter < baseWriter || beforeSeq < baseSeq) { throw new VerifyM2QuantError( `${contextLabel}: shard prefix '${prefix}' beforeWal (writerTxn=${shard.beforeWal.writerTxn}/sequencerTxn=${shard.beforeWal.sequencerTxn}) predates resend baseline WAL (writerTxn=${base.writerTxn}/sequencerTxn=${base.sequencerTxn}).` ); } if (liveWriter <= baseWriter || liveSeq <= baseSeq) { throw new VerifyM2QuantError( `${contextLabel}: live QuestDB WAL for '${table}' did not advance past resend baseline (baseline writerTxn=${base.writerTxn}/sequencerTxn=${base.sequencerTxn}, live writerTxn=${live.writerTxn}/sequencerTxn=${live.sequencerTxn}).` ); } } results.push({ shardPrefix: prefix, table, beforeWriterTxn: shard.beforeWal.writerTxn, afterWriterTxn: shard.afterWal.writerTxn, beforeSequencerTxn: shard.beforeWal.sequencerTxn, afterSequencerTxn: shard.afterWal.sequencerTxn, liveWriterTxn: live.writerTxn, liveSequencerTxn: live.sequencerTxn, }); } return results; } async function computeBars1mContentDigest(executor: QuestDbPgQueryExecutor): Promise { const sql = 'SELECT source, utc_day, count() AS row_count, ' + 'sum(open) AS sum_open, sum(high) AS sum_high, sum(low) AS sum_low, ' + 'sum(close) AS sum_close, sum(volume) AS sum_volume, sum(close_sq) AS sum_close_sq, ' + 'min(close) AS min_close, max(close) AS max_close, ' + 'CAST(min(ts) AS LONG) AS min_ts_us, CAST(max(ts) AS LONG) AS max_ts_us ' + 'FROM (SELECT source, CAST(ts AS LONG) / 86400000000 AS utc_day, ' + 'open, high, low, close, volume, close * close AS close_sq, ts FROM bars_1m) ' + 'GROUP BY source, utc_day ORDER BY source, utc_day'; const res = await executor.query(sql); if (res.rows.length === 0) { throw new VerifyM2QuantError('QuestDB bars_1m content digest query returned zero buckets.'); } const hash = createHash('sha256'); for (const row of res.rows) { const source = parseRequiredStringCell(row.source, 'bars_1m_digest.source'); const utcDay = parseBigIntCell(row.utc_day, 'bars_1m_digest.utc_day'); const rowCount = parseBigIntCell(row.row_count, 'bars_1m_digest.row_count'); const sumOpen = parseFiniteNumberCell(row.sum_open, 'bars_1m_digest.sum_open'); const sumHigh = parseFiniteNumberCell(row.sum_high, 'bars_1m_digest.sum_high'); const sumLow = parseFiniteNumberCell(row.sum_low, 'bars_1m_digest.sum_low'); const sumClose = parseFiniteNumberCell(row.sum_close, 'bars_1m_digest.sum_close'); const sumVolume = parseFiniteNumberCell(row.sum_volume, 'bars_1m_digest.sum_volume'); const sumCloseSq = parseFiniteNumberCell(row.sum_close_sq, 'bars_1m_digest.sum_close_sq'); const minClose = parseFiniteNumberCell(row.min_close, 'bars_1m_digest.min_close'); const maxClose = parseFiniteNumberCell(row.max_close, 'bars_1m_digest.max_close'); const minTsUs = parseBigIntCell(row.min_ts_us, 'bars_1m_digest.min_ts_us'); const maxTsUs = parseBigIntCell(row.max_ts_us, 'bars_1m_digest.max_ts_us'); hash.update( `${source}|${utcDay.toString()}|${rowCount.toString()}|${sumOpen}|${sumHigh}|${sumLow}|${sumClose}|${sumVolume}|${sumCloseSq}|${minClose}|${maxClose}|${minTsUs.toString()}|${maxTsUs.toString()}\n` ); } return hash.digest('hex'); } async function computeFx1mContentDigest(executor: QuestDbPgQueryExecutor): Promise { const sql = 'SELECT pair, source, utc_day, count() AS row_count, ' + 'sum(open) AS sum_open, sum(high) AS sum_high, sum(low) AS sum_low, ' + 'sum(close) AS sum_close, sum(close_sq) AS sum_close_sq, ' + 'min(close) AS min_close, max(close) AS max_close, ' + 'CAST(min(ts) AS LONG) AS min_ts_us, CAST(max(ts) AS LONG) AS max_ts_us ' + 'FROM (SELECT pair, source, CAST(ts AS LONG) / 86400000000 AS utc_day, ' + 'open, high, low, close, close * close AS close_sq, ts FROM fx_1m) ' + 'GROUP BY pair, source, utc_day ORDER BY pair, source, utc_day'; const res = await executor.query(sql); if (res.rows.length === 0) { throw new VerifyM2QuantError('QuestDB fx_1m content digest query returned zero buckets.'); } const hash = createHash('sha256'); for (const row of res.rows) { const pair = parseRequiredStringCell(row.pair, 'fx_1m_digest.pair'); const source = parseRequiredStringCell(row.source, 'fx_1m_digest.source'); const utcDay = parseBigIntCell(row.utc_day, 'fx_1m_digest.utc_day'); const rowCount = parseBigIntCell(row.row_count, 'fx_1m_digest.row_count'); const sumOpen = parseFiniteNumberCell(row.sum_open, 'fx_1m_digest.sum_open'); const sumHigh = parseFiniteNumberCell(row.sum_high, 'fx_1m_digest.sum_high'); const sumLow = parseFiniteNumberCell(row.sum_low, 'fx_1m_digest.sum_low'); const sumClose = parseFiniteNumberCell(row.sum_close, 'fx_1m_digest.sum_close'); const sumCloseSq = parseFiniteNumberCell(row.sum_close_sq, 'fx_1m_digest.sum_close_sq'); const minClose = parseFiniteNumberCell(row.min_close, 'fx_1m_digest.min_close'); const maxClose = parseFiniteNumberCell(row.max_close, 'fx_1m_digest.max_close'); const minTsUs = parseBigIntCell(row.min_ts_us, 'fx_1m_digest.min_ts_us'); const maxTsUs = parseBigIntCell(row.max_ts_us, 'fx_1m_digest.max_ts_us'); hash.update( `${pair}|${source}|${utcDay.toString()}|${rowCount.toString()}|${sumOpen}|${sumHigh}|${sumLow}|${sumClose}|${sumCloseSq}|${minClose}|${maxClose}|${minTsUs.toString()}|${maxTsUs.toString()}\n` ); } return hash.digest('hex'); } async function verifyBars1mProbe( executor: QuestDbPgQueryExecutor, shardPrefix: 'bars_1m' | 'bars_1m_qm' | 'dedup_overlap', probe: Bars1mProbeExpectation ): Promise { 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 { 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 { const walAdvancement = verifyPerPrefixWalAdvancement( receipt, walTables, undefined, 'Load receipt WAL check' ); const bySource = new Map( bars1mSummary.map(row => [row.source, row]) ); const eodGroup = bySource.get(BARS_1M_SOURCE_EOD); const qmGroup = bySource.get(BARS_1M_SOURCE_QM); if (eodGroup === undefined) { throw new VerifyM2QuantError( `Load receipt verification failed: QuestDB bars_1m is missing required source='${BARS_1M_SOURCE_EOD}' group (bars_1m shard prefix).` ); } if (qmGroup === undefined) { throw new VerifyM2QuantError( `Load receipt verification failed: QuestDB bars_1m is missing required source='${BARS_1M_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 === BARS_1M_SOURCE_QM ? eodSentRows - overlapRows : eodSentRows; const minExpectedQmRows = overlapWinnerSource === BARS_1M_SOURCE_EOD ? qmSentRows - overlapRows : qmSentRows; const minExpectedTotalBars1mRows = eodSentRows + qmSentRows - overlapRows; const observedTotalBars1mRows = eodGroup.rowCount + qmGroup.rowCount; if (eodGroup.rowCount < minExpectedEodRows) { throw new VerifyM2QuantError( `EOD/QM dedup accounting failed: observed bars_1m source='${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='${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, shardHashes: { bars_1m: receipt.shards.bars_1m.shardSha256, bars_1m_qm: receipt.shards.bars_1m_qm.shardSha256, fx_1m: receipt.shards.fx_1m.shardSha256, }, dedupAccounting: { eodSentRows, qmSentRows, overlapRows, overlapWinnerSource, minExpectedEodRows, minExpectedQmRows, minExpectedTotalBars1mRows, observedEodRows: eodGroup.rowCount, observedQmRows: qmGroup.rowCount, observedTotalBars1mRows, }, probesVerified, }; } function assertShardHashesMatch( prefix: RequiredShardPrefix, baselineHashes: readonly string[], currentHashes: readonly string[] ): void { if (baselineHashes.length !== currentHashes.length) { throw new VerifyM2QuantError( `Idempotent resend failed: shard hash count diverged for '${prefix}' (${baselineHashes.length} -> ${currentHashes.length}).` ); } for (let i = 0; i < baselineHashes.length; i += 1) { if (baselineHashes[i] !== currentHashes[i]) { throw new VerifyM2QuantError( `Idempotent resend failed: shard SHA-256 diverged for '${prefix}'[${i}] (${baselineHashes[i]} -> ${currentHashes[i]}).` ); } } } function verifyIdempotentResend( baseline: ParsedResendBaseline, receipt: M2LoadReceipt, walTables: readonly WalTableStatusRow[], bars1mSummary: readonly Bars1mSourceSummaryRow[], fx1mSummary: readonly Fx1mPairSourceSummaryRow[], bars1mContentDigest: string, fx1mContentDigest: string ): ResendVerificationResult { for (const prefix of REQUIRED_SHARD_PREFIXES) { assertShardHashesMatch( prefix, baseline.shardHashes[prefix], receipt.shards[prefix].shardSha256 ); } const walAdvancement = verifyPerPrefixWalAdvancement( receipt, walTables, baseline.walTables, 'Idempotent resend WAL check' ); 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}]).` ); } } if (bars1mContentDigest !== baseline.bars1mContentDigest) { throw new VerifyM2QuantError( `Idempotent resend failed: bars_1m retained row content digest diverged (${baseline.bars1mContentDigest} -> ${bars1mContentDigest}).` ); } if (fx1mContentDigest !== baseline.fx1mContentDigest) { throw new VerifyM2QuantError( `Idempotent resend failed: fx_1m retained row content digest diverged (${baseline.fx1mContentDigest} -> ${fx1mContentDigest}).` ); } return { ok: true, walAdvancement, shardHashesMatched: true, bars1mRowCountsUnchanged: true, fx1mRowCountsUnchanged: true, bars1mContentDigestMatched: true, fx1mContentDigestMatched: true, }; } 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, perfNowMs: () => number ): Promise { 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 { return readFile(path, 'utf8'); } async function defaultWriteReportFile(path: string, content: string): Promise { await mkdir(dirname(path), { recursive: true }); await writeFile(path, content, 'utf8'); } async function defaultCreateDuckDbExecutor(): Promise { const { createNodeDuckDbExecutor } = await import('@stock-bot/duckdb'); return createNodeDuckDbExecutor(); } async function defaultOpenResearchCopilotStore( config: ResearchCopilotHostConfig, options?: OpenResearchCopilotStoreOptions ): Promise { const { openResearchCopilotStore } = await import('@stock-bot/duckdb'); return openResearchCopilotStore(config, options); } function defaultSleepMs(ms: number): Promise { return new Promise(resolveSleep => { setTimeout(resolveSleep, ms); }); } /** * Runs the QuestDB/DuckDB M2 verification CLI with injectable I/O, executors, * store factory, and clocks for deterministic offline testing. */ export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Promise { const argv = deps.argv ?? process.argv.slice(2); const stdout = deps.stdout ?? process.stdout; const stderr = deps.stderr ?? process.stderr; const secretNeedles = collectArgvSecretNeedles(argv); const writeRedactedError = (prefix: string, err: unknown): void => { const raw = err instanceof Error ? err.message : String(err); const safe = sanitizeSingleLine(redactSecrets(raw, secretNeedles)); stderr.write(`${prefix}: ${safe}\n`); }; let parsed: ParsedVerifyM2QuantArgs; try { parsed = parseVerifyM2QuantArgs(argv, { ...(deps.cwd !== undefined ? { cwd: deps.cwd } : {}), }); } catch (err: unknown) { writeRedactedError('Invalid arguments', err); return 1; } if (parsed.kind === 'help') { stdout.write(VERIFY_M2_QUANT_USAGE); return 0; } const openPg = deps.openQuestDbPgExecutor ?? openQuestDbPgExecutor; const applyDdlFn = deps.applyM2IntradayDDL ?? applyM2IntradayDDL; const createDuck = deps.createDuckDbExecutor ?? 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); const requiredMinWal = getRequiredMinWalFromReceipt(receipt); let ddlResult: { readonly applied: boolean; readonly appliedTables: readonly M2IntradayTableName[]; } = { applied: false, appliedTables: [] }; let walTables: readonly WalTableStatusRow[]; // Poll wal_tables() (metadata only, zero bar-table scans) and confirm all expected // load transactions are applied BEFORE starting the timed cold benchmark read. const preBenchPgHandle = await openPg(parsed.questdb); try { if (parsed.applyDdl) { const applied = await applyDdlFn(preBenchPgHandle.executor); ddlResult = { applied: true, appliedTables: applied.appliedTables }; } walTables = await waitForHealthyWalTables( preBenchPgHandle.executor, parsed.walSettleTimeoutMs, walPollIntervalMs, nowMs, sleepMs, requiredMinWal ); } finally { await preBenchPgHandle.close(); } // Measure the cold 1-year 1m benchmark read BEFORE any verifier query scans bars_1m // or fx_1m so QuestDB and OS page caches are not pre-warmed after restart. const benchmark = await runIntradayLatencyBenchmark(parsed, fence, openStore, perfNowMs); let bars1mSummary: readonly Bars1mSourceSummaryRow[]; let fx1mSummary: readonly Fx1mPairSourceSummaryRow[]; let bars1mContentDigest: string; let fx1mContentDigest: string; let loadVerification: LoadReceiptVerificationResult; let resendVerification: ResendVerificationResult | undefined; const splitChecks: SplitBoundaryCheckResult[] = []; const pgHandle = await openPg(parsed.questdb); try { bars1mSummary = await verifyBars1mCommits(pgHandle.executor); fx1mSummary = await verifyFx1mCommits(pgHandle.executor); loadVerification = await verifyLoadReceipt( pgHandle.executor, receipt, walTables, bars1mSummary, fx1mSummary ); bars1mContentDigest = await computeBars1mContentDigest(pgHandle.executor); fx1mContentDigest = await computeFx1mContentDigest(pgHandle.executor); if (resendBaseline !== undefined) { resendVerification = verifyIdempotentResend( resendBaseline, receipt, walTables, bars1mSummary, fx1mSummary, bars1mContentDigest, fx1mContentDigest ); } 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, bars1mContentDigest, fx1mContentDigest, 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(); }