import { randomUUID } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, test } from 'bun:test'; import { Pool } from 'pg'; import { deflatedSharpeRatio, effectiveIndependentTrials } from '@stock-bot/calculations'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { TrialLedgerError, buildTrialRow, canonicalExpressionHash, clusterDeflatedSharpe, loadClusterTrials, recordTrials, type TrialRowInput, } from '@stock-bot/research'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('trial-ledger-writer-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); const VAULT_CUTOFF = '2025-05-01'; const cleanup: (() => Promise | void)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); async function createIsolatedFixture() { if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { throw new Error('Dedicated stock_bot_safety database required'); } const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: url }); await admin.query(`CREATE SCHEMA ${schema}`); const pool = new Pool({ connectionString: url, options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, }); cleanup.push(async () => { await pool.end(); await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); }); // Bootstrap pre-additive tables needed by the research migration track. for (const filename of [ '06-create-backtest-tables.sql', '07-fix-execution-time-type.sql', '08-create-runs-table.sql', ]) { await pool.query(readFileSync(`${initDir}${filename}`, 'utf8')); } const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, logger ); Object.defineProperty(postgres, 'connectionPool', { get: () => ({ connect: () => pool.connect(), }), }); await runPostgresMigrations(postgres, { track: 'research' }); return { pool, schema, postgres }; } async function expectPgErrorCode( operation: Promise, expectedCode: string, messagePattern?: RegExp ): Promise { try { await operation; } catch (error) { const pgError = error as { code?: string; message?: string } | null; expect(pgError?.code).toBe(expectedCode); if (messagePattern) { expect(pgError?.message ?? '').toMatch(messagePattern); } return; } throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`); } function createSeededRng(seed: number): () => number { let state = seed >>> 0; return () => { state = (state + 0x6d2b79f5) >>> 0; let t = Math.imul(state ^ (state >>> 15), 1 | state); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; }; } function createGaussianSampler(seed: number): () => number { const next = createSeededRng(seed); let spare: number | null = null; return () => { if (spare !== null) { const value = spare; spare = null; return value; } let u = 0; while (u <= 1e-12) { u = next(); } const v = next(); const mag = Math.sqrt(-2 * Math.log(u)); const theta = 2 * Math.PI * v; spare = mag * Math.sin(theta); return mag * Math.cos(theta); }; } function makeBusinessDates(startDate: string, count: number): string[] { const out = new Array(count); const current = new Date(`${startDate}T00:00:00.000Z`); let written = 0; while (written < count) { const day = current.getUTCDay(); if (day !== 0 && day !== 6) { out[written] = current.toISOString().slice(0, 10); written += 1; } current.setUTCDate(current.getUTCDate() + 1); } return out; } function makeSeries(seed: number, length: number, mean = 0.0005, std = 0.01): number[] { const gauss = createGaussianSampler(seed); const out = new Array(length); for (let i = 0; i < length; i += 1) { out[i] = mean + std * gauss(); } return out; } describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', () => { test('3-horizon recordTrials inserts 3 ascending rows, round-trips REAL series, rejects bad batch atomically, and preserves immutability triggers', async () => { const f = await createIsolatedFixture(); const horizons = [ { label: '1d', bucket: 'swing_1_10d' as const, seed: 1001 }, { label: '5d', bucket: 'swing_1_10d' as const, seed: 1002 }, { label: '20d', bucket: 'position_10d_plus' as const, seed: 1003 }, ]; const rows = horizons.map(h => buildTrialRow({ principalId: 'operator', stage: 'signal_ic', universeMarket: 'US_EQ', horizonBucket: h.bucket, expressionHash: canonicalExpressionHash({ expression: 'rank(ret_20d) - zscore(vol_20d)', params: { lookback: 20 }, universe: 'US_EQ', sampleStart: '2020-01-02', sampleEnd: '2024-12-31', horizon: h.label, }), sampleStart: '2020-01-02', sampleEnd: '2024-12-31', vaultCutoffDate: VAULT_CUTOFF, dailySeries: makeSeries(h.seed, 25), }) ); const receipts = await recordTrials(f.pool, rows); expect(receipts).toHaveLength(3); expect(receipts[0]!.trialId).toBeLessThan(receipts[1]!.trialId); expect(receipts[1]!.trialId).toBeLessThan(receipts[2]!.trialId); const swingRows = await loadClusterTrials(f.pool, { universeMarket: 'US_EQ', horizonBucket: 'swing_1_10d', }); const positionRows = await loadClusterTrials(f.pool, { universeMarket: 'US_EQ', horizonBucket: 'position_10d_plus', }); expect(swingRows).toHaveLength(2); expect(positionRows).toHaveLength(1); // Verify daily_series round-trips within IEEE-754 REAL precision (float4 text parses to float64 with identical float32 bits). for (let i = 0; i < rows[0]!.dailySeries.length; i += 1) { expect(Math.fround(swingRows[0]!.dailySeries[i]!)).toBe(Math.fround(rows[0]!.dailySeries[i]!)); } // Batch with one invalid row throws TrialLedgerError and inserts 0 additional rows. const badBatch: TrialRowInput[] = [ { principalId: 'operator', stage: 'event_study', universeMarket: 'CA_EQ', horizonBucket: 'swing_1_10d', expressionHash: 'b'.repeat(64), sampleStart: '2020-01-02', sampleEnd: '2024-12-31', vaultCutoffDate: VAULT_CUTOFF, dailySeries: makeSeries(2001, 10), }, { principalId: 'operator', stage: 'event_study', universeMarket: 'CA_EQ', horizonBucket: 'swing_1_10d', expressionHash: 'c'.repeat(64), sampleStart: '2020-01-02', sampleEnd: VAULT_CUTOFF, // violates exclusive vault fence vaultCutoffDate: VAULT_CUTOFF, dailySeries: makeSeries(2002, 10), }, ]; try { await recordTrials(f.pool, badBatch); throw new Error('Expected VAULT_FENCE_VIOLATION'); } catch (error) { expect(error).toBeInstanceOf(TrialLedgerError); expect((error as TrialLedgerError).code).toBe('VAULT_FENCE_VIOLATION'); } const caRows = await loadClusterTrials(f.pool, { universeMarket: 'CA_EQ', horizonBucket: 'swing_1_10d', }); expect(caRows).toHaveLength(0); // Existing append-only triggers still block UPDATE, DELETE, and TRUNCATE. const expectedMsg = /Retained research evidence cannot be rewritten or deleted/; await expectPgErrorCode( f.pool.query('UPDATE trial_ledger SET n_obs = 999'), '23514', expectedMsg ); await expectPgErrorCode(f.pool.query('DELETE FROM trial_ledger'), '23514', expectedMsg); await expectPgErrorCode(f.pool.query('TRUNCATE trial_ledger'), '23514', expectedMsg); const totalCount = (await f.pool.query('SELECT count(*)::int AS c FROM trial_ledger')).rows[0] .c as number; expect(totalCount).toBe(3); }); test('computes N-hat and DSR end-to-end through PostgreSQL for near-duplicate vs independent clusters, cluster isolation, and asOf', async () => { const f = await createIsolatedFixture(); const nObs = 500; const clusterK = 12; const sessionDates = makeBusinessDates('2022-01-03', nObs); const sampleStart = sessionDates[0]!; const sampleEnd = sessionDates[nObs - 1]!; // 1. Near-duplicate cluster in (US_EQ, swing_1_10d): target pairwise rho ~ 0.97 const factorGauss = createGaussianSampler(9001); const baseFactor = new Array(nObs); for (let t = 0; t < nObs; t += 1) { baseFactor[t] = 0.0008 + 0.01 * factorGauss(); } const noiseGauss = createGaussianSampler(9002); const nearDupRows = new Array(clusterK); const loading = Math.sqrt(0.97); const noiseWeight = Math.sqrt(1 - 0.97); for (let k = 0; k < clusterK; k += 1) { const series = new Array(nObs); for (let t = 0; t < nObs; t += 1) { series[t] = loading * (baseFactor[t] as number) + noiseWeight * 0.01 * noiseGauss(); } nearDupRows[k] = { principalId: 'operator', stage: 'screen', universeMarket: 'US_EQ', horizonBucket: 'swing_1_10d', expressionHash: canonicalExpressionHash({ expression: `dup_signal_${k}`, params: { k }, universe: 'US_EQ', sampleStart, sampleEnd, horizon: '5d', }), sampleStart, sampleEnd, vaultCutoffDate: VAULT_CUTOFF, dailySeries: series, }; } const nearDupReceipts = await recordTrials(f.pool, nearDupRows); // 2. Independent cluster in (CA_EQ, swing_1_10d) — also tests cluster isolation from US_EQ! const indepRows = new Array(clusterK); for (let k = 0; k < clusterK; k += 1) { indepRows[k] = { principalId: 'operator', stage: 'screen', universeMarket: 'CA_EQ', horizonBucket: 'swing_1_10d', expressionHash: canonicalExpressionHash({ expression: `indep_signal_${k}`, params: { k }, universe: 'CA_EQ', sampleStart, sampleEnd, horizon: '5d', }), sampleStart, sampleEnd, vaultCutoffDate: VAULT_CUTOFF, dailySeries: makeSeries(5000 + k, nObs, 0.0005, 0.01), }; } const indepReceipts = await recordTrials(f.pool, indepRows); // 3. Another cluster in (US_EQ, position_10d_plus) to verify horizon_bucket isolation. await recordTrials(f.pool, [ { principalId: 'operator', stage: 'engine_backtest', universeMarket: 'US_EQ', horizonBucket: 'position_10d_plus', expressionHash: 'd'.repeat(64), sampleStart, sampleEnd, vaultCutoffDate: VAULT_CUTOFF, dailySeries: makeSeries(7777, nObs), }, ]); const nearDupDsr = await clusterDeflatedSharpe(f.pool, { trialId: nearDupReceipts[0]!.trialId, sessionDates, }); expect(nearDupDsr.clusterSize).toBe(clusterK); expect(nearDupDsr.meanCorrelation).not.toBeNull(); expect(nearDupDsr.meanCorrelation!).toBeGreaterThan(0.95); expect(nearDupDsr.effectiveTrials).toBeLessThan(clusterK * 0.25); const indepDsr = await clusterDeflatedSharpe(f.pool, { trialId: indepReceipts[0]!.trialId, sessionDates, }); expect(indepDsr.clusterSize).toBe(clusterK); expect(indepDsr.effectiveTrials).toBeGreaterThan(clusterK * 0.85); expect(indepDsr.effectiveTrials).toBeLessThanOrEqual(clusterK); // Direct deflatedSharpeRatio parity within 1e-9 on the persisted cluster rows. const persistedNearDup = await loadClusterTrials(f.pool, { universeMarket: 'US_EQ', horizonBucket: 'swing_1_10d', }); const directEff = effectiveIndependentTrials(persistedNearDup.map(r => r.dailySeries)); const directDsr = deflatedSharpeRatio({ sharpeUnann: persistedNearDup[0]!.sharpeUnann, nObs: persistedNearDup[0]!.nObs, skewness: persistedNearDup[0]!.skewness, kurtosis: persistedNearDup[0]!.kurtosis, nHat: directEff.nHat, clusterSharpes: persistedNearDup.map(r => r.sharpeUnann), }); expect(directDsr).not.toBeNull(); expect(Math.abs((nearDupDsr.dsr ?? Number.NaN) - directDsr!.dsr)).toBeLessThan(1e-9); // Writer receipt timestamp round-trip: exact receipt timestamp with Z and +00:00 select the same rows. const receiptTs = nearDupReceipts[clusterK - 1]!.createdAt; const atReceiptZ = await loadClusterTrials(f.pool, { universeMarket: 'US_EQ', horizonBucket: 'swing_1_10d', asOf: receiptTs, }); const atReceiptOffset = await loadClusterTrials(f.pool, { universeMarket: 'US_EQ', horizonBucket: 'swing_1_10d', asOf: receiptTs.replace(/Z$/, '+00:00'), }); expect(atReceiptZ).toHaveLength(clusterK); expect(atReceiptOffset.map(r => r.trialId)).toEqual(atReceiptZ.map(r => r.trialId)); // Deterministic asOf ordering fixture: explicit distinct microsecond created_at values (no wall-clock sleep). const olderRow = buildTrialRow({ principalId: 'operator', stage: 'screen', universeMarket: 'FX', horizonBucket: 'intraday', expressionHash: 'e'.repeat(64), sampleStart, sampleEnd, vaultCutoffDate: VAULT_CUTOFF, dailySeries: makeSeries(9998, 10), }); const newerRow = buildTrialRow({ principalId: 'operator', stage: 'screen', universeMarket: 'FX', horizonBucket: 'intraday', expressionHash: 'f'.repeat(64), sampleStart, sampleEnd, vaultCutoffDate: VAULT_CUTOFF, dailySeries: makeSeries(9999, 10), }); await f.pool.query( `INSERT INTO trial_ledger ( created_at, principal_id, campaign_id, stage, universe_market, horizon_bucket, hypothesis_id, expression_hash, sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series ) VALUES ($1::timestamptz, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::double precision, $13::double precision, $14::double precision, $15::real[]), ($16::timestamptz, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27::double precision, $28::double precision, $29::double precision, $30::real[])`, [ '2025-04-01T10:00:00.123456Z', olderRow.principalId, olderRow.campaignId, olderRow.stage, olderRow.universeMarket, olderRow.horizonBucket, olderRow.hypothesisId, olderRow.expressionHash, olderRow.sampleStart, olderRow.sampleEnd, olderRow.nObs, olderRow.sharpeUnann, olderRow.skewness, olderRow.kurtosis, olderRow.dailySeries, '2025-04-01T10:00:00.123457Z', newerRow.principalId, newerRow.campaignId, newerRow.stage, newerRow.universeMarket, newerRow.horizonBucket, newerRow.hypothesisId, newerRow.expressionHash, newerRow.sampleStart, newerRow.sampleEnd, newerRow.nObs, newerRow.sharpeUnann, newerRow.skewness, newerRow.kurtosis, newerRow.dailySeries, ] ); const fxAll = await loadClusterTrials(f.pool, { universeMarket: 'FX', horizonBucket: 'intraday', }); const fxAtZ = await loadClusterTrials(f.pool, { universeMarket: 'FX', horizonBucket: 'intraday', asOf: '2025-04-01T10:00:00.123456Z', }); const fxAtPlusZero = await loadClusterTrials(f.pool, { universeMarket: 'FX', horizonBucket: 'intraday', asOf: '2025-04-01T10:00:00.123456+00:00', }); const fxAtPlusTwo = await loadClusterTrials(f.pool, { universeMarket: 'FX', horizonBucket: 'intraday', asOf: '2025-04-01T12:00:00.123456+02:00', }); expect(fxAll).toHaveLength(2); expect(fxAtZ).toHaveLength(1); expect(fxAtPlusZero).toHaveLength(1); expect(fxAtPlusTwo).toHaveLength(1); expect(fxAtPlusZero[0]!.trialId).toBe(fxAtZ[0]!.trialId); expect(fxAtPlusTwo[0]!.trialId).toBe(fxAtZ[0]!.trialId); }); });