T-151: M2.1i — findings + provider_caveats append-only PostgreSQL migration (research track, 37-research-findings.sql) with fresh-database schema tests (no adapters, no new deps)
This commit is contained in:
parent
34fdfd6bc4
commit
c16d6b3f60
7 changed files with 672 additions and 11 deletions
|
|
@ -78,6 +78,7 @@ const RESEARCH_FILES = [
|
|||
'32-candidate-parameter-defaults.sql',
|
||||
'33-candidate-decimal-normalization.sql',
|
||||
'36-trial-ledger.sql',
|
||||
'37-research-findings.sql',
|
||||
];
|
||||
|
||||
const cleanup: (() => Promise<void> | void)[] = [];
|
||||
|
|
@ -138,13 +139,13 @@ async function createIsolatedFixture() {
|
|||
}
|
||||
|
||||
describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
||||
test('Case A: init SQL 01-36 contain no CREATE DATABASE/\\c and create all master and research tables', async () => {
|
||||
test('Case A: init SQL 01-37 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(36);
|
||||
expect(sqlFiles.length).toBeGreaterThanOrEqual(37);
|
||||
|
||||
for (const file of sqlFiles) {
|
||||
const sql = readFileSync(join(initDir, file), 'utf8');
|
||||
|
|
@ -159,7 +160,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
|||
...LEGACY_MASTER_TABLES,
|
||||
// Security master tables (34)
|
||||
...SECURITY_MASTER_TABLES,
|
||||
// Research tables (06-33, 36, including representatives from 12, 16, 20, 22, 28, 30, 36)
|
||||
// Research tables (06-33, 36-37, including representatives from 12, 16, 20, 22, 28, 30, 36, 37)
|
||||
'backtests',
|
||||
'backtest_results',
|
||||
'runs',
|
||||
|
|
@ -171,6 +172,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
|||
'paper_deployments',
|
||||
'trial_ledger',
|
||||
'vault_evaluations',
|
||||
'findings',
|
||||
'provider_caveats',
|
||||
]) {
|
||||
expect(createdTables.has(expectedTable)).toBe(true);
|
||||
}
|
||||
|
|
@ -193,6 +196,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
|||
}
|
||||
expect(createdTables.has('trial_ledger')).toBe(false);
|
||||
expect(createdTables.has('vault_evaluations')).toBe(false);
|
||||
expect(createdTables.has('findings')).toBe(false);
|
||||
expect(createdTables.has('provider_caveats')).toBe(false);
|
||||
expect(await f.hasColumn('exchanges', 'visible')).toBe(true);
|
||||
|
||||
const second = await runPostgresMigrations(f.postgres, { track: 'master' });
|
||||
|
|
@ -200,7 +205,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 + research (including 36) and never records 06-08', async () => {
|
||||
test('Case C: all track with 06-08 pre-applied records master + research (including 36-37) and never records 06-08', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
for (const file of BOOTSTRAP_FILES) {
|
||||
|
|
@ -223,6 +228,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
|||
}
|
||||
expect(createdTables.has('trial_ledger')).toBe(true);
|
||||
expect(createdTables.has('vault_evaluations')).toBe(true);
|
||||
expect(createdTables.has('findings')).toBe(true);
|
||||
expect(createdTables.has('provider_caveats')).toBe(true);
|
||||
|
||||
const second = await runPostgresMigrations(f.postgres, { track: 'all' });
|
||||
expect(second).toEqual([]);
|
||||
|
|
|
|||
|
|
@ -37,6 +37,7 @@ const migrations = [
|
|||
'32-candidate-parameter-defaults.sql',
|
||||
'33-candidate-decimal-normalization.sql',
|
||||
'36-trial-ledger.sql',
|
||||
'37-research-findings.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
@ -384,17 +385,22 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
|
|||
];
|
||||
|
||||
// 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.
|
||||
// and MUST apply 36-trial-ledger.sql and 37-research-findings.sql; master track applies 34-35 (not 36-37) 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');
|
||||
expect(researchApplied).toContain('37-research-findings.sql');
|
||||
expect(researchApplied.indexOf('37-research-findings.sql')).toBe(
|
||||
researchApplied.indexOf('36-trial-ledger.sql') + 1
|
||||
);
|
||||
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');
|
||||
expect(recordedAfterResearch).toContain('37-research-findings.sql');
|
||||
|
||||
const tablesAfterResearch = new Set(await f1.relations());
|
||||
for (const table of securityMasterTables) {
|
||||
|
|
@ -402,11 +408,14 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
|
|||
}
|
||||
expect(tablesAfterResearch.has('trial_ledger')).toBe(true);
|
||||
expect(tablesAfterResearch.has('vault_evaluations')).toBe(true);
|
||||
expect(tablesAfterResearch.has('findings')).toBe(true);
|
||||
expect(tablesAfterResearch.has('provider_caveats')).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).not.toContain('37-research-findings.sql');
|
||||
expect(masterApplied.indexOf('35-security-master-exchange-seed.sql')).toBe(
|
||||
masterApplied.indexOf('34-security-master.sql') + 1
|
||||
);
|
||||
|
|
@ -421,7 +430,7 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
|
|||
|
||||
expect(await runner1.runTrack('master')).toEqual([]);
|
||||
|
||||
// 2. all track applies 34, 35, and 36 alongside 01-05 and 09-33 and is idempotent.
|
||||
// 2. all track applies 34, 35, 36, and 37 alongside 01-05 and 09-33 and is idempotent.
|
||||
const f2 = await fixture();
|
||||
const runner2 = f2.startup();
|
||||
const allApplied = await runner2.runTrack('all');
|
||||
|
|
@ -432,10 +441,12 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
|
|||
expect(allApplied).toContain('34-security-master.sql');
|
||||
expect(allApplied).toContain('35-security-master-exchange-seed.sql');
|
||||
expect(allApplied).toContain('36-trial-ledger.sql');
|
||||
expect(allApplied).toContain('37-research-findings.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');
|
||||
expect(recordedAfterAll).toContain('37-research-findings.sql');
|
||||
|
||||
const tablesAfterAll = new Set(await f2.relations());
|
||||
for (const table of securityMasterTables) {
|
||||
|
|
@ -443,6 +454,8 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
|
|||
}
|
||||
expect(tablesAfterAll.has('trial_ledger')).toBe(true);
|
||||
expect(tablesAfterAll.has('vault_evaluations')).toBe(true);
|
||||
expect(tablesAfterAll.has('findings')).toBe(true);
|
||||
expect(tablesAfterAll.has('provider_caveats')).toBe(true);
|
||||
|
||||
expect(await runner2.runTrack('all')).toEqual([]);
|
||||
});
|
||||
|
|
|
|||
495
test/postgres/research-findings-schema.test.ts
Normal file
495
test/postgres/research-findings-schema.test.ts
Normal file
|
|
@ -0,0 +1,495 @@
|
|||
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('research-findings-schema-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
|
||||
const researchFindingsSqlPath = `${initDir}37-research-findings.sql`;
|
||||
|
||||
const FIXED_TS = '2026-01-15T12:34:56.789Z';
|
||||
const EXPECTED_IMMUTABLE_MSG = /Retained research evidence cannot be rewritten or deleted/;
|
||||
|
||||
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`);
|
||||
}
|
||||
|
||||
interface FindingInsertOverrides {
|
||||
id?: string;
|
||||
kind?: string;
|
||||
title?: string;
|
||||
summary?: string;
|
||||
status?: string;
|
||||
createdAt?: string;
|
||||
trialRefs?: (string | null)[];
|
||||
evidenceRefs?: (string | null)[];
|
||||
idempotencyKey?: string | null;
|
||||
}
|
||||
|
||||
function insertFinding(pool: Pool, overrides: FindingInsertOverrides = {}) {
|
||||
const id = overrides.id ?? `finding-${randomUUID()}`;
|
||||
const kind = overrides.kind ?? 'finding';
|
||||
const title = overrides.title ?? 'Momentum factor decays after 5 sessions';
|
||||
const summary = overrides.summary ?? 'Cross-sectional rank IC turns negative past day 5.';
|
||||
const createdAt = overrides.createdAt ?? FIXED_TS;
|
||||
const trialRefs = overrides.trialRefs ?? ['101', '102'];
|
||||
const evidenceRefs = overrides.evidenceRefs ?? ['snap:2026-01-15:ic'];
|
||||
const idempotencyKey = overrides.idempotencyKey === undefined ? null : overrides.idempotencyKey;
|
||||
|
||||
if (overrides.status !== undefined) {
|
||||
return pool.query(
|
||||
`INSERT INTO findings (
|
||||
id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key
|
||||
) VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9)
|
||||
RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`,
|
||||
[id, kind, title, summary, overrides.status, createdAt, trialRefs, evidenceRefs, idempotencyKey]
|
||||
);
|
||||
}
|
||||
|
||||
return pool.query(
|
||||
`INSERT INTO findings (
|
||||
id, kind, title, summary, created_at, trial_refs, evidence_refs, idempotency_key
|
||||
) VALUES ($1, $2, $3, $4, $5::timestamptz, $6::text[], $7::text[], $8)
|
||||
RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`,
|
||||
[id, kind, title, summary, createdAt, trialRefs, evidenceRefs, idempotencyKey]
|
||||
);
|
||||
}
|
||||
|
||||
interface ProviderCaveatInsertOverrides {
|
||||
id?: string;
|
||||
provider?: string;
|
||||
dataset?: string;
|
||||
caveat?: string;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
function insertProviderCaveat(pool: Pool, overrides: ProviderCaveatInsertOverrides = {}) {
|
||||
const id = overrides.id ?? `caveat-${randomUUID()}`;
|
||||
const provider = overrides.provider ?? 'EODHD';
|
||||
const dataset = overrides.dataset ?? 'eodIntraday1M';
|
||||
const caveat =
|
||||
overrides.caveat ?? 'Intraday 1m OHLCV is retroactively split-adjusted; un-adjust before use.';
|
||||
|
||||
if (overrides.createdAt !== undefined) {
|
||||
return pool.query(
|
||||
`INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5::timestamptz)
|
||||
RETURNING id, provider, dataset, caveat, created_at`,
|
||||
[id, provider, dataset, caveat, overrides.createdAt]
|
||||
);
|
||||
}
|
||||
|
||||
return pool.query(
|
||||
`INSERT INTO provider_caveats (id, provider, dataset, caveat)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, provider, dataset, caveat, created_at`,
|
||||
[id, provider, dataset, caveat]
|
||||
);
|
||||
}
|
||||
|
||||
interface ProtectionTriggerRow {
|
||||
relname: string;
|
||||
tgname: string;
|
||||
proname: string;
|
||||
tgenabled: string;
|
||||
}
|
||||
|
||||
const EXPECTED_PROTECTION_TRIGGERS: ProtectionTriggerRow[] = [
|
||||
{
|
||||
relname: 'findings',
|
||||
tgname: 'findings_no_truncate',
|
||||
proname: 'reject_research_evidence_mutation',
|
||||
tgenabled: 'O',
|
||||
},
|
||||
{
|
||||
relname: 'findings',
|
||||
tgname: 'findings_retained',
|
||||
proname: 'reject_research_evidence_mutation',
|
||||
tgenabled: 'O',
|
||||
},
|
||||
{
|
||||
relname: 'provider_caveats',
|
||||
tgname: 'provider_caveats_no_truncate',
|
||||
proname: 'reject_research_evidence_mutation',
|
||||
tgenabled: 'O',
|
||||
},
|
||||
{
|
||||
relname: 'provider_caveats',
|
||||
tgname: 'provider_caveats_retained',
|
||||
proname: 'reject_research_evidence_mutation',
|
||||
tgenabled: 'O',
|
||||
},
|
||||
];
|
||||
|
||||
async function listProtectionTriggers(pool: Pool, schema: string): Promise<ProtectionTriggerRow[]> {
|
||||
const result = await pool.query<ProtectionTriggerRow>(
|
||||
`SELECT c.relname, t.tgname, p.proname, t.tgenabled::text AS tgenabled
|
||||
FROM pg_trigger t
|
||||
JOIN pg_class c ON c.oid = t.tgrelid
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
JOIN pg_proc p ON p.oid = t.tgfoid
|
||||
WHERE NOT t.tgisinternal
|
||||
AND n.nspname = $1
|
||||
AND c.relname IN ('findings', 'provider_caveats')
|
||||
ORDER BY c.relname COLLATE "C", t.tgname COLLATE "C"`,
|
||||
[schema]
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => {
|
||||
test('creates tables, indexes, and triggers 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('findings')).toBe(true);
|
||||
expect(tables.has('provider_caveats')).toBe(true);
|
||||
|
||||
const indexDefs = new Map(
|
||||
(
|
||||
await f.pool.query('SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = $1', [
|
||||
f.schema,
|
||||
])
|
||||
).rows.map(row => [row.indexname as string, row.indexdef as string])
|
||||
);
|
||||
expect(indexDefs.get('idx_findings_idempotency_key')).toMatch(
|
||||
/CREATE UNIQUE INDEX idx_findings_idempotency_key ON .*findings .* \(idempotency_key\) WHERE \(idempotency_key IS NOT NULL\)/
|
||||
);
|
||||
expect(indexDefs.get('idx_findings_created_at')).toMatch(
|
||||
/CREATE INDEX idx_findings_created_at ON .*findings .* \(created_at\)/
|
||||
);
|
||||
expect(indexDefs.get('idx_provider_caveats_lower_provider')).toMatch(
|
||||
/CREATE INDEX idx_provider_caveats_lower_provider ON .*provider_caveats .* \(lower\(provider\)\)/
|
||||
);
|
||||
|
||||
expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS);
|
||||
|
||||
const insertedFinding = (
|
||||
await insertFinding(f.pool, { id: 'f-idempotent', idempotencyKey: 'idem-keep' })
|
||||
).rows[0];
|
||||
const insertedCaveat = (
|
||||
await insertProviderCaveat(f.pool, { id: 'c-idempotent', createdAt: FIXED_TS })
|
||||
).rows[0];
|
||||
|
||||
expect(await runPostgresMigrations(f.postgres, { track: 'research' })).toEqual([]);
|
||||
|
||||
const rawSql = readFileSync(researchFindingsSqlPath, 'utf8');
|
||||
await f.pool.query(rawSql);
|
||||
|
||||
expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS);
|
||||
|
||||
const findingsAfter = (await f.pool.query('SELECT * FROM findings')).rows;
|
||||
const caveatsAfter = (await f.pool.query('SELECT * FROM provider_caveats')).rows;
|
||||
expect(findingsAfter).toEqual([insertedFinding]);
|
||||
expect(caveatsAfter).toEqual([insertedCaveat]);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query("UPDATE findings SET title = 'mutated'"),
|
||||
'23514',
|
||||
EXPECTED_IMMUTABLE_MSG
|
||||
);
|
||||
await expectPgErrorCode(f.pool.query('DELETE FROM findings'), '23514', EXPECTED_IMMUTABLE_MSG);
|
||||
await expectPgErrorCode(f.pool.query('TRUNCATE findings'), '23514', EXPECTED_IMMUTABLE_MSG);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query("UPDATE provider_caveats SET caveat = 'mutated'"),
|
||||
'23514',
|
||||
EXPECTED_IMMUTABLE_MSG
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query('DELETE FROM provider_caveats'),
|
||||
'23514',
|
||||
EXPECTED_IMMUTABLE_MSG
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query('TRUNCATE provider_caveats'),
|
||||
'23514',
|
||||
EXPECTED_IMMUTABLE_MSG
|
||||
);
|
||||
|
||||
expect((await f.pool.query('SELECT * FROM findings')).rows).toEqual([insertedFinding]);
|
||||
expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([insertedCaveat]);
|
||||
});
|
||||
|
||||
test('findings round-trips every FiledFindingRecord field, defaults status, and accepts exact limit boundaries', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const first = (
|
||||
await insertFinding(f.pool, {
|
||||
id: 'finding-001',
|
||||
kind: 'finding',
|
||||
title: 'Earnings drift persists through day 3',
|
||||
summary: 'Post-announcement drift remains positive across US large caps.',
|
||||
createdAt: FIXED_TS,
|
||||
trialRefs: ['42', '43'],
|
||||
evidenceRefs: ['artifact:drift-v1'],
|
||||
idempotencyKey: 'req-001',
|
||||
})
|
||||
).rows[0];
|
||||
|
||||
expect(first.id).toBe('finding-001');
|
||||
expect(first.kind).toBe('finding');
|
||||
expect(first.title).toBe('Earnings drift persists through day 3');
|
||||
expect(first.summary).toBe('Post-announcement drift remains positive across US large caps.');
|
||||
expect(first.status).toBe('pending_review');
|
||||
expect((first.created_at as Date).toISOString()).toBe(FIXED_TS);
|
||||
expect(first.trial_refs).toEqual(['42', '43']);
|
||||
expect(first.evidence_refs).toEqual(['artifact:drift-v1']);
|
||||
expect(first.idempotency_key).toBe('req-001');
|
||||
|
||||
// Second row exercises dead_end, empty evidence_refs, and exact boundary lengths/cardinalities.
|
||||
const maxRefs = Array.from({ length: 32 }, (_, i) => `${i}`.padStart(256, 'r'));
|
||||
const boundary = (
|
||||
await insertFinding(f.pool, {
|
||||
id: 'finding-002',
|
||||
kind: 'dead_end',
|
||||
title: ` ${'t'.repeat(256)} `,
|
||||
summary: 's'.repeat(4096),
|
||||
createdAt: '2026-02-01T00:00:00.000Z',
|
||||
trialRefs: maxRefs,
|
||||
evidenceRefs: [],
|
||||
idempotencyKey: 'k'.repeat(128),
|
||||
})
|
||||
).rows[0];
|
||||
|
||||
expect(boundary.kind).toBe('dead_end');
|
||||
expect(boundary.status).toBe('pending_review');
|
||||
expect((boundary.created_at as Date).toISOString()).toBe('2026-02-01T00:00:00.000Z');
|
||||
expect(boundary.trial_refs).toEqual(maxRefs);
|
||||
expect(boundary.evidence_refs).toEqual([]);
|
||||
expect(boundary.idempotency_key).toBe('k'.repeat(128));
|
||||
|
||||
// 32 evidence_refs at 256 chars and 1-char idempotency key also succeed.
|
||||
const maxEvidence = (
|
||||
await insertFinding(f.pool, {
|
||||
id: 'finding-003',
|
||||
trialRefs: [],
|
||||
evidenceRefs: maxRefs,
|
||||
idempotencyKey: 'x',
|
||||
})
|
||||
).rows[0];
|
||||
expect(maxEvidence.trial_refs).toEqual([]);
|
||||
expect(maxEvidence.evidence_refs).toEqual(maxRefs);
|
||||
expect(maxEvidence.idempotency_key).toBe('x');
|
||||
});
|
||||
|
||||
test('findings rejects invalid kind, blank or oversized fields, malformed ref arrays, and invalid idempotency keys', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
// Blank / whitespace-only id and status
|
||||
await expectPgErrorCode(insertFinding(f.pool, { id: '' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { id: ' \t\n ' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { status: '' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { status: ' \t\r\n ' }), '23514');
|
||||
|
||||
// Invalid kind
|
||||
await expectPgErrorCode(insertFinding(f.pool, { kind: 'hypothesis' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { kind: 'FINDING' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { kind: '' }), '23514');
|
||||
|
||||
// Blank, whitespace-only, or oversized title / summary
|
||||
await expectPgErrorCode(insertFinding(f.pool, { title: '' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { title: ' \t\n\r ' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { title: 't'.repeat(257) }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { summary: '' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { summary: ' \t\n\r ' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { summary: 's'.repeat(4097) }), '23514');
|
||||
|
||||
// Cardinality > 32
|
||||
const refs33 = Array.from({ length: 33 }, (_, i) => `ref-${i}`);
|
||||
await expectPgErrorCode(insertFinding(f.pool, { trialRefs: refs33 }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: refs33 }), '23514');
|
||||
|
||||
// Ref length > 256
|
||||
const ref257 = 'r'.repeat(257);
|
||||
await expectPgErrorCode(insertFinding(f.pool, { trialRefs: [ref257] }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: ['ok', ref257] }), '23514');
|
||||
|
||||
// NULL array elements
|
||||
await expectPgErrorCode(insertFinding(f.pool, { trialRefs: ['101', null] }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: [null] }), '23514');
|
||||
|
||||
// Multidimensional arrays
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs)
|
||||
VALUES ('f-2d-trial', 'finding', 'Title', 'Summary', $1::timestamptz, '{{a,b},{c,d}}'::text[], '{}'::text[])`,
|
||||
[FIXED_TS]
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs)
|
||||
VALUES ('f-2d-ev', 'finding', 'Title', 'Summary', $1::timestamptz, '{101}'::text[], '{{a,b},{c,d}}'::text[])`,
|
||||
[FIXED_TS]
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
|
||||
// Invalid idempotency_key (empty, whitespace-only, > 128 chars)
|
||||
await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: '' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: ' \t\n ' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: 'k'.repeat(129) }), '23514');
|
||||
|
||||
expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0);
|
||||
});
|
||||
|
||||
test('findings enforces unique non-NULL idempotency_key while allowing multiple NULL keys', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
await insertFinding(f.pool, { id: 'f-key-1', idempotencyKey: 'shared-key' });
|
||||
await expectPgErrorCode(
|
||||
insertFinding(f.pool, { id: 'f-key-2', idempotencyKey: 'shared-key' }),
|
||||
'23505'
|
||||
);
|
||||
|
||||
await insertFinding(f.pool, { id: 'f-null-1', idempotencyKey: null });
|
||||
await insertFinding(f.pool, { id: 'f-null-2', idempotencyKey: null });
|
||||
|
||||
expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(3);
|
||||
});
|
||||
|
||||
test('provider_caveats round-trips every ProviderCaveatRecord field, defaults created_at, and rejects blank fields', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const explicit = (
|
||||
await insertProviderCaveat(f.pool, {
|
||||
id: 'caveat-001',
|
||||
provider: 'QuoteMedia',
|
||||
dataset: 'qmSplits',
|
||||
caveat: 'splitratio stores old_shares / new_shares; invert to canonical new / old.',
|
||||
createdAt: FIXED_TS,
|
||||
})
|
||||
).rows[0];
|
||||
|
||||
expect(explicit.id).toBe('caveat-001');
|
||||
expect(explicit.provider).toBe('QuoteMedia');
|
||||
expect(explicit.dataset).toBe('qmSplits');
|
||||
expect(explicit.caveat).toBe(
|
||||
'splitratio stores old_shares / new_shares; invert to canonical new / old.'
|
||||
);
|
||||
expect((explicit.created_at as Date).toISOString()).toBe(FIXED_TS);
|
||||
|
||||
const defaulted = (await insertProviderCaveat(f.pool, { id: 'caveat-002' })).rows[0];
|
||||
expect(defaulted.created_at).toBeInstanceOf(Date);
|
||||
|
||||
for (const blank of ['', ' ', '\t\n\r']) {
|
||||
await expectPgErrorCode(insertProviderCaveat(f.pool, { id: blank }), '23514');
|
||||
await expectPgErrorCode(insertProviderCaveat(f.pool, { provider: blank }), '23514');
|
||||
await expectPgErrorCode(insertProviderCaveat(f.pool, { dataset: blank }), '23514');
|
||||
await expectPgErrorCode(insertProviderCaveat(f.pool, { caveat: blank }), '23514');
|
||||
}
|
||||
|
||||
expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe(
|
||||
2
|
||||
);
|
||||
});
|
||||
|
||||
test('UPDATE, DELETE, and TRUNCATE are blocked on both findings and provider_caveats', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const findingBefore = (await insertFinding(f.pool, { id: 'f-immutable' })).rows[0];
|
||||
const caveatBefore = (
|
||||
await insertProviderCaveat(f.pool, { id: 'c-immutable', createdAt: FIXED_TS })
|
||||
).rows[0];
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query("UPDATE findings SET status = 'approved'"),
|
||||
'23514',
|
||||
EXPECTED_IMMUTABLE_MSG
|
||||
);
|
||||
await expectPgErrorCode(f.pool.query('DELETE FROM findings'), '23514', EXPECTED_IMMUTABLE_MSG);
|
||||
await expectPgErrorCode(f.pool.query('TRUNCATE findings'), '23514', EXPECTED_IMMUTABLE_MSG);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query("UPDATE provider_caveats SET provider = 'Other'"),
|
||||
'23514',
|
||||
EXPECTED_IMMUTABLE_MSG
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query('DELETE FROM provider_caveats'),
|
||||
'23514',
|
||||
EXPECTED_IMMUTABLE_MSG
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query('TRUNCATE provider_caveats'),
|
||||
'23514',
|
||||
EXPECTED_IMMUTABLE_MSG
|
||||
);
|
||||
|
||||
expect((await f.pool.query('SELECT * FROM findings')).rows).toEqual([findingBefore]);
|
||||
expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([caveatBefore]);
|
||||
});
|
||||
});
|
||||
|
|
@ -274,12 +274,13 @@ describe('34-security-master.sql track registration', () => {
|
|||
expect(await runPostgresMigrations(postgres as never)).toEqual(research);
|
||||
});
|
||||
|
||||
test('all track runs 33, 34, 35, 36 last in exact order and skips 06-08', async () => {
|
||||
test('all track runs 33, 34, 35, 36, 37 last in exact order and skips 06-08', async () => {
|
||||
const all = await filesForTrack('all');
|
||||
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');
|
||||
expect(all.at(-5)).toBe('33-candidate-decimal-normalization.sql');
|
||||
expect(all.at(-4)).toBe('34-security-master.sql');
|
||||
expect(all.at(-3)).toBe('35-security-master-exchange-seed.sql');
|
||||
expect(all.at(-2)).toBe('36-trial-ledger.sql');
|
||||
expect(all.at(-1)).toBe('37-research-findings.sql');
|
||||
for (const bootstrap of [
|
||||
'06-create-backtest-tables.sql',
|
||||
'07-fix-execution-time-type.sql',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue