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

565 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

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 {
type AppendFindingResult,
FILE_FINDING_ERROR_FILING_FAILED,
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
FILE_FINDING_INITIAL_STATUS,
type FileFindingResultPayload,
type FiledFindingRecord,
type FindingWritePort,
PostgresTrialRefError,
type TrialRefExecutor,
createFileFindingTool,
createMcpServer,
createPostgresTrialRefLookupPort,
createPostgresTrialRefPort,
} from '../src/mcp/index';
import { utcDateOf } from '../src/mcp/tools/vault-fenced-input';
interface RecordedCall {
readonly text: string;
readonly params: readonly unknown[] | undefined;
}
function createFakeExecutor(rows: readonly Record<string, unknown>[] = []): {
readonly calls: RecordedCall[];
readonly executor: TrialRefExecutor;
} {
const calls: RecordedCall[] = [];
const executor: TrialRefExecutor = {
async query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
calls.push({ text, params });
return { rows: rows as readonly Row[] };
},
};
return { calls, executor };
}
function createFakeWritePort(): {
readonly appended: FiledFindingRecord[];
readonly port: FindingWritePort;
} {
const appended: FiledFindingRecord[] = [];
const port: FindingWritePort = {
async appendFinding(record: FiledFindingRecord): Promise<AppendFindingResult> {
appended.push(record);
return {
status: 'created',
id: record.id,
createdAt: record.createdAt,
};
},
};
return { appended, port };
}
const CUTOFF_MIDNIGHT_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); // 2025-06-30T00:00:00.000Z
describe('createPostgresTrialRefLookupPort', () => {
test('exposes createPostgresTrialRefPort as an alias', () => {
expect(createPostgresTrialRefPort).toBe(createPostgresTrialRefLookupPort);
});
test('rejects missing or non-callable executor with INVALID_EXECUTOR', () => {
const invalidOptions: unknown[] = [
null,
undefined,
{},
{ executor: null, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
{ executor: {}, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
{ executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
];
for (const opts of invalidOptions) {
let caught: unknown;
try {
createPostgresTrialRefLookupPort(
opts as Parameters<typeof createPostgresTrialRefLookupPort>[0]
);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect(caught).toBeInstanceOf(RangeError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR');
}
});
test('rejects invalid schema names with INVALID_SCHEMA before any query', () => {
const fake = createFakeExecutor([]);
const badSchemas: unknown[] = [
'',
'Public',
'Bad-Schema',
'a;drop',
'1schema',
'bad.name',
'space name',
'public"; DROP TABLE trial_ledger; --',
123,
null,
];
for (const schema of badSchemas) {
let caught: unknown;
try {
createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
schema: schema as string,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_SCHEMA');
}
expect(fake.calls).toHaveLength(0);
});
test('rejects invalid or extended-year vaultCutoffTs with INVALID_VAULT_CUTOFF', () => {
const fake = createFakeExecutor([]);
const badCutoffs: unknown[] = [
Number.NaN,
Number.POSITIVE_INFINITY,
Number.NEGATIVE_INFINITY,
'2025-06-30',
null,
undefined,
123.45,
Number.MAX_SAFE_INTEGER + 1,
8_640_000_000_000_000,
-8_640_000_000_000_000,
Date.parse('+010000-01-01T00:00:00.000Z'),
Date.parse('-000001-01-01T00:00:00.000Z'),
Date.parse('0000-01-01T00:00:00.000Z'),
];
for (const vaultCutoffTs of badCutoffs) {
let caught: unknown;
try {
createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: vaultCutoffTs as number,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF');
}
expect(fake.calls).toHaveLength(0);
});
test('returns true for a visible trial with one parameterized read-only SELECT and exact params', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const visible = await port.hasResearchVisibleTrial('42');
expect(visible).toBe(true);
expect(fake.calls).toHaveLength(1);
const call = fake.calls[0]!;
expect(call.text.trimStart().startsWith('SELECT')).toBe(true);
expect(call.text).not.toContain(';');
expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i);
expect(call.text).toBe(
'SELECT 1 AS visible FROM trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1'
);
expect(call.params).toEqual(['42', '2025-06-30']);
expect(typeof call.params?.[0]).toBe('string');
});
test('returns false when the executor returns empty rows (unknown or Vault-only trial)', async () => {
const fake = createFakeExecutor([]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const visible = await port.hasResearchVisibleTrial('42');
expect(visible).toBe(false);
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']);
});
test('maps midnight and non-midnight UTC vaultCutoffTs to the same UTC date as utcDateOf', async () => {
const nonMidnightTs = Date.UTC(2025, 5, 30, 23, 59, 59, 999);
const nextDayTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0);
const fakeSameDay = createFakeExecutor([{ visible: 1 }]);
const sameDayPort = createPostgresTrialRefLookupPort({
executor: fakeSameDay.executor,
vaultCutoffTs: nonMidnightTs,
});
await sameDayPort.hasResearchVisibleTrial('7');
expect(fakeSameDay.calls[0]!.params).toEqual(['7', utcDateOf(nonMidnightTs)]);
expect(fakeSameDay.calls[0]!.params?.[1]).toBe('2025-06-30');
const fakeNextDay = createFakeExecutor([{ visible: 1 }]);
const nextDayPort = createPostgresTrialRefLookupPort({
executor: fakeNextDay.executor,
vaultCutoffTs: nextDayTs,
});
await nextDayPort.hasResearchVisibleTrial('7');
expect(fakeNextDay.calls[0]!.params).toEqual(['7', '2025-07-01']);
});
test('returns false with zero executor calls for malformed, injection-shaped, overflowing, and non-string refs', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const invalidRefs: unknown[] = [
'',
' 42',
'42 ',
'042',
'0',
'-1',
'+1',
'1.0',
'1e3',
'0x10',
'1_000',
'42; DROP TABLE trial_ledger',
'9223372036854775808',
'10000000000000000000',
42,
42n,
null,
undefined,
{},
[],
];
for (const ref of invalidRefs) {
const result = await port.hasResearchVisibleTrial(ref as string);
expect(result).toBe(false);
}
expect(fake.calls).toHaveLength(0);
});
test('queries the maximum signed 64-bit BIGINT verbatim as a string without numeric coercion', async () => {
const maxBigIntRef = '9223372036854775807';
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const visible = await port.hasResearchVisibleTrial(maxBigIntRef);
expect(visible).toBe(true);
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]!.text).not.toContain(maxBigIntRef);
expect(fake.calls[0]!.params).toEqual([maxBigIntRef, '2025-06-30']);
});
test('quotes validated optional schema and leaves table unqualified when omitted', async () => {
const fakeDefault = createFakeExecutor([]);
const defaultPort = createPostgresTrialRefLookupPort({
executor: fakeDefault.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
await defaultPort.hasResearchVisibleTrial('1');
expect(fakeDefault.calls[0]!.text).toContain('FROM trial_ledger ');
for (const schema of ['_', 'a', 'research_x', 'stock_bot_safety_0abc']) {
const fakeScoped = createFakeExecutor([]);
const scopedPort = createPostgresTrialRefLookupPort({
executor: fakeScoped.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
schema,
});
await scopedPort.hasResearchVisibleTrial('1');
expect(fakeScoped.calls[0]!.text).toContain(`FROM "${schema}".trial_ledger `);
}
});
test('throws INVALID_ROW for malformed envelopes, invalid singleton rows, and multiple rows (regression)', async () => {
const badResponses: unknown[] = [
null,
undefined,
{},
{ rows: null },
{ rows: 'not-an-array' },
{ rows: {} },
{ rows: [null] },
{ rows: [undefined] },
{ rows: [1] },
{ rows: [{}] },
{ rows: [{ visible: '1' }] },
{ rows: [{ visible: true }] },
{ rows: [{ visible: 0 }] },
{ rows: [{ visible: 2 }] },
{ rows: [{ visible: null }] },
// Regression: multiple rows must fail closed rather than returning true.
{ rows: [{ visible: 1 }, { visible: 1 }] },
];
for (const response of badResponses) {
const executor: TrialRefExecutor = {
async query() {
return response as { readonly rows: readonly never[] };
},
};
const port = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
let caught: unknown;
try {
await port.hasResearchVisibleTrial('101');
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_ROW');
}
});
test('propagates rejected and synchronously thrown executor errors unchanged without retrying', async () => {
const asyncFailure = new Error('postgres connection lost');
let asyncAttempts = 0;
const asyncExecutor: TrialRefExecutor = {
async query() {
asyncAttempts += 1;
throw asyncFailure;
},
};
const asyncPort = createPostgresTrialRefLookupPort({
executor: asyncExecutor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
await expect(asyncPort.hasResearchVisibleTrial('42')).rejects.toBe(asyncFailure);
expect(asyncAttempts).toBe(1);
const syncFailure = new Error('pool exhausted');
let syncAttempts = 0;
const syncExecutor = {
query() {
syncAttempts += 1;
throw syncFailure;
},
} as unknown as TrialRefExecutor;
const syncPort = createPostgresTrialRefLookupPort({
executor: syncExecutor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
await expect(syncPort.hasResearchVisibleTrial('42')).rejects.toBe(syncFailure);
expect(syncAttempts).toBe(1);
});
test('accepts a pg.Pool-shaped executor with query on its prototype', async () => {
class PoolLikeExecutor {
readonly calls: RecordedCall[] = [];
async query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
this.calls.push({ text, params });
return { rows: [{ visible: 1 }] as unknown as readonly Row[] };
}
}
const executor = new PoolLikeExecutor();
const port = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
expect(await port.hasResearchVisibleTrial('99')).toBe(true);
expect(executor.calls).toHaveLength(1);
});
});
describe('createPostgresTrialRefLookupPort wired into createFileFindingTool', () => {
async function callFileFinding(
executor: TrialRefExecutor,
trialRefs: readonly string[]
): Promise<{
readonly appended: FiledFindingRecord[];
readonly result: { readonly content: readonly { type: string; text: string }[]; readonly isError?: boolean };
}> {
const trialLookup = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const { appended, port } = createFakeWritePort();
const tool = createFileFindingTool({
port,
trialLookup,
newId: () => 'finding-0001',
now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0),
});
const server = createMcpServer({
name: 'test-copilot',
version: '0.1.0',
tools: [tool],
});
const rawResponse = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'file_finding',
arguments: {
kind: 'finding',
title: 'Pre-vault momentum signal',
summary: 'Observed stable rank IC across US equities prior to cutoff.',
trialRefs,
},
},
})
);
const parsed = JSON.parse(rawResponse!) as {
readonly result: {
readonly content: readonly { type: string; text: string }[];
readonly isError?: boolean;
};
};
return { appended, result: parsed.result };
}
test('files a pending_review finding and returns a created receipt when the trial is visible', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const { appended, result } = await callFileFinding(fake.executor, ['42']);
expect(result.isError).toBeUndefined();
const payload = JSON.parse(result.content[0]!.text) as FileFindingResultPayload;
expect(payload).toEqual({
id: 'finding-0001',
createdAt: '2025-06-29T12:00:00.000Z',
created: true,
});
expect(appended).toHaveLength(1);
expect(appended[0]).toEqual({
id: 'finding-0001',
kind: 'finding',
title: 'Pre-vault momentum signal',
status: FILE_FINDING_INITIAL_STATUS,
createdAt: '2025-06-29T12:00:00.000Z',
summary: 'Observed stable rank IC across US equities prior to cutoff.',
trialRefs: ['42'],
evidenceRefs: [],
});
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']);
});
test('returns FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF with zero appends when executor returns no rows', async () => {
const fake = createFakeExecutor([]);
const { appended, result } = await callFileFinding(fake.executor, ['42']);
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
expect(appended).toHaveLength(0);
expect(fake.calls).toHaveLength(1);
});
test('returns FILE_FINDING_ERROR_FILING_FAILED with zero appends when executor rejects', async () => {
const executor: TrialRefExecutor = {
async query() {
throw new Error('database unavailable');
},
};
const { appended, result } = await callFileFinding(executor, ['42']);
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_FILING_FAILED);
expect(appended).toHaveLength(0);
});
});
describe('createPostgresTrialRefLookupPort (QA edge cases)', () => {
test('queries in-range 19-digit refs and rejects 19-digit refs above the signed BIGINT max', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
expect(await port.hasResearchVisibleTrial('1000000000000000000')).toBe(true);
expect(await port.hasResearchVisibleTrial('9223372036854775806')).toBe(true);
expect(await port.hasResearchVisibleTrial('9223372036854775900')).toBe(false);
expect(await port.hasResearchVisibleTrial('9999999999999999999')).toBe(false);
expect(fake.calls.map(c => c.params?.[0])).toEqual([
'1000000000000000000',
'9223372036854775806',
]);
});
test('rejects trailing-newline, tab, fullwidth-digit, and boxed-String refs without querying', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
for (const ref of ['42\n', '\n42', '4\t2', '42', '42\u0000', new String('42')] as unknown[]) {
expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false);
}
expect(fake.calls).toHaveLength(0);
});
test('accepts the four-digit PostgreSQL calendar bounds 0001-01-01 and 9999-12-31 as cutoff dates', async () => {
const earliest = Date.parse('0001-01-01T00:00:00.000Z');
const latest = Date.parse('9999-12-31T23:59:59.999Z');
for (const [ts, expected] of [
[earliest, '0001-01-01'],
[latest, '9999-12-31'],
[Date.UTC(1969, 11, 31, 23, 59, 59, 999), '1969-12-31'],
] as const) {
const fake = createFakeExecutor([]);
const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: ts });
await port.hasResearchVisibleTrial('5');
expect(fake.calls[0]!.params).toEqual(['5', expected]);
}
let caught: unknown;
try {
createPostgresTrialRefLookupPort({
executor: createFakeExecutor().executor,
vaultCutoffTs: latest + 1,
});
} catch (err) {
caught = err;
}
expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF');
});
test('freezes the cutoff date and SQL text at construction across repeated lookups', async () => {
const fake = createFakeExecutor([]);
const options = { executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS };
const port = createPostgresTrialRefLookupPort(options);
await port.hasResearchVisibleTrial('1');
(options as { vaultCutoffTs: number }).vaultCutoffTs = Date.UTC(2030, 0, 1);
await port.hasResearchVisibleTrial('2');
expect(fake.calls).toHaveLength(2);
expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text);
expect(fake.calls[1]!.params).toEqual(['2', '2025-06-30']);
});
});