stock-bot/libs/research/test/mcp-postgres-trial-ref-qa.test.ts
2026-12-02 11:11:27 -05:00

263 lines
9.4 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<Row = Record<string, unknown>>(
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<AppendFindingResult> {
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);
});
});