T-165: M2.1l (re-queue) — PostgreSQL trial_ledger adapter for the MCP copilot file_finding tool: TrialRefLookupPort over an injected executor in libs/research/src/mcp/adapters/postgres-trial-ref.ts (research-visible = sample_end before the Vault cutoff date, parameterized SQL, no new deps)

This commit is contained in:
Studio 2026-12-02 11:05:08 -05:00
parent 2932f5640d
commit 272d336603
4 changed files with 877 additions and 0 deletions

View file

@ -0,0 +1,165 @@
/**
* Read-only PostgreSQL `trial_ledger` adapter implementing {@link TrialRefLookupPort}
* for the MCP copilot `file_finding` tool.
*
* Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is
* injected via {@link TrialRefExecutor}.
*/
import { MarketDataStoreValidationError } from '../../market-data-store';
import type { TrialRefLookupPort } from '../tools/file-finding';
import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input';
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
const CANONICAL_TRIAL_ID_RE = /^[1-9][0-9]{0,18}$/;
const MAX_PG_BIGINT_STR = '9223372036854775807';
const PG_ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
/** Error codes thrown by {@link PostgresTrialRefError}. */
export type PostgresTrialRefErrorCode = 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' | 'INVALID_ROW';
/** Typed validation error thrown by the PostgreSQL trial-ref lookup adapter. */
export class PostgresTrialRefError extends RangeError {
readonly code: PostgresTrialRefErrorCode;
constructor(code: PostgresTrialRefErrorCode, message: string) {
super(message);
this.name = 'PostgresTrialRefError';
this.code = code;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/**
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module
* has no runtime dependency on `pg` and is unit-testable with a fake executor.
*/
export interface TrialRefExecutor {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }>;
}
/** Factory options for {@link createPostgresTrialRefPort}. */
export interface PostgresTrialRefPortOptions {
readonly executor: TrialRefExecutor;
/** Server-injected Vault cutoff epoch-ms timestamp; trials with `sample_end < utcDate(vaultCutoffTs)` are visible. */
readonly vaultCutoffTs: number;
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
readonly schema?: string;
}
interface RawTrialRefVisibilityRow {
readonly visible: unknown;
}
function isCanonicalPositiveBigInt(value: unknown): value is string {
if (typeof value !== 'string' || !CANONICAL_TRIAL_ID_RE.test(value)) {
return false;
}
if (value.length === MAX_PG_BIGINT_STR.length && value > MAX_PG_BIGINT_STR) {
return false;
}
return true;
}
function buildTrialRefVisibilitySql(schemaPrefix: string): string {
return `SELECT 1 AS visible FROM ${schemaPrefix}trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1`;
}
function validateFactoryOptions(options: PostgresTrialRefPortOptions): {
readonly executor: TrialRefExecutor;
readonly schemaPrefix: string;
readonly vaultCutoffDate: string;
} {
if (typeof options !== 'object' || options === null) {
throw new PostgresTrialRefError(
'INVALID_EXECUTOR',
'Invalid options: expected an object with a TrialRefExecutor.'
);
}
const { executor, vaultCutoffTs, schema } = options;
if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') {
throw new PostgresTrialRefError(
'INVALID_EXECUTOR',
'Invalid executor: expected an object with a callable query(text, params?) method.'
);
}
let schemaPrefix = '';
if (schema !== undefined) {
if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) {
throw new PostgresTrialRefError(
'INVALID_SCHEMA',
'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.'
);
}
schemaPrefix = `"${schema}".`;
}
const cutoffTs = validateVaultCutoffTs(vaultCutoffTs);
const vaultCutoffDate = utcDateOf(cutoffTs);
if (!PG_ISO_DATE_RE.test(vaultCutoffDate) || vaultCutoffDate.startsWith('0000-')) {
throw new MarketDataStoreValidationError(
`Invalid \`vaultCutoffTs\`: ${String(vaultCutoffTs)} does not produce a PostgreSQL YYYY-MM-DD date.`,
'vaultCutoffTs'
);
}
return { executor, schemaPrefix, vaultCutoffDate };
}
/**
* Creates a read-only PostgreSQL {@link TrialRefLookupPort} backed by `trial_ledger`
* (`36-trial-ledger.sql`), enforcing `sample_end < vaultCutoffDate` so unknown and
* Vault-only trial references are indistinguishable.
*/
export function createPostgresTrialRefPort(
options: PostgresTrialRefPortOptions
): TrialRefLookupPort {
const { executor, schemaPrefix, vaultCutoffDate } = validateFactoryOptions(options);
const sql = buildTrialRefVisibilitySql(schemaPrefix);
return {
async hasResearchVisibleTrial(trialRef: string): Promise<boolean> {
if (!isCanonicalPositiveBigInt(trialRef)) {
return false;
}
const result = await executor.query<RawTrialRefVisibilityRow>(sql, [
trialRef,
vaultCutoffDate,
]);
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
throw new PostgresTrialRefError(
'INVALID_ROW',
'Invalid executor response: expected an object with a rows array.'
);
}
if (result.rows.length === 0) {
return false;
}
if (result.rows.length !== 1) {
throw new PostgresTrialRefError(
'INVALID_ROW',
`Invalid executor response: expected at most 1 trial_ledger row, received ${result.rows.length}.`
);
}
const raw = result.rows[0];
if (typeof raw !== 'object' || raw === null || raw.visible !== 1) {
throw new PostgresTrialRefError(
'INVALID_ROW',
'Invalid trial_ledger visibility row: expected an object with visible === 1.'
);
}
return true;
},
};
}

