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:46:21 -05:00
parent 5654b9cc05
commit a535ebefb5
4 changed files with 280 additions and 47 deletions

View file

@ -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

View file

@ -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;
},

View file

@ -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)', () => {