T-57: M1.3b — trial_ledger + vault_evaluations append-only PostgreSQL migration (research track)

This commit is contained in:
Studio 2026-11-27 17:08:47 -05:00 • committed by Boki
parent ed56ec1bbf
commit bb6e91ef53
4 changed files with 155 additions and 22 deletions

View file

@ -71,14 +71,20 @@ LANGUAGE plpgsql AS $$
DECLARE DECLARE
recent_count BIGINT; recent_count BIGINT;
BEGIN 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( PERFORM pg_advisory_xact_lock(
hashtext('stock_bot_vault_evaluations_cap'), hashtext('stock_bot_vault_evaluations_cap'),
hashtext(TG_TABLE_SCHEMA) hashtext(TG_TABLE_SCHEMA)
); );
NEW.evaluated_at := now(); NEW.evaluated_at := now();
SELECT count(*) INTO recent_count EXECUTE format(
FROM vault_evaluations 'SELECT count(*) FROM %s WHERE evaluated_at > now() - interval ''1 year''',
WHERE evaluated_at > now() - interval '1 year'; TG_RELID::regclass
) INTO recent_count;
IF recent_count >= 10 THEN IF recent_count >= 10 THEN
RAISE EXCEPTION 'Vault evaluation cap exceeded: at most 10 evaluations are permitted per rolling year' RAISE EXCEPTION 'Vault evaluation cap exceeded: at most 10 evaluations are permitted per rolling year'
USING ERRCODE = '23514'; USING ERRCODE = '23514';
@ -96,9 +102,10 @@ LANGUAGE plpgsql AS $$
DECLARE DECLARE
recent_count BIGINT; recent_count BIGINT;
BEGIN BEGIN
SELECT count(*) INTO recent_count EXECUTE format(
FROM vault_evaluations 'SELECT count(*) FROM %s WHERE evaluated_at > now() - interval ''1 year''',
WHERE evaluated_at > now() - interval '1 year'; TG_RELID::regclass
) INTO recent_count;
IF recent_count > 10 THEN IF recent_count > 10 THEN
RAISE EXCEPTION 'Vault evaluation cap exceeded: at most 10 evaluations are permitted per rolling year' RAISE EXCEPTION 'Vault evaluation cap exceeded: at most 10 evaluations are permitted per rolling year'
USING ERRCODE = '23514'; USING ERRCODE = '23514';

View file

@ -88,7 +88,7 @@ Computed on any synchronous screen/experiment return matrix $M \in \mathbb{R}^{T
### Vault Evaluations Schema (Append-Only) ### 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 ```sql
CREATE TABLE IF NOT EXISTS vault_evaluations ( CREATE TABLE IF NOT EXISTS vault_evaluations (

View file

@ -175,9 +175,15 @@ describe('36-trial-ledger.sql static contract', () => {
// Rolling-year cap functions & triggers // Rolling-year cap functions & triggers
expect(sql).toContain('CREATE OR REPLACE FUNCTION enforce_vault_evaluation_cap()'); 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('pg_advisory_xact_lock');
expect(sql).toContain('NEW.evaluated_at := now();'); 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('IF recent_count >= 10 THEN');
expect(sql).toContain('DROP TRIGGER IF EXISTS vault_evaluations_cap ON vault_evaluations;'); expect(sql).toContain('DROP TRIGGER IF EXISTS vault_evaluations_cap ON vault_evaluations;');
expect(sql).toContain( 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('CREATE OR REPLACE FUNCTION verify_vault_evaluation_cap_after()');
expect(sql).toContain('IF recent_count > 10 THEN'); expect(sql).toContain('IF recent_count > 10 THEN');
expect(sql.match(/TG_RELID::regclass/g)?.length).toBe(2);
expect(sql).toContain( expect(sql).toContain(
'DROP TRIGGER IF EXISTS vault_evaluations_cap_after ON vault_evaluations;' 'DROP TRIGGER IF EXISTS vault_evaluations_cap_after ON vault_evaluations;'
); );

View file

@ -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 () => { test('vault_evaluations enforces <= 10 rolling-year cap, blocks back-dating, multi-row bypass, and concurrent races', async () => {
const f = await createIsolatedFixture(); 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 = ( const backdated = (
await insertVaultEvaluation(f.pool, { await f.pool.query(
evaluatedAt: '2020-01-01T00:00:00Z', `INSERT INTO vault_evaluations (
strategyRef: 'strat:burn-1', 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]; ).rows[0];
const nowDiffSec = Number( expect(backdated.matches_tx_ts).toBe(true);
(
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);
// 2. Insert 8 more rows (total = 9), then race two concurrent 10th-row inserts // 2. Insert 8 more rows (total = 9), then race two concurrent 10th-row inserts
for (let i = 2; i <= 9; i++) { 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 (await f2.pool.query('SELECT count(*)::int AS c FROM vault_evaluations')).rows[0].c
).toBe(0); ).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);
});
}); });