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:
commit
dfafe99ab7
8 changed files with 1071 additions and 11 deletions
99
database/postgres/init/37-research-findings.sql
Normal file
99
database/postgres/init/37-research-findings.sql
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
-- 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_trim_ecmascript(value TEXT)
|
||||
RETURNS TEXT
|
||||
LANGUAGE SQL
|
||||
IMMUTABLE
|
||||
STRICT
|
||||
AS $$
|
||||
-- Explicit ECMAScript WhiteSpace + LineTerminator set so nonblank checks and
|
||||
-- trimmed length caps match String.prototype.trim() regardless of DB collation.
|
||||
SELECT btrim(
|
||||
value,
|
||||
U&'\0009\000A\000B\000C\000D\0020\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000\FEFF'
|
||||
);
|
||||
$$;
|
||||
|
||||
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 (research_trim_ecmascript(id) <> ''),
|
||||
kind TEXT NOT NULL
|
||||
CHECK (kind IN ('finding', 'dead_end')),
|
||||
title TEXT NOT NULL
|
||||
CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256),
|
||||
summary TEXT NOT NULL
|
||||
CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096),
|
||||
status TEXT NOT NULL DEFAULT 'pending_review'
|
||||
CHECK (research_trim_ecmascript(status) <> ''),
|
||||
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 (research_trim_ecmascript(idempotency_key) <> '' 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 (research_trim_ecmascript(id) <> ''),
|
||||
provider TEXT NOT NULL
|
||||
CHECK (research_trim_ecmascript(provider) <> ''),
|
||||
dataset TEXT NOT NULL
|
||||
CHECK (research_trim_ecmascript(dataset) <> ''),
|
||||
caveat TEXT NOT NULL
|
||||
CHECK (research_trim_ecmascript(caveat) <> ''),
|
||||
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();
|
||||
|
|
@ -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 & whitespace 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`). Nonblank and trimmed-length checks use `research_trim_ecmascript(...)`, which strips the explicit 25-character ECMAScript `WhiteSpace` + `LineTerminator` set (`U+0009`..`U+000D`, `U+0020`, `U+00A0`, `U+1680`, `U+2000`..`U+200A`, `U+2028`, `U+2029`, `U+202F`, `U+205F`, `U+3000`, `U+FEFF`) regardless of database collation. 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 (research_trim_ecmascript(id) <> ''),
|
||||
kind TEXT NOT NULL
|
||||
CHECK (kind IN ('finding', 'dead_end')),
|
||||
title TEXT NOT NULL
|
||||
CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256),
|
||||
summary TEXT NOT NULL
|
||||
CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096),
|
||||
status TEXT NOT NULL DEFAULT 'pending_review'
|
||||
CHECK (research_trim_ecmascript(status) <> ''),
|
||||
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 (research_trim_ecmascript(idempotency_key) <> '' 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 (research_trim_ecmascript(id) <> ''),
|
||||
provider TEXT NOT NULL
|
||||
CHECK (research_trim_ecmascript(provider) <> ''),
|
||||
dataset TEXT NOT NULL
|
||||
CHECK (research_trim_ecmascript(dataset) <> ''),
|
||||
caveat TEXT NOT NULL
|
||||
CHECK (research_trim_ecmascript(caveat) <> ''),
|
||||
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
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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([]);
|
||||
});
|
||||
|
|
|
|||
180
test/postgres/research-findings-contract.test.ts
Normal file
180
test/postgres/research-findings-contract.test.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
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';
|
||||
import {
|
||||
FILE_FINDING_INITIAL_STATUS,
|
||||
FILE_FINDING_KINDS,
|
||||
FILE_FINDING_MAX_EVIDENCE_REFS,
|
||||
FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH,
|
||||
FILE_FINDING_MAX_REF_LENGTH,
|
||||
FILE_FINDING_MAX_SUMMARY_LENGTH,
|
||||
FILE_FINDING_MAX_TITLE_LENGTH,
|
||||
FILE_FINDING_MAX_TRIAL_REFS,
|
||||
} from '@stock-bot/research/mcp';
|
||||
|
||||
// Static contract checks for 37-research-findings.sql. No database needed, so these run in the
|
||||
// sandbox as well as in Studio's unsandboxed run. They guard against drift between the SQL CHECKs,
|
||||
// the MCP tool limits they mirror, and the design/DATA-CONTRACTS.md copy of the schema.
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
|
||||
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
|
||||
const sqlPath = `${initDir}37-research-findings.sql`;
|
||||
const docPath = fileURLToPath(new URL('../../design/DATA-CONTRACTS.md', import.meta.url));
|
||||
|
||||
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 normalize(sql: string): string {
|
||||
return stripComments(sql).replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
function tableBlock(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].replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
function docSqlBlock(): string {
|
||||
const doc = readDoc();
|
||||
const tableStart = doc.indexOf('CREATE TABLE IF NOT EXISTS findings (');
|
||||
expect(tableStart).toBeGreaterThan(-1);
|
||||
const fenceStart = doc.lastIndexOf('```sql', tableStart);
|
||||
const fenceEnd = doc.indexOf('```', tableStart);
|
||||
return doc.slice(fenceStart + '```sql'.length, fenceEnd).trim();
|
||||
}
|
||||
|
||||
function trimCodePointsFromSql(): number[] {
|
||||
const match = /U&'([^']*)'/.exec(stripComments(readSql()));
|
||||
if (!match?.[1]) {
|
||||
throw new Error('research_trim_ecmascript U& character set not found');
|
||||
}
|
||||
return match[1]
|
||||
.split('\\')
|
||||
.filter(part => part.length > 0)
|
||||
.map(part => {
|
||||
expect(part).toMatch(/^[0-9A-F]{4}$/i);
|
||||
return Number.parseInt(part, 16);
|
||||
});
|
||||
}
|
||||
|
||||
async function filesForTrack(track: MigrationTrack): Promise<string[]> {
|
||||
const postgres = {
|
||||
transaction: async <T>(callback: (client: { query: (sql: string) => unknown }) => Promise<T>) =>
|
||||
callback({ query: async () => ({ rows: [] }) }),
|
||||
};
|
||||
return runPostgresMigrations(postgres as never, { track });
|
||||
}
|
||||
|
||||
describe('37-research-findings.sql static contract', () => {
|
||||
test('creates exactly findings and provider_caveats with IF NOT EXISTS and no schema qualifiers', () => {
|
||||
const sql = stripComments(readSql());
|
||||
const created = [...sql.matchAll(/CREATE TABLE\s+(IF NOT EXISTS\s+)?("?[\w.]+"?)/g)];
|
||||
expect(created.map(m => m[2])).toEqual(['findings', 'provider_caveats']);
|
||||
expect(created.every(m => m[1] !== undefined)).toBe(true);
|
||||
expect(sql).not.toMatch(/CREATE\s+DATABASE/i);
|
||||
expect(sql).not.toMatch(/^\s*\\c\b/m);
|
||||
expect(sql).not.toMatch(/\bSET\s+search_path\b/i);
|
||||
expect(sql).not.toMatch(/\b(?:TABLE|EXISTS|ON|FROM)\s+"?\w+"?\."?\w+/i);
|
||||
});
|
||||
|
||||
test('findings CHECKs mirror the file_finding tool limits exported from file-finding.ts', () => {
|
||||
const findings = tableBlock(readSql(), 'findings');
|
||||
const kinds = FILE_FINDING_KINDS.map(kind => `'${kind}'`).join(', ');
|
||||
|
||||
expect(findings).toContain(`CHECK (kind IN (${kinds}))`);
|
||||
expect(findings).toContain(`DEFAULT '${FILE_FINDING_INITIAL_STATUS}'`);
|
||||
expect(findings).toContain(
|
||||
`CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND ${FILE_FINDING_MAX_TITLE_LENGTH})`
|
||||
);
|
||||
expect(findings).toContain(
|
||||
`CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND ${FILE_FINDING_MAX_SUMMARY_LENGTH})`
|
||||
);
|
||||
expect(findings).toContain(`CHECK (cardinality(trial_refs) <= ${FILE_FINDING_MAX_TRIAL_REFS})`);
|
||||
expect(findings).toContain(
|
||||
`CHECK (cardinality(evidence_refs) <= ${FILE_FINDING_MAX_EVIDENCE_REFS})`
|
||||
);
|
||||
expect(findings).toContain(
|
||||
`CHECK (research_finding_refs_valid(trial_refs, ${FILE_FINDING_MAX_REF_LENGTH}))`
|
||||
);
|
||||
expect(findings).toContain(
|
||||
`CHECK (research_finding_refs_valid(evidence_refs, ${FILE_FINDING_MAX_REF_LENGTH}))`
|
||||
);
|
||||
expect(findings).toContain(
|
||||
`char_length(idempotency_key) BETWEEN 1 AND ${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH}`
|
||||
);
|
||||
expect(findings).toContain('created_at TIMESTAMPTZ NOT NULL,');
|
||||
expect(findings).toMatch(/idempotency_key TEXT CHECK \(idempotency_key IS NULL OR/);
|
||||
});
|
||||
|
||||
test('research_trim_ecmascript strips exactly the BMP code points String.prototype.trim() strips', () => {
|
||||
const sqlSet = trimCodePointsFromSql();
|
||||
const jsSet: number[] = [];
|
||||
for (let cp = 0; cp <= 0xffff; cp++) {
|
||||
if (cp >= 0xd800 && cp <= 0xdfff) {
|
||||
continue;
|
||||
}
|
||||
if (String.fromCharCode(cp).trim() === '') {
|
||||
jsSet.push(cp);
|
||||
}
|
||||
}
|
||||
|
||||
expect(new Set(sqlSet).size).toBe(sqlSet.length);
|
||||
expect([...sqlSet].sort((a, b) => a - b)).toEqual(jsSet);
|
||||
expect(sqlSet).toHaveLength(25);
|
||||
});
|
||||
|
||||
test('both tables are append-only via reject_research_evidence_mutation row and TRUNCATE triggers', () => {
|
||||
const sql = normalize(readSql());
|
||||
for (const table of ['findings', 'provider_caveats']) {
|
||||
expect(sql).toContain(
|
||||
`DROP TRIGGER IF EXISTS ${table}_retained ON ${table}; 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}; CREATE TRIGGER ${table}_no_truncate BEFORE TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();`
|
||||
);
|
||||
}
|
||||
// The migration must reuse the shared function, never redefine it.
|
||||
expect(sql).not.toMatch(/FUNCTION reject_research_evidence_mutation\s*\(\s*\)\s*RETURNS/i);
|
||||
});
|
||||
|
||||
test('design/DATA-CONTRACTS.md documents both tables and indexes exactly as the migration creates them', () => {
|
||||
const doc = docSqlBlock();
|
||||
const sql = readSql();
|
||||
expect(tableBlock(doc, 'findings')).toBe(tableBlock(sql, 'findings'));
|
||||
expect(tableBlock(doc, 'provider_caveats')).toBe(tableBlock(sql, 'provider_caveats'));
|
||||
|
||||
const indexes = (text: string) =>
|
||||
[...normalize(text).matchAll(/CREATE (?:UNIQUE )?INDEX IF NOT EXISTS [^;]+;/g)].map(
|
||||
m => m[0]
|
||||
);
|
||||
expect(indexes(doc)).toEqual(indexes(sql));
|
||||
expect(indexes(sql)).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('37-research-findings.sql runs on research and all tracks right after 36 and never on master', async () => {
|
||||
const research = await filesForTrack('research');
|
||||
const all = await filesForTrack('all');
|
||||
const master = await filesForTrack('master');
|
||||
|
||||
expect(research.indexOf('37-research-findings.sql')).toBe(
|
||||
research.indexOf('36-trial-ledger.sql') + 1
|
||||
);
|
||||
expect(research.indexOf('36-trial-ledger.sql')).toBeGreaterThan(-1);
|
||||
expect(all).toContain('37-research-findings.sql');
|
||||
expect(master).not.toContain('37-research-findings.sql');
|
||||
});
|
||||
});
|
||||
700
test/postgres/research-findings-schema.test.ts
Normal file
700
test/postgres/research-findings-schema.test.ts
Normal file
|
|
@ -0,0 +1,700 @@
|
|||
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 poolUrl = new URL(url);
|
||||
const existingOptions = poolUrl.searchParams.get('options')?.trim();
|
||||
const fixtureOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`;
|
||||
poolUrl.searchParams.set(
|
||||
'options',
|
||||
existingOptions ? `${existingOptions} ${fixtureOptions}` : fixtureOptions
|
||||
);
|
||||
const pool = new Pool({ connectionString: poolUrl.toString() });
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
|
||||
const activeSchema = (await pool.query<{ schema: string }>('SELECT current_schema() AS schema'))
|
||||
.rows[0]?.schema;
|
||||
if (activeSchema !== schema) {
|
||||
throw new Error(`Expected active fixture schema ${schema}, got ${activeSchema ?? 'null'}`);
|
||||
}
|
||||
|
||||
// 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
|
||||
// including Unicode NBSP / ideographic-space padding around max-length title and summary.
|
||||
const maxRefs = Array.from({ length: 32 }, (_, i) => `${i}`.padStart(256, 'r'));
|
||||
const boundary = (
|
||||
await insertFinding(f.pool, {
|
||||
id: 'finding-002',
|
||||
kind: 'dead_end',
|
||||
title: `\u00A0${'t'.repeat(256)}\u00A0`,
|
||||
summary: `\u00A0\u3000${'s'.repeat(4096)}\u00A0`,
|
||||
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 (ASCII and ECMAScript Unicode) id and status
|
||||
const unicodeBlanks = ['\u00A0', '\u00A0\u2003\u3000\uFEFF', '\u2028\u2029'];
|
||||
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');
|
||||
for (const blank of unicodeBlanks) {
|
||||
await expectPgErrorCode(insertFinding(f.pool, { id: blank }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { status: blank }), '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 (ASCII and ECMAScript Unicode), 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, { title: `\u00A0${'t'.repeat(257)}\u00A0` }),
|
||||
'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');
|
||||
for (const blank of unicodeBlanks) {
|
||||
await expectPgErrorCode(insertFinding(f.pool, { title: blank }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { summary: blank }), '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');
|
||||
for (const blank of unicodeBlanks) {
|
||||
await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: blank }), '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',
|
||||
'\u00A0',
|
||||
'\u00A0\u2003\u3000\uFEFF',
|
||||
'\u2028\u2029',
|
||||
]) {
|
||||
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]);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema edge cases (QA)', () => {
|
||||
test('research_trim_ecmascript matches String.prototype.trim() for every ECMAScript blank and for look-alike non-blanks', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
// 25 ECMAScript WhiteSpace + LineTerminator code points, plus characters JS trim() keeps:
|
||||
// ZERO WIDTH SPACE, NEXT LINE, MONGOLIAN VOWEL SEPARATOR, WORD JOINER.
|
||||
const codePoints = [
|
||||
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0xa0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004,
|
||||
0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000,
|
||||
0xfeff, 0x200b, 0x0085, 0x180e, 0x2060,
|
||||
];
|
||||
for (const cp of codePoints) {
|
||||
const c = String.fromCodePoint(cp);
|
||||
for (const input of [c, `${c}${c}a b${c}`]) {
|
||||
const sqlTrimmed = (
|
||||
await f.pool.query<{ v: string }>('SELECT research_trim_ecmascript($1) AS v', [input])
|
||||
).rows[0]?.v;
|
||||
expect({ cp, input, trimmed: sqlTrimmed }).toEqual({ cp, input, trimmed: input.trim() });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('non-ECMAScript blanks the MCP tool accepts (U+200B, U+0085) are accepted, and text is stored untrimmed', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const paddedTitle = `\u00A0 Interior spacing\tkept \u3000`;
|
||||
|
||||
const zwsp = (await insertFinding(f.pool, { id: 'f-zwsp', title: '\u200B' })).rows[0];
|
||||
const nel = (await insertFinding(f.pool, { id: 'f-nel', summary: '\u0085' })).rows[0];
|
||||
const padded = (await insertFinding(f.pool, { id: 'f-padded', title: paddedTitle })).rows[0];
|
||||
|
||||
expect(zwsp.title).toBe('\u200B');
|
||||
expect(nel.summary).toBe('\u0085');
|
||||
expect(padded.title).toBe(paddedTitle);
|
||||
});
|
||||
|
||||
test('title/summary caps count code points: 256 astral characters accepted, 257 rejected', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const emoji = '\u{1F4C8}';
|
||||
|
||||
const ok = (await insertFinding(f.pool, { id: 'f-astral-ok', title: emoji.repeat(256) }))
|
||||
.rows[0];
|
||||
expect(ok.title).toBe(emoji.repeat(256));
|
||||
await expectPgErrorCode(
|
||||
insertFinding(f.pool, { id: 'f-astral-bad', title: emoji.repeat(257) }),
|
||||
'23514'
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
insertFinding(f.pool, { id: 'f-astral-ref', trialRefs: [emoji.repeat(257)] }),
|
||||
'23514'
|
||||
);
|
||||
});
|
||||
|
||||
test('NOT NULL columns reject NULL with SQLSTATE 23502 and leave no rows', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const base = {
|
||||
id: 'f-null',
|
||||
kind: 'finding',
|
||||
title: 'Title',
|
||||
summary: 'Summary',
|
||||
created_at: FIXED_TS,
|
||||
trial_refs: ['1'],
|
||||
evidence_refs: [] as string[],
|
||||
};
|
||||
for (const column of Object.keys(base) as (keyof typeof base)[]) {
|
||||
const row = { ...base, [column]: null };
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs)
|
||||
VALUES ($1, $2, $3, $4, $5::timestamptz, $6::text[], $7::text[])`,
|
||||
[
|
||||
row.id,
|
||||
row.kind,
|
||||
row.title,
|
||||
row.summary,
|
||||
row.created_at,
|
||||
row.trial_refs,
|
||||
row.evidence_refs,
|
||||
]
|
||||
),
|
||||
'23502'
|
||||
);
|
||||
}
|
||||
// created_at has no default on findings: the tool's clock must supply it.
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO findings (id, kind, title, summary, trial_refs, evidence_refs)
|
||||
VALUES ('f-no-ts', 'finding', 'Title', 'Summary', '{1}', '{}')`
|
||||
),
|
||||
'23502'
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs, status)
|
||||
VALUES ('f-null-status', 'finding', 'Title', 'Summary', $1::timestamptz, '{1}', '{}', NULL)`,
|
||||
[FIXED_TS]
|
||||
),
|
||||
'23502'
|
||||
);
|
||||
for (const column of ['id', 'provider', 'dataset', 'caveat', 'created_at']) {
|
||||
const values: Record<string, string | null> = {
|
||||
id: 'c-null',
|
||||
provider: 'EODHD',
|
||||
dataset: 'eodPrices',
|
||||
caveat: 'Caveat text',
|
||||
created_at: FIXED_TS,
|
||||
[column]: null,
|
||||
};
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5::timestamptz)`,
|
||||
[values.id, values.provider, values.dataset, values.caveat, values.created_at]
|
||||
),
|
||||
'23502'
|
||||
);
|
||||
}
|
||||
|
||||
expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe(
|
||||
0
|
||||
);
|
||||
});
|
||||
|
||||
test('duplicate ids are rejected (23505) on both tables and idempotency keys are case-sensitive', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
await insertFinding(f.pool, { id: 'dup-finding' });
|
||||
await expectPgErrorCode(insertFinding(f.pool, { id: 'dup-finding' }), '23505');
|
||||
await insertProviderCaveat(f.pool, { id: 'dup-caveat' });
|
||||
await expectPgErrorCode(insertProviderCaveat(f.pool, { id: 'dup-caveat' }), '23505');
|
||||
|
||||
// file_finding compares idempotency keys exactly; the unique index must not fold case.
|
||||
await insertFinding(f.pool, { id: 'f-case-1', idempotencyKey: 'Retry-Key' });
|
||||
await insertFinding(f.pool, { id: 'f-case-2', idempotencyKey: 'retry-key' });
|
||||
|
||||
expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(3);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe(
|
||||
1
|
||||
);
|
||||
});
|
||||
|
||||
test('a rejected UPDATE matching one row leaves every other row and column untouched', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
await insertFinding(f.pool, { id: 'f-a', createdAt: '2026-01-01T00:00:00.000Z' });
|
||||
await insertFinding(f.pool, { id: 'f-b', createdAt: '2026-01-02T00:00:00.000Z' });
|
||||
const before = (await f.pool.query('SELECT * FROM findings ORDER BY id')).rows;
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query("UPDATE findings SET status = 'approved' WHERE id = 'f-b'"),
|
||||
'23514',
|
||||
EXPECTED_IMMUTABLE_MSG
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query("DELETE FROM findings WHERE id = 'f-a'"),
|
||||
'23514',
|
||||
EXPECTED_IMMUTABLE_MSG
|
||||
);
|
||||
|
||||
expect((await f.pool.query('SELECT * FROM findings ORDER BY id')).rows).toEqual(before);
|
||||
});
|
||||
});
|
||||
|
|
@ -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