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 { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('trial-ledger-schema-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); const trialLedgerSqlPath = `${initDir}36-trial-ledger.sql`; const VALID_HASH = 'a'.repeat(64); const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; 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`); } async function until(check: () => Promise): Promise { const deadline = Date.now() + 3_000; while (Date.now() < deadline) { if (await check()) { return; } await Bun.sleep(10); } throw new Error('Timed out waiting for PostgreSQL advisory-lock waiter'); } interface TrialInsertOverrides { principalId?: string; campaignId?: string | null; stage?: string; universeMarket?: string; horizonBucket?: string; hypothesisId?: string | null; expressionHash?: string; sampleStart?: string; sampleEnd?: string; nObs?: number; sharpeUnann?: number | string; skewness?: number | string; kurtosis?: number | string; dailySeries?: number[] | (number | null | string)[]; } function insertTrial(pool: Pool, overrides: TrialInsertOverrides = {}) { return pool.query( `INSERT INTO trial_ledger ( 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, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::double precision, $12::double precision, $13::double precision, $14::real[]) RETURNING trial_id, created_at, principal_id`, [ overrides.principalId ?? 'operator', overrides.campaignId === undefined ? null : overrides.campaignId, overrides.stage ?? 'signal_ic', overrides.universeMarket ?? 'US_EQ', overrides.horizonBucket ?? 'swing_1_10d', overrides.hypothesisId === undefined ? null : overrides.hypothesisId, overrides.expressionHash ?? VALID_HASH, overrides.sampleStart ?? '2020-01-02', overrides.sampleEnd ?? '2024-12-31', overrides.nObs ?? 252, overrides.sharpeUnann ?? 0.08, overrides.skewness ?? -0.15, overrides.kurtosis ?? 3.2, overrides.dailySeries ?? [0.001, -0.002, 0.003], ] ); } interface VaultInsertOverrides { evaluatedAt?: string; principalId?: string; strategyRef?: string; expressionHash?: string; vaultCutoffDate?: string; vaultStart?: string; vaultEnd?: string; nObs?: number; sharpePostCost?: number | string; passed?: boolean; notes?: string | null; } function insertVaultEvaluation(pool: Pool, overrides: VaultInsertOverrides = {}) { if (overrides.evaluatedAt !== undefined) { return pool.query( `INSERT INTO vault_evaluations ( evaluated_at, principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) VALUES ($1::timestamptz, $2, $3, $4, $5, $6, $7, $8, $9::double precision, $10, $11) RETURNING evaluation_id, evaluated_at`, [ overrides.evaluatedAt, overrides.principalId ?? 'operator', overrides.strategyRef ?? 'strat:momentum-v1', overrides.expressionHash ?? VALID_HASH, overrides.vaultCutoffDate ?? '2025-05-01', overrides.vaultStart ?? '2025-05-01', overrides.vaultEnd ?? '2025-11-01', overrides.nObs ?? 126, overrides.sharpePostCost ?? 0.85, overrides.passed ?? true, overrides.notes === undefined ? 'Initial vault burn' : overrides.notes, ] ); } return pool.query( `INSERT INTO vault_evaluations ( principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::double precision, $9, $10) RETURNING evaluation_id, evaluated_at`, [ overrides.principalId ?? 'operator', overrides.strategyRef ?? 'strat:momentum-v1', overrides.expressionHash ?? VALID_HASH, overrides.vaultCutoffDate ?? '2025-05-01', overrides.vaultStart ?? '2025-05-01', overrides.vaultEnd ?? '2025-11-01', overrides.nObs ?? 126, overrides.sharpePostCost ?? 0.85, overrides.passed ?? true, overrides.notes === undefined ? 'Initial vault burn' : overrides.notes, ] ); } describe.skipIf(!url)('trial_ledger and vault_evaluations PostgreSQL schema', () => { test('creates tables and indexes and is idempotent on runner re-run and raw SQL re-execution', async () => { const f = await createIsolatedFixture(); const tables = new Set( ( await f.pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1', [f.schema]) ).rows.map(row => row.tablename as string) ); expect(tables.has('trial_ledger')).toBe(true); expect(tables.has('vault_evaluations')).toBe(true); const indexes = new Set( ( await f.pool.query('SELECT indexname FROM pg_indexes WHERE schemaname = $1', [f.schema]) ).rows.map(row => row.indexname as string) ); expect(indexes.has('idx_trial_ledger_cluster')).toBe(true); expect(indexes.has('idx_trial_ledger_expression_hash')).toBe(true); expect(indexes.has('idx_vault_evaluations_evaluated_at')).toBe(true); await insertTrial(f.pool); await insertVaultEvaluation(f.pool); expect(await runPostgresMigrations(f.postgres, { track: 'research' })).toEqual([]); const rawSql = readFileSync(trialLedgerSqlPath, 'utf8'); await f.pool.query(rawSql); expect((await f.pool.query('SELECT count(*)::int AS c FROM trial_ledger')).rows[0].c).toBe(1); expect((await f.pool.query('SELECT count(*)::int AS c FROM vault_evaluations')).rows[0].c).toBe( 1 ); }); test('trial_ledger accepts valid operator and agent inserts across all enum values', async () => { const f = await createIsolatedFixture(); const first = (await insertTrial(f.pool)).rows[0]; expect(BigInt(first.trial_id as string)).toBe(1n); expect(first.principal_id).toBe('operator'); const second = ( await insertTrial(f.pool, { principalId: VALID_AGENT_PRINCIPAL, campaignId: randomUUID(), hypothesisId: randomUUID(), stage: 'engine_backtest', universeMarket: 'CA_EQ', horizonBucket: 'intraday', sampleStart: '2024-06-03', sampleEnd: '2024-06-03', nObs: 2, dailySeries: [0.0, 0.01], }) ).rows[0]; expect(BigInt(second.trial_id as string)).toBe(2n); expect(second.principal_id).toBe(VALID_AGENT_PRINCIPAL); for (const [stage, universeMarket, horizonBucket] of [ ['event_study', 'US_CA_EQ', 'position_10d_plus'], ['screen', 'FX', 'swing_1_10d'], ] as const) { const row = (await insertTrial(f.pool, { stage, universeMarket, horizonBucket })).rows[0]; expect(BigInt(row.trial_id as string)).toBeGreaterThan(2n); } }); test('trial_ledger rejects invalid enums, hashes, dates, counts, series, floats, and principals', async () => { const f = await createIsolatedFixture(); // Unknown enums (including PLATFORM-PLAN's bare 'US' spelling) await expectPgErrorCode(insertTrial(f.pool, { stage: 'live_trade' }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { universeMarket: 'US' }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { universeMarket: 'EU_EQ' }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { horizonBucket: 'weekly' }), '23514'); // Malformed / wrong-length expression_hash await expectPgErrorCode(insertTrial(f.pool, { expressionHash: 'g'.repeat(64) }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { expressionHash: 'A'.repeat(64) }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { expressionHash: 'a'.repeat(63) }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { expressionHash: 'a'.repeat(65) }), '22001'); // Date ordering and observation count await expectPgErrorCode( insertTrial(f.pool, { sampleStart: '2024-05-02', sampleEnd: '2024-05-01' }), '23514' ); await expectPgErrorCode(insertTrial(f.pool, { nObs: 1 }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { nObs: 0 }), '23514'); // daily_series: empty, 1-element, NULL element, 2D array, NaN, +Infinity, -Infinity await expectPgErrorCode(insertTrial(f.pool, { dailySeries: [] }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { dailySeries: [0.01] }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { dailySeries: [0.01, null] }), '23514'); await expectPgErrorCode( f.pool.query( `INSERT INTO trial_ledger ( principal_id, stage, universe_market, horizon_bucket, expression_hash, sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series ) VALUES ('operator', 'signal_ic', 'US_EQ', 'swing_1_10d', $1, '2020-01-02', '2024-12-31', 4, 0.1, 0.0, 3.0, '{{0.01,0.02},{0.03,0.04}}'::real[])`, [VALID_HASH] ), '23514' ); for (const badReal of ['NaN', 'Infinity', '-Infinity']) { await expectPgErrorCode( f.pool.query( `INSERT INTO trial_ledger ( principal_id, stage, universe_market, horizon_bucket, expression_hash, sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series ) VALUES ('operator', 'signal_ic', 'US_EQ', 'swing_1_10d', $1, '2020-01-02', '2024-12-31', 2, 0.1, 0.0, 3.0, ARRAY[0.01::real, $2::real])`, [VALID_HASH, badReal] ), '23514' ); } // Non-finite sharpe_unann, skewness, kurtosis for (const badFloat of ['NaN', 'Infinity', '-Infinity']) { await expectPgErrorCode(insertTrial(f.pool, { sharpeUnann: badFloat }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { skewness: badFloat }), '23514'); await expectPgErrorCode(insertTrial(f.pool, { kurtosis: badFloat }), '23514'); } // Invalid principal_id values for (const badPrincipal of [ 'service', '', 'agent:not-a-uuid', 'agent:00000000-0000-0000-0000-000000000000', 'agent:11111111-2222-4333-8444-55555555555A', ]) { await expectPgErrorCode(insertTrial(f.pool, { principalId: badPrincipal }), '23514'); } expect((await f.pool.query('SELECT count(*)::int AS c FROM trial_ledger')).rows[0].c).toBe(0); }); test('UPDATE, DELETE, and TRUNCATE are blocked on both trial_ledger and vault_evaluations', async () => { const f = await createIsolatedFixture(); await insertTrial(f.pool); await insertVaultEvaluation(f.pool); 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); await expectPgErrorCode( f.pool.query('UPDATE vault_evaluations SET passed = false'), '23514', expectedMsg ); await expectPgErrorCode(f.pool.query('DELETE FROM vault_evaluations'), '23514', expectedMsg); await expectPgErrorCode(f.pool.query('TRUNCATE vault_evaluations'), '23514', expectedMsg); expect((await f.pool.query('SELECT count(*)::int AS c FROM trial_ledger')).rows[0].c).toBe(1); expect((await f.pool.query('SELECT count(*)::int AS c FROM vault_evaluations')).rows[0].c).toBe( 1 ); }); test('vault_evaluations rejects non-operator principals and invalid field constraints', async () => { const f = await createIsolatedFixture(); await expectPgErrorCode( insertVaultEvaluation(f.pool, { principalId: VALID_AGENT_PRINCIPAL }), '23514' ); await expectPgErrorCode(insertVaultEvaluation(f.pool, { principalId: 'service' }), '23514'); await expectPgErrorCode(insertVaultEvaluation(f.pool, { strategyRef: ' ' }), '23514'); await expectPgErrorCode( insertVaultEvaluation(f.pool, { expressionHash: 'z'.repeat(64) }), '23514' ); await expectPgErrorCode( insertVaultEvaluation(f.pool, { vaultCutoffDate: '2025-05-01', vaultStart: '2025-06-01', vaultEnd: '2025-05-15', }), '23514' ); await expectPgErrorCode( insertVaultEvaluation(f.pool, { vaultCutoffDate: '2025-05-01', vaultStart: '2025-04-30', vaultEnd: '2025-11-01', }), '23514' ); await expectPgErrorCode(insertVaultEvaluation(f.pool, { nObs: 1 }), '23514'); for (const badFloat of ['NaN', 'Infinity', '-Infinity']) { await expectPgErrorCode(insertVaultEvaluation(f.pool, { sharpePostCost: badFloat }), '23514'); } expect((await f.pool.query('SELECT count(*)::int AS c FROM vault_evaluations')).rows[0].c).toBe( 0 ); }); test('vault_evaluations enforces <= 10 rolling-year cap, blocks back-dating, multi-row bypass, and concurrent races', async () => { const f = await createIsolatedFixture(); // 1. Back-dated evaluated_at is overwritten to transaction_timestamp() in the same transaction const backdated = ( await f.pool.query( `INSERT INTO vault_evaluations ( evaluated_at, principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) VALUES ($1::timestamptz, 'operator', 'strat:burn-1', $2, '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.85, true, 'Initial vault burn') RETURNING evaluation_id, evaluated_at = transaction_timestamp() AS matches_tx_ts`, ['2020-01-01T00:00:00Z', VALID_HASH] ) ).rows[0]; expect(backdated.matches_tx_ts).toBe(true); // 2. Insert 8 more rows (total = 9), then race two concurrent 10th-row inserts for (let i = 2; i <= 9; i++) { await insertVaultEvaluation(f.pool, { strategyRef: `strat:burn-${i}` }); } const clientA = await f.pool.connect(); const clientB = await f.pool.connect(); try { const pidB = (await clientB.query('SELECT pg_backend_pid() AS pid')).rows[0].pid as number; await clientA.query('BEGIN'); await clientA.query( `INSERT INTO vault_evaluations ( principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) VALUES ('operator', 'strat:burn-10a', $1, '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.9, true, 'race A')`, [VALID_HASH] ); await clientB.query('BEGIN'); const insertB = clientB.query( `INSERT INTO vault_evaluations ( principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) VALUES ('operator', 'strat:burn-10b', $1, '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.9, true, 'race B')`, [VALID_HASH] ); // Prevent unhandled rejection while waiting on the lock barrier. insertB.catch(() => undefined); await until(async () => { const res = await f.pool.query( "SELECT 1 FROM pg_locks WHERE pid = $1 AND locktype = 'advisory' AND NOT granted", [pidB] ); return res.rowCount === 1; }); await clientA.query('COMMIT'); await expectPgErrorCode(insertB, '23514', /at most 10 evaluations/i); await clientB.query('ROLLBACK'); } finally { clientA.release(); clientB.release(); } expect((await f.pool.query('SELECT count(*)::int AS c FROM vault_evaluations')).rows[0].c).toBe( 10 ); // 3. 11th insert rejected with default evaluated_at and with back-dated evaluated_at await expectPgErrorCode( insertVaultEvaluation(f.pool, { strategyRef: 'strat:burn-11' }), '23514', /at most 10 evaluations/i ); await expectPgErrorCode( insertVaultEvaluation(f.pool, { evaluatedAt: '2020-01-01T00:00:00Z', strategyRef: 'strat:burn-11-backdated', }), '23514', /at most 10 evaluations/i ); expect((await f.pool.query('SELECT count(*)::int AS c FROM vault_evaluations')).rows[0].c).toBe( 10 ); // 4. Single 11-row multi-row INSERT on a fresh schema is rejected leaving 0 rows const f2 = await createIsolatedFixture(); await expectPgErrorCode( f2.pool.query( `INSERT INTO vault_evaluations ( principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) SELECT 'operator', 'strat:batch-' || g, $1, '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.9, true, 'batch' FROM generate_series(1, 11) AS g`, [VALID_HASH] ), '23514', /at most 10 evaluations/i ); expect( (await f2.pool.query('SELECT count(*)::int AS c FROM vault_evaluations')).rows[0].c ).toBe(0); }); test('vault_evaluations rejects REPEATABLE READ and SERIALIZABLE inserts to prevent stale-snapshot cap bypass', async () => { const f = await createIsolatedFixture(); for (let i = 1; i <= 9; i++) { await insertVaultEvaluation(f.pool, { strategyRef: `strat:iso-${i}` }); } const clientA = await f.pool.connect(); const clientB = await f.pool.connect(); try { // Simulate the stale-snapshot race: clientA inserts the 10th row under READ COMMITTED // while clientB establishes a REPEATABLE READ snapshot seeing only 9 rows, then attempts to insert. await clientA.query('BEGIN'); await clientA.query( `INSERT INTO vault_evaluations ( principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) VALUES ('operator', 'strat:iso-10', $1, '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.9, true, 'rc 10th')`, [VALID_HASH] ); await clientB.query('BEGIN ISOLATION LEVEL REPEATABLE READ'); await clientB.query('SELECT count(*) FROM vault_evaluations'); await clientA.query('COMMIT'); await expectPgErrorCode( clientB.query( `INSERT INTO vault_evaluations ( principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) VALUES ('operator', 'strat:iso-rr', $1, '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.9, true, 'stale rr')`, [VALID_HASH] ), '25000', /READ COMMITTED isolation/i ); await clientB.query('ROLLBACK'); // SERIALIZABLE is also rejected so a mixed READ COMMITTED + SERIALIZABLE race cannot bypass the cap. await clientB.query('BEGIN ISOLATION LEVEL SERIALIZABLE'); await clientB.query('SELECT 1'); await expectPgErrorCode( clientB.query( `INSERT INTO vault_evaluations ( principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) VALUES ('operator', 'strat:iso-ser', $1, '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.9, true, 'stale ser')`, [VALID_HASH] ), '25000', /READ COMMITTED isolation/i ); await clientB.query('ROLLBACK'); } finally { clientA.release(); clientB.release(); } expect((await f.pool.query('SELECT count(*)::int AS c FROM vault_evaluations')).rows[0].c).toBe( 10 ); }); test('vault_evaluations cap counts the target table via TG_RELID across schemas regardless of search_path', async () => { const target = await createIsolatedFixture(); const other = await createIsolatedFixture(); for (let i = 1; i <= 10; i++) { await insertVaultEvaluation(target.pool, { strategyRef: `strat:target-${i}` }); } // Session search_path points to `other` (0 rows), while inserting schema-qualified into `target` (10 rows). await expectPgErrorCode( other.pool.query( `INSERT INTO ${target.schema}.vault_evaluations ( principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) VALUES ('operator', 'strat:cross-schema-11', $1, '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.9, true, 'cross-schema')`, [VALID_HASH] ), '23514', /at most 10 evaluations/i ); // Multi-row schema-qualified insert from `target` (10 rows) into `other` (0 rows): // 1 row succeeds (proving it counted `other` = 0, not `target` = 10), while 11 rows in one statement fails. await expectPgErrorCode( target.pool.query( `INSERT INTO ${other.schema}.vault_evaluations ( principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) SELECT 'operator', 'strat:cross-batch-' || g, $1, '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.9, true, 'cross-batch' FROM generate_series(1, 11) AS g`, [VALID_HASH] ), '23514', /at most 10 evaluations/i ); await target.pool.query( `INSERT INTO ${other.schema}.vault_evaluations ( principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes ) VALUES ('operator', 'strat:cross-schema-ok', $1, '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.9, true, 'cross-schema ok')`, [VALID_HASH] ); expect( (await target.pool.query('SELECT count(*)::int AS c FROM vault_evaluations')).rows[0].c ).toBe(10); expect( (await other.pool.query('SELECT count(*)::int AS c FROM vault_evaluations')).rows[0].c ).toBe(1); }); }); const VAULT_COLUMNS_SQL = `principal_id, strategy_ref, expression_hash, vault_cutoff_date, vault_start, vault_end, n_obs, sharpe_post_cost, passed, notes`; const VAULT_VALUES_SQL = `'operator', 'strat:qa', '${VALID_HASH}', '2025-05-01', '2025-05-01', '2025-11-01', 126, 0.9, true, 'qa'`; async function countRows(pool: Pool, table: string): Promise { return (await pool.query(`SELECT count(*)::int AS c FROM ${table}`)).rows[0].c as number; } describe.skipIf(!url)( 'trial_ledger and vault_evaluations PostgreSQL schema (QA edge cases)', () => { test('catalog column types, nullability, identity and defaults match design/VALIDATION-AND-RIGOR.md', async () => { const f = await createIsolatedFixture(); const columns = async (table: string) => ( await f.pool.query( `SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, a.attnotnull AS not_null, a.attidentity AS identity, pg_get_expr(d.adbin, d.adrelid) AS default_expr FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum WHERE a.attrelid = $1::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`, [table] ) ).rows.map( r => `${r.name}|${r.type}|${r.not_null ? 'NN' : 'NULL'}|${r.identity}|${r.default_expr ?? ''}` ); expect(await columns('trial_ledger')).toEqual([ 'trial_id|bigint|NN|a|', 'created_at|timestamp with time zone|NN||now()', 'principal_id|text|NN||', 'campaign_id|uuid|NULL||', 'stage|character varying(16)|NN||', 'universe_market|character varying(12)|NN||', 'horizon_bucket|character varying(32)|NN||', 'hypothesis_id|uuid|NULL||', 'expression_hash|character(64)|NN||', 'sample_start|date|NN||', 'sample_end|date|NN||', 'n_obs|integer|NN||', 'sharpe_unann|double precision|NN||', 'skewness|double precision|NN||', 'kurtosis|double precision|NN||', 'daily_series|real[]|NN||', ]); expect(await columns('vault_evaluations')).toEqual([ 'evaluation_id|bigint|NN|a|', 'evaluated_at|timestamp with time zone|NN||now()', 'principal_id|text|NN||', 'strategy_ref|text|NN||', 'expression_hash|character(64)|NN||', 'vault_cutoff_date|date|NN||', 'vault_start|date|NN||', 'vault_end|date|NN||', 'n_obs|integer|NN||', 'sharpe_post_cost|double precision|NN||', 'passed|boolean|NN||', 'notes|text|NULL||', ]); const primaryKeys = ( await f.pool.query( `SELECT conrelid::regclass::text AS rel, pg_get_constraintdef(oid) AS def FROM pg_constraint WHERE contype = 'p' AND connamespace = $1::regnamespace AND conrelid IN ('trial_ledger'::regclass, 'vault_evaluations'::regclass) ORDER BY 1`, [f.schema] ) ).rows.map(r => `${r.rel}:${r.def}`); expect(primaryKeys).toEqual([ 'trial_ledger:PRIMARY KEY (trial_id)', 'vault_evaluations:PRIMARY KEY (evaluation_id)', ]); }); test('GENERATED ALWAYS identities reject caller-supplied trial_id and evaluation_id', async () => { const f = await createIsolatedFixture(); await expectPgErrorCode( f.pool.query( `INSERT INTO trial_ledger (trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash, sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series) VALUES (42, 'operator', 'signal_ic', 'US_EQ', 'intraday', $1, '2020-01-02', '2020-12-31', 2, 0.1, 0, 3, '{0.1,0.2}')`, [VALID_HASH] ), '428C9' ); await expectPgErrorCode( f.pool.query( `INSERT INTO vault_evaluations (evaluation_id, ${VAULT_COLUMNS_SQL}) VALUES (42, ${VAULT_VALUES_SQL})` ), '428C9' ); expect(await countRows(f.pool, 'trial_ledger')).toBe(0); expect(await countRows(f.pool, 'vault_evaluations')).toBe(0); }); test('trial_ledger rejects NULL required fields and unanchored or case-variant principals', async () => { const f = await createIsolatedFixture(); await expectPgErrorCode( f.pool.query( `INSERT INTO trial_ledger (principal_id, stage, universe_market, horizon_bucket, expression_hash, sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series) VALUES ('operator', NULL, 'US_EQ', 'intraday', $1, '2020-01-02', '2020-12-31', 2, 0.1, 0, 3, '{0.1,0.2}')`, [VALID_HASH] ), '23502' ); await expectPgErrorCode( f.pool.query( `INSERT INTO trial_ledger (principal_id, stage, universe_market, horizon_bucket, expression_hash, sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series) VALUES ('operator', 'signal_ic', 'US_EQ', 'intraday', $1, '2020-01-02', '2020-12-31', 2, 0.1, 0, 3, NULL)`, [VALID_HASH] ), '23502' ); for (const badPrincipal of [ 'Operator', 'operator ', ' operator', `${VALID_AGENT_PRINCIPAL}\n`, `${VALID_AGENT_PRINCIPAL}x`, `x${VALID_AGENT_PRINCIPAL}`, VALID_AGENT_PRINCIPAL.replace('agent:', 'AGENT:'), ]) { await expectPgErrorCode(insertTrial(f.pool, { principalId: badPrincipal }), '23514'); } expect(await countRows(f.pool, 'trial_ledger')).toBe(0); }); test('vault cap counts only the rolling year: rows exactly 1 year old free a slot, rows 364 days old do not', async () => { const f = await createIsolatedFixture(); const client = await f.pool.connect(); try { // Seed historical rows as table owner with the timestamp-forcing trigger disabled; DDL is // transactional so now() is identical for the seed and the capped insert below. await client.query('BEGIN'); await client.query('ALTER TABLE vault_evaluations DISABLE TRIGGER vault_evaluations_cap'); await client.query( `INSERT INTO vault_evaluations (evaluated_at, ${VAULT_COLUMNS_SQL}) SELECT now() - interval '1 year', ${VAULT_VALUES_SQL} FROM generate_series(1, 10)` ); await client.query('ALTER TABLE vault_evaluations ENABLE TRIGGER vault_evaluations_cap'); await client.query( `INSERT INTO vault_evaluations (${VAULT_COLUMNS_SQL}) VALUES (${VAULT_VALUES_SQL})` ); await client.query('COMMIT'); } finally { client.release(); } expect(await countRows(f.pool, 'vault_evaluations')).toBe(11); const g = await createIsolatedFixture(); const seeder = await g.pool.connect(); try { await seeder.query('BEGIN'); await seeder.query('ALTER TABLE vault_evaluations DISABLE TRIGGER vault_evaluations_cap'); await seeder.query( `INSERT INTO vault_evaluations (evaluated_at, ${VAULT_COLUMNS_SQL}) SELECT now() - interval '364 days', ${VAULT_VALUES_SQL} FROM generate_series(1, 10)` ); await seeder.query('ALTER TABLE vault_evaluations ENABLE TRIGGER vault_evaluations_cap'); await seeder.query('COMMIT'); } finally { seeder.release(); } await expectPgErrorCode(insertVaultEvaluation(g.pool), '23514', /at most 10 evaluations/i); expect(await countRows(g.pool, 'vault_evaluations')).toBe(10); }); test('a single 10-row INSERT fills the cap exactly and the next insert is rejected', async () => { const f = await createIsolatedFixture(); await f.pool.query( `INSERT INTO vault_evaluations (${VAULT_COLUMNS_SQL}) SELECT ${VAULT_VALUES_SQL} FROM generate_series(1, 10)` ); expect(await countRows(f.pool, 'vault_evaluations')).toBe(10); await expectPgErrorCode(insertVaultEvaluation(f.pool), '23514', /at most 10 evaluations/i); expect(await countRows(f.pool, 'vault_evaluations')).toBe(10); }); test('rolled-back vault inserts do not consume the yearly cap', async () => { const f = await createIsolatedFixture(); const client = await f.pool.connect(); try { await client.query('BEGIN'); await client.query( `INSERT INTO vault_evaluations (${VAULT_COLUMNS_SQL}) SELECT ${VAULT_VALUES_SQL} FROM generate_series(1, 10)` ); await client.query('ROLLBACK'); } finally { client.release(); } expect(await countRows(f.pool, 'vault_evaluations')).toBe(0); for (let i = 1; i <= 10; i++) { await insertVaultEvaluation(f.pool, { strategyRef: `strat:after-rollback-${i}` }); } expect(await countRows(f.pool, 'vault_evaluations')).toBe(10); }); test('READ UNCOMMITTED (treated as READ COMMITTED by PostgreSQL) vault inserts are accepted', async () => { const f = await createIsolatedFixture(); const client = await f.pool.connect(); try { await client.query('BEGIN ISOLATION LEVEL READ UNCOMMITTED'); await client.query( `INSERT INTO vault_evaluations (${VAULT_COLUMNS_SQL}) VALUES (${VAULT_VALUES_SQL})` ); await client.query('COMMIT'); } finally { client.release(); } expect(await countRows(f.pool, 'vault_evaluations')).toBe(1); }); test('schema-qualified inserts work and are capped from a session whose search_path has no vault_evaluations', async () => { const target = await createIsolatedFixture(); const emptySchema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: url }); await admin.query(`CREATE SCHEMA ${emptySchema}`); const emptyPool = new Pool({ connectionString: url, options: `-c search_path=${emptySchema} -c statement_timeout=5000 -c lock_timeout=5000`, }); cleanup.push(async () => { await emptyPool.end(); await admin.query(`DROP SCHEMA ${emptySchema} CASCADE`); await admin.end(); }); const qualifiedInsert = `INSERT INTO ${target.schema}.vault_evaluations (${VAULT_COLUMNS_SQL}) VALUES (${VAULT_VALUES_SQL})`; // An unqualified table lookup in either cap trigger would raise 42P01 here. for (let i = 1; i <= 10; i++) { await emptyPool.query(qualifiedInsert); } await expectPgErrorCode(emptyPool.query(qualifiedInsert), '23514', /at most 10 evaluations/i); await expectPgErrorCode( emptyPool.query(`UPDATE ${target.schema}.vault_evaluations SET passed = NOT passed`), '23514', /Retained research evidence/ ); expect(await countRows(target.pool, 'vault_evaluations')).toBe(10); }); test('the cap advisory lock is schema-scoped: an open vault insert in one schema does not block another', async () => { const a = await createIsolatedFixture(); const b = await createIsolatedFixture(); const holder = await a.pool.connect(); try { await holder.query('BEGIN'); await holder.query( `INSERT INTO vault_evaluations (${VAULT_COLUMNS_SQL}) VALUES (${VAULT_VALUES_SQL})` ); // b's pool has lock_timeout/statement_timeout=5000; a shared lock key would block and fail here. await insertVaultEvaluation(b.pool); expect(await countRows(b.pool, 'vault_evaluations')).toBe(1); await holder.query('COMMIT'); } finally { holder.release(); } expect(await countRows(a.pool, 'vault_evaluations')).toBe(1); }); } ); describe.skipIf(!url)( 'trial_ledger and vault_evaluations PostgreSQL schema (QA re-run edge cases)', () => { test('raw re-execution of 36-trial-ledger.sql keeps exactly one copy of each trigger and enforcement still holds', async () => { const f = await createIsolatedFixture(); const triggers = async () => ( await f.pool.query( `SELECT c.relname || ':' || t.tgname || ':' || p.proname AS t FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_proc p ON p.oid = t.tgfoid WHERE NOT t.tgisinternal AND c.relnamespace = $1::regnamespace AND c.relname IN ('trial_ledger', 'vault_evaluations') ORDER BY 1`, [f.schema] ) ).rows.map(r => r.t as string); const expected = [ 'trial_ledger:trial_ledger_no_truncate:reject_research_evidence_mutation', 'trial_ledger:trial_ledger_retained:reject_research_evidence_mutation', 'vault_evaluations:vault_evaluations_cap:enforce_vault_evaluation_cap', 'vault_evaluations:vault_evaluations_cap_after:verify_vault_evaluation_cap_after', 'vault_evaluations:vault_evaluations_no_truncate:reject_research_evidence_mutation', 'vault_evaluations:vault_evaluations_retained:reject_research_evidence_mutation', ]; expect(await triggers()).toEqual(expected); await insertTrial(f.pool); for (let i = 1; i <= 10; i++) { await insertVaultEvaluation(f.pool, { strategyRef: `strat:rerun-${i}` }); } const rawSql = readFileSync(trialLedgerSqlPath, 'utf8'); await f.pool.query(rawSql); await f.pool.query(rawSql); expect(await triggers()).toEqual(expected); await expectPgErrorCode( f.pool.query('UPDATE trial_ledger SET n_obs = 3'), '23514', /Retained research evidence/ ); await expectPgErrorCode(f.pool.query('TRUNCATE vault_evaluations'), '23514'); await expectPgErrorCode(insertVaultEvaluation(f.pool), '23514', /at most 10 evaluations/i); expect(await countRows(f.pool, 'trial_ledger')).toBe(1); expect(await countRows(f.pool, 'vault_evaluations')).toBe(10); }); test('a session defaulting to REPEATABLE READ cannot insert a vault evaluation in autocommit mode', async () => { const f = await createIsolatedFixture(); const client = await f.pool.connect(); try { await client.query("SET default_transaction_isolation = 'repeatable read'"); await expectPgErrorCode( client.query( `INSERT INTO vault_evaluations (${VAULT_COLUMNS_SQL}) VALUES (${VAULT_VALUES_SQL})` ), '25000', /READ COMMITTED isolation/i ); await client.query('RESET default_transaction_isolation'); } finally { client.release(); } expect(await countRows(f.pool, 'vault_evaluations')).toBe(0); }); test('ten single-row inserts inside one transaction fill the cap and the eleventh fails in that transaction', async () => { const f = await createIsolatedFixture(); const client = await f.pool.connect(); try { await client.query('BEGIN'); for (let i = 1; i <= 10; i++) { await client.query( `INSERT INTO vault_evaluations (${VAULT_COLUMNS_SQL}) VALUES (${VAULT_VALUES_SQL})` ); } await expectPgErrorCode( client.query( `INSERT INTO vault_evaluations (${VAULT_COLUMNS_SQL}) VALUES (${VAULT_VALUES_SQL})` ), '23514', /at most 10 evaluations/i ); await client.query('ROLLBACK'); } finally { client.release(); } expect(await countRows(f.pool, 'vault_evaluations')).toBe(0); }); test('agent principal accepts UUID versions 1-8 with RFC variants and rejects other versions and variants', async () => { const f = await createIsolatedFixture(); for (const ok of [ 'agent:11111111-2222-1333-8444-555555555555', 'agent:11111111-2222-7333-9444-555555555555', 'agent:11111111-2222-8333-a444-555555555555', 'agent:11111111-2222-4333-b444-555555555555', ]) { await insertTrial(f.pool, { principalId: ok }); } for (const bad of [ 'agent:11111111-2222-0333-8444-555555555555', 'agent:11111111-2222-9333-8444-555555555555', 'agent:11111111-2222-4333-c444-555555555555', 'agent:11111111-2222-4333-7444-555555555555', 'agent:111111112222433384445555555555555', 'agent:', ]) { await expectPgErrorCode(insertTrial(f.pool, { principalId: bad }), '23514'); } expect(await countRows(f.pool, 'trial_ledger')).toBe(4); }); test('trial_ledger keeps daily_series values exactly as REAL and stores created_at from the server clock', async () => { const f = await createIsolatedFixture(); const row = ( await f.pool.query( `INSERT INTO trial_ledger (principal_id, stage, universe_market, horizon_bucket, expression_hash, sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series) VALUES ('operator', 'screen', 'FX', 'intraday', $1, '2021-01-04', '2021-01-05', 2, 0, 0, 3, ARRAY[0.5::real, -0.25::real, 0::real]) RETURNING daily_series::text AS series, created_at = transaction_timestamp() AS server_ts`, [VALID_HASH] ) ).rows[0]; expect(row.series).toBe('{0.5,-0.25,0}'); expect(row.server_ts).toBe(true); }); } ); describe.skipIf(!url)( 'trial_ledger and vault_evaluations PostgreSQL schema (QA round 3 edge cases)', () => { test('the statement-level AFTER INSERT check alone rejects an 11-row batch when the row trigger is off', async () => { const f = await createIsolatedFixture(); const client = await f.pool.connect(); try { // Isolates verify_vault_evaluation_cap_after(): with the BEFORE row trigger disabled, only the // AFTER statement trigger can stop the batch. evaluated_at defaults to now(), so all 11 count. await client.query('BEGIN'); await client.query('ALTER TABLE vault_evaluations DISABLE TRIGGER vault_evaluations_cap'); await expectPgErrorCode( client.query( `INSERT INTO vault_evaluations (${VAULT_COLUMNS_SQL}) SELECT ${VAULT_VALUES_SQL} FROM generate_series(1, 11)` ), '23514', /at most 10 evaluations/i ); await client.query('ROLLBACK'); } finally { client.release(); } expect(await countRows(f.pool, 'vault_evaluations')).toBe(0); }); test('failed burns (passed = false, negative Sharpe, NULL notes) still count toward the yearly cap', async () => { const f = await createIsolatedFixture(); for (let i = 1; i <= 10; i++) { await insertVaultEvaluation(f.pool, { strategyRef: `strat:failed-${i}`, passed: false, sharpePostCost: -1.25, notes: null, }); } const stored = ( await f.pool.query( `SELECT count(*)::int AS c, bool_or(passed) AS any_passed, max(sharpe_post_cost) AS max_sharpe, count(notes)::int AS with_notes FROM vault_evaluations` ) ).rows[0]; expect(stored).toEqual({ c: 10, any_passed: false, max_sharpe: -1.25, with_notes: 0 }); await expectPgErrorCode( insertVaultEvaluation(f.pool, { strategyRef: 'strat:after-failures' }), '23514', /at most 10 evaluations/i ); expect(await countRows(f.pool, 'vault_evaluations')).toBe(10); }); test('trial_ledger keeps every repeated trial: duplicate expression_hash rows, negative and extreme finite stats', async () => { const f = await createIsolatedFixture(); // N-hat counting needs every attempt recorded, so there must be no uniqueness on the hash. for (let i = 0; i < 3; i++) { await insertTrial(f.pool); } await insertTrial(f.pool, { sharpeUnann: -0.5, skewness: '-1.7976931348623157e308', kurtosis: '1.7976931348623157e308', dailySeries: ['3.4e38', '-3.4e38'], }); const hashes = ( await f.pool.query( `SELECT expression_hash, count(*)::int AS c FROM trial_ledger GROUP BY expression_hash` ) ).rows; expect(hashes).toEqual([{ expression_hash: VALID_HASH, c: 4 }]); }); test('MERGE cannot update or delete retained trial_ledger and vault_evaluations rows', async () => { const f = await createIsolatedFixture(); const version = Number( (await f.pool.query('SHOW server_version_num')).rows[0].server_version_num ); await insertTrial(f.pool); await insertVaultEvaluation(f.pool); if (version < 150000) { // MERGE does not exist before PostgreSQL 15, so it is not a mutation path there. await expectPgErrorCode( f.pool.query( 'MERGE INTO trial_ledger t USING (SELECT 1) s ON true WHEN MATCHED THEN DELETE' ), '42601' ); return; } const expectedMsg = /Retained research evidence cannot be rewritten or deleted/; for (const table of ['trial_ledger', 'vault_evaluations']) { await expectPgErrorCode( f.pool.query(`MERGE INTO ${table} t USING (SELECT 1) s ON true WHEN MATCHED THEN DELETE`), '23514', expectedMsg ); await expectPgErrorCode( f.pool.query( `MERGE INTO ${table} t USING (SELECT 1) s ON true WHEN MATCHED THEN UPDATE SET n_obs = 999` ), '23514', expectedMsg ); } expect( (await f.pool.query('SELECT n_obs FROM trial_ledger')).rows.map(r => r.n_obs as number) ).toEqual([252]); expect( (await f.pool.query('SELECT n_obs FROM vault_evaluations')).rows.map(r => r.n_obs as number) ).toEqual([126]); }); test('a writable CTE cannot delete trial_ledger rows', async () => { const f = await createIsolatedFixture(); await insertTrial(f.pool); await expectPgErrorCode( f.pool.query( 'WITH gone AS (DELETE FROM trial_ledger RETURNING trial_id) SELECT count(*) FROM gone' ), '23514', /Retained research evidence/ ); expect(await countRows(f.pool, 'trial_ledger')).toBe(1); }); } );