diff --git a/test/postgres/research-findings-contract.test.ts b/test/postgres/research-findings-contract.test.ts new file mode 100644 index 00000000..36c9d2e3 --- /dev/null +++ b/test/postgres/research-findings-contract.test.ts @@ -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 { + const postgres = { + transaction: async (callback: (client: { query: (sql: string) => unknown }) => Promise) => + 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'); + }); +}); diff --git a/test/postgres/research-findings-schema.test.ts b/test/postgres/research-findings-schema.test.ts index 18c75c16..60324763 100644 --- a/test/postgres/research-findings-schema.test.ts +++ b/test/postgres/research-findings-schema.test.ts @@ -119,7 +119,17 @@ function insertFinding(pool: Pool, overrides: FindingInsertOverrides = {}) { 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] + [ + id, + kind, + title, + summary, + overrides.status, + createdAt, + trialRefs, + evidenceRefs, + idempotencyKey, + ] ); } @@ -527,3 +537,164 @@ describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => { 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 = { + 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); + }); +});