stock-bot/test/postgres/trial-ledger-schema.test.ts

521 lines
19 KiB
TypeScript

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);
});
});