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:
parent
5654b9cc05
commit
a535ebefb5
4 changed files with 280 additions and 47 deletions
|
|
@ -2,7 +2,7 @@ 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 { Client, Pool, type PoolClient, type PoolConfig } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
||||
import {
|
||||
|
|
@ -33,19 +33,39 @@ afterEach(async () => {
|
|||
});
|
||||
|
||||
function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
|
||||
if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) {
|
||||
if (!connectionString) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(connectionString);
|
||||
} catch {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const client = new Client({ connectionString });
|
||||
const effectiveDb = (
|
||||
client as unknown as { connectionParameters?: { database?: unknown } }
|
||||
).connectionParameters?.database;
|
||||
if (
|
||||
typeof effectiveDb !== 'string' ||
|
||||
!effectiveDb.startsWith('stock_bot_safety') ||
|
||||
!parsed.pathname.startsWith('/stock_bot_safety')
|
||||
) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
return connectionString;
|
||||
}
|
||||
|
||||
function createPgExecutor(pool: Pool): PostgresFindingsExecutor {
|
||||
function createPgExecutor(queryable: Pick<Pool, 'query'> | Pick<PoolClient, 'query'>): PostgresFindingsExecutor {
|
||||
return {
|
||||
query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }> {
|
||||
return pool.query(
|
||||
return queryable.query(
|
||||
text,
|
||||
params === undefined ? undefined : [...params]
|
||||
) as unknown as Promise<{ readonly rows: readonly Row[] }>;
|
||||
|
|
@ -53,6 +73,21 @@ function createPgExecutor(pool: Pool): PostgresFindingsExecutor {
|
|||
};
|
||||
}
|
||||
|
||||
async function waitForBackendLockWait(pool: Pool, pid: number, timeoutMs = 2000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
const { rows } = await pool.query<{ wait_event_type: string | null }>(
|
||||
'SELECT wait_event_type FROM pg_stat_activity WHERE pid = $1',
|
||||
[pid]
|
||||
);
|
||||
if (rows[0]?.wait_event_type === 'Lock') {
|
||||
return;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
throw new Error(`Timed out waiting for backend pid ${pid} to enter Lock wait`);
|
||||
}
|
||||
|
||||
function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig {
|
||||
const safeUrl = assertSafetyDatabaseUrl(connectionString);
|
||||
const parsed = new URL(safeUrl);
|
||||
|
|
@ -141,9 +176,26 @@ describe('PostgreSQL findings adapter safety guard', () => {
|
|||
expect(() =>
|
||||
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev')
|
||||
).toThrow('Dedicated stock_bot_safety database required');
|
||||
expect(() =>
|
||||
assertSafetyDatabaseUrl('socket:/stock_bot_safety?db=trading_bot')
|
||||
).toThrow('Dedicated stock_bot_safety database required');
|
||||
expect(() =>
|
||||
assertSafetyDatabaseUrl('socket:///stock_bot_safety?db=trading_bot')
|
||||
).toThrow('Dedicated stock_bot_safety database required');
|
||||
expect(() =>
|
||||
assertSafetyDatabaseUrl('http://127.0.0.1:5432/stock_bot_safety_test')
|
||||
).toThrow('Dedicated stock_bot_safety database required');
|
||||
expect(() => assertSafetyDatabaseUrl('not-a-valid-url')).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');
|
||||
expect(
|
||||
assertSafetyDatabaseUrl(
|
||||
'postgresql://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'
|
||||
)
|
||||
).toBe('postgresql://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test');
|
||||
});
|
||||
|
||||
test('preserves isolated schema search_path precedence over URL startup options', () => {
|
||||
|
|
@ -235,25 +287,66 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () =
|
|||
expect(countRow?.c).toBe(3);
|
||||
});
|
||||
|
||||
test('concurrent same-key appends on separate connections leave exactly one stored row for identical and differing payloads', async () => {
|
||||
test('concurrent same-key appends on pinned connections observe committed winner via fresh snapshot for identical and differing payloads', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const writePort = createPostgresFindingWritePort({ executor: createPgExecutor(f.pool) });
|
||||
|
||||
// Concurrent identical payloads
|
||||
const runPinnedRace = async (
|
||||
key: string,
|
||||
winnerRecord: FiledFindingRecord,
|
||||
loserRecord: FiledFindingRecord
|
||||
) => {
|
||||
const winnerClient = await f.pool.connect();
|
||||
const loserClient = await f.pool.connect();
|
||||
let winnerOpen = false;
|
||||
cleanup.push(async () => {
|
||||
if (winnerOpen) {
|
||||
await winnerClient.query('ROLLBACK').catch(() => {});
|
||||
}
|
||||
winnerClient.release();
|
||||
loserClient.release();
|
||||
});
|
||||
|
||||
const loserPid = (
|
||||
await loserClient.query<{ pid: number }>('SELECT pg_backend_pid() AS pid')
|
||||
).rows[0]!.pid;
|
||||
|
||||
const winnerPort = createPostgresFindingWritePort({
|
||||
executor: createPgExecutor(winnerClient),
|
||||
});
|
||||
const loserPort = createPostgresFindingWritePort({
|
||||
executor: createPgExecutor(loserClient),
|
||||
});
|
||||
|
||||
await winnerClient.query('BEGIN');
|
||||
winnerOpen = true;
|
||||
const winnerOutcome = await winnerPort.appendFinding(winnerRecord, key);
|
||||
expect(winnerOutcome).toEqual({
|
||||
status: 'created',
|
||||
id: winnerRecord.id,
|
||||
createdAt: winnerRecord.createdAt,
|
||||
});
|
||||
|
||||
// Start the competing append on the second connection and wait until PostgreSQL
|
||||
// blocks its INSERT ... ON CONFLICT DO NOTHING on the winner's uncommitted tuple.
|
||||
const loserPromise = loserPort.appendFinding(loserRecord, key);
|
||||
await waitForBackendLockWait(f.pool, loserPid);
|
||||
|
||||
await winnerClient.query('COMMIT');
|
||||
winnerOpen = false;
|
||||
|
||||
const loserOutcome = await loserPromise;
|
||||
return { winnerOutcome, loserOutcome };
|
||||
};
|
||||
|
||||
// Concurrent identical payloads: loser's separate READ COMMITTED lookup sees winner -> replayed
|
||||
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 sameRace = await runPinnedRace('idem-race-same', recA, recB);
|
||||
expect(sameRace.loserOutcome).toEqual({
|
||||
status: 'replayed',
|
||||
id: recA.id,
|
||||
createdAt: recA.createdAt,
|
||||
});
|
||||
|
||||
const storedSame = (
|
||||
await f.pool.query<{ id: string }>(
|
||||
|
|
@ -261,9 +354,9 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () =
|
|||
['idem-race-same']
|
||||
)
|
||||
).rows;
|
||||
expect(storedSame).toEqual([{ id: winnerSame.id }]);
|
||||
expect(storedSame).toEqual([{ id: recA.id }]);
|
||||
|
||||
// Concurrent differing payloads
|
||||
// Concurrent differing payloads: loser's separate READ COMMITTED lookup sees winner -> conflict
|
||||
const diffA = makeFinding({
|
||||
id: 'f-race-diff-a',
|
||||
title: 'Race title A',
|
||||
|
|
@ -274,22 +367,16 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () =
|
|||
title: 'Race title B',
|
||||
createdAt: '2026-01-15T11:00:01.000Z',
|
||||
});
|
||||
const diffRace = await runPinnedRace('idem-race-diff', diffA, diffB);
|
||||
expect(diffRace.loserOutcome).toEqual({ status: 'conflict' });
|
||||
|
||||
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 }]);
|
||||
expect(storedDiff).toEqual([{ id: diffA.id }]);
|
||||
});
|
||||
|
||||
test('readers return all eligible candidates in deterministic id order with mixed-case, provider, exact-id precedence, wildcard escaping, and explicit schema', async () => {
|
||||
|
|
@ -533,5 +620,44 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () =
|
|||
await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings')
|
||||
).rows[0]?.c;
|
||||
expect(totalFindings).toBe(1);
|
||||
|
||||
// Regression: Unicode final sigma (κοσμος vs ΚΟΣΜΟΣ) must not be dropped by libc ILIKE
|
||||
const sigmaFileRes = await callTool('file_finding', {
|
||||
kind: 'finding',
|
||||
title: 'κοσμος',
|
||||
summary: 'Greek final sigma regression finding.',
|
||||
trialRefs: ['101'],
|
||||
evidenceRefs: [],
|
||||
});
|
||||
expect(sigmaFileRes.isError).toBeUndefined();
|
||||
const sigmaReceipt = JSON.parse(sigmaFileRes.content[0]!.text) as FileFindingResultPayload;
|
||||
|
||||
const sigmaReadRes = await callTool('read_knowledge', {
|
||||
source: 'findings',
|
||||
query: 'ΚΟΣΜΟΣ',
|
||||
});
|
||||
expect(sigmaReadRes.isError).toBeUndefined();
|
||||
const sigmaKnowledge = JSON.parse(
|
||||
sigmaReadRes.content[0]!.text
|
||||
) as ReadKnowledgeResultPayload;
|
||||
expect(sigmaKnowledge.rowCount).toBe(1);
|
||||
expect(sigmaKnowledge.rows[0]?.id).toBe(sigmaReceipt.id);
|
||||
|
||||
await f.pool.query(
|
||||
`INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at)
|
||||
VALUES ('caveat-sigma-1', 'EODHD', 'eodPrices', 'Caveat for κοσμος tickers.', $1::timestamptz)`,
|
||||
[FIXED_TS]
|
||||
);
|
||||
const sigmaCaveatRes = await callTool('read_knowledge', {
|
||||
source: 'provider_caveats',
|
||||
provider: 'eodhd',
|
||||
query: 'ΚΟΣΜΟΣ',
|
||||
});
|
||||
expect(sigmaCaveatRes.isError).toBeUndefined();
|
||||
const sigmaCaveats = JSON.parse(
|
||||
sigmaCaveatRes.content[0]!.text
|
||||
) as ReadKnowledgeResultPayload;
|
||||
expect(sigmaCaveats.rowCount).toBe(1);
|
||||
expect(sigmaCaveats.rows[0]?.id).toBe('caveat-sigma-1');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue