/** * 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: string; readonly fromDate: string; readonly toDate: string; readonly exDate: string; readonly ratio: string; } export interface ExtraSplitBoundaryCase extends SplitBoundaryCaseSpec { readonly listingId: number; } 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 nvdaFromDate?: string; readonly nvdaToDate?: string; readonly nexmFromDate?: string; readonly nexmToDate?: string; readonly extraSplitCase?: ExtraSplitBoundaryCase; 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: string; 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})`, ' --nvda-from Optional NVDA.US split window start (< 2024-06-10)', ' --nvda-to Optional NVDA.US split window end (>= 2024-06-10)', ' --nexm-from Optional NEXM.V split window start (< 2025-06-20)', ' --nexm-to Optional NEXM.V split window end (>= 2025-06-20)', ' --eod-split-label