T-161: M2.1j (re-queue) — PostgreSQL findings adapter for the MCP copilot: FindingWritePort (atomic idempotent append) + listFindings / listProviderCaveats readers over an injected executor in libs/research/src/mcp/adapters/postgres-findings.ts (no new deps)

This commit is contained in:
Studio 2026-12-02 09:35:55 -05:00
parent ac12439fe2
commit 5654b9cc05
5 changed files with 1872 additions and 0 deletions

View file

@ -0,0 +1,537 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import { Client, Pool, type PoolConfig } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
type FileFindingResultPayload,
type FiledFindingRecord,
type PostgresFindingsExecutor,
type ReadKnowledgeResultPayload,
createFileFindingTool,
createMcpServer,
createPostgresFindingWritePort,
createPostgresKnowledgeReaders,
createReadKnowledgeTool,
} from '../../libs/research/src/mcp/index';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('mcp-findings-adapter-pg-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
const FIXED_TS = '2026-01-15T12:34:56.789Z';
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety database required');
}
return connectionString;
}
function createPgExecutor(pool: Pool): PostgresFindingsExecutor {
return {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
return pool.query(
text,
params === undefined ? undefined : [...params]
) as unknown as Promise<{ readonly rows: readonly Row[] }>;
},
};
}
function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig {
const safeUrl = assertSafetyDatabaseUrl(connectionString);
const parsed = new URL(safeUrl);
const existingOptions = parsed.searchParams
.getAll('options')
.map(value => value.trim())
.filter(value => value.length > 0);
parsed.searchParams.delete('options');
const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`;
const options = [...existingOptions, schemaOptions].join(' ');
return {
connectionString: parsed.toString(),
options,
};
}
async function createIsolatedFixture(connectionString: string | undefined = url) {
const safeUrl = assertSafetyDatabaseUrl(connectionString);
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: safeUrl });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema));
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>(
'SELECT current_schema() AS current_schema'
);
if (schemaRows[0]?.current_schema !== schema) {
throw new Error(
`Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}`
);
}
// 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 { admin, pool, schema };
}
function makeFinding(overrides: Partial<FiledFindingRecord> = {}): FiledFindingRecord {
return {
id: `finding-${randomUUID()}`,
kind: 'finding',
title: 'Momentum factor decays after 5 sessions',
status: 'pending_review',
createdAt: FIXED_TS,
summary: 'Cross-sectional rank IC turns negative past day 5.',
trialRefs: ['101', '102'],
evidenceRefs: ['snap:2026-01-15:ic'],
...overrides,
};
}
describe('PostgreSQL findings adapter safety guard', () => {
test('rejects unsafe database targets before connecting', () => {
expect(() => assertSafetyDatabaseUrl(undefined)).toThrow(
'Dedicated stock_bot_safety database required'
);
expect(() =>
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot')
).toThrow('Dedicated stock_bot_safety database required');
expect(() =>
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev')
).toThrow('Dedicated stock_bot_safety database required');
expect(
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test')
).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test');
});
test('preserves isolated schema search_path precedence over URL startup options', () => {
const schema = 'stock_bot_safety_findings_options';
const urlWithOptions =
'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic';
const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema);
expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false);
const client = new Client(poolConfig);
const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } })
.connectionParameters.options;
expect(resolvedOptions).toBe(
`-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`
);
});
});
describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () => {
test('supports unkeyed inserts, keyed created -> replayed -> conflict, same-ID retries, and unrelated duplicate PK errors', async () => {
const f = await createIsolatedFixture();
const writePort = createPostgresFindingWritePort({ executor: createPgExecutor(f.pool) });
// Two independent unkeyed inserts produce two distinct rows.
const u1 = await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-1' }));
const u2 = await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-2' }));
expect(u1).toEqual({ status: 'created', id: 'f-unkeyed-1', createdAt: FIXED_TS });
expect(u2).toEqual({ status: 'created', id: 'f-unkeyed-2', createdAt: FIXED_TS });
// Keyed create -> replay -> conflict
const original = makeFinding({
id: 'f-keyed-1',
createdAt: '2026-01-15T12:34:56.789Z',
});
const created = await writePort.appendFinding(original, 'idem-roundtrip');
expect(created).toEqual({
status: 'created',
id: 'f-keyed-1',
createdAt: '2026-01-15T12:34:56.789Z',
});
// Replay with new generated ID and timestamp returns original stored ID and timestamp.
const replayed = await writePort.appendFinding(
{
...original,
id: 'f-keyed-retry-new-id',
createdAt: '2026-01-16T00:00:00.000Z',
},
'idem-roundtrip'
);
expect(replayed).toEqual({
status: 'replayed',
id: 'f-keyed-1',
createdAt: '2026-01-15T12:34:56.789Z',
});
// Same-ID retry (triggers PK 23505) resolves cleanly as replayed / conflict.
const sameIdReplay = await writePort.appendFinding(original, 'idem-roundtrip');
expect(sameIdReplay).toEqual({
status: 'replayed',
id: 'f-keyed-1',
createdAt: '2026-01-15T12:34:56.789Z',
});
const sameIdConflict = await writePort.appendFinding(
{ ...original, title: 'Mutated title on same-ID retry' },
'idem-roundtrip'
);
expect(sameIdConflict).toEqual({ status: 'conflict' });
// Different payload with new ID returns conflict and leaves row count unchanged.
const conflict = await writePort.appendFinding(
{ ...original, id: 'f-keyed-conflict', summary: 'Different summary' },
'idem-roundtrip'
);
expect(conflict).toEqual({ status: 'conflict' });
// Unrelated duplicate primary key (collides with unkeyed row f-unkeyed-1) propagates 23505.
let pkError: unknown;
try {
await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-1' }), 'idem-fresh-unrelated');
} catch (err) {
pkError = err;
}
expect((pkError as { code?: string } | null)?.code).toBe('23505');
const countRow = (await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings'))
.rows[0];
expect(countRow?.c).toBe(3);
});
test('concurrent same-key appends on separate connections leave exactly one stored row for identical and differing payloads', async () => {
const f = await createIsolatedFixture();
const writePort = createPostgresFindingWritePort({ executor: createPgExecutor(f.pool) });
// Concurrent identical payloads
const recA = makeFinding({ id: 'f-race-same-a', createdAt: '2026-01-15T10:00:00.000Z' });
const recB = { ...recA, id: 'f-race-same-b', createdAt: '2026-01-15T10:00:01.000Z' };
const sameOutcomes = await Promise.all([
writePort.appendFinding(recA, 'idem-race-same'),
writePort.appendFinding(recB, 'idem-race-same'),
]);
const sameStatuses = sameOutcomes.map(o => o.status).sort();
expect(sameStatuses).toEqual(['created', 'replayed']);
const winnerSame = sameOutcomes.find(o => o.status === 'created')!;
const loserSame = sameOutcomes.find(o => o.status === 'replayed')!;
expect(loserSame.id).toBe(winnerSame.id);
expect(loserSame.createdAt).toBe(winnerSame.createdAt);
const storedSame = (
await f.pool.query<{ id: string }>(
'SELECT id FROM findings WHERE idempotency_key = $1',
['idem-race-same']
)
).rows;
expect(storedSame).toEqual([{ id: winnerSame.id }]);
// Concurrent differing payloads
const diffA = makeFinding({
id: 'f-race-diff-a',
title: 'Race title A',
createdAt: '2026-01-15T11:00:00.000Z',
});
const diffB = makeFinding({
id: 'f-race-diff-b',
title: 'Race title B',
createdAt: '2026-01-15T11:00:01.000Z',
});
const diffOutcomes = await Promise.all([
writePort.appendFinding(diffA, 'idem-race-diff'),
writePort.appendFinding(diffB, 'idem-race-diff'),
]);
const diffStatuses = diffOutcomes.map(o => o.status).sort();
expect(diffStatuses).toEqual(['conflict', 'created']);
const winnerDiff = diffOutcomes.find(o => o.status === 'created')!;
const storedDiff = (
await f.pool.query<{ id: string }>(
'SELECT id FROM findings WHERE idempotency_key = $1',
['idem-race-diff']
)
).rows;
expect(storedDiff).toEqual([{ id: winnerDiff.id }]);
});
test('readers return all eligible candidates in deterministic id order with mixed-case, provider, exact-id precedence, wildcard escaping, and explicit schema', async () => {
const f = await createIsolatedFixture();
// Use admin pool (default search_path) with explicit schema option to verify quoting.
const writePort = createPostgresFindingWritePort({
executor: createPgExecutor(f.admin),
schema: f.schema,
});
const readers = createPostgresKnowledgeReaders({
executor: createPgExecutor(f.admin),
schema: f.schema,
});
await writePort.appendFinding(
makeFinding({
id: 'f-003',
title: '100% Pure_Wild\\Match',
summary: 'Literal wildcard finding.',
createdAt: '2026-01-15T03:00:00.000Z',
})
);
await writePort.appendFinding(
makeFinding({
id: 'f-001',
title: '100X PureAWildXMatch',
summary: 'Near-match without literal wildcards.',
createdAt: '2026-01-15T01:00:00.000Z',
})
);
await writePort.appendFinding(
makeFinding({
id: 'f-002',
title: 'Alpha Drift Signal',
summary: 'Observed on TSX equities.',
createdAt: '2026-01-15T02:00:00.000Z',
})
);
await f.pool.query(
`INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at)
VALUES
('c-003', 'EODHD', 'eodIntraday1M', '100% split_adjusted\\bars', '2026-01-15T03:00:00.000Z'),
('c-001', 'QuoteMedia', 'qmSplits', '100X splitXadjustedYbars', '2026-01-15T01:00:00.000Z'),
('c-002', 'EODHD', 'eodPrices', 'Daily raw OHLCV needs un-adjustment.', '2026-01-15T02:00:00.000Z')`
);
// Deterministic id ASC order for unfiltered reads
expect((await readers.listFindings({})).map(r => r.id)).toEqual(['f-001', 'f-002', 'f-003']);
expect((await readers.listProviderCaveats({})).map(r => r.id)).toEqual([
'c-001',
'c-002',
'c-003',
]);
// Mixed-case query matching
expect((await readers.listFindings({ query: 'tsx EQUITIES' })).map(r => r.id)).toEqual([
'f-002',
]);
expect((await readers.listProviderCaveats({ query: 'DAILY RAW' })).map(r => r.id)).toEqual([
'c-002',
]);
// Case-insensitive provider filter
expect((await readers.listProviderCaveats({ provider: 'eodhd' })).map(r => r.id)).toEqual([
'c-002',
'c-003',
]);
// Exact id is case-sensitive and takes precedence over query
expect(
(await readers.listFindings({ id: 'f-002', query: 'does-not-match' })).map(r => r.id)
).toEqual(['f-002']);
expect(await readers.listFindings({ id: 'F-002' })).toEqual([]);
// Provider condition still applies with exact id
expect(
(await readers.listProviderCaveats({ id: 'c-002', provider: 'eodhd', query: 'nope' })).map(
r => r.id
)
).toEqual(['c-002']);
expect(
await readers.listProviderCaveats({ id: 'c-002', provider: 'quotemedia' })
).toEqual([]);
// Literal wildcard escaping: matches f-003 / c-003 and excludes near-matches f-001 / c-001
expect((await readers.listFindings({ query: '100% Pure_Wild\\' })).map(r => r.id)).toEqual([
'f-003',
]);
expect(
(await readers.listProviderCaveats({ query: '100% split_adjusted\\' })).map(r => r.id)
).toEqual(['c-003']);
});
test('round-trips createFileFindingTool -> createReadKnowledgeTool through MCP server', async () => {
const f = await createIsolatedFixture();
const executor = createPgExecutor(f.pool);
const writePort = createPostgresFindingWritePort({ executor });
const readers = createPostgresKnowledgeReaders({ executor });
await f.pool.query(
`INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at)
VALUES ('caveat-eod-1', 'EODHD', 'eodIntraday1M', 'Retroactively split-adjusted.', $1::timestamptz)`,
[FIXED_TS]
);
let idSeq = 0;
const allowedTrials = new Set(['101', '102']);
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createFileFindingTool({
port: writePort,
trialLookup: {
hasResearchVisibleTrial(ref) {
return allowedTrials.has(ref);
},
},
newId: () => {
idSeq += 1;
return `finding-mcp-${idSeq}`;
},
now: () => new Date(FIXED_TS),
}),
createReadKnowledgeTool({
port: {
listLibraryCards: async () => [],
...readers,
},
}),
],
});
const callTool = async (name: string, args: Record<string, unknown>) => {
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: `req-${name}`,
method: 'tools/call',
params: { name, arguments: args },
})
);
expect(raw).not.toBeNull();
const parsed = JSON.parse(raw!) as {
result: { isError?: boolean; content: Array<{ text: string }> };
};
return parsed.result;
};
// File a new finding through MCP
const fileRes = await callTool('file_finding', {
kind: 'finding',
title: 'Post-earnings drift persists 3 sessions',
summary: 'Positive rank IC across research-visible trials 101 and 102.',
trialRefs: ['102', '101'],
evidenceRefs: ['snap:b', 'snap:a'],
idempotencyKey: 'mcp-idem-1',
});
expect(fileRes.isError).toBeUndefined();
const receipt = JSON.parse(fileRes.content[0]!.text) as FileFindingResultPayload;
expect(receipt).toEqual({
id: 'finding-mcp-1',
createdAt: FIXED_TS,
created: true,
});
// Retry with reordered & duplicate refs -> normalized replay with original receipt
const retryRes = await callTool('file_finding', {
kind: 'finding',
title: 'Post-earnings drift persists 3 sessions',
summary: 'Positive rank IC across research-visible trials 101 and 102.',
trialRefs: ['101', '102', '101'],
evidenceRefs: ['snap:a', 'snap:b', 'snap:a'],
idempotencyKey: 'mcp-idem-1',
});
expect(retryRes.isError).toBeUndefined();
const retryReceipt = JSON.parse(retryRes.content[0]!.text) as FileFindingResultPayload;
expect(retryReceipt).toEqual({
id: 'finding-mcp-1',
createdAt: FIXED_TS,
created: false,
});
// Unavailable / Vault-only trial ref returns error and writes zero rows
const deniedRes = await callTool('file_finding', {
kind: 'dead_end',
title: 'Should not persist',
summary: 'References unavailable trial.',
trialRefs: ['999-vault'],
});
expect(deniedRes.isError).toBe(true);
expect(deniedRes.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
// Read back the filed finding by receipt ID via read_knowledge
const readRes = await callTool('read_knowledge', {
source: 'findings',
id: receipt.id,
});
expect(readRes.isError).toBeUndefined();
const knowledge = JSON.parse(readRes.content[0]!.text) as ReadKnowledgeResultPayload;
expect(knowledge).toEqual({
rowCount: 1,
sources: { library: 0, findings: 1, provider_caveats: 0 },
rows: [
{
source: 'findings',
id: 'finding-mcp-1',
title: 'Post-earnings drift persists 3 sessions',
status: 'pending_review',
createdAt: FIXED_TS,
summary: 'Positive rank IC across research-visible trials 101 and 102.',
trialRefs: ['101', '102'],
evidenceRefs: ['snap:a', 'snap:b'],
truncated: false,
},
],
});
// Verify provider_caveats case-insensitive filter through read_knowledge
const caveatRes = await callTool('read_knowledge', {
source: 'provider_caveats',
provider: 'eodhd',
});
expect(caveatRes.isError).toBeUndefined();
const caveatsPayload = JSON.parse(caveatRes.content[0]!.text) as ReadKnowledgeResultPayload;
expect(caveatsPayload.rowCount).toBe(1);
expect(caveatsPayload.sources).toEqual({ library: 0, findings: 0, provider_caveats: 1 });
expect(caveatsPayload.rows[0]).toEqual({
source: 'provider_caveats',
id: 'caveat-eod-1',
provider: 'EODHD',
dataset: 'eodIntraday1M',
caveat: 'Retroactively split-adjusted.',
createdAt: FIXED_TS,
truncated: false,
});
// Confirm only 1 finding row was persisted in total
const totalFindings = (
await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings')
).rows[0]?.c;
expect(totalFindings).toBe(1);
});
});