700 lines
27 KiB
TypeScript
700 lines
27 KiB
TypeScript
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);
|
|
});
|
|
});
|