diff --git a/test/postgres/trial-ledger-schema.test.ts b/test/postgres/trial-ledger-schema.test.ts index 2fd79519..0f34c03d 100644 --- a/test/postgres/trial-ledger-schema.test.ts +++ b/test/postgres/trial-ledger-schema.test.ts @@ -397,10 +397,7 @@ describe.skipIf(!url)('trial_ledger and vault_evaluations PostgreSQL schema', () ); await expectPgErrorCode(insertVaultEvaluation(f.pool, { nObs: 1 }), '23514'); for (const badFloat of ['NaN', 'Infinity', '-Infinity']) { - await expectPgErrorCode( - insertVaultEvaluation(f.pool, { sharpePostCost: badFloat }), - '23514' - ); + 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( @@ -638,3 +635,274 @@ describe.skipIf(!url)('trial_ledger and vault_evaluations PostgreSQL schema', () ).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); + }); + } +);