235 lines
9.7 KiB
TypeScript
235 lines
9.7 KiB
TypeScript
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(32) 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('every VARCHAR(N) column fits all literals in its IN (...) CHECK constraint', () => {
|
|
const sql = stripComments(readSql());
|
|
const matches = [
|
|
...sql.matchAll(/(\w+)\s+VARCHAR\((\d+)\)\s+NOT NULL\s+CHECK\s*\(\1\s+IN\s*\(([^)]+)\)\)/g),
|
|
];
|
|
expect(matches.length).toBeGreaterThanOrEqual(3);
|
|
for (const [, col, maxLenStr, valuesList] of matches) {
|
|
const maxLen = Number(maxLenStr);
|
|
const literals = [...valuesList!.matchAll(/'([^']+)'/g)].map(m => m[1]!);
|
|
expect(literals.length).toBeGreaterThan(0);
|
|
for (const literal of literals) {
|
|
expect(
|
|
literal.length,
|
|
`${col} VARCHAR(${maxLen}) must fit enum value '${literal}' (length ${literal.length})`
|
|
).toBeLessThanOrEqual(maxLen);
|
|
}
|
|
}
|
|
});
|
|
|
|
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(
|
|
"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('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(
|
|
'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.match(/TG_RELID::regclass/g)?.length).toBe(2);
|
|
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')
|
|
);
|
|
});
|
|
});
|