diff --git a/libs/research/test/mcp-postgres-trial-ref-qa.test.ts b/libs/research/test/mcp-postgres-trial-ref-qa.test.ts new file mode 100644 index 00000000..f4cf1d66 --- /dev/null +++ b/libs/research/test/mcp-postgres-trial-ref-qa.test.ts @@ -0,0 +1,263 @@ +import { describe, expect, test } from 'bun:test'; +import { + createFileFindingTool, + createPostgresTrialRefPort, + FILE_FINDING_ERROR_FILING_FAILED, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + PostgresTrialRefError, + type AppendFindingResult, + type FiledFindingRecord, + type FindingWritePort, + type PostgresTrialRefPortOptions, + type TrialRefExecutor, +} from '../src/mcp/index'; + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +function scriptedExecutor(respond: (params: readonly unknown[] | undefined) => unknown): { + readonly calls: RecordedCall[]; + readonly executor: TrialRefExecutor; +} { + const calls: RecordedCall[] = []; + return { + calls, + executor: { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return respond(params) as { readonly rows: readonly Row[] }; + }, + }, + }; +} + +function recordingWritePort(): { + readonly appended: FiledFindingRecord[]; + readonly port: FindingWritePort; +} { + const appended: FiledFindingRecord[] = []; + return { + appended, + port: { + async appendFinding(record): Promise { + appended.push(record); + return { status: 'created', id: record.id, createdAt: record.createdAt }; + }, + }, + }; +} + +const CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); // 2025-06-30T15:45:30.500Z +const CUTOFF_DATE = '2025-06-30'; +const FIXED_EPOCH_MS = Date.UTC(2026, 0, 15, 12, 0, 0); + +describe('createPostgresTrialRefPort QA edge cases', () => { + test('snapshots executor, schema and cutoff at construction so later option mutation has no effect', async () => { + const original = scriptedExecutor(() => ({ rows: [] })); + const replacement = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); + const options: { + -readonly [K in keyof PostgresTrialRefPortOptions]: PostgresTrialRefPortOptions[K]; + } = { + executor: original.executor, + vaultCutoffTs: CUTOFF_TS, + schema: 'research_a', + }; + const port = createPostgresTrialRefPort(options); + + options.executor = replacement.executor; + options.vaultCutoffTs = Date.UTC(2030, 0, 1); + options.schema = 'research_b'; + + expect(await port.hasResearchVisibleTrial('5')).toBe(false); + expect(replacement.calls).toHaveLength(0); + expect(original.calls).toEqual([ + { + text: 'SELECT 1 AS visible FROM "research_a".trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1', + params: ['5', CUTOFF_DATE], + }, + ]); + }); + + test('binds UTC dates for epoch, pre-1970 and four-digit-year extreme cutoffs', async () => { + const cases: [number, string][] = [ + [0, '1970-01-01'], + [-1, '1969-12-31'], + [Date.UTC(2025, 5, 30, 0, 0, 0, 0), '2025-06-30'], + [Date.UTC(2025, 5, 30, 23, 59, 59, 999), '2025-06-30'], + [new Date('0001-01-01T00:00:00.000Z').getTime(), '0001-01-01'], + [new Date('9999-12-31T23:59:59.999Z').getTime(), '9999-12-31'], + ]; + + for (const [vaultCutoffTs, expectedDate] of cases) { + const fake = scriptedExecutor(() => ({ rows: [] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs }); + expect(await port.hasResearchVisibleTrial('1')).toBe(false); + expect(fake.calls[0]?.params).toEqual(['1', expectedDate]); + } + }); + + test('reports INVALID_EXECUTOR before schema or cutoff errors when several options are invalid', () => { + let caught: unknown; + try { + createPostgresTrialRefPort({ + executor: {} as TrialRefExecutor, + vaultCutoffTs: Number.NaN, + schema: 'Bad-Schema', + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect(caught).toBeInstanceOf(RangeError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR'); + expect((caught as PostgresTrialRefError).name).toBe('PostgresTrialRefError'); + }); + + test('queries every canonical id across the 1..19 digit range up to the PostgreSQL bigint max', async () => { + const fake = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + const accepted = [ + '1', + '9', + '10', + '999999999999999999', + '1000000000000000000', + '9223372036854775799', + '9223372036854775806', + '9223372036854775807', + ]; + + for (const ref of accepted) { + expect(await port.hasResearchVisibleTrial(ref)).toBe(true); + } + expect(fake.calls.map(call => call.params?.[0])).toEqual(accepted); + }); + + test('returns false without querying for out-of-range, unicode-digit, control-char and boxed refs', async () => { + const fake = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + const rejected: unknown[] = [ + '9223372036854775810', + '9300000000000000000', + '12345678901234567890', + '١', // Arabic-Indic digit one + '1', // full-width digit one + '1\u0000', + ' 1', + '1​', + new String('1'), + Number.MAX_SAFE_INTEGER, + ]; + + for (const ref of rejected) { + expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); + } + expect(fake.calls).toHaveLength(0); + }); + + test('concurrent lookups each issue their own query and keep their own answers', async () => { + const fake = scriptedExecutor(params => ({ + rows: params?.[0] === '2' ? [{ visible: 1 }] : [], + })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + + const results = await Promise.all( + ['1', '2', '3', '2'].map(ref => port.hasResearchVisibleTrial(ref)) + ); + + expect(results).toEqual([false, true, false, true]); + expect(fake.calls).toHaveLength(4); + for (const call of fake.calls) { + expect(call.text).toMatch(/^SELECT 1 AS visible FROM trial_ledger WHERE /); + expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i); + expect(call.params?.[1]).toBe(CUTOFF_DATE); + } + }); + + test('exposes only the read-only hasResearchVisibleTrial method', () => { + const fake = scriptedExecutor(() => ({ rows: [] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + expect(Object.keys(port)).toEqual(['hasResearchVisibleTrial']); + }); +}); + +describe('createPostgresTrialRefPort composed with file_finding (fake executor)', () => { + function composeTool(respond: (params: readonly unknown[] | undefined) => unknown) { + const fake = scriptedExecutor(respond); + const writes = recordingWritePort(); + const tool = createFileFindingTool({ + port: writes.port, + trialLookup: createPostgresTrialRefPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_TS, + }), + newId: () => 'finding-qa-1', + now: () => FIXED_EPOCH_MS, + }); + return { fake, tool, writes }; + } + + const baseArgs = { kind: 'finding', title: 'QA filing', summary: 'Visible-only summary.' }; + + test('a visible ref files one finding with the original string ref', async () => { + const { fake, tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }] })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['9223372036854775807'] }); + + expect(res.isError).toBeUndefined(); + expect(fake.calls).toHaveLength(1); + expect(writes.appended).toHaveLength(1); + expect(writes.appended[0]?.trialRefs).toEqual(['9223372036854775807']); + expect(writes.appended[0]?.status).toBe('pending_review'); + }); + + test('a non-canonical ref is reported unavailable without any query or append', async () => { + const { fake, tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }] })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['1; DROP TABLE trial_ledger'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(fake.calls).toHaveLength(0); + expect(writes.appended).toHaveLength(0); + }); + + test('one Vault-only ref among visible refs rejects the whole filing with zero appends', async () => { + const { tool, writes } = composeTool(params => ({ + rows: params?.[0] === '20' ? [] : [{ visible: 1 }], + })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['10', '20', '30'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(writes.appended).toHaveLength(0); + }); + + test('a malformed multi-row response fails closed as filing_failed with zero appends', async () => { + const { tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }, { visible: 1 }] })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['10'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(writes.appended).toHaveLength(0); + }); + + test('an executor failure fails closed as filing_failed with zero appends', async () => { + const { tool, writes } = composeTool(() => { + throw new Error('connection terminated'); + }); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['10'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(writes.appended).toHaveLength(0); + }); +}); diff --git a/test/postgres/mcp-trial-ref-adapter.test.ts b/test/postgres/mcp-trial-ref-adapter.test.ts index 9fc8029b..371f583d 100644 --- a/test/postgres/mcp-trial-ref-adapter.test.ts +++ b/test/postgres/mcp-trial-ref-adapter.test.ts @@ -26,8 +26,17 @@ const FIXED_TS = '2026-01-15T12:34:56.789Z'; const cleanup: (() => Promise | void)[] = []; afterEach(async () => { + // Run every cleanup step even if an earlier one fails, then surface the first failure. + let firstError: unknown; for (const close of cleanup.splice(0).reverse()) { - await close(); + try { + await close(); + } catch (err) { + firstError ??= err; + } + } + if (firstError !== undefined) { + throw firstError; } }); @@ -96,13 +105,12 @@ async function createIsolatedFixture(connectionString: string | undefined = url) const safeUrl = assertSafetyDatabaseUrl(connectionString); const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: safeUrl }); + // Registered before CREATE SCHEMA so the admin pool closes even if creation or teardown fails. + cleanup.push(() => admin.end()); await admin.query(`CREATE SCHEMA ${schema}`); + cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined)); const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); + cleanup.push(() => pool.end()); const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( 'SELECT current_schema() AS current_schema' @@ -237,6 +245,12 @@ describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => { expect(await defaultPort.hasResearchVisibleTrial(afterCutoffId)).toBe(false); expect(await defaultPort.hasResearchVisibleTrial('999999999')).toBe(false); expect(await defaultPort.hasResearchVisibleTrial('1; DROP TABLE trial_ledger')).toBe(false); + // Largest bigint binds through $1::bigint without overflow and is simply unknown. + expect(await defaultPort.hasResearchVisibleTrial('9223372036854775807')).toBe(false); + const { rows: ledgerCount } = await f.pool.query<{ c: number }>( + 'SELECT count(*)::int AS c FROM trial_ledger' + ); + expect(ledgerCount[0]?.c).toBe(3); // Explicit schema option against the admin pool (default search_path) const scopedPort = createPostgresTrialRefPort({