1314 lines
44 KiB
TypeScript
1314 lines
44 KiB
TypeScript
/**
|
|
* Deterministic QuestDB 10.2.0 / DuckDB M2 verification CLI for `quant` (`10.0.0.51`).
|
|
*
|
|
* Verifies Milestone M2 Exit Criterion 3 fail-closed:
|
|
* 1. Optional opt-in `applyM2IntradayDDL` (`--apply-ddl`).
|
|
* 2. `wal_tables()` health (`bars_1m`, `fx_1m`, `bar_revisions` present,
|
|
* `suspended = false`, `writerTxn >= sequencerTxn`) and non-zero finite
|
|
* `0x10` binary-double commits on `bars_1m` and `fx_1m`.
|
|
* 3. 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`).
|
|
* 4. 1-year single-listing `1m` PGWire latency benchmark (`< 1000 ms` cold,
|
|
* `< 250 ms` warm across `--warm-runs`, `rowCount > 0`, identical bar
|
|
* digests across runs, Vault-fenced with `vaultOperatorAuthorized: false`).
|
|
*
|
|
* Fail-closed: any validation, WAL, 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, 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,
|
|
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_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/;
|
|
const STRICT_UTC_INSTANT_RE =
|
|
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/;
|
|
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
const URL_CREDENTIAL_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^:@/\s]+):([^@/\s]+)@/g;
|
|
const POSTGRES_URL_RE = /postgres(?:ql)?:\/\/[^\s'"]+/gi;
|
|
|
|
export const DEFAULT_WARM_RUNS = 5;
|
|
export const DEFAULT_WAL_SETTLE_TIMEOUT_MS = 30_000;
|
|
export const DEFAULT_WAL_POLL_INTERVAL_MS = 250;
|
|
export const MAX_SPLIT_CLOSE_REL_DIFF = 0.005;
|
|
export const MAX_COLD_READ_MS = 1_000;
|
|
export const MAX_WARM_READ_MS = 250;
|
|
|
|
export 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 applyDdl: boolean;
|
|
readonly warmRuns: number;
|
|
readonly walSettleTimeoutMs: number;
|
|
readonly outPath?: string;
|
|
}
|
|
|
|
export interface ParsedVerifyM2QuantHelp {
|
|
readonly kind: 'help';
|
|
}
|
|
|
|
export type ParsedVerifyM2QuantArgs = ParsedVerifyM2QuantRun | ParsedVerifyM2QuantHelp;
|
|
|
|
export interface VerifyM2QuantCliDeps {
|
|
readonly argv?: readonly string[];
|
|
readonly cwd?: string;
|
|
readonly stdout?: VerifyM2QuantStream;
|
|
readonly stderr?: VerifyM2QuantStream;
|
|
readonly openQuestDbPgExecutor?: (
|
|
config: QuestDbPgExecutorConfig
|
|
) => Promise<QuestDbPgExecutorHandle>;
|
|
readonly applyM2IntradayDDL?: (
|
|
client: QuestDbPgQueryExecutor
|
|
) => Promise<ApplyM2IntradayDDLResult>;
|
|
readonly createDuckDbExecutor?: () => Promise<ClosableDuckDbExecutor>;
|
|
readonly openResearchCopilotStore?: (
|
|
config: ResearchCopilotHostConfig,
|
|
options?: OpenResearchCopilotStoreOptions
|
|
) => Promise<ManagedMarketDataStore>;
|
|
readonly writeReportFile?: (path: string, content: string) => Promise<void>;
|
|
readonly nowMs?: () => number;
|
|
readonly perfNowMs?: () => number;
|
|
readonly sleepMs?: (ms: number) => Promise<void>;
|
|
readonly walPollIntervalMs?: number;
|
|
}
|
|
|
|
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 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;
|
|
};
|
|
}
|
|
|
|
export interface VerifyM2QuantReport {
|
|
readonly ok: true;
|
|
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 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]',
|
|
'',
|
|
'Required options:',
|
|
' --questdb-url <url> QuestDB PGWire URL (mutually exclusive with --questdb-host/--questdb-pg-port)',
|
|
' --questdb-host <host> QuestDB PGWire host (requires --questdb-pg-port)',
|
|
' --questdb-pg-port <port> QuestDB PGWire port (requires --questdb-host)',
|
|
' --curated-root <dir> Curated Parquet root containing bars_1d/year=*/part.parquet',
|
|
' --vault-cutoff-ts <iso-utc-z> Authoritative Vault cutoff ISO-8601 UTC timestamp ending in Z',
|
|
' --nvda-listing-id <int32> Permanent listing_id for NVDA.US',
|
|
' --nexm-listing-id <int32> Permanent listing_id for NEXM.V',
|
|
' --bench-listing-id <int32> Permanent listing_id for 1y 1m PGWire latency benchmark',
|
|
' --bench-from <iso-or-date> Benchmark window start (must be < --vault-cutoff-ts)',
|
|
' --bench-to <iso-or-date> Benchmark window end',
|
|
' --bench-as-of <iso-or-date> Benchmark point-in-time as-of bound',
|
|
'',
|
|
'Optional options:',
|
|
' --questdb-database <name> QuestDB PGWire database name (host/port mode)',
|
|
' --questdb-user <user> QuestDB PGWire user (host/port mode)',
|
|
' --questdb-password <pass> QuestDB PGWire password (host/port mode)',
|
|
' --questdb-ssl <true|false> Explicit TLS flag',
|
|
' --bench-scope <scope> DataScope for benchmark (default: vault_fenced)',
|
|
' --apply-ddl Execute applyM2IntradayDDL before checks',
|
|
` --warm-runs <pos-int> Number of warm 1y 1m benchmark reads (default: ${DEFAULT_WARM_RUNS})`,
|
|
` --wal-settle-timeout-ms <pos-int> WAL settle polling timeout in ms (default: ${DEFAULT_WAL_SETTLE_TIMEOUT_MS})`,
|
|
' --out <path> Optional JSON output file path',
|
|
' -h, --help Show this help message',
|
|
'',
|
|
].join('\n');
|
|
|
|
const VALUE_FLAGS = new Set([
|
|
'--questdb-url',
|
|
'--questdb-host',
|
|
'--questdb-pg-port',
|
|
'--questdb-database',
|
|
'--questdb-user',
|
|
'--questdb-password',
|
|
'--questdb-ssl',
|
|
'--curated-root',
|
|
'--vault-cutoff-ts',
|
|
'--nvda-listing-id',
|
|
'--nexm-listing-id',
|
|
'--bench-listing-id',
|
|
'--bench-from',
|
|
'--bench-to',
|
|
'--bench-as-of',
|
|
'--bench-scope',
|
|
'--warm-runs',
|
|
'--wal-settle-timeout-ms',
|
|
'--out',
|
|
]);
|
|
|
|
const BOOLEAN_FLAGS = new Set(['--apply-ddl']);
|
|
const SECRET_FLAGS = new Set(['--questdb-url', '--questdb-password']);
|
|
|
|
function sanitizeSingleLine(message: string): string {
|
|
return message.replace(/\r?\n/g, ' ').trim();
|
|
}
|
|
|
|
function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
|
|
if (raw.length === 0) {
|
|
return;
|
|
}
|
|
needles.add(raw);
|
|
try {
|
|
const decoded = decodeURIComponent(raw);
|
|
if (decoded.length > 0) {
|
|
needles.add(decoded);
|
|
}
|
|
} catch {
|
|
// Malformed percent-encoding: raw value is already registered.
|
|
}
|
|
}
|
|
|
|
function collectArgvSecretNeedles(argv: readonly string[]): Set<string> {
|
|
const needles = new Set<string>();
|
|
for (let i = 0; i < argv.length; i += 1) {
|
|
const token = argv[i] as string;
|
|
const eqIndex = token.indexOf('=');
|
|
let flag: string;
|
|
let rawValue: string | undefined;
|
|
if (eqIndex !== -1) {
|
|
flag = token.slice(0, eqIndex);
|
|
rawValue = token.slice(eqIndex + 1);
|
|
} else {
|
|
flag = token;
|
|
if (SECRET_FLAGS.has(flag) && i + 1 < argv.length) {
|
|
rawValue = argv[i + 1];
|
|
}
|
|
}
|
|
if (SECRET_FLAGS.has(flag) && rawValue !== undefined && rawValue.length > 0) {
|
|
addRawAndDecodedNeedle(needles, rawValue);
|
|
if (flag === '--questdb-url') {
|
|
try {
|
|
const parsed = new URL(rawValue);
|
|
if (parsed.href.length > 0) {
|
|
needles.add(parsed.href);
|
|
}
|
|
addRawAndDecodedNeedle(needles, parsed.password);
|
|
for (const [k, v] of parsed.searchParams.entries()) {
|
|
if (k.toLowerCase() === 'password' && v.length > 0) {
|
|
addRawAndDecodedNeedle(needles, v);
|
|
}
|
|
}
|
|
} catch {
|
|
// Non-URL string: raw string already registered.
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return needles;
|
|
}
|
|
|
|
export function redactSecrets(message: string, needles: Iterable<string>): string {
|
|
let out = message;
|
|
const sorted = Array.from(new Set(needles))
|
|
.filter(n => n.length > 0)
|
|
.sort((a, b) => b.length - a.length);
|
|
for (const needle of sorted) {
|
|
out = out.split(needle).join('[REDACTED]');
|
|
}
|
|
out = out.replace(POSTGRES_URL_RE, '[REDACTED_DSN]');
|
|
out = out.replace(URL_CREDENTIAL_RE, '$1[REDACTED]:[REDACTED]@');
|
|
return out;
|
|
}
|
|
|
|
function validateRawTokenValue(flag: string, rawValue: string): string {
|
|
if (rawValue.length === 0 || rawValue.trim().length === 0) {
|
|
throw new VerifyM2QuantError(`Flag '${flag}' requires a non-empty value.`);
|
|
}
|
|
if (rawValue.includes('\0')) {
|
|
throw new VerifyM2QuantError(`Flag '${flag}' value must not contain NUL bytes.`);
|
|
}
|
|
if (!SECRET_FLAGS.has(flag) && rawValue.startsWith('-')) {
|
|
throw new VerifyM2QuantError(
|
|
`Flag '${flag}' value must not start with '-' (received '${rawValue}').`
|
|
);
|
|
}
|
|
return rawValue;
|
|
}
|
|
|
|
function parsePositiveIntFlag(flag: string, rawValue: string, maxValue?: number): number {
|
|
const validated = validateRawTokenValue(flag, rawValue);
|
|
if (!STRICT_POSITIVE_INT_RE.test(validated)) {
|
|
throw new VerifyM2QuantError(
|
|
`Flag '${flag}' must be a positive integer (received '${validated}').`
|
|
);
|
|
}
|
|
const parsed = Number(validated);
|
|
if (!Number.isSafeInteger(parsed) || parsed <= 0 || (maxValue !== undefined && parsed > maxValue)) {
|
|
throw new VerifyM2QuantError(
|
|
`Flag '${flag}' is out of allowed range (received '${validated}').`
|
|
);
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
function parseBooleanFlagValue(flag: string, rawValue: string): boolean {
|
|
const normalized = validateRawTokenValue(flag, rawValue).trim().toLowerCase();
|
|
if (normalized === 'true') {
|
|
return true;
|
|
}
|
|
if (normalized === 'false') {
|
|
return false;
|
|
}
|
|
throw new VerifyM2QuantError(
|
|
`Flag '${flag}' must be 'true' or 'false' (received '${rawValue}').`
|
|
);
|
|
}
|
|
|
|
function parseStrictUtcIsoZ(flag: string, rawValue: string): number {
|
|
const validated = validateRawTokenValue(flag, rawValue);
|
|
const match = STRICT_UTC_INSTANT_RE.exec(validated);
|
|
if (match === null) {
|
|
throw new VerifyM2QuantError(
|
|
`Flag '${flag}' must be a strict ISO-8601 UTC timestamp ending in 'Z' (received '${validated}').`
|
|
);
|
|
}
|
|
const year = Number(match[1]);
|
|
const month = Number(match[2]);
|
|
const day = Number(match[3]);
|
|
const hours = Number(match[4]);
|
|
const minutes = Number(match[5]);
|
|
const seconds = Number(match[6]);
|
|
const frac = match[7] !== undefined ? Number(match[7].padEnd(3, '0')) : 0;
|
|
const epochMs = Date.UTC(year, month - 1, day, hours, minutes, seconds, frac);
|
|
const check = new Date(epochMs);
|
|
if (
|
|
!Number.isSafeInteger(epochMs) ||
|
|
check.getUTCFullYear() !== year ||
|
|
check.getUTCMonth() !== month - 1 ||
|
|
check.getUTCDate() !== day ||
|
|
check.getUTCHours() !== hours ||
|
|
check.getUTCMinutes() !== minutes ||
|
|
check.getUTCSeconds() !== seconds ||
|
|
check.getUTCMilliseconds() !== frac
|
|
) {
|
|
throw new VerifyM2QuantError(
|
|
`Flag '${flag}' contains an invalid UTC calendar instant (received '${validated}').`
|
|
);
|
|
}
|
|
return epochMs;
|
|
}
|
|
|
|
function assertSafeDuckDbPath(rawPath: string, flag: string): string {
|
|
for (let i = 0; i < rawPath.length; i += 1) {
|
|
const code = rawPath.charCodeAt(i);
|
|
if (code <= 0x1f || code === 0x7f || code === 0x27 || code === 0x3b) {
|
|
throw new VerifyM2QuantError(
|
|
`Flag '${flag}' contains characters disallowed in DuckDB Parquet paths.`
|
|
);
|
|
}
|
|
}
|
|
return rawPath.replace(/\/+$/, '') || '/';
|
|
}
|
|
|
|
export function parseVerifyM2QuantArgs(
|
|
argv: readonly string[],
|
|
options?: ParseVerifyM2QuantArgsOptions
|
|
): ParsedVerifyM2QuantArgs {
|
|
const baseCwd = options?.cwd ?? process.cwd();
|
|
const seenValues = new Map<string, string>();
|
|
const seenBooleans = new Set<string>();
|
|
|
|
for (let i = 0; i < argv.length; i += 1) {
|
|
const token = argv[i] as string;
|
|
if (token === '--help' || token === '-h') {
|
|
return { kind: 'help' };
|
|
}
|
|
if (token === '--') {
|
|
throw new VerifyM2QuantError('Unexpected positional argument separator "--".');
|
|
}
|
|
if (!token.startsWith('-')) {
|
|
throw new VerifyM2QuantError(`Unexpected positional argument '${token}'.`);
|
|
}
|
|
|
|
const eqIndex = token.indexOf('=');
|
|
if (eqIndex !== -1) {
|
|
const flag = token.slice(0, eqIndex);
|
|
const rawValue = token.slice(eqIndex + 1);
|
|
if (BOOLEAN_FLAGS.has(flag)) {
|
|
throw new VerifyM2QuantError(`Flag '${flag}' does not accept a value.`);
|
|
}
|
|
if (!VALUE_FLAGS.has(flag)) {
|
|
throw new VerifyM2QuantError(`Unknown flag '${flag}'.`);
|
|
}
|
|
if (seenValues.has(flag)) {
|
|
throw new VerifyM2QuantError(`Duplicate flag '${flag}'.`);
|
|
}
|
|
seenValues.set(flag, validateRawTokenValue(flag, rawValue));
|
|
continue;
|
|
}
|
|
|
|
if (BOOLEAN_FLAGS.has(token)) {
|
|
if (seenBooleans.has(token)) {
|
|
throw new VerifyM2QuantError(`Duplicate flag '${token}'.`);
|
|
}
|
|
seenBooleans.add(token);
|
|
continue;
|
|
}
|
|
|
|
if (!VALUE_FLAGS.has(token)) {
|
|
throw new VerifyM2QuantError(`Unknown flag '${token}'.`);
|
|
}
|
|
if (seenValues.has(token)) {
|
|
throw new VerifyM2QuantError(`Duplicate flag '${token}'.`);
|
|
}
|
|
if (i + 1 >= argv.length) {
|
|
throw new VerifyM2QuantError(`Flag '${token}' requires a value.`);
|
|
}
|
|
i += 1;
|
|
seenValues.set(token, validateRawTokenValue(token, argv[i] as string));
|
|
}
|
|
|
|
const rawUrl = seenValues.get('--questdb-url');
|
|
const rawHost = seenValues.get('--questdb-host');
|
|
const rawPort = seenValues.get('--questdb-pg-port');
|
|
const rawDb = seenValues.get('--questdb-database');
|
|
const rawUser = seenValues.get('--questdb-user');
|
|
const rawPassword = seenValues.get('--questdb-password');
|
|
const rawSsl = seenValues.get('--questdb-ssl');
|
|
const ssl = rawSsl !== undefined ? parseBooleanFlagValue('--questdb-ssl', rawSsl) : undefined;
|
|
|
|
let questdb: QuestDbPgExecutorConfig;
|
|
if (rawUrl !== undefined) {
|
|
if (
|
|
rawHost !== undefined ||
|
|
rawPort !== undefined ||
|
|
rawDb !== undefined ||
|
|
rawUser !== undefined ||
|
|
rawPassword !== undefined
|
|
) {
|
|
throw new VerifyM2QuantError(
|
|
'Cannot combine --questdb-url with --questdb-host/--questdb-pg-port/--questdb-database/--questdb-user/--questdb-password.'
|
|
);
|
|
}
|
|
questdb = {
|
|
url: rawUrl,
|
|
...(ssl !== undefined ? { ssl } : {}),
|
|
};
|
|
} else {
|
|
if (rawHost === undefined || rawPort === undefined) {
|
|
throw new VerifyM2QuantError(
|
|
'Missing required QuestDB connection flags: provide --questdb-url or both --questdb-host and --questdb-pg-port.'
|
|
);
|
|
}
|
|
const port = parsePositiveIntFlag('--questdb-pg-port', rawPort, 65_535);
|
|
questdb = {
|
|
host: rawHost,
|
|
port,
|
|
...(rawDb !== undefined ? { database: rawDb } : {}),
|
|
...(rawUser !== undefined ? { user: rawUser } : {}),
|
|
...(rawPassword !== undefined ? { password: rawPassword } : {}),
|
|
...(ssl !== undefined ? { ssl } : {}),
|
|
};
|
|
}
|
|
|
|
const 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 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;
|
|
|
|
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;
|
|
|
|
return {
|
|
kind: 'run',
|
|
questdb,
|
|
curatedRoot,
|
|
vaultCutoffIso,
|
|
vaultCutoffTs,
|
|
nvdaListingId,
|
|
nexmListingId,
|
|
benchListingId,
|
|
benchFrom,
|
|
benchTo,
|
|
benchAsOf,
|
|
benchScope,
|
|
applyDdl: seenBooleans.has('--apply-ddl'),
|
|
warmRuns,
|
|
walSettleTimeoutMs,
|
|
...(outPath !== undefined ? { outPath } : {}),
|
|
};
|
|
}
|
|
|
|
function parseBigIntCell(value: unknown, field: string): bigint {
|
|
if (typeof value === 'bigint') {
|
|
return value;
|
|
}
|
|
if (typeof value === 'number' && Number.isSafeInteger(value)) {
|
|
return BigInt(value);
|
|
}
|
|
if (typeof value === 'string' && STRICT_SIGNED_INT_RE.test(value.trim())) {
|
|
return BigInt(value.trim());
|
|
}
|
|
throw new VerifyM2QuantError(`Invalid integer value for '${field}': ${String(value)}.`);
|
|
}
|
|
|
|
function parseFiniteNumberCell(value: unknown, field: string): number {
|
|
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
return Object.is(value, -0) ? 0 : value;
|
|
}
|
|
if (typeof value === 'string' && value.trim().length > 0) {
|
|
const parsed = Number(value.trim());
|
|
if (Number.isFinite(parsed)) {
|
|
return Object.is(parsed, -0) ? 0 : parsed;
|
|
}
|
|
}
|
|
throw new VerifyM2QuantError(`Invalid finite numeric value for '${field}': ${String(value)}.`);
|
|
}
|
|
|
|
function parseBooleanCell(value: unknown, field: string): boolean {
|
|
if (typeof value === 'boolean') {
|
|
return value;
|
|
}
|
|
if (typeof value === 'string') {
|
|
const lower = value.trim().toLowerCase();
|
|
if (lower === 'true' || lower === 't') {
|
|
return true;
|
|
}
|
|
if (lower === 'false' || lower === 'f') {
|
|
return false;
|
|
}
|
|
}
|
|
throw new VerifyM2QuantError(`Invalid boolean value for '${field}': ${String(value)}.`);
|
|
}
|
|
|
|
function parseRequiredStringCell(value: unknown, field: string): string {
|
|
if (typeof value === 'string' && value.trim().length > 0) {
|
|
return value.trim();
|
|
}
|
|
throw new VerifyM2QuantError(`Invalid string value for '${field}': ${String(value)}.`);
|
|
}
|
|
|
|
function formatNySessionDateFromMicros(tsUs: bigint): string {
|
|
const epochMs = Number(tsUs / 1000n);
|
|
if (!Number.isSafeInteger(epochMs)) {
|
|
throw new VerifyM2QuantError(`Out-of-range QuestDB timestamp micros: ${tsUs.toString()}.`);
|
|
}
|
|
const formatted = NY_DATE_FORMATTER.format(new Date(epochMs));
|
|
if (!DATE_ONLY_RE.test(formatted)) {
|
|
throw new VerifyM2QuantError(`Unexpected America/New_York session date format: '${formatted}'.`);
|
|
}
|
|
return formatted;
|
|
}
|
|
|
|
function addUtcDays(isoDate: string, deltaDays: number): string {
|
|
const parts = isoDate.split('-').map(Number);
|
|
const year = parts[0] as number;
|
|
const month = parts[1] as number;
|
|
const day = parts[2] as number;
|
|
const ms = Date.UTC(year, month - 1, day + deltaDays);
|
|
return new Date(ms).toISOString().slice(0, 10);
|
|
}
|
|
|
|
function computeBarsDigest(bars: readonly BarRecord[]): string {
|
|
const hash = createHash('sha256');
|
|
for (let i = 0; i < bars.length; i += 1) {
|
|
const bar = bars[i] as BarRecord;
|
|
hash.update(
|
|
`${bar.listingId},${bar.ts},${bar.open},${bar.high},${bar.low},${bar.close},${bar.volume},${bar.vwap ?? ''},${bar.knownAt}\n`
|
|
);
|
|
}
|
|
return hash.digest('hex');
|
|
}
|
|
|
|
function computeMedian(values: readonly number[]): number {
|
|
const sorted = [...values].sort((a, b) => a - b);
|
|
const mid = Math.floor(sorted.length / 2);
|
|
if (sorted.length % 2 === 1) {
|
|
return sorted[mid] as number;
|
|
}
|
|
return ((sorted[mid - 1] as number) + (sorted[mid] as number)) / 2;
|
|
}
|
|
|
|
function describeSafeQuestDbTarget(config: QuestDbPgExecutorConfig): string {
|
|
if (config.url !== undefined) {
|
|
try {
|
|
const parsed = new URL(config.url);
|
|
const port = parsed.port || '8812';
|
|
return `${parsed.hostname}:${port}`;
|
|
} catch {
|
|
return '[redacted-url]';
|
|
}
|
|
}
|
|
return `${config.host ?? 'localhost'}:${config.port ?? 8812}`;
|
|
}
|
|
|
|
async function waitForHealthyWalTables(
|
|
executor: QuestDbPgQueryExecutor,
|
|
timeoutMs: number,
|
|
pollIntervalMs: number,
|
|
nowMs: () => number,
|
|
sleepMs: (ms: number) => Promise<void>
|
|
): Promise<readonly WalTableStatusRow[]> {
|
|
const deadline = nowMs() + timeoutMs;
|
|
const sql =
|
|
"SELECT name, suspended, writerTxn, sequencerTxn FROM wal_tables() WHERE name IN ('bars_1m', 'fx_1m', 'bar_revisions') ORDER BY name";
|
|
|
|
while (true) {
|
|
const res = await executor.query(sql);
|
|
const byName = new Map<
|
|
M2IntradayTableName,
|
|
{ suspended: boolean; writerTxn: bigint; sequencerTxn: bigint }
|
|
>();
|
|
|
|
for (const row of res.rows) {
|
|
const name = parseRequiredStringCell(row.name, 'wal_tables.name');
|
|
if (!(M2_INTRADAY_TABLE_NAMES as readonly string[]).includes(name)) {
|
|
continue;
|
|
}
|
|
const suspended = parseBooleanCell(row.suspended, `${name}.suspended`);
|
|
const writerTxn = parseBigIntCell(
|
|
row.writerTxn ?? row.writertxn,
|
|
`${name}.writerTxn`
|
|
);
|
|
const sequencerTxn = parseBigIntCell(
|
|
row.sequencerTxn ?? row.sequencertxn,
|
|
`${name}.sequencerTxn`
|
|
);
|
|
byName.set(name as M2IntradayTableName, { suspended, writerTxn, sequencerTxn });
|
|
}
|
|
|
|
const missing = M2_INTRADAY_TABLE_NAMES.filter(name => !byName.has(name));
|
|
if (missing.length > 0) {
|
|
throw new VerifyM2QuantError(
|
|
`Missing required M2 WAL tables in wal_tables(): ${missing.join(', ')}.`
|
|
);
|
|
}
|
|
|
|
const suspendedTables = M2_INTRADAY_TABLE_NAMES.filter(
|
|
name => byName.get(name)?.suspended === true
|
|
);
|
|
if (suspendedTables.length > 0) {
|
|
throw new VerifyM2QuantError(
|
|
`Suspended QuestDB WAL table(s) detected: ${suspendedTables.join(', ')}.`
|
|
);
|
|
}
|
|
|
|
const unsettled = M2_INTRADAY_TABLE_NAMES.filter(name => {
|
|
const status = byName.get(name)!;
|
|
return status.writerTxn < status.sequencerTxn;
|
|
});
|
|
|
|
if (unsettled.length === 0) {
|
|
return M2_INTRADAY_TABLE_NAMES.map(name => {
|
|
const status = byName.get(name)!;
|
|
return {
|
|
name,
|
|
suspended: status.suspended,
|
|
writerTxn: status.writerTxn.toString(),
|
|
sequencerTxn: status.sequencerTxn.toString(),
|
|
};
|
|
});
|
|
}
|
|
|
|
if (nowMs() >= deadline) {
|
|
const details = unsettled
|
|
.map(name => {
|
|
const status = byName.get(name)!;
|
|
return `${name}(writerTxn=${status.writerTxn.toString()}<sequencerTxn=${status.sequencerTxn.toString()})`;
|
|
})
|
|
.join(', ');
|
|
throw new VerifyM2QuantError(
|
|
`Timed out after ${timeoutMs}ms waiting for QuestDB WAL tables to settle: ${details}.`
|
|
);
|
|
}
|
|
|
|
await sleepMs(pollIntervalMs);
|
|
}
|
|
}
|
|
|
|
async function verifyBars1mCommits(
|
|
executor: QuestDbPgQueryExecutor
|
|
): Promise<readonly Bars1mSourceSummaryRow[]> {
|
|
const sql =
|
|
'SELECT source, count() AS row_count, min(close) AS min_close, max(close) AS max_close, ' +
|
|
'CAST(min(ts) AS LONG) AS min_ts_us, CAST(max(ts) AS LONG) AS max_ts_us ' +
|
|
'FROM bars_1m GROUP BY source ORDER BY source';
|
|
const res = await executor.query(sql);
|
|
if (res.rows.length === 0) {
|
|
throw new VerifyM2QuantError('QuestDB bars_1m contains zero rows.');
|
|
}
|
|
|
|
const out: Bars1mSourceSummaryRow[] = [];
|
|
let totalRows = 0;
|
|
for (const row of res.rows) {
|
|
const source = parseRequiredStringCell(row.source, 'bars_1m.source');
|
|
const rowCount = Number(parseBigIntCell(row.row_count, `bars_1m[${source}].row_count`));
|
|
if (!Number.isSafeInteger(rowCount) || rowCount <= 0) {
|
|
throw new VerifyM2QuantError(`QuestDB bars_1m source '${source}' has non-positive row_count: ${rowCount}.`);
|
|
}
|
|
const minClose = parseFiniteNumberCell(row.min_close, `bars_1m[${source}].min_close`);
|
|
const maxClose = parseFiniteNumberCell(row.max_close, `bars_1m[${source}].max_close`);
|
|
if (minClose <= 0 || maxClose <= 0 || minClose > maxClose) {
|
|
throw new VerifyM2QuantError(
|
|
`QuestDB bars_1m source '${source}' has invalid close bounds [${minClose}, ${maxClose}].`
|
|
);
|
|
}
|
|
const minTsUs = parseBigIntCell(row.min_ts_us, `bars_1m[${source}].min_ts_us`);
|
|
const maxTsUs = parseBigIntCell(row.max_ts_us, `bars_1m[${source}].max_ts_us`);
|
|
if (minTsUs > maxTsUs) {
|
|
throw new VerifyM2QuantError(
|
|
`QuestDB bars_1m source '${source}' has inverted timestamp range [${minTsUs.toString()}, ${maxTsUs.toString()}].`
|
|
);
|
|
}
|
|
totalRows += rowCount;
|
|
out.push({
|
|
source,
|
|
rowCount,
|
|
minClose,
|
|
maxClose,
|
|
minTsUs: minTsUs.toString(),
|
|
maxTsUs: maxTsUs.toString(),
|
|
});
|
|
}
|
|
|
|
if (totalRows <= 0) {
|
|
throw new VerifyM2QuantError('QuestDB bars_1m total row count is zero.');
|
|
}
|
|
|
|
return out;
|
|
}
|
|
|
|
async function verifyFx1mCommits(
|
|
executor: QuestDbPgQueryExecutor
|
|
): Promise<readonly Fx1mPairSourceSummaryRow[]> {
|
|
const sql =
|
|
'SELECT pair, source, count() AS row_count, min(close) AS min_close, max(close) AS max_close, ' +
|
|
'CAST(min(ts) AS LONG) AS min_ts_us, CAST(max(ts) AS LONG) AS max_ts_us ' +
|
|
'FROM fx_1m GROUP BY pair, source ORDER BY pair, source';
|
|
const res = await executor.query(sql);
|
|
if (res.rows.length === 0) {
|
|
throw new VerifyM2QuantError('QuestDB fx_1m contains zero rows.');
|
|
}
|
|
|
|
const out: Fx1mPairSourceSummaryRow[] = [];
|
|
let totalRows = 0;
|
|
for (const row of res.rows) {
|
|
const pair = parseRequiredStringCell(row.pair, 'fx_1m.pair');
|
|
const source = parseRequiredStringCell(row.source, 'fx_1m.source');
|
|
const rowCount = Number(parseBigIntCell(row.row_count, `fx_1m[${pair}/${source}].row_count`));
|
|
if (!Number.isSafeInteger(rowCount) || rowCount <= 0) {
|
|
throw new VerifyM2QuantError(
|
|
`QuestDB fx_1m group '${pair}/${source}' has non-positive row_count: ${rowCount}.`
|
|
);
|
|
}
|
|
const minClose = parseFiniteNumberCell(row.min_close, `fx_1m[${pair}/${source}].min_close`);
|
|
const maxClose = parseFiniteNumberCell(row.max_close, `fx_1m[${pair}/${source}].max_close`);
|
|
if (minClose <= 0 || maxClose <= 0 || minClose > maxClose) {
|
|
throw new VerifyM2QuantError(
|
|
`QuestDB fx_1m group '${pair}/${source}' has invalid close bounds [${minClose}, ${maxClose}].`
|
|
);
|
|
}
|
|
const minTsUs = parseBigIntCell(row.min_ts_us, `fx_1m[${pair}/${source}].min_ts_us`);
|
|
const maxTsUs = parseBigIntCell(row.max_ts_us, `fx_1m[${pair}/${source}].max_ts_us`);
|
|
if (minTsUs > maxTsUs) {
|
|
throw new VerifyM2QuantError(
|
|
`QuestDB fx_1m group '${pair}/${source}' has inverted timestamp range [${minTsUs.toString()}, ${maxTsUs.toString()}].`
|
|
);
|
|
}
|
|
totalRows += rowCount;
|
|
out.push({
|
|
pair,
|
|
source,
|
|
rowCount,
|
|
minClose,
|
|
maxClose,
|
|
minTsUs: minTsUs.toString(),
|
|
maxTsUs: maxTsUs.toString(),
|
|
});
|
|
}
|
|
|
|
if (totalRows <= 0) {
|
|
throw new VerifyM2QuantError('QuestDB fx_1m total row count is zero.');
|
|
}
|
|
|
|
return out;
|
|
}
|
|
|
|
async function verifySplitBoundaryCase(
|
|
spec: SplitBoundaryCaseSpec,
|
|
listingId: number,
|
|
questExecutor: QuestDbPgQueryExecutor,
|
|
duckExecutor: ClosableDuckDbExecutor,
|
|
curatedRoot: string
|
|
): Promise<SplitBoundaryCheckResult> {
|
|
const fromUtcIso = `${spec.fromDate}T00:00:00.000Z`;
|
|
const toUtcIso = `${addUtcDays(spec.toDate, 1)}T05:00:00.000Z`;
|
|
|
|
const qdbSql =
|
|
"SELECT CAST(ts AS LONG) AS ts_us, close FROM bars_1m WHERE listing_id = $1 AND session = 'RTH' AND ts >= $2 AND ts <= $3 ORDER BY ts ASC";
|
|
const qdbRes = await questExecutor.query(qdbSql, [String(listingId), fromUtcIso, toUtcIso]);
|
|
|
|
const latestClose1mByDate = new Map<string, { tsUs: bigint; close: number }>();
|
|
for (const row of qdbRes.rows) {
|
|
const tsUs = parseBigIntCell(row.ts_us, `${spec.label}.bars_1m.ts_us`);
|
|
const close = parseFiniteNumberCell(row.close, `${spec.label}.bars_1m.close`);
|
|
if (close <= 0) {
|
|
throw new VerifyM2QuantError(
|
|
`${spec.label} bars_1m returned non-positive close (${close}) at ts_us=${tsUs.toString()}.`
|
|
);
|
|
}
|
|
const nyDate = formatNySessionDateFromMicros(tsUs);
|
|
if (nyDate < spec.fromDate || nyDate > spec.toDate) {
|
|
continue;
|
|
}
|
|
const prev = latestClose1mByDate.get(nyDate);
|
|
if (prev === undefined || tsUs >= prev.tsUs) {
|
|
latestClose1mByDate.set(nyDate, { tsUs, close });
|
|
}
|
|
}
|
|
|
|
const bars1dPath = `${curatedRoot}/bars_1d/year=*/part.parquet`;
|
|
const duckSql =
|
|
'SELECT CAST(session_date AS VARCHAR) AS session_date, close ' +
|
|
`FROM read_parquet('${bars1dPath}', hive_partitioning = true) ` +
|
|
'WHERE listing_id = ? AND session_date >= CAST(? AS DATE) AND session_date <= CAST(? AS DATE) ' +
|
|
'ORDER BY session_date ASC';
|
|
const duckRows = await duckExecutor.query(duckSql, [listingId, spec.fromDate, spec.toDate]);
|
|
|
|
const close1dByDate = new Map<string, number>();
|
|
for (const row of duckRows) {
|
|
const sessionDate = parseRequiredStringCell(row.session_date, `${spec.label}.bars_1d.session_date`);
|
|
const close = parseFiniteNumberCell(row.close, `${spec.label}.bars_1d.close`);
|
|
if (close <= 0) {
|
|
throw new VerifyM2QuantError(
|
|
`${spec.label} bars_1d returned non-positive close (${close}) on ${sessionDate}.`
|
|
);
|
|
}
|
|
close1dByDate.set(sessionDate, close);
|
|
}
|
|
|
|
const matchedDates = Array.from(latestClose1mByDate.keys())
|
|
.filter(date => close1dByDate.has(date))
|
|
.sort();
|
|
|
|
const sessions: SplitBoundarySessionComparison[] = [];
|
|
let preSplitCount = 0;
|
|
let exOrPostSplitCount = 0;
|
|
let maxRelDiff = 0;
|
|
|
|
for (const sessionDate of matchedDates) {
|
|
const close1m = latestClose1mByDate.get(sessionDate)!.close;
|
|
const close1d = close1dByDate.get(sessionDate)!;
|
|
const relDiff = Math.abs(close1m - close1d) / close1d;
|
|
const phase: 'pre_split' | 'ex_or_post_split' =
|
|
sessionDate < spec.exDate ? 'pre_split' : 'ex_or_post_split';
|
|
if (phase === 'pre_split') {
|
|
preSplitCount += 1;
|
|
} else {
|
|
exOrPostSplitCount += 1;
|
|
}
|
|
if (relDiff > maxRelDiff) {
|
|
maxRelDiff = relDiff;
|
|
}
|
|
if (relDiff > MAX_SPLIT_CLOSE_REL_DIFF) {
|
|
throw new VerifyM2QuantError(
|
|
`${spec.label} split-boundary close mismatch on ${sessionDate}: bars_1m=${close1m}, bars_1d=${close1d}, relDiff=${(relDiff * 100).toFixed(4)}% > ${(MAX_SPLIT_CLOSE_REL_DIFF * 100).toFixed(2)}%.`
|
|
);
|
|
}
|
|
sessions.push({ sessionDate, phase, close1m, close1d, relDiff });
|
|
}
|
|
|
|
if (preSplitCount < 1) {
|
|
throw new VerifyM2QuantError(
|
|
`${spec.label} split-boundary check requires >= 1 matched pre-split session before ${spec.exDate} (found ${preSplitCount}).`
|
|
);
|
|
}
|
|
if (exOrPostSplitCount < 1) {
|
|
throw new VerifyM2QuantError(
|
|
`${spec.label} split-boundary check requires >= 1 matched ex-date/post-split session on/after ${spec.exDate} (found ${exOrPostSplitCount}).`
|
|
);
|
|
}
|
|
|
|
return {
|
|
label: spec.label,
|
|
listingId,
|
|
fromDate: spec.fromDate,
|
|
toDate: spec.toDate,
|
|
exDate: spec.exDate,
|
|
ratio: spec.ratio,
|
|
preSplitCount,
|
|
exOrPostSplitCount,
|
|
maxRelDiff,
|
|
sessions,
|
|
};
|
|
}
|
|
|
|
async function runIntradayLatencyBenchmark(
|
|
parsed: ParsedVerifyM2QuantRun,
|
|
openStore: (
|
|
config: ResearchCopilotHostConfig,
|
|
options?: OpenResearchCopilotStoreOptions
|
|
) => Promise<ManagedMarketDataStore>,
|
|
perfNowMs: () => number
|
|
): Promise<IntradayBenchmarkResult> {
|
|
// Pre-validate Vault fence with vaultOperatorAuthorized: false so violations
|
|
// fail closed deterministically even before opening a store handle.
|
|
const fence = applyVaultFence(
|
|
{
|
|
from: parsed.benchFrom,
|
|
to: parsed.benchTo,
|
|
asOf: parsed.benchAsOf,
|
|
scope: parsed.benchScope,
|
|
},
|
|
{
|
|
vaultCutoffTs: parsed.vaultCutoffTs,
|
|
vaultOperatorAuthorized: false,
|
|
}
|
|
);
|
|
|
|
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,
|
|
scope: parsed.benchScope,
|
|
rowCount: coldBars.length,
|
|
digest: coldDigest,
|
|
coldMs,
|
|
warmRuns,
|
|
minWarmMs,
|
|
medianWarmMs,
|
|
maxWarmMs,
|
|
thresholds: {
|
|
maxColdMs: MAX_COLD_READ_MS,
|
|
maxWarmMs: MAX_WARM_READ_MS,
|
|
},
|
|
};
|
|
} finally {
|
|
await handle.close();
|
|
}
|
|
}
|
|
|
|
async function defaultWriteReportFile(path: string, content: string): Promise<void> {
|
|
await mkdir(dirname(path), { recursive: true });
|
|
await writeFile(path, content, 'utf8');
|
|
}
|
|
|
|
async function defaultCreateDuckDbExecutor(): Promise<ClosableDuckDbExecutor> {
|
|
const { createNodeDuckDbExecutor } = await import('@stock-bot/duckdb');
|
|
return createNodeDuckDbExecutor();
|
|
}
|
|
|
|
async function defaultOpenResearchCopilotStore(
|
|
config: ResearchCopilotHostConfig,
|
|
options?: OpenResearchCopilotStoreOptions
|
|
): Promise<ManagedMarketDataStore> {
|
|
const { openResearchCopilotStore } = await import('@stock-bot/duckdb');
|
|
return openResearchCopilotStore(config, options);
|
|
}
|
|
|
|
function defaultSleepMs(ms: number): Promise<void> {
|
|
return new Promise(resolveSleep => {
|
|
setTimeout(resolveSleep, ms);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Runs the QuestDB/DuckDB M2 verification CLI with injectable I/O, executors,
|
|
* store factory, and clocks for deterministic offline testing.
|
|
*/
|
|
export async function runVerifyM2QuantCli(deps: VerifyM2QuantCliDeps = {}): Promise<number> {
|
|
const argv = deps.argv ?? process.argv.slice(2);
|
|
const stdout = deps.stdout ?? process.stdout;
|
|
const stderr = deps.stderr ?? process.stderr;
|
|
const secretNeedles = collectArgvSecretNeedles(argv);
|
|
|
|
const writeRedactedError = (prefix: string, err: unknown): void => {
|
|
const raw = err instanceof Error ? err.message : String(err);
|
|
const safe = sanitizeSingleLine(redactSecrets(raw, secretNeedles));
|
|
stderr.write(`${prefix}: ${safe}\n`);
|
|
};
|
|
|
|
let parsed: ParsedVerifyM2QuantArgs;
|
|
try {
|
|
parsed = parseVerifyM2QuantArgs(argv, {
|
|
...(deps.cwd !== undefined ? { cwd: deps.cwd } : {}),
|
|
});
|
|
} catch (err: unknown) {
|
|
writeRedactedError('Invalid arguments', err);
|
|
return 1;
|
|
}
|
|
|
|
if (parsed.kind === 'help') {
|
|
stdout.write(VERIFY_M2_QUANT_USAGE);
|
|
return 0;
|
|
}
|
|
|
|
const openPg = deps.openQuestDbPgExecutor ?? openQuestDbPgExecutor;
|
|
const applyDdlFn = deps.applyM2IntradayDDL ?? applyM2IntradayDDL;
|
|
const createDuck = deps.createDuckDbExecutor ?? defaultCreateDuckDbExecutor;
|
|
const openStore = deps.openResearchCopilotStore ?? defaultOpenResearchCopilotStore;
|
|
const 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 {
|
|
let ddlResult: { readonly applied: boolean; readonly appliedTables: readonly M2IntradayTableName[] } =
|
|
{ applied: false, appliedTables: [] };
|
|
let walTables: readonly WalTableStatusRow[];
|
|
let bars1mSummary: readonly Bars1mSourceSummaryRow[];
|
|
let fx1mSummary: readonly Fx1mPairSourceSummaryRow[];
|
|
const splitChecks: SplitBoundaryCheckResult[] = [];
|
|
|
|
const pgHandle = await openPg(parsed.questdb);
|
|
try {
|
|
if (parsed.applyDdl) {
|
|
const applied = await applyDdlFn(pgHandle.executor);
|
|
ddlResult = { applied: true, appliedTables: applied.appliedTables };
|
|
}
|
|
|
|
walTables = await waitForHealthyWalTables(
|
|
pgHandle.executor,
|
|
parsed.walSettleTimeoutMs,
|
|
walPollIntervalMs,
|
|
nowMs,
|
|
sleepMs
|
|
);
|
|
bars1mSummary = await verifyBars1mCommits(pgHandle.executor);
|
|
fx1mSummary = await verifyFx1mCommits(pgHandle.executor);
|
|
|
|
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 benchmark = await runIntradayLatencyBenchmark(parsed, openStore, perfNowMs);
|
|
|
|
const report: VerifyM2QuantReport = {
|
|
ok: true,
|
|
target: {
|
|
questdb: describeSafeQuestDbTarget(parsed.questdb),
|
|
curatedRoot: parsed.curatedRoot,
|
|
vaultCutoffTs: parsed.vaultCutoffIso,
|
|
},
|
|
ddl: ddlResult,
|
|
walTables,
|
|
bars1mSummary,
|
|
fx1mSummary,
|
|
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();
|
|
}
|