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

This commit is contained in:
Studio 2026-11-27 16:45:16 -05:00 • committed by Boki
parent 2ea7316af6
commit 5025286e49
8 changed files with 920 additions and 11 deletions

View file

@ -77,6 +77,7 @@ const RESEARCH_FILES = [
'31-research-agent-project-links.sql',
'32-candidate-parameter-defaults.sql',
'33-candidate-decimal-normalization.sql',
'36-trial-ledger.sql',
];
const cleanup: (() => Promise<void> | void)[] = [];
@ -137,13 +138,13 @@ async function createIsolatedFixture() {
}
describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
test('Case A: init SQL 01-35 contain no CREATE DATABASE/\\c and create all master and research tables', async () => {
test('Case A: init SQL 01-36 contain no CREATE DATABASE/\\c and create all master and research tables', async () => {
const f = await createIsolatedFixture();
const sqlFiles = readdirSync(initDir)
.filter(file => file.endsWith('.sql'))
.sort();
expect(sqlFiles.length).toBeGreaterThanOrEqual(35);
expect(sqlFiles.length).toBeGreaterThanOrEqual(36);
for (const file of sqlFiles) {
const sql = readFileSync(join(initDir, file), 'utf8');
@ -158,7 +159,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
...LEGACY_MASTER_TABLES,
// Security master tables (34)
...SECURITY_MASTER_TABLES,
// Research tables (06-33, including representatives from 12, 16, 20, 22, 28, 30)
// Research tables (06-33, 36, including representatives from 12, 16, 20, 22, 28, 30, 36)
'backtests',
'backtest_results',
'runs',
@ -168,6 +169,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
'research_experiments',
'research_agents',
'paper_deployments',
'trial_ledger',
'vault_evaluations',
]) {
expect(createdTables.has(expectedTable)).toBe(true);
}
@ -188,6 +191,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
for (const table of [...LEGACY_MASTER_TABLES, ...SECURITY_MASTER_TABLES]) {
expect(createdTables.has(table)).toBe(true);
}
expect(createdTables.has('trial_ledger')).toBe(false);
expect(createdTables.has('vault_evaluations')).toBe(false);
expect(await f.hasColumn('exchanges', 'visible')).toBe(true);
const second = await runPostgresMigrations(f.postgres, { track: 'master' });
@ -195,7 +200,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
expect(await f.recorded()).toEqual(MASTER_FILES);
});
test('Case C: all track with 06-08 pre-applied records master + 09-33 and never records 06-08', async () => {
test('Case C: all track with 06-08 pre-applied records master + research (including 36) and never records 06-08', async () => {
const f = await createIsolatedFixture();
for (const file of BOOTSTRAP_FILES) {
@ -216,6 +221,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
for (const table of [...LEGACY_MASTER_TABLES, ...SECURITY_MASTER_TABLES]) {
expect(createdTables.has(table)).toBe(true);
}
expect(createdTables.has('trial_ledger')).toBe(true);
expect(createdTables.has('vault_evaluations')).toBe(true);
const second = await runPostgresMigrations(f.postgres, { track: 'all' });
expect(second).toEqual([]);

View file

@ -36,6 +36,7 @@ const migrations = [
'31-research-agent-project-links.sql',
'32-candidate-parameter-defaults.sql',
'33-candidate-decimal-normalization.sql',
'36-trial-ledger.sql',
];
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
@ -382,25 +383,30 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
'golden_field_audit',
];
// 1. research track must NOT apply 34-security-master.sql or 35-security-master-exchange-seed.sql;
// master track applies both in order and is idempotent on re-run.
// 1. research track must NOT apply 34-security-master.sql or 35-security-master-exchange-seed.sql,
// and MUST apply 36-trial-ledger.sql; master track applies 34-35 (not 36) and is idempotent on re-run.
const f1 = await fixture();
const runner1 = f1.startup();
const researchApplied = await runner1.runTrack('research');
expect(researchApplied).not.toContain('34-security-master.sql');
expect(researchApplied).not.toContain('35-security-master-exchange-seed.sql');
expect(researchApplied).toContain('36-trial-ledger.sql');
const recordedAfterResearch = await f1.recorded();
expect(recordedAfterResearch).not.toContain('34-security-master.sql');
expect(recordedAfterResearch).not.toContain('35-security-master-exchange-seed.sql');
expect(recordedAfterResearch).toContain('36-trial-ledger.sql');
const tablesAfterResearch = new Set(await f1.relations());
for (const table of securityMasterTables) {
expect(tablesAfterResearch.has(table)).toBe(false);
}
expect(tablesAfterResearch.has('trial_ledger')).toBe(true);
expect(tablesAfterResearch.has('vault_evaluations')).toBe(true);
const masterApplied = await runner1.runTrack('master');
expect(masterApplied).toContain('34-security-master.sql');
expect(masterApplied).toContain('35-security-master-exchange-seed.sql');
expect(masterApplied).not.toContain('36-trial-ledger.sql');
expect(masterApplied.indexOf('35-security-master-exchange-seed.sql')).toBe(
masterApplied.indexOf('34-security-master.sql') + 1
);
@ -415,7 +421,7 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
expect(await runner1.runTrack('master')).toEqual([]);
// 2. all track applies 34 and 35 alongside 01-05 and 09-33 and is idempotent.
// 2. all track applies 34, 35, and 36 alongside 01-05 and 09-33 and is idempotent.
const f2 = await fixture();
const runner2 = f2.startup();
const allApplied = await runner2.runTrack('all');
@ -425,14 +431,18 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
expect(allApplied).toContain('33-candidate-decimal-normalization.sql');
expect(allApplied).toContain('34-security-master.sql');
expect(allApplied).toContain('35-security-master-exchange-seed.sql');
expect(allApplied).toContain('36-trial-ledger.sql');
const recordedAfterAll = await f2.recorded();
expect(recordedAfterAll).toContain('34-security-master.sql');
expect(recordedAfterAll).toContain('35-security-master-exchange-seed.sql');
expect(recordedAfterAll).toContain('36-trial-ledger.sql');
const tablesAfterAll = new Set(await f2.relations());
for (const table of securityMasterTables) {
expect(tablesAfterAll.has(table)).toBe(true);
}
expect(tablesAfterAll.has('trial_ledger')).toBe(true);
expect(tablesAfterAll.has('vault_evaluations')).toBe(true);
expect(await runner2.runTrack('all')).toEqual([]);
});

View file

@ -274,11 +274,12 @@ describe('34-security-master.sql track registration', () => {
expect(await runPostgresMigrations(postgres as never)).toEqual(research);
});
test('all track runs 34-security-master.sql and 35-security-master-exchange-seed.sql last, after research 09-33, and skips 06-08', async () => {
test('all track runs 33, 34, 35, 36 last in exact order and skips 06-08', async () => {
const all = await filesForTrack('all');
expect(all.at(-2)).toBe('34-security-master.sql');
expect(all.at(-1)).toBe('35-security-master-exchange-seed.sql');
expect(all.indexOf('33-candidate-decimal-normalization.sql')).toBe(all.length - 3);
expect(all.at(-4)).toBe('33-candidate-decimal-normalization.sql');
expect(all.at(-3)).toBe('34-security-master.sql');
expect(all.at(-2)).toBe('35-security-master-exchange-seed.sql');
expect(all.at(-1)).toBe('36-trial-ledger.sql');
for (const bootstrap of [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',

View file

@ -0,0 +1,209 @@
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'bun:test';
import { setLoggerConfig } from '@stock-bot/logger';
import { runPostgresMigrations, type MigrationTrack } from '@stock-bot/postgres';
// Static contract checks for 36-trial-ledger.sql. These need no database, so they run in the
// sandbox as well as in Studio's unsandboxed run.
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
const sqlPath = `${initDir}36-trial-ledger.sql`;
const docPath = fileURLToPath(new URL('../../design/VALIDATION-AND-RIGOR.md', import.meta.url));
const FROZEN_TRIAL_LEDGER_COLUMNS = [
'trial_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY',
'created_at TIMESTAMPTZ NOT NULL DEFAULT now()',
'principal_id TEXT NOT NULL',
'campaign_id UUID',
'stage VARCHAR(16) NOT NULL',
'universe_market VARCHAR(12) NOT NULL',
'horizon_bucket VARCHAR(16) NOT NULL',
'hypothesis_id UUID',
'expression_hash CHAR(64) NOT NULL',
'sample_start DATE NOT NULL',
'sample_end DATE NOT NULL',
'n_obs INTEGER NOT NULL',
'sharpe_unann DOUBLE PRECISION NOT NULL',
'skewness DOUBLE PRECISION NOT NULL',
'kurtosis DOUBLE PRECISION NOT NULL',
'daily_series REAL[] NOT NULL',
];
const FROZEN_VAULT_EVALUATIONS_COLUMNS = [
'evaluation_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY',
'evaluated_at TIMESTAMPTZ NOT NULL DEFAULT now()',
'principal_id TEXT NOT NULL',
'strategy_ref TEXT NOT NULL',
'expression_hash CHAR(64) NOT NULL',
'vault_cutoff_date DATE NOT NULL',
'vault_start DATE NOT NULL',
'vault_end DATE NOT NULL',
'n_obs INTEGER NOT NULL',
'sharpe_post_cost DOUBLE PRECISION NOT NULL',
'passed BOOLEAN NOT NULL',
'notes TEXT',
];
const readSql = () => readFileSync(sqlPath, 'utf8');
const readDoc = () => readFileSync(docPath, 'utf8');
function stripComments(sql: string): string {
return sql
.split('\n')
.map(line => line.replace(/--.*$/, '').trimEnd())
.join('\n');
}
function tableDefinitionLines(sql: string, table: string): string[] {
const match = new RegExp(`CREATE TABLE IF NOT EXISTS ${table} \\(\\n([\\s\\S]*?)\\n\\);`).exec(
stripComments(sql)
);
if (!match?.[1]) {
throw new Error(`CREATE TABLE ${table} not found`);
}
return match[1]
.split('\n')
.map(line => line.trim().replace(/,$/, '').replace(/\s+/g, ' '))
.filter(line => line.length > 0 && !line.startsWith('CHECK ('));
}
function extractDocSqlBlock(table: string): string {
const doc = readDoc();
const tableStart = doc.indexOf(`CREATE TABLE IF NOT EXISTS ${table} (`);
expect(tableStart).toBeGreaterThan(-1);
const fenceStart = doc.lastIndexOf('```sql', tableStart);
const fenceEnd = doc.indexOf('```', tableStart);
return doc.slice(fenceStart + '```sql'.length, fenceEnd).trim();
}
function recordingClient() {
const ran: string[] = [];
const postgres = {
transaction: async <T>(
callback: (client: { query: (sql: string, values?: unknown[]) => unknown }) => Promise<T>
) =>
callback({
query: async (sql: string) => {
ran.push(sql);
return { rows: [] };
},
}),
};
return { postgres, ran };
}
async function filesForTrack(track: MigrationTrack): Promise<string[]> {
const { postgres } = recordingClient();
return runPostgresMigrations(postgres as never, { track });
}
describe('36-trial-ledger.sql static contract', () => {
test('creates exactly trial_ledger and vault_evaluations with IF NOT EXISTS', () => {
const sql = stripComments(readSql());
const created = [...sql.matchAll(/CREATE TABLE\s+(IF NOT EXISTS\s+)?("?[\w.]+"?)/g)];
expect(created.map(m => m[2])).toEqual(['trial_ledger', 'vault_evaluations']);
expect(created.every(m => m[1] !== undefined)).toBe(true);
});
test('creates the 3 lookup indexes with IF NOT EXISTS on the expected columns', () => {
const sql = stripComments(readSql()).replace(/\s+/g, ' ');
const indexes = [...sql.matchAll(/CREATE INDEX (IF NOT EXISTS )?(\w+) ON ([^;]+);/g)];
expect(indexes.every(m => m[1] !== undefined)).toBe(true);
expect(Object.fromEntries(indexes.map(m => [m[2], m[3]!.trim()]))).toEqual({
idx_trial_ledger_cluster: 'trial_ledger (universe_market, horizon_bucket, created_at)',
idx_trial_ledger_expression_hash: 'trial_ledger (expression_hash)',
idx_vault_evaluations_evaluated_at: 'vault_evaluations (evaluated_at)',
});
});
test('contains no CREATE DATABASE, \\c, schema qualifiers, or SET search_path', () => {
const sql = stripComments(readSql());
expect(sql).not.toMatch(/CREATE\s+DATABASE/i);
expect(sql).not.toMatch(/^\s*\\c\b/m);
expect(sql).not.toMatch(/\b(?:TABLE|EXISTS|REFERENCES|ON|FROM)\s+"?\w+"?\."?\w+/i);
expect(sql).not.toMatch(/\bSET\s+search_path\b/i);
});
test('trial_ledger columns match frozen spec and design/VALIDATION-AND-RIGOR.md §2A', () => {
const migrationCols = tableDefinitionLines(readSql(), 'trial_ledger');
const docCols = tableDefinitionLines(extractDocSqlBlock('trial_ledger'), 'trial_ledger');
expect(migrationCols).toEqual(FROZEN_TRIAL_LEDGER_COLUMNS);
expect(migrationCols).toEqual(docCols);
});
test('vault_evaluations columns match frozen spec and design/VALIDATION-AND-RIGOR.md §3', () => {
const migrationSql = readSql();
const docBlock = extractDocSqlBlock('vault_evaluations');
const migrationCols = tableDefinitionLines(migrationSql, 'vault_evaluations');
const docCols = tableDefinitionLines(docBlock, 'vault_evaluations');
expect(migrationCols).toEqual(FROZEN_VAULT_EVALUATIONS_COLUMNS);
expect(migrationCols).toEqual(docCols);
const migrationTableBlock =
/CREATE TABLE IF NOT EXISTS vault_evaluations \([\s\S]*?\n\);/.exec(migrationSql)?.[0];
expect(migrationTableBlock).toBe(docBlock);
});
test('documents dynamic VAULT_CUTOFF_DATE enforcement in a SQL comment', () => {
expect(readSql()).toMatch(/sample_end.*VAULT_CUTOFF_DATE/);
});
test('defines idempotent immutability and rolling-year vault cap triggers', () => {
const sql = stripComments(readSql()).replace(/\s+/g, ' ');
// Rolling-year cap functions & triggers
expect(sql).toContain('CREATE OR REPLACE FUNCTION enforce_vault_evaluation_cap()');
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('IF recent_count >= 10 THEN');
expect(sql).toContain('DROP TRIGGER IF EXISTS vault_evaluations_cap ON vault_evaluations;');
expect(sql).toContain(
'CREATE TRIGGER vault_evaluations_cap BEFORE INSERT ON vault_evaluations FOR EACH ROW EXECUTE FUNCTION enforce_vault_evaluation_cap();'
);
expect(sql).toContain('CREATE OR REPLACE FUNCTION verify_vault_evaluation_cap_after()');
expect(sql).toContain('IF recent_count > 10 THEN');
expect(sql).toContain(
'DROP TRIGGER IF EXISTS vault_evaluations_cap_after ON vault_evaluations;'
);
expect(sql).toContain(
'CREATE TRIGGER vault_evaluations_cap_after AFTER INSERT ON vault_evaluations FOR EACH STATEMENT EXECUTE FUNCTION verify_vault_evaluation_cap_after();'
);
// Append-only immutability triggers on both tables
for (const table of ['trial_ledger', 'vault_evaluations']) {
expect(sql).toContain(`DROP TRIGGER IF EXISTS ${table}_retained ON ${table};`);
expect(sql).toContain(
`CREATE TRIGGER ${table}_retained BEFORE UPDATE OR DELETE ON ${table} FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();`
);
expect(sql).toContain(`DROP TRIGGER IF EXISTS ${table}_no_truncate ON ${table};`);
expect(sql).toContain(
`CREATE TRIGGER ${table}_no_truncate BEFORE TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();`
);
}
});
});
describe('36-trial-ledger.sql track registration', () => {
test('is registered on research and all tracks after 17-research-retention.sql, and absent from master', async () => {
const research = await filesForTrack('research');
const all = await filesForTrack('all');
const master = await filesForTrack('master');
expect(master).not.toContain('36-trial-ledger.sql');
expect(research).toContain('36-trial-ledger.sql');
expect(research.indexOf('36-trial-ledger.sql')).toBeGreaterThan(
research.indexOf('17-research-retention.sql')
);
expect(all).toContain('36-trial-ledger.sql');
expect(all.indexOf('36-trial-ledger.sql')).toBeGreaterThan(
all.indexOf('17-research-retention.sql')
);
});
});

View file

@ -0,0 +1,521 @@
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> | 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<unknown>,
expectedCode: string,
messagePattern?: RegExp
): Promise<void> {
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<boolean>): Promise<void> {
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 now()
const backdated = (
await insertVaultEvaluation(f.pool, {
evaluatedAt: '2020-01-01T00:00:00Z',
strategyRef: 'strat:burn-1',
})
).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);
// 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);
});
});