diff --git a/database/postgres/init/36-trial-ledger.sql b/database/postgres/init/36-trial-ledger.sql index 2648b9dd..d87abb18 100644 --- a/database/postgres/init/36-trial-ledger.sql +++ b/database/postgres/init/36-trial-ledger.sql @@ -71,14 +71,20 @@ LANGUAGE plpgsql AS $$ DECLARE recent_count BIGINT; BEGIN + IF current_setting('transaction_isolation') NOT IN ('read committed', 'read uncommitted') THEN + RAISE EXCEPTION 'Vault evaluations must be inserted under READ COMMITTED isolation (got %)', + current_setting('transaction_isolation') + USING ERRCODE = '25000'; + END IF; PERFORM pg_advisory_xact_lock( hashtext('stock_bot_vault_evaluations_cap'), hashtext(TG_TABLE_SCHEMA) ); NEW.evaluated_at := now(); - SELECT count(*) INTO recent_count - FROM vault_evaluations - WHERE evaluated_at > now() - interval '1 year'; + EXECUTE format( + 'SELECT count(*) FROM %s WHERE evaluated_at > now() - interval ''1 year''', + TG_RELID::regclass + ) INTO recent_count; IF recent_count >= 10 THEN RAISE EXCEPTION 'Vault evaluation cap exceeded: at most 10 evaluations are permitted per rolling year' USING ERRCODE = '23514'; @@ -96,9 +102,10 @@ LANGUAGE plpgsql AS $$ DECLARE recent_count BIGINT; BEGIN - SELECT count(*) INTO recent_count - FROM vault_evaluations - WHERE evaluated_at > now() - interval '1 year'; + EXECUTE format( + 'SELECT count(*) FROM %s WHERE evaluated_at > now() - interval ''1 year''', + TG_RELID::regclass + ) INTO recent_count; IF recent_count > 10 THEN RAISE EXCEPTION 'Vault evaluation cap exceeded: at most 10 evaluations are permitted per rolling year' USING ERRCODE = '23514'; diff --git a/design/VALIDATION-AND-RIGOR.md b/design/VALIDATION-AND-RIGOR.md index b5831963..b2266cac 100644 --- a/design/VALIDATION-AND-RIGOR.md +++ b/design/VALIDATION-AND-RIGOR.md @@ -88,7 +88,7 @@ Computed on any synchronous screen/experiment return matrix $M \in \mathbb{R}^{T ### Vault Evaluations Schema (Append-Only) -Protected against `UPDATE`/`DELETE`/`TRUNCATE` by `reject_research_evidence_mutation()`. A `BEFORE INSERT` trigger forces `evaluated_at := now()` under a schema-scoped transaction advisory lock and rejects inserts once 10 evaluations exist in the rolling 1-year window (`evaluated_at > now() - interval '1 year'`), paired with a statement-level `AFTER INSERT` check so multi-row inserts cannot bypass the cap: +Protected against `UPDATE`/`DELETE`/`TRUNCATE` by `reject_research_evidence_mutation()`. A `BEFORE INSERT` trigger requires `READ COMMITTED` transaction isolation (rejecting `REPEATABLE READ` and `SERIALIZABLE` so a waiting writer cannot evaluate the cap against a stale snapshot), forces `evaluated_at := now()` under a schema-scoped transaction advisory lock, and rejects inserts once 10 evaluations exist in the rolling 1-year window (`evaluated_at > now() - interval '1 year'`) on the target table (`TG_RELID`), paired with a statement-level `AFTER INSERT` check so multi-row inserts cannot bypass the cap: ```sql CREATE TABLE IF NOT EXISTS vault_evaluations ( diff --git a/test/postgres/trial-ledger-contract.test.ts b/test/postgres/trial-ledger-contract.test.ts index a8ab3a69..55b7c197 100644 --- a/test/postgres/trial-ledger-contract.test.ts +++ b/test/postgres/trial-ledger-contract.test.ts @@ -175,9 +175,15 @@ describe('36-trial-ledger.sql static contract', () => { // Rolling-year cap functions & triggers expect(sql).toContain('CREATE OR REPLACE FUNCTION enforce_vault_evaluation_cap()'); + expect(sql).toContain( + "current_setting('transaction_isolation') NOT IN ('read committed', 'read uncommitted')" + ); + expect(sql).toContain("USING ERRCODE = '25000'"); expect(sql).toContain('pg_advisory_xact_lock'); expect(sql).toContain('NEW.evaluated_at := now();'); - expect(sql).toContain("evaluated_at > now() - interval '1 year'"); + expect(sql).toContain("evaluated_at > now() - interval ''1 year''"); + expect(sql).toContain('TG_RELID::regclass'); + expect(sql).not.toContain('FROM vault_evaluations'); expect(sql).toContain('IF recent_count >= 10 THEN'); expect(sql).toContain('DROP TRIGGER IF EXISTS vault_evaluations_cap ON vault_evaluations;'); expect(sql).toContain( @@ -186,6 +192,7 @@ describe('36-trial-ledger.sql static contract', () => { expect(sql).toContain('CREATE OR REPLACE FUNCTION verify_vault_evaluation_cap_after()'); expect(sql).toContain('IF recent_count > 10 THEN'); + expect(sql.match(/TG_RELID::regclass/g)?.length).toBe(2); expect(sql).toContain( 'DROP TRIGGER IF EXISTS vault_evaluations_cap_after ON vault_evaluations;' ); diff --git a/test/postgres/trial-ledger-schema.test.ts b/test/postgres/trial-ledger-schema.test.ts index eb808e9f..2fd79519 100644 --- a/test/postgres/trial-ledger-schema.test.ts +++ b/test/postgres/trial-ledger-schema.test.ts @@ -411,22 +411,19 @@ describe.skipIf(!url)('trial_ledger and vault_evaluations PostgreSQL schema', () 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 now() + // 1. Back-dated evaluated_at is overwritten to transaction_timestamp() in the same transaction const backdated = ( - await insertVaultEvaluation(f.pool, { - evaluatedAt: '2020-01-01T00:00:00Z', - strategyRef: 'strat:burn-1', - }) + 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]; - const nowDiffSec = Number( - ( - await f.pool.query( - 'SELECT abs(extract(epoch FROM (now() - $1::timestamptz))) AS diff_sec', - [backdated.evaluated_at] - ) - ).rows[0].diff_sec - ); - expect(nowDiffSec).toBeLessThan(30); + 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++) { @@ -518,4 +515,126 @@ describe.skipIf(!url)('trial_ledger and vault_evaluations PostgreSQL schema', () (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); + }); });