754 lines
26 KiB
TypeScript
754 lines
26 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import type { ClosableDuckDbExecutor } from '@stock-bot/duckdb';
|
|
import {
|
|
M2_INTRADAY_TABLE_NAMES,
|
|
type ApplyM2IntradayDDLResult,
|
|
type QuestDbPgExecutorConfig,
|
|
type QuestDbPgExecutorHandle,
|
|
type QuestDbPgQueryExecutor,
|
|
} from '@stock-bot/questdb';
|
|
import type { BarBatch, BarRecord, MarketDataStore, TableRow } from '@stock-bot/research';
|
|
import type { ManagedMarketDataStore, ResearchCopilotHostConfig } from '@stock-bot/research/mcp';
|
|
import {
|
|
MAX_COLD_READ_MS,
|
|
MAX_WARM_READ_MS,
|
|
type VerifyM2QuantCliDeps,
|
|
type VerifyM2QuantReport,
|
|
runVerifyM2QuantCli,
|
|
} from '../verify-m2-quant';
|
|
|
|
const NVDA_LISTING_ID = 101;
|
|
const NEXM_LISTING_ID = 202;
|
|
const VAULT_CUTOFF_ISO = '2025-02-13T00:00:00Z';
|
|
const VAULT_CUTOFF_MS = Date.parse(VAULT_CUTOFF_ISO);
|
|
|
|
function createBufferStream(): {
|
|
readonly write: (chunk: string) => boolean;
|
|
readonly text: () => string;
|
|
} {
|
|
const chunks: string[] = [];
|
|
return {
|
|
write(chunk: string): boolean {
|
|
chunks.push(chunk);
|
|
return true;
|
|
},
|
|
text(): string {
|
|
return chunks.join('');
|
|
},
|
|
};
|
|
}
|
|
|
|
function baseArgs(overrides: Record<string, string | null> = {}): string[] {
|
|
const defaults: Record<string, string | null> = {
|
|
'--questdb-host': '10.0.0.51',
|
|
'--questdb-pg-port': '8812',
|
|
'--curated-root': '/mnt/data/stockbot/curated',
|
|
'--vault-cutoff-ts': VAULT_CUTOFF_ISO,
|
|
'--nvda-listing-id': String(NVDA_LISTING_ID),
|
|
'--nexm-listing-id': String(NEXM_LISTING_ID),
|
|
'--bench-listing-id': String(NVDA_LISTING_ID),
|
|
'--bench-from': '2024-01-02T00:00:00Z',
|
|
'--bench-to': '2025-01-02T00:00:00Z',
|
|
'--bench-as-of': '2025-02-01T00:00:00Z',
|
|
'--warm-runs': '3',
|
|
'--wal-settle-timeout-ms': '5000',
|
|
};
|
|
const merged = { ...defaults, ...overrides };
|
|
const argv: string[] = [];
|
|
for (const [flag, value] of Object.entries(merged)) {
|
|
if (value === null) {
|
|
continue;
|
|
}
|
|
argv.push(flag, value);
|
|
}
|
|
return argv;
|
|
}
|
|
|
|
function isoToMicros(iso: string): string {
|
|
return (BigInt(Date.parse(iso)) * 1000n).toString();
|
|
}
|
|
|
|
interface MockFixtureOptions {
|
|
readonly walSequence?: readonly (readonly Record<string, unknown>[])[];
|
|
readonly bars1mSummaryRows?: readonly Record<string, unknown>[];
|
|
readonly fx1mSummaryRows?: readonly Record<string, unknown>[];
|
|
readonly nvda1mRows?: readonly Record<string, unknown>[];
|
|
readonly nexm1mRows?: readonly Record<string, unknown>[];
|
|
readonly nvda1dRows?: readonly TableRow[];
|
|
readonly nexm1dRows?: readonly TableRow[];
|
|
readonly benchBatchesByCall?: readonly (readonly BarRecord[])[];
|
|
readonly perfDurationsMs?: readonly number[];
|
|
readonly openPgError?: Error;
|
|
readonly queryError?: Error;
|
|
}
|
|
|
|
function defaultWalRows(): readonly Record<string, unknown>[] {
|
|
return [
|
|
{ name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' },
|
|
{ name: 'bars_1m', suspended: false, writerTxn: '120', sequencerTxn: '120' },
|
|
{ name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' },
|
|
];
|
|
}
|
|
|
|
function defaultBars1mSummaryRows(): readonly Record<string, unknown>[] {
|
|
return [
|
|
{
|
|
source: 'eod',
|
|
row_count: '500000',
|
|
min_close: 0.42,
|
|
max_close: 1210.5,
|
|
min_ts_us: isoToMicros('2024-01-02T14:30:00Z'),
|
|
max_ts_us: isoToMicros('2025-06-23T20:00:00Z'),
|
|
},
|
|
{
|
|
source: 'qm',
|
|
row_count: '25000',
|
|
min_close: 0.15,
|
|
max_close: 24.5,
|
|
min_ts_us: isoToMicros('2024-05-01T13:30:00Z'),
|
|
max_ts_us: isoToMicros('2025-06-23T20:00:00Z'),
|
|
},
|
|
];
|
|
}
|
|
|
|
function defaultFx1mSummaryRows(): readonly Record<string, unknown>[] {
|
|
return [
|
|
{
|
|
pair: 'USDCAD',
|
|
source: 'eod',
|
|
row_count: '380000',
|
|
min_close: 1.31,
|
|
max_close: 1.45,
|
|
min_ts_us: isoToMicros('2024-01-02T00:00:00Z'),
|
|
max_ts_us: isoToMicros('2025-01-31T23:59:00Z'),
|
|
},
|
|
];
|
|
}
|
|
|
|
function defaultNvda1mRows(): readonly Record<string, unknown>[] {
|
|
return [
|
|
// Multiple RTH bars on 2024-06-07 (pre-split 10:1); latest ts (19:59 UTC = 15:59 ET) must win.
|
|
{ ts_us: isoToMicros('2024-06-07T14:30:00Z'), close: 1190.0 },
|
|
{ ts_us: isoToMicros('2024-06-07T19:59:00Z'), close: 1208.88 },
|
|
// Ex-date 2024-06-10 (post 10:1 split)
|
|
{ ts_us: isoToMicros('2024-06-10T19:59:00Z'), close: 121.79 },
|
|
// Post-split 2024-06-11
|
|
{ ts_us: isoToMicros('2024-06-11T19:59:00Z'), close: 120.91 },
|
|
];
|
|
}
|
|
|
|
function defaultNvda1dRows(): readonly TableRow[] {
|
|
return [
|
|
{ session_date: '2024-06-07', close: 1208.88 },
|
|
{ session_date: '2024-06-10', close: 121.79 },
|
|
{ session_date: '2024-06-11', close: 120.91 },
|
|
];
|
|
}
|
|
|
|
function defaultNexm1mRows(): readonly Record<string, unknown>[] {
|
|
return [
|
|
// Pre-split 2025-06-19 (before 1:20 reverse split)
|
|
{ ts_us: isoToMicros('2025-06-19T19:59:00Z'), close: 0.40 },
|
|
// Ex-date 2025-06-20 (after 1:20 reverse split)
|
|
{ ts_us: isoToMicros('2025-06-20T19:59:00Z'), close: 8.02 },
|
|
];
|
|
}
|
|
|
|
function defaultNexm1dRows(): readonly TableRow[] {
|
|
return [
|
|
{ session_date: '2025-06-19', close: 0.40 },
|
|
{ session_date: '2025-06-20', close: 8.00 },
|
|
];
|
|
}
|
|
|
|
function defaultBenchBars(): readonly BarRecord[] {
|
|
const knownAt = Date.parse('2025-02-01T00:00:00Z');
|
|
return [
|
|
{
|
|
listingId: NVDA_LISTING_ID,
|
|
ts: Date.parse('2024-01-02T14:30:00Z'),
|
|
open: 492.0,
|
|
high: 493.5,
|
|
low: 491.5,
|
|
close: 492.8,
|
|
volume: 12_000,
|
|
vwap: 492.5,
|
|
knownAt,
|
|
},
|
|
{
|
|
listingId: NVDA_LISTING_ID,
|
|
ts: Date.parse('2024-06-10T19:59:00Z'),
|
|
open: 121.5,
|
|
high: 121.9,
|
|
low: 121.4,
|
|
close: 121.79,
|
|
volume: 45_000,
|
|
vwap: 121.7,
|
|
knownAt,
|
|
},
|
|
];
|
|
}
|
|
|
|
function createHarness(
|
|
argv: readonly string[],
|
|
options: MockFixtureOptions = {}
|
|
): {
|
|
readonly deps: VerifyM2QuantCliDeps;
|
|
readonly stdout: ReturnType<typeof createBufferStream>;
|
|
readonly stderr: ReturnType<typeof createBufferStream>;
|
|
readonly state: {
|
|
ddlCalls: number;
|
|
pgClosed: boolean;
|
|
duckClosed: boolean;
|
|
storeClosed: boolean;
|
|
writtenFiles: Map<string, string>;
|
|
openedPgConfigs: QuestDbPgExecutorConfig[];
|
|
openedStoreConfigs: ResearchCopilotHostConfig[];
|
|
walPollCount: number;
|
|
};
|
|
} {
|
|
const stdout = createBufferStream();
|
|
const stderr = createBufferStream();
|
|
const state = {
|
|
ddlCalls: 0,
|
|
pgClosed: false,
|
|
duckClosed: false,
|
|
storeClosed: false,
|
|
writtenFiles: new Map<string, string>(),
|
|
openedPgConfigs: [] as QuestDbPgExecutorConfig[],
|
|
openedStoreConfigs: [] as ResearchCopilotHostConfig[],
|
|
walPollCount: 0,
|
|
};
|
|
|
|
const walSeq = options.walSequence ?? [defaultWalRows()];
|
|
const bars1mSummary = options.bars1mSummaryRows ?? defaultBars1mSummaryRows();
|
|
const fx1mSummary = options.fx1mSummaryRows ?? defaultFx1mSummaryRows();
|
|
const nvda1m = options.nvda1mRows ?? defaultNvda1mRows();
|
|
const nexm1m = options.nexm1mRows ?? defaultNexm1mRows();
|
|
const nvda1d = options.nvda1dRows ?? defaultNvda1dRows();
|
|
const nexm1d = options.nexm1dRows ?? defaultNexm1dRows();
|
|
|
|
let nowClock = 1_000_000;
|
|
let benchCallIdx = 0;
|
|
const durations = options.perfDurationsMs ?? [180, 42, 38, 41, 39, 40];
|
|
let perfCursor = 0;
|
|
let perfTime = 0;
|
|
let expectEndRead = false;
|
|
|
|
const perfNowMs = (): number => {
|
|
if (!expectEndRead) {
|
|
expectEndRead = true;
|
|
return perfTime;
|
|
}
|
|
expectEndRead = false;
|
|
const delta = durations[Math.min(perfCursor, durations.length - 1)] ?? 20;
|
|
perfCursor += 1;
|
|
perfTime += delta;
|
|
return perfTime;
|
|
};
|
|
|
|
const pgExecutor: QuestDbPgQueryExecutor = {
|
|
async query(sql: string, params?: readonly unknown[]) {
|
|
if (options.queryError !== undefined) {
|
|
throw options.queryError;
|
|
}
|
|
if (sql.includes('FROM wal_tables()')) {
|
|
const idx = Math.min(state.walPollCount, walSeq.length - 1);
|
|
state.walPollCount += 1;
|
|
return { rows: walSeq[idx] ?? [] };
|
|
}
|
|
if (sql.includes('FROM bars_1m GROUP BY source')) {
|
|
return { rows: bars1mSummary };
|
|
}
|
|
if (sql.includes('FROM fx_1m GROUP BY pair, source')) {
|
|
return { rows: fx1mSummary };
|
|
}
|
|
if (sql.includes("session = 'RTH'")) {
|
|
const listingId = String(params?.[0] ?? '');
|
|
if (listingId === String(NVDA_LISTING_ID)) {
|
|
return { rows: nvda1m };
|
|
}
|
|
if (listingId === String(NEXM_LISTING_ID)) {
|
|
return { rows: nexm1m };
|
|
}
|
|
return { rows: [] };
|
|
}
|
|
throw new Error(`Unexpected QuestDB SQL in mock: ${sql}`);
|
|
},
|
|
};
|
|
|
|
const duckExecutor: ClosableDuckDbExecutor = {
|
|
async run(): Promise<void> {
|
|
return undefined;
|
|
},
|
|
async query(sql: string, params: readonly unknown[]): Promise<readonly TableRow[]> {
|
|
if (sql.includes('read_parquet')) {
|
|
const listingId = Number(params[0]);
|
|
if (listingId === NVDA_LISTING_ID) {
|
|
return nvda1d;
|
|
}
|
|
if (listingId === NEXM_LISTING_ID) {
|
|
return nexm1d;
|
|
}
|
|
return [];
|
|
}
|
|
throw new Error(`Unexpected DuckDB SQL in mock: ${sql}`);
|
|
},
|
|
async close(): Promise<void> {
|
|
state.duckClosed = true;
|
|
},
|
|
};
|
|
|
|
const mockStore: MarketDataStore = {
|
|
async *bars(): AsyncIterable<BarBatch> {
|
|
const batches = options.benchBatchesByCall;
|
|
const rows =
|
|
batches !== undefined
|
|
? (batches[Math.min(benchCallIdx, batches.length - 1)] ?? [])
|
|
: defaultBenchBars();
|
|
benchCallIdx += 1;
|
|
if (rows.length > 0) {
|
|
yield { rows };
|
|
}
|
|
},
|
|
async crossSection() {
|
|
throw new Error('unused');
|
|
},
|
|
async fundamentalsAsOf() {
|
|
throw new Error('unused');
|
|
},
|
|
async events() {
|
|
throw new Error('unused');
|
|
},
|
|
async shortsAsOf() {
|
|
throw new Error('unused');
|
|
},
|
|
async macroAsOf() {
|
|
throw new Error('unused');
|
|
},
|
|
async fx() {
|
|
throw new Error('unused');
|
|
},
|
|
async universe() {
|
|
throw new Error('unused');
|
|
},
|
|
};
|
|
|
|
const deps: VerifyM2QuantCliDeps = {
|
|
argv,
|
|
cwd: '/tmp/verify-m2-quant-test',
|
|
stdout,
|
|
stderr,
|
|
async openQuestDbPgExecutor(config: QuestDbPgExecutorConfig): Promise<QuestDbPgExecutorHandle> {
|
|
state.openedPgConfigs.push(config);
|
|
if (options.openPgError !== undefined) {
|
|
throw options.openPgError;
|
|
}
|
|
return {
|
|
executor: pgExecutor,
|
|
async close(): Promise<void> {
|
|
state.pgClosed = true;
|
|
},
|
|
};
|
|
},
|
|
async applyM2IntradayDDL(): Promise<ApplyM2IntradayDDLResult> {
|
|
state.ddlCalls += 1;
|
|
return {
|
|
appliedTables: [...M2_INTRADAY_TABLE_NAMES],
|
|
statements: ['CREATE TABLE IF NOT EXISTS bars_1m ...'],
|
|
};
|
|
},
|
|
async createDuckDbExecutor(): Promise<ClosableDuckDbExecutor> {
|
|
return duckExecutor;
|
|
},
|
|
async openResearchCopilotStore(
|
|
config: ResearchCopilotHostConfig
|
|
): Promise<ManagedMarketDataStore> {
|
|
state.openedStoreConfigs.push(config);
|
|
return {
|
|
store: mockStore,
|
|
async close(): Promise<void> {
|
|
state.storeClosed = true;
|
|
},
|
|
};
|
|
},
|
|
async writeReportFile(path: string, content: string): Promise<void> {
|
|
state.writtenFiles.set(path, content);
|
|
},
|
|
nowMs: () => nowClock,
|
|
perfNowMs,
|
|
sleepMs: async (ms: number) => {
|
|
nowClock += ms;
|
|
},
|
|
walPollIntervalMs: 1000,
|
|
};
|
|
|
|
return { deps, stdout, stderr, state };
|
|
}
|
|
|
|
function assertSingleLineError(stderrText: string): void {
|
|
expect(stderrText.length).toBeGreaterThan(0);
|
|
expect(stderrText.endsWith('\n')).toBe(true);
|
|
expect(stderrText.slice(0, -1)).not.toContain('\n');
|
|
}
|
|
|
|
describe('scripts/verify-m2-quant.ts', () => {
|
|
test('prints usage and exits 0 on --help', async () => {
|
|
const { deps, stdout, stderr } = createHarness(['--help']);
|
|
const code = await runVerifyM2QuantCli(deps);
|
|
expect(code).toBe(0);
|
|
expect(stdout.text()).toContain('Usage: bun run scripts/verify-m2-quant.ts');
|
|
expect(stderr.text()).toBe('');
|
|
});
|
|
|
|
test('passes end-to-end without --apply-ddl, writes --out, and closes all handles', async () => {
|
|
const argv = [...baseArgs(), '--out', 'out/m2-quant-verify.json'];
|
|
const { deps, stdout, stderr, state } = createHarness(argv);
|
|
|
|
const code = await runVerifyM2QuantCli(deps);
|
|
expect(code).toBe(0);
|
|
expect(stderr.text()).toBe('');
|
|
expect(state.ddlCalls).toBe(0);
|
|
expect(state.pgClosed).toBe(true);
|
|
expect(state.duckClosed).toBe(true);
|
|
expect(state.storeClosed).toBe(true);
|
|
|
|
const report = JSON.parse(stdout.text()) as VerifyM2QuantReport;
|
|
expect(report.ok).toBe(true);
|
|
expect(report.ddl).toEqual({ applied: false, appliedTables: [] });
|
|
expect(report.walTables).toHaveLength(3);
|
|
expect(report.bars1mSummary).toHaveLength(2);
|
|
expect(report.fx1mSummary).toHaveLength(1);
|
|
expect(report.splitChecks).toHaveLength(2);
|
|
expect(report.splitChecks[0]?.label).toBe('NVDA.US');
|
|
expect(report.splitChecks[0]?.preSplitCount).toBe(1);
|
|
expect(report.splitChecks[0]?.exOrPostSplitCount).toBe(2);
|
|
expect(report.splitChecks[0]?.maxRelDiff).toBeLessThanOrEqual(0.005);
|
|
expect(report.splitChecks[1]?.label).toBe('NEXM.V');
|
|
expect(report.splitChecks[1]?.maxRelDiff).toBeCloseTo(0.0025, 6);
|
|
expect(report.benchmark.rowCount).toBe(2);
|
|
expect(report.benchmark.coldMs).toBe(180);
|
|
expect(report.benchmark.warmRuns).toEqual([42, 38, 41]);
|
|
expect(report.benchmark.maxWarmMs).toBe(42);
|
|
expect(report.benchmark.thresholds).toEqual({
|
|
maxColdMs: MAX_COLD_READ_MS,
|
|
maxWarmMs: MAX_WARM_READ_MS,
|
|
});
|
|
expect(state.writtenFiles.size).toBe(1);
|
|
});
|
|
|
|
test('invokes applyM2IntradayDDL when --apply-ddl is set', async () => {
|
|
const argv = [...baseArgs(), '--apply-ddl'];
|
|
const { deps, stdout, stderr, state } = createHarness(argv);
|
|
|
|
const code = await runVerifyM2QuantCli(deps);
|
|
expect(code).toBe(0);
|
|
expect(stderr.text()).toBe('');
|
|
expect(state.ddlCalls).toBe(1);
|
|
|
|
const report = JSON.parse(stdout.text()) as VerifyM2QuantReport;
|
|
expect(report.ddl).toEqual({
|
|
applied: true,
|
|
appliedTables: [...M2_INTRADAY_TABLE_NAMES],
|
|
});
|
|
});
|
|
|
|
test('polls wal_tables() until writerTxn catches up to sequencerTxn', async () => {
|
|
const { deps, stdout, stderr, state } = createHarness(baseArgs(), {
|
|
walSequence: [
|
|
[
|
|
{ name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' },
|
|
{ name: 'bars_1m', suspended: false, writerTxn: '118', sequencerTxn: '120' },
|
|
{ name: 'fx_1m', suspended: false, writerTxn: '45', sequencerTxn: '45' },
|
|
],
|
|
defaultWalRows(),
|
|
],
|
|
});
|
|
|
|
const code = await runVerifyM2QuantCli(deps);
|
|
expect(code).toBe(0);
|
|
expect(stderr.text()).toBe('');
|
|
expect(state.walPollCount).toBe(2);
|
|
expect((JSON.parse(stdout.text()) as VerifyM2QuantReport).ok).toBe(true);
|
|
});
|
|
|
|
test('fails closed when a required table is missing from wal_tables()', async () => {
|
|
const { deps, stdout, stderr } = createHarness(baseArgs(), {
|
|
walSequence: [
|
|
[
|
|
{ name: 'bars_1m', suspended: false, writerTxn: '10', sequencerTxn: '10' },
|
|
{ name: 'fx_1m', suspended: false, writerTxn: '10', sequencerTxn: '10' },
|
|
],
|
|
],
|
|
});
|
|
|
|
const code = await runVerifyM2QuantCli(deps);
|
|
expect(code).toBe(1);
|
|
expect(stdout.text()).toBe('');
|
|
assertSingleLineError(stderr.text());
|
|
expect(stderr.text()).toContain('bar_revisions');
|
|
});
|
|
|
|
test('fails closed when any WAL table is suspended', async () => {
|
|
const { deps, stdout, stderr } = createHarness(baseArgs(), {
|
|
walSequence: [
|
|
[
|
|
{ name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' },
|
|
{ name: 'bars_1m', suspended: true, writerTxn: '10', sequencerTxn: '10' },
|
|
{ name: 'fx_1m', suspended: false, writerTxn: '10', sequencerTxn: '10' },
|
|
],
|
|
],
|
|
});
|
|
|
|
const code = await runVerifyM2QuantCli(deps);
|
|
expect(code).toBe(1);
|
|
expect(stdout.text()).toBe('');
|
|
assertSingleLineError(stderr.text());
|
|
expect(stderr.text()).toContain('Suspended QuestDB WAL table');
|
|
});
|
|
|
|
test('fails closed when WAL remains unsettled past --wal-settle-timeout-ms', async () => {
|
|
const { deps, stdout, stderr } = createHarness(
|
|
baseArgs({ '--wal-settle-timeout-ms': '2000' }),
|
|
{
|
|
walSequence: [
|
|
[
|
|
{ name: 'bar_revisions', suspended: false, writerTxn: '0', sequencerTxn: '0' },
|
|
{ name: 'bars_1m', suspended: false, writerTxn: '10', sequencerTxn: '20' },
|
|
{ name: 'fx_1m', suspended: false, writerTxn: '5', sequencerTxn: '5' },
|
|
],
|
|
],
|
|
}
|
|
);
|
|
|
|
const code = await runVerifyM2QuantCli(deps);
|
|
expect(code).toBe(1);
|
|
expect(stdout.text()).toBe('');
|
|
assertSingleLineError(stderr.text());
|
|
expect(stderr.text()).toContain('Timed out');
|
|
expect(stderr.text()).toContain('writerTxn=10<sequencerTxn=20');
|
|
});
|
|
|
|
test('fails closed when bars_1m or fx_1m has zero rows or non-finite 0x10 closes', async () => {
|
|
const zeroBars = createHarness(baseArgs(), { bars1mSummaryRows: [] });
|
|
expect(await runVerifyM2QuantCli(zeroBars.deps)).toBe(1);
|
|
expect(zeroBars.stdout.text()).toBe('');
|
|
expect(zeroBars.stderr.text()).toContain('bars_1m contains zero rows');
|
|
|
|
const zeroFx = createHarness(baseArgs(), { fx1mSummaryRows: [] });
|
|
expect(await runVerifyM2QuantCli(zeroFx.deps)).toBe(1);
|
|
expect(zeroFx.stdout.text()).toBe('');
|
|
expect(zeroFx.stderr.text()).toContain('fx_1m contains zero rows');
|
|
|
|
const nanClose = createHarness(baseArgs(), {
|
|
bars1mSummaryRows: [
|
|
{
|
|
source: 'eod',
|
|
row_count: '100',
|
|
min_close: Number.NaN,
|
|
max_close: 120.5,
|
|
min_ts_us: isoToMicros('2024-01-02T14:30:00Z'),
|
|
max_ts_us: isoToMicros('2024-06-10T20:00:00Z'),
|
|
},
|
|
],
|
|
});
|
|
expect(await runVerifyM2QuantCli(nanClose.deps)).toBe(1);
|
|
expect(nanClose.stdout.text()).toBe('');
|
|
expect(nanClose.stderr.text()).toContain('Invalid finite numeric value');
|
|
|
|
const nonPositiveFxClose = createHarness(baseArgs(), {
|
|
fx1mSummaryRows: [
|
|
{
|
|
pair: 'USDCAD',
|
|
source: 'eod',
|
|
row_count: '100',
|
|
min_close: 0,
|
|
max_close: 1.4,
|
|
min_ts_us: isoToMicros('2024-01-02T00:00:00Z'),
|
|
max_ts_us: isoToMicros('2025-01-31T23:59:00Z'),
|
|
},
|
|
],
|
|
});
|
|
expect(await runVerifyM2QuantCli(nonPositiveFxClose.deps)).toBe(1);
|
|
expect(nonPositiveFxClose.stderr.text()).toContain('invalid close bounds');
|
|
});
|
|
|
|
test('enforces split-boundary 0.5% tolerance and pre/post-split session presence', async () => {
|
|
// Exactly at 0.5% passes
|
|
const atLimit = createHarness(baseArgs(), {
|
|
nvda1mRows: [
|
|
{ ts_us: isoToMicros('2024-06-07T19:59:00Z'), close: 1005.0 },
|
|
{ ts_us: isoToMicros('2024-06-10T19:59:00Z'), close: 100.5 },
|
|
],
|
|
nvda1dRows: [
|
|
{ session_date: '2024-06-07', close: 1000.0 },
|
|
{ session_date: '2024-06-10', close: 100.0 },
|
|
],
|
|
});
|
|
expect(await runVerifyM2QuantCli(atLimit.deps)).toBe(0);
|
|
|
|
// Above 0.5% fails
|
|
const overLimit = createHarness(baseArgs(), {
|
|
nvda1mRows: [
|
|
{ ts_us: isoToMicros('2024-06-07T19:59:00Z'), close: 1005.1 },
|
|
{ ts_us: isoToMicros('2024-06-10T19:59:00Z'), close: 100.0 },
|
|
],
|
|
nvda1dRows: [
|
|
{ session_date: '2024-06-07', close: 1000.0 },
|
|
{ session_date: '2024-06-10', close: 100.0 },
|
|
],
|
|
});
|
|
expect(await runVerifyM2QuantCli(overLimit.deps)).toBe(1);
|
|
expect(overLimit.stderr.text()).toContain('NVDA.US split-boundary close mismatch');
|
|
|
|
// Missing pre-split session fails
|
|
const missingPreSplit = createHarness(baseArgs(), {
|
|
nexm1mRows: [{ ts_us: isoToMicros('2025-06-20T19:59:00Z'), close: 8.0 }],
|
|
nexm1dRows: [{ session_date: '2025-06-20', close: 8.0 }],
|
|
});
|
|
expect(await runVerifyM2QuantCli(missingPreSplit.deps)).toBe(1);
|
|
expect(missingPreSplit.stderr.text()).toContain('>= 1 matched pre-split session');
|
|
|
|
// Missing ex-date/post-split session fails
|
|
const missingPostSplit = createHarness(baseArgs(), {
|
|
nexm1mRows: [{ ts_us: isoToMicros('2025-06-19T19:59:00Z'), close: 0.4 }],
|
|
nexm1dRows: [{ session_date: '2025-06-19', close: 0.4 }],
|
|
});
|
|
expect(await runVerifyM2QuantCli(missingPostSplit.deps)).toBe(1);
|
|
expect(missingPostSplit.stderr.text()).toContain('>= 1 matched ex-date/post-split session');
|
|
});
|
|
|
|
test('enforces cold (< 1000 ms), warm (< 250 ms), non-empty, and digest equality benchmark checks', async () => {
|
|
const slowCold = createHarness(baseArgs(), {
|
|
perfDurationsMs: [1000, 40, 40, 40],
|
|
});
|
|
expect(await runVerifyM2QuantCli(slowCold.deps)).toBe(1);
|
|
expect(slowCold.stderr.text()).toContain('Cold 1y 1m PGWire read exceeded threshold');
|
|
|
|
const slowWarm = createHarness(baseArgs(), {
|
|
perfDurationsMs: [200, 50, 250, 50],
|
|
});
|
|
expect(await runVerifyM2QuantCli(slowWarm.deps)).toBe(1);
|
|
expect(slowWarm.stderr.text()).toContain('Warm 1y 1m PGWire read #2 exceeded threshold');
|
|
|
|
const emptyBench = createHarness(baseArgs(), {
|
|
benchBatchesByCall: [[]],
|
|
});
|
|
expect(await runVerifyM2QuantCli(emptyBench.deps)).toBe(1);
|
|
expect(emptyBench.stderr.text()).toContain('returned 0 rows');
|
|
|
|
const coldRows = defaultBenchBars();
|
|
const mutatedRows: BarRecord[] = [
|
|
coldRows[0]!,
|
|
{ ...coldRows[1]!, close: coldRows[1]!.close + 0.01 },
|
|
];
|
|
const digestMismatch = createHarness(baseArgs(), {
|
|
benchBatchesByCall: [coldRows, mutatedRows],
|
|
});
|
|
expect(await runVerifyM2QuantCli(digestMismatch.deps)).toBe(1);
|
|
expect(digestMismatch.stderr.text()).toContain('diverged from cold baseline');
|
|
});
|
|
|
|
test('blocks post-Vault benchmark queries, vault_evaluation_only scope, and leaked bar timestamps', async () => {
|
|
const postVaultFrom = createHarness(
|
|
baseArgs({ '--bench-from': VAULT_CUTOFF_ISO, '--bench-to': '2025-06-01T00:00:00Z' })
|
|
);
|
|
expect(await runVerifyM2QuantCli(postVaultFrom.deps)).toBe(1);
|
|
expect(postVaultFrom.stderr.text()).toContain('Vault cutoff');
|
|
expect(postVaultFrom.state.openedStoreConfigs).toHaveLength(0);
|
|
|
|
const unauthorizedScope = createHarness(
|
|
baseArgs({ '--bench-scope': 'vault_evaluation_only' })
|
|
);
|
|
expect(await runVerifyM2QuantCli(unauthorizedScope.deps)).toBe(1);
|
|
expect(unauthorizedScope.stderr.text()).toContain('operator authorization');
|
|
expect(unauthorizedScope.state.openedStoreConfigs).toHaveLength(0);
|
|
|
|
const leakedBarTs = createHarness(baseArgs(), {
|
|
benchBatchesByCall: [
|
|
[
|
|
{
|
|
...defaultBenchBars()[0]!,
|
|
ts: VAULT_CUTOFF_MS,
|
|
},
|
|
],
|
|
],
|
|
});
|
|
expect(await runVerifyM2QuantCli(leakedBarTs.deps)).toBe(1);
|
|
expect(leakedBarTs.stderr.text()).toContain('post-Vault bar');
|
|
|
|
const futureKnownAt = createHarness(baseArgs(), {
|
|
benchBatchesByCall: [
|
|
[
|
|
{
|
|
...defaultBenchBars()[0]!,
|
|
knownAt: Date.parse('2025-02-02T00:00:00Z'),
|
|
},
|
|
],
|
|
],
|
|
});
|
|
expect(await runVerifyM2QuantCli(futureKnownAt.deps)).toBe(1);
|
|
expect(futureKnownAt.stderr.text()).toContain('future-known bar');
|
|
});
|
|
|
|
test('redacts QuestDB URL DSNs and passwords on stderr', async () => {
|
|
const secretUrl = 'postgresql://qdb_user:s3cr3t%21Pass@10.0.0.51:8812/qdb?password=altSecret';
|
|
const urlHarness = createHarness(
|
|
baseArgs({
|
|
'--questdb-host': null,
|
|
'--questdb-pg-port': null,
|
|
'--questdb-url': secretUrl,
|
|
}),
|
|
{
|
|
openPgError: new Error(
|
|
`Connection failed for ${secretUrl} (decoded s3cr3t!Pass / altSecret)\nstack line`
|
|
),
|
|
}
|
|
);
|
|
|
|
const urlCode = await runVerifyM2QuantCli(urlHarness.deps);
|
|
expect(urlCode).toBe(1);
|
|
expect(urlHarness.stdout.text()).toBe('');
|
|
assertSingleLineError(urlHarness.stderr.text());
|
|
expect(urlHarness.stderr.text()).not.toContain('s3cr3t!Pass');
|
|
expect(urlHarness.stderr.text()).not.toContain('s3cr3t%21Pass');
|
|
expect(urlHarness.stderr.text()).not.toContain('altSecret');
|
|
expect(urlHarness.stderr.text()).not.toContain('qdb_user:');
|
|
expect(urlHarness.stderr.text()).toContain('[REDACTED]');
|
|
|
|
const passHarness = createHarness(
|
|
baseArgs({ '--questdb-password': 'MySuperSecretPassword!' }),
|
|
{
|
|
queryError: new Error('Auth error for MySuperSecretPassword! on 10.0.0.51'),
|
|
}
|
|
);
|
|
const passCode = await runVerifyM2QuantCli(passHarness.deps);
|
|
expect(passCode).toBe(1);
|
|
assertSingleLineError(passHarness.stderr.text());
|
|
expect(passHarness.stderr.text()).not.toContain('MySuperSecretPassword!');
|
|
expect(passHarness.stderr.text()).toContain('[REDACTED]');
|
|
});
|
|
|
|
test('rejects invalid CLI arguments fail-closed', async () => {
|
|
const missingHost = createHarness(
|
|
baseArgs({ '--questdb-host': null, '--questdb-pg-port': null })
|
|
);
|
|
expect(await runVerifyM2QuantCli(missingHost.deps)).toBe(1);
|
|
assertSingleLineError(missingHost.stderr.text());
|
|
expect(missingHost.stderr.text()).toContain('Missing required QuestDB connection flags');
|
|
|
|
const conflictingConn = createHarness(
|
|
baseArgs({ '--questdb-url': 'postgres://user:pass@10.0.0.51:8812/qdb' })
|
|
);
|
|
expect(await runVerifyM2QuantCli(conflictingConn.deps)).toBe(1);
|
|
assertSingleLineError(conflictingConn.stderr.text());
|
|
expect(conflictingConn.stderr.text()).not.toContain('pass');
|
|
|
|
const nonUtcCutoff = createHarness(
|
|
baseArgs({ '--vault-cutoff-ts': '2025-02-13T00:00:00+02:00' })
|
|
);
|
|
expect(await runVerifyM2QuantCli(nonUtcCutoff.deps)).toBe(1);
|
|
assertSingleLineError(nonUtcCutoff.stderr.text());
|
|
expect(nonUtcCutoff.stderr.text()).toContain('UTC timestamp ending in');
|
|
});
|
|
});
|