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
|
|
@ -268,8 +268,8 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
|
|||
|
||||
- **`createPostgresFindingWritePort({ executor, schema? })`** and **`createPostgresKnowledgeReaders({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `PostgresFindingsExecutor`, `PostgresFindingsOptions`, `PostgresKnowledgeReaders`, `PostgresFindingsError`, and `PostgresFindingsErrorCode`) back `file_finding` (`FindingWritePort`) and the `findings` / `provider_caveats` halves of `read_knowledge` (`Pick<KnowledgePort, 'listFindings' | 'listProviderCaveats'>`) over `37-research-findings.sql` with zero runtime `pg` dependency.
|
||||
- **Inputs, schema & row validation:** Validates `executor.query` (`INVALID_EXECUTOR`) and optional `schema` against `^[a-z_][a-z0-9_]*$` (`INVALID_SCHEMA`; defaults to the executor's `search_path`), binds every caller value via `$n` parameters, issues zero `UPDATE`/`DELETE` statements, and fails closed (`INVALID_ROW`) on malformed result envelopes, non-1D/non-string ref arrays, unknown `kind`, or invalid timestamps (converting PostgreSQL `Date` values or strictly parsed timezone-qualified ISO-8601 strings to UTC ISO-8601 output).
|
||||
- **Atomic idempotency & fresh-snapshot requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass a fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` transaction) so concurrent callers can observe the committed winner.
|
||||
- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`), and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`), returning all eligible rows ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing.
|
||||
- **Atomic idempotency & autocommit requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass an autocommit, fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` or explicit `BEGIN` transaction unless the executor rolls back a `SAVEPOINT` before rethrowing errors) so concurrent callers observe the committed winner and `23505` retry lookups do not hit `25P02`.
|
||||
- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`) for ASCII queries, and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`) for ASCII provider filters, falling back to JavaScript `.toLowerCase()` matching on validated candidates for non-ASCII text (e.g., Greek final sigma) so PostgreSQL libc casing never drops `read_knowledge` matches. All eligible rows are returned ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing.
|
||||
|
||||
### Copilot Server
|
||||
|
||||
|
|
|
|||
|
|
@ -51,10 +51,13 @@ export class PostgresFindingsError extends RangeError {
|
|||
* 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.
|
||||
*
|
||||
* For {@link createPostgresFindingWritePort}, the executor should run each call on
|
||||
* a fresh `READ COMMITTED` snapshot (such as a `pg.Pool`) rather than inside a
|
||||
* `REPEATABLE READ` / `SERIALIZABLE` transaction so concurrent idempotent callers
|
||||
* can observe the committed winner after `ON CONFLICT ... DO NOTHING`.
|
||||
* For {@link createPostgresFindingWritePort}, the executor must run each `query()`
|
||||
* call in autocommit mode on a fresh `READ COMMITTED` snapshot (such as a `pg.Pool`)
|
||||
* rather than inside a `REPEATABLE READ` / `SERIALIZABLE` or explicit `BEGIN`
|
||||
* transaction (unless the executor wraps each statement in a `SAVEPOINT` and rolls
|
||||
* it back before rethrowing errors). Autocommit ensures that `ON CONFLICT ... DO
|
||||
* NOTHING` winner lookups observe the committed winner and that same-ID `23505`
|
||||
* primary-key retry lookups do not fail with `25P02` (aborted transaction).
|
||||
*/
|
||||
export interface PostgresFindingsExecutor {
|
||||
query<Row = Record<string, unknown>>(
|
||||
|
|
@ -136,6 +139,24 @@ function escapeLikePattern(value: string): string {
|
|||
return value.replace(/[\\%_]/g, '\\$&');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` when every UTF-16 code unit in `value` is ASCII (`<= 0x7F`).
|
||||
*
|
||||
* PostgreSQL libc `ILIKE` / `lower()` lowercases characters individually, which
|
||||
* diverges from JavaScript's context-sensitive Unicode `.toLowerCase()` (e.g.
|
||||
* Greek final sigma `ΚΟΣΜΟΣ` -> `κοσμος`). SQL pushdown is used only for ASCII
|
||||
* text where casing agrees with `read_knowledge`; non-ASCII queries fall back
|
||||
* to filtering validated candidates with JavaScript's `.toLowerCase()` rules.
|
||||
*/
|
||||
function isAsciiOnly(value: string): boolean {
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
if (value.charCodeAt(i) > 0x7f) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function quoteTable(schemaPrefix: string, table: string): string {
|
||||
return `${schemaPrefix}${table}`;
|
||||
}
|
||||
|
|
@ -586,13 +607,18 @@ export function createPostgresKnowledgeReaders(
|
|||
`FROM ${findingsTable}`,
|
||||
];
|
||||
const params: unknown[] = [];
|
||||
let fallbackNormalizedQuery: string | null = null;
|
||||
|
||||
if (q.id !== undefined) {
|
||||
params.push(q.id);
|
||||
lines.push('WHERE id = $1::text');
|
||||
} else if (q.query !== undefined) {
|
||||
params.push(`%${escapeLikePattern(q.query)}%`);
|
||||
lines.push("WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\'");
|
||||
if (isAsciiOnly(q.query)) {
|
||||
params.push(`%${escapeLikePattern(q.query)}%`);
|
||||
lines.push("WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\'");
|
||||
} else {
|
||||
fallbackNormalizedQuery = q.query.toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
lines.push('ORDER BY id ASC');
|
||||
|
|
@ -601,7 +627,15 @@ export function createPostgresKnowledgeReaders(
|
|||
const rows = extractRows<RawFindingRow>(result);
|
||||
const mapped: FindingRecord[] = [];
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
mapped.push(parseFindingRow(rows[i]));
|
||||
const finding = parseFindingRow(rows[i]);
|
||||
if (
|
||||
fallbackNormalizedQuery !== null &&
|
||||
!finding.title.toLowerCase().includes(fallbackNormalizedQuery) &&
|
||||
!finding.summary.toLowerCase().includes(fallbackNormalizedQuery)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
mapped.push(finding);
|
||||
}
|
||||
return mapped;
|
||||
},
|
||||
|
|
@ -618,21 +652,31 @@ export function createPostgresKnowledgeReaders(
|
|||
];
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let fallbackNormalizedProvider: string | null = null;
|
||||
let fallbackNormalizedQuery: string | null = null;
|
||||
|
||||
if (q.provider !== undefined) {
|
||||
params.push(q.provider);
|
||||
conditions.push(`lower(provider) = lower($${params.length}::text)`);
|
||||
if (isAsciiOnly(q.provider)) {
|
||||
params.push(q.provider);
|
||||
conditions.push(`lower(provider) = lower($${params.length}::text)`);
|
||||
} else {
|
||||
fallbackNormalizedProvider = q.provider.toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
if (q.id !== undefined) {
|
||||
params.push(q.id);
|
||||
conditions.push(`id = $${params.length}::text`);
|
||||
} else if (q.query !== undefined) {
|
||||
params.push(`%${escapeLikePattern(q.query)}%`);
|
||||
const idx = params.length;
|
||||
conditions.push(
|
||||
`(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\')`
|
||||
);
|
||||
if (isAsciiOnly(q.query)) {
|
||||
params.push(`%${escapeLikePattern(q.query)}%`);
|
||||
const idx = params.length;
|
||||
conditions.push(
|
||||
`(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\')`
|
||||
);
|
||||
} else {
|
||||
fallbackNormalizedQuery = q.query.toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
if (conditions.length > 0) {
|
||||
|
|
@ -645,7 +689,22 @@ export function createPostgresKnowledgeReaders(
|
|||
const rows = extractRows<RawProviderCaveatRow>(result);
|
||||
const mapped: ProviderCaveatRecord[] = [];
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
mapped.push(parseProviderCaveatRow(rows[i]));
|
||||
const caveat = parseProviderCaveatRow(rows[i]);
|
||||
if (
|
||||
fallbackNormalizedProvider !== null &&
|
||||
caveat.provider.toLowerCase() !== fallbackNormalizedProvider
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
fallbackNormalizedQuery !== null &&
|
||||
!caveat.provider.toLowerCase().includes(fallbackNormalizedQuery) &&
|
||||
!caveat.dataset.toLowerCase().includes(fallbackNormalizedQuery) &&
|
||||
!caveat.caveat.toLowerCase().includes(fallbackNormalizedQuery)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
mapped.push(caveat);
|
||||
}
|
||||
return mapped;
|
||||
},
|
||||
|
|
|
|||
|
|
@ -426,6 +426,54 @@ describe('createPostgresKnowledgeReaders (fake executor)', () => {
|
|||
|
||||
assertNoMutationOrReaderLimitSql(fake.calls, true);
|
||||
});
|
||||
|
||||
test('falls back to JS Unicode lowercasing for non-ASCII query/provider while preserving ASCII SQL pushdown and row validation', async () => {
|
||||
// Findings: non-ASCII query (Greek final sigma) omits SQL ILIKE and filters with JS .toLowerCase()
|
||||
const findingFake = createFakeExecutor([
|
||||
makeRawFindingRow({ id: 'f-1', title: 'Αλφα κοσμος', summary: 'Greek cosmos finding.' }),
|
||||
makeRawFindingRow({ id: 'f-2', title: 'Unrelated', summary: 'Does not match.' }),
|
||||
makeRawFindingRow({ id: 'f-3', title: 'Other', summary: 'Summary has κοσμος too.' }),
|
||||
]);
|
||||
const findingReaders = createPostgresKnowledgeReaders({ executor: findingFake.executor });
|
||||
const findingMatches = await findingReaders.listFindings({ query: 'ΚΟΣΜΟΣ' });
|
||||
expect(findingMatches.map(r => r.id)).toEqual(['f-1', 'f-3']);
|
||||
expect(findingFake.calls[0]!.text).not.toContain('ILIKE');
|
||||
expect(findingFake.calls[0]!.text).not.toContain('WHERE');
|
||||
expect(findingFake.calls[0]!.params).toEqual([]);
|
||||
|
||||
// Provider caveats: ASCII provider still pushes down SQL lower(provider), non-ASCII query filters in JS
|
||||
const caveatFake = createFakeExecutor([
|
||||
makeRawCaveatRow({ id: 'c-1', provider: 'EODHD', caveat: 'Note on κοσμος regime.' }),
|
||||
makeRawCaveatRow({ id: 'c-2', provider: 'EODHD', caveat: 'Unrelated note.' }),
|
||||
]);
|
||||
const caveatReaders = createPostgresKnowledgeReaders({ executor: caveatFake.executor });
|
||||
const caveatMatches = await caveatReaders.listProviderCaveats({
|
||||
provider: 'eodhd',
|
||||
query: 'ΚΟΣΜΟΣ',
|
||||
});
|
||||
expect(caveatMatches.map(r => r.id)).toEqual(['c-1']);
|
||||
expect(caveatFake.calls[0]!.text).toContain('WHERE lower(provider) = lower($1::text)');
|
||||
expect(caveatFake.calls[0]!.text).not.toContain('ILIKE');
|
||||
expect(caveatFake.calls[0]!.params).toEqual(['eodhd']);
|
||||
|
||||
// Provider caveats: non-ASCII provider falls back to JS exact case-insensitive match
|
||||
const nonAsciiProvFake = createFakeExecutor([
|
||||
makeRawCaveatRow({ id: 'c-1', provider: 'κοσμος', dataset: 'ds', caveat: 'c' }),
|
||||
makeRawCaveatRow({ id: 'c-2', provider: 'EODHD', dataset: 'ds', caveat: 'c' }),
|
||||
]);
|
||||
const nonAsciiProvReaders = createPostgresKnowledgeReaders({
|
||||
executor: nonAsciiProvFake.executor,
|
||||
});
|
||||
const provMatches = await nonAsciiProvReaders.listProviderCaveats({ provider: 'ΚΟΣΜΟΣ' });
|
||||
expect(provMatches.map(r => r.id)).toEqual(['c-1']);
|
||||
expect(nonAsciiProvFake.calls[0]!.text).not.toContain('WHERE');
|
||||
expect(nonAsciiProvFake.calls[0]!.params).toEqual([]);
|
||||
|
||||
assertNoMutationOrReaderLimitSql(
|
||||
[...findingFake.calls, ...caveatFake.calls, ...nonAsciiProvFake.calls],
|
||||
true
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PostgreSQL findings adapter validation (fake executor)', () => {
|
||||
|
|
|
|||
|
|
@ -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