View file

@ -1,5 +1,6 @@
export * from './adapters/postgres-findings';
export * from './adapters/postgres-symbol-search';
export * from './adapters/postgres-trial-ref';
export * from './copilot-server';
export * from './protocol';
export * from './server';

View file

@ -0,0 +1,361 @@
import { describe, expect, test } from 'bun:test';
import { MarketDataStoreValidationError } from '../src/market-data-store';
import {
PostgresTrialRefError,
type TrialRefExecutor,
createPostgresTrialRefPort,
} from '../src/mcp/index';
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 };
}
const CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); // 2025-06-30T15:45:30.500Z
const CUTOFF_DATE = '2025-06-30';
describe('createPostgresTrialRefPort (fake executor)', () => {
test('issues exact parameterized SELECT with default search_path and explicit quoted schema', async () => {
const fakeDefault = createFakeExecutor([{ visible: 1 }]);
const defaultPort = createPostgresTrialRefPort({
executor: fakeDefault.executor,
vaultCutoffTs: CUTOFF_TS,
});
expect(await defaultPort.hasResearchVisibleTrial('42')).toBe(true);
expect(fakeDefault.calls).toEqual([
{
text: 'SELECT 1 AS visible FROM trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1',
params: ['42', CUTOFF_DATE],
},
]);
const fakeScoped = createFakeExecutor([{ visible: 1 }]);
const scopedPort = createPostgresTrialRefPort({
executor: fakeScoped.executor,
vaultCutoffTs: CUTOFF_TS,
schema: 'research_iso_1',
});
expect(await scopedPort.hasResearchVisibleTrial('42')).toBe(true);
expect(fakeScoped.calls).toEqual([
{
text: 'SELECT 1 AS visible FROM "research_iso_1".trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1',
params: ['42', CUTOFF_DATE],
},
]);
});
test('converts vaultCutoffTs once to UTC calendar date across midnight boundaries', async () => {
const lateFake = createFakeExecutor([]);
// 2025-06-30T23:30:00.000Z is already 2025-07-01 in UTC+1 zones; must bind UTC date 2025-06-30.
const latePort = createPostgresTrialRefPort({
executor: lateFake.executor,
vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 30, 0, 0),
});
expect(await latePort.hasResearchVisibleTrial('7')).toBe(false);
expect(lateFake.calls[0]?.params).toEqual(['7', '2025-06-30']);
const nextFake = createFakeExecutor([]);
const nextPort = createPostgresTrialRefPort({
executor: nextFake.executor,
vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0),
});
expect(await nextPort.hasResearchVisibleTrial('7')).toBe(false);
expect(nextFake.calls[0]?.params).toEqual(['7', '2025-07-01']);
});
test('rejects invalid options and executors with INVALID_EXECUTOR before any query', () => {
const invalidOptions: unknown[] = [
null,
undefined,
{},
{ executor: null, vaultCutoffTs: CUTOFF_TS },
{ executor: {}, vaultCutoffTs: CUTOFF_TS },
{ executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_TS },
];
for (const opts of invalidOptions) {
let caught: unknown;
try {
createPostgresTrialRefPort(opts as Parameters<typeof createPostgresTrialRefPort>[0]);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR');
}
});
test('rejects invalid schema identifiers with INVALID_SCHEMA before any query', () => {
const fake = createFakeExecutor([]);
const badSchemas: unknown[] = [
'',
'Public',
'1schema',
'bad-name',
'bad.name',
'public"; DROP TABLE trial_ledger; --',
'space name',
123,
null,
];
for (const schema of badSchemas) {
let caught: unknown;
try {
createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_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('accepts minimal valid schema identifiers and prototype-method pg.Pool-shaped executors', async () => {
for (const schema of ['_', 'a', 'stock_bot_safety_0abc']) {
const fake = createFakeExecutor([]);
const port = createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_TS,
schema,
});
await port.hasResearchVisibleTrial('1');
expect(fake.calls[0]?.text).toContain(`FROM "${schema}".trial_ledger `);
}
class PrototypeExecutor {
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 PrototypeExecutor();
const port = createPostgresTrialRefPort({ executor, vaultCutoffTs: CUTOFF_TS });
expect(await port.hasResearchVisibleTrial('101')).toBe(true);
expect(executor.calls).toHaveLength(1);
});
test('rejects invalid or non-PostgreSQL-date vaultCutoffTs with MarketDataStoreValidationError', () => {
const fake = createFakeExecutor([]);
const yearZeroTs = new Date('0000-06-15T00:00:00.000Z').getTime();
const negativeYearTs = new Date('-000001-01-01T00:00:00.000Z').getTime();
const fiveDigitYearTs = new Date('+010000-01-01T00:00:00.000Z').getTime();
const invalidCutoffs: unknown[] = [
undefined,
null,
'2025-06-30',
Number.NaN,
Number.POSITIVE_INFINITY,
Number.NEGATIVE_INFINITY,
1.5,
Number.MAX_SAFE_INTEGER + 1,
8_640_000_000_000_000,
-8_640_000_000_000_000,
yearZeroTs,
negativeYearTs,
fiveDigitYearTs,
];
for (const vaultCutoffTs of invalidCutoffs) {
let caught: unknown;
try {
createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: vaultCutoffTs as number,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
expect((caught as MarketDataStoreValidationError).field).toBe('vaultCutoffTs');
}
expect(fake.calls).toHaveLength(0);
});
test('returns false with zero executor calls for every invalid, non-canonical, overflow, or injection-shaped ref', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_TS,
});
const invalidRefs: unknown[] = [
'',
' ',
' 1',
'1 ',
'\t1',
'1\n',
'0',
'-1',
'+1',
'01',
'0001',
'1.0',
'1e2',
'1E2',
'0x10',
'1_000',
'abc',
'1; DROP TABLE trial_ledger',
'1 OR 1=1',
'9223372036854775808',
'9999999999999999999',
'10000000000000000000',
1,
0,
null,
undefined,
{},
[],
1n,
];
for (const ref of invalidRefs) {
expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false);
}
expect(fake.calls).toHaveLength(0);
});
test('passes 9223372036854775807 as an exact string without Number coercion and skips 9223372036854775808', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial('9223372036854775807')).toBe(true);
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]?.params).toEqual(['9223372036854775807', CUTOFF_DATE]);
expect(typeof fake.calls[0]?.params?.[0]).toBe('string');
expect(await port.hasResearchVisibleTrial('9223372036854775808')).toBe(false);
expect(fake.calls).toHaveLength(1);
});
test('returns false for zero rows and true for exactly one valid visibility row', async () => {
const emptyFake = createFakeExecutor([]);
const emptyPort = createPostgresTrialRefPort({
executor: emptyFake.executor,
vaultCutoffTs: CUTOFF_TS,
});
expect(await emptyPort.hasResearchVisibleTrial('123')).toBe(false);
const hitFake = createFakeExecutor([{ visible: 1 }]);
const hitPort = createPostgresTrialRefPort({
executor: hitFake.executor,
vaultCutoffTs: CUTOFF_TS,
});
expect(await hitPort.hasResearchVisibleTrial('123')).toBe(true);
});
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 = createPostgresTrialRefPort({
executor,
vaultCutoffTs: CUTOFF_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('connection terminated');
let asyncAttempts = 0;
const asyncExecutor: TrialRefExecutor = {
async query() {
asyncAttempts += 1;
throw asyncFailure;
},
};
const asyncPort = createPostgresTrialRefPort({
executor: asyncExecutor,
vaultCutoffTs: CUTOFF_TS,
});
await expect(asyncPort.hasResearchVisibleTrial('101')).rejects.toBe(asyncFailure);
expect(asyncAttempts).toBe(1);
const syncFailure = new Error('sync driver failure');
let syncAttempts = 0;
const syncExecutor: TrialRefExecutor = {
query() {
syncAttempts += 1;
throw syncFailure;
},
};
const syncPort = createPostgresTrialRefPort({
executor: syncExecutor,
vaultCutoffTs: CUTOFF_TS,
});
await expect(syncPort.hasResearchVisibleTrial('101')).rejects.toBe(syncFailure);
expect(syncAttempts).toBe(1);
});
});