From c16d6b3f603870b9bd5afc0fa7648a278cd567d2 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:12:13 -0500 Subject: [PATCH] =?UTF-8?q?T-151:=20M2.1i=20=E2=80=94=20`findings`=20+=20`?= =?UTF-8?q?provider=5Fcaveats`=20append-only=20PostgreSQL=20migration=20(r?= =?UTF-8?q?esearch=20track,=20`37-research-findings.sql`)=20with=20fresh-d?= =?UTF-8?q?atabase=20schema=20tests=20(no=20adapters,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../postgres/init/37-research-findings.sql | 85 +++ design/DATA-CONTRACTS.md | 59 +++ libs/data/postgres/src/migrations.ts | 1 + test/postgres/fresh-database-schema.test.ts | 15 +- test/postgres/migration-runner.test.ts | 17 +- .../postgres/research-findings-schema.test.ts | 495 ++++++++++++++++++ .../postgres/security-master-contract.test.ts | 11 +- 7 files changed, 672 insertions(+), 11 deletions(-) create mode 100644 database/postgres/init/37-research-findings.sql create mode 100644 test/postgres/research-findings-schema.test.ts diff --git a/database/postgres/init/37-research-findings.sql b/database/postgres/init/37-research-findings.sql new file mode 100644 index 00000000..ac9d156f --- /dev/null +++ b/database/postgres/init/37-research-findings.sql @@ -0,0 +1,85 @@ +-- Research findings & provider caveats schema (M2.1i) +-- Research track migration: creates append-only findings and provider_caveats tables, +-- lookup/idempotency indexes, and immutability triggers reusing +-- reject_research_evidence_mutation() from 17-research-retention.sql. + +CREATE OR REPLACE FUNCTION research_finding_refs_valid(refs TEXT[], max_len INTEGER) +RETURNS BOOLEAN +LANGUAGE SQL +IMMUTABLE +STRICT +AS $$ + SELECT COALESCE(array_ndims(refs), 1) = 1 + AND NOT EXISTS ( + SELECT 1 + FROM unnest(refs) AS r + WHERE r IS NULL + OR char_length(r) > max_len + ); +$$; + +CREATE TABLE IF NOT EXISTS findings ( + id TEXT PRIMARY KEY + CHECK (id ~ '\S'), + kind TEXT NOT NULL + CHECK (kind IN ('finding', 'dead_end')), + title TEXT NOT NULL + CHECK (char_length(regexp_replace(title, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 256), + summary TEXT NOT NULL + CHECK (char_length(regexp_replace(summary, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 4096), + status TEXT NOT NULL DEFAULT 'pending_review' + CHECK (status ~ '\S'), + created_at TIMESTAMPTZ NOT NULL, + trial_refs TEXT[] NOT NULL + CHECK (cardinality(trial_refs) <= 32) + CHECK (COALESCE(array_ndims(trial_refs), 1) = 1) + CHECK (research_finding_refs_valid(trial_refs, 256)), + evidence_refs TEXT[] NOT NULL + CHECK (cardinality(evidence_refs) <= 32) + CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) + CHECK (research_finding_refs_valid(evidence_refs, 256)), + idempotency_key TEXT + CHECK (idempotency_key IS NULL OR (idempotency_key ~ '\S' AND char_length(idempotency_key) BETWEEN 1 AND 128)) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key + ON findings (idempotency_key) + WHERE idempotency_key IS NOT NULL; + +CREATE INDEX IF NOT EXISTS idx_findings_created_at + ON findings (created_at); + +CREATE TABLE IF NOT EXISTS provider_caveats ( + id TEXT PRIMARY KEY + CHECK (id ~ '\S'), + provider TEXT NOT NULL + CHECK (provider ~ '\S'), + dataset TEXT NOT NULL + CHECK (dataset ~ '\S'), + caveat TEXT NOT NULL + CHECK (caveat ~ '\S'), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider + ON provider_caveats (lower(provider)); + +DROP TRIGGER IF EXISTS findings_retained ON findings; +CREATE TRIGGER findings_retained + BEFORE UPDATE OR DELETE ON findings + FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); + +DROP TRIGGER IF EXISTS findings_no_truncate ON findings; +CREATE TRIGGER findings_no_truncate + BEFORE TRUNCATE ON findings + FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); + +DROP TRIGGER IF EXISTS provider_caveats_retained ON provider_caveats; +CREATE TRIGGER provider_caveats_retained + BEFORE UPDATE OR DELETE ON provider_caveats + FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); + +DROP TRIGGER IF EXISTS provider_caveats_no_truncate ON provider_caveats; +CREATE TRIGGER provider_caveats_no_truncate + BEFORE TRUNCATE ON provider_caveats + FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); diff --git a/design/DATA-CONTRACTS.md b/design/DATA-CONTRACTS.md index 278c1999..e119ac72 100644 --- a/design/DATA-CONTRACTS.md +++ b/design/DATA-CONTRACTS.md @@ -194,6 +194,65 @@ The M1 exit gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD 2. `uncovered_venue` — listings on exchanges absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`, `ceo`, and `ib:AEQLIT`, plus `ceo:NEOE` where EODHD carries only 19 of 587 listings). 3. `non_equity_instrument` — non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX inactive shells `.H`, TSXV CPCs `.P`, and exchange test symbols). +### Research Knowledge & Findings Schema (PostgreSQL, Append-Only) + +Applied via `@stock-bot/postgres` (`research` migration track, `database/postgres/init/37-research-findings.sql`, immediately after `36-trial-ledger.sql`). Owned by Stock Bot research alongside `trial_ledger` and `vault_evaluations` (see [`design/VALIDATION-AND-RIGOR.md`](VALIDATION-AND-RIGOR.md) §2A and §3 for those tables). + +- **Research-visible boundary:** `findings` and `provider_caveats` store research-visible empirical evidence only. Callers and MCP adapters (`file_finding`, `read_knowledge`) are responsible for verifying that every `trial_ref` belongs to the research-visible `trial_ledger` and for excluding Vault holdout observations or Vault-only evidence from stored text and opaque `evidence_refs`. +- **Append-only enforcement:** Both tables reuse `reject_research_evidence_mutation()` from `17-research-retention.sql` via row-level `BEFORE UPDATE OR DELETE` (`findings_retained`, `provider_caveats_retained`) and statement-level `BEFORE TRUNCATE` (`findings_no_truncate`, `provider_caveats_no_truncate`) triggers, raising SQLSTATE `23514` on any mutation attempt. +- **Character-length convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters. + +```sql +CREATE TABLE IF NOT EXISTS findings ( + id TEXT PRIMARY KEY + CHECK (id ~ '\S'), + kind TEXT NOT NULL + CHECK (kind IN ('finding', 'dead_end')), + title TEXT NOT NULL + CHECK (char_length(regexp_replace(title, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 256), + summary TEXT NOT NULL + CHECK (char_length(regexp_replace(summary, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 4096), + status TEXT NOT NULL DEFAULT 'pending_review' + CHECK (status ~ '\S'), + created_at TIMESTAMPTZ NOT NULL, + trial_refs TEXT[] NOT NULL + CHECK (cardinality(trial_refs) <= 32) + CHECK (COALESCE(array_ndims(trial_refs), 1) = 1) + CHECK (research_finding_refs_valid(trial_refs, 256)), + evidence_refs TEXT[] NOT NULL + CHECK (cardinality(evidence_refs) <= 32) + CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) + CHECK (research_finding_refs_valid(evidence_refs, 256)), + idempotency_key TEXT + CHECK (idempotency_key IS NULL OR (idempotency_key ~ '\S' AND char_length(idempotency_key) BETWEEN 1 AND 128)) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key + ON findings (idempotency_key) + WHERE idempotency_key IS NOT NULL; + +CREATE INDEX IF NOT EXISTS idx_findings_created_at + ON findings (created_at); + +CREATE TABLE IF NOT EXISTS provider_caveats ( + id TEXT PRIMARY KEY + CHECK (id ~ '\S'), + provider TEXT NOT NULL + CHECK (provider ~ '\S'), + dataset TEXT NOT NULL + CHECK (dataset ~ '\S'), + caveat TEXT NOT NULL + CHECK (caveat ~ '\S'), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider + ON provider_caveats (lower(provider)); +``` + +- **Reference arrays (`trial_refs`, `evidence_refs`):** Stored as opaque 1-dimensional `TEXT[]` arrays (empty arrays permitted via `COALESCE(array_ndims(...), 1) = 1`, max 32 entries each, no `NULL` elements, max 256 chars per entry enforced via `research_finding_refs_valid`). Reference normalization, deduplication, minimum `trial_refs` count, and research-visibility checks remain in the MCP tool/adapter layer. +- **Indexes:** `idx_findings_idempotency_key` (partial unique `WHERE idempotency_key IS NOT NULL`) supports atomic compare-and-append idempotency while allowing multiple `NULL` keys; `idx_findings_created_at` supports chronological listing; `idx_provider_caveats_lower_provider` supports case-insensitive provider filtering in `read_knowledge`. + --- ## 3. Curated Storage Schemas diff --git a/libs/data/postgres/src/migrations.ts b/libs/data/postgres/src/migrations.ts index 1f05331a..1fa68e3c 100644 --- a/libs/data/postgres/src/migrations.ts +++ b/libs/data/postgres/src/migrations.ts @@ -45,6 +45,7 @@ const RESEARCH_FILES = new Set([ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', + '37-research-findings.sql', ]); function locateMigrationsDir(): string { diff --git a/test/postgres/fresh-database-schema.test.ts b/test/postgres/fresh-database-schema.test.ts index df95c7b7..8bfb3325 100644 --- a/test/postgres/fresh-database-schema.test.ts +++ b/test/postgres/fresh-database-schema.test.ts @@ -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)[] = []; @@ -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([]); diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index 6b43c3d3..0e87eebb 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -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)[] = []; 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([]); }); diff --git a/test/postgres/research-findings-schema.test.ts b/test/postgres/research-findings-schema.test.ts new file mode 100644 index 00000000..651f2882 --- /dev/null +++ b/test/postgres/research-findings-schema.test.ts @@ -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)[] = []; +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, + expectedCode: string, + messagePattern?: RegExp +): Promise { + 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 { + const result = await pool.query( + `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]); + }); +}); diff --git a/test/postgres/security-master-contract.test.ts b/test/postgres/security-master-contract.test.ts index eb140bb2..292bca21 100644 --- a/test/postgres/security-master-contract.test.ts +++ b/test/postgres/security-master-contract.test.ts @@ -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',