772 lines
28 KiB
TypeScript
772 lines
28 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
||
import {
|
||
type FiledFindingRecord,
|
||
type PostgresFindingsExecutor,
|
||
PostgresFindingsError,
|
||
createPostgresFindingWritePort,
|
||
createPostgresKnowledgeReaders,
|
||
} from '../src/mcp/index';
|
||
|
||
interface RecordedCall {
|
||
readonly text: string;
|
||
readonly params: readonly unknown[] | undefined;
|
||
}
|
||
|
||
type QueryHandler = (
|
||
text: string,
|
||
params: readonly unknown[] | undefined,
|
||
callIndex: number
|
||
) => Promise<{ readonly rows: readonly Record<string, unknown>[] }> | { readonly rows: readonly Record<string, unknown>[] };
|
||
|
||
function createSequenceExecutor(handler: QueryHandler): {
|
||
readonly calls: RecordedCall[];
|
||
readonly executor: PostgresFindingsExecutor;
|
||
} {
|
||
const calls: RecordedCall[] = [];
|
||
const executor: PostgresFindingsExecutor = {
|
||
async query<Row = Record<string, unknown>>(
|
||
text: string,
|
||
params?: readonly unknown[]
|
||
): Promise<{ readonly rows: readonly Row[] }> {
|
||
const idx = calls.length;
|
||
calls.push({ text, params });
|
||
const res = await handler(text, params, idx);
|
||
return res as unknown as { readonly rows: readonly Row[] };
|
||
},
|
||
};
|
||
return { calls, executor };
|
||
}
|
||
|
||
function createFakeExecutor(rows: readonly Record<string, unknown>[] = []): {
|
||
readonly calls: RecordedCall[];
|
||
readonly executor: PostgresFindingsExecutor;
|
||
} {
|
||
return createSequenceExecutor(() => ({ rows }));
|
||
}
|
||
|
||
const FIXED_TS = '2026-01-15T12:34:56.789Z';
|
||
|
||
function makeFiledRecord(overrides: Partial<FiledFindingRecord> = {}): FiledFindingRecord {
|
||
return {
|
||
id: 'finding-001',
|
||
kind: 'finding',
|
||
title: 'Momentum 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,
|
||
};
|
||
}
|
||
|
||
function makeRawFindingRow(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||
return {
|
||
id: 'finding-001',
|
||
title: 'Momentum decays after 5 sessions',
|
||
status: 'pending_review',
|
||
created_at: new Date(FIXED_TS),
|
||
summary: 'Cross-sectional rank IC turns negative past day 5.',
|
||
trial_refs: ['101', '102'],
|
||
evidence_refs: ['snap:2026-01-15:ic'],
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
function makeRawReplayRow(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||
return {
|
||
id: 'finding-001',
|
||
kind: 'finding',
|
||
title: 'Momentum decays after 5 sessions',
|
||
summary: 'Cross-sectional rank IC turns negative past day 5.',
|
||
created_at: new Date(FIXED_TS),
|
||
trial_refs: ['101', '102'],
|
||
evidence_refs: ['snap:2026-01-15:ic'],
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
function makeRawCaveatRow(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||
return {
|
||
id: 'caveat-001',
|
||
provider: 'EODHD',
|
||
dataset: 'eodIntraday1M',
|
||
caveat: 'Intraday 1m OHLCV is retroactively split-adjusted.',
|
||
created_at: new Date(FIXED_TS),
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
function assertNoMutationOrReaderLimitSql(calls: readonly RecordedCall[], checkNoLimit = false): void {
|
||
for (const call of calls) {
|
||
expect(call.text).not.toMatch(/\bUPDATE\b/i);
|
||
expect(call.text).not.toMatch(/\bDELETE\b/i);
|
||
expect(call.text).not.toMatch(/\bTRUNCATE\b/i);
|
||
if (checkNoLimit) {
|
||
expect(call.text).not.toMatch(/\bLIMIT\b/i);
|
||
}
|
||
}
|
||
}
|
||
|
||
describe('createPostgresFindingWritePort (fake executor)', () => {
|
||
test('unkeyed append issues plain parameterized INSERT with NULL key and never interpolates values', async () => {
|
||
const injection = "'; DROP TABLE findings; --";
|
||
const fake = createFakeExecutor([{ id: 'finding-inj', created_at: new Date(FIXED_TS) }]);
|
||
const port = createPostgresFindingWritePort({ executor: fake.executor });
|
||
|
||
const record = makeFiledRecord({
|
||
id: 'finding-inj',
|
||
title: injection,
|
||
summary: `summary ${injection}`,
|
||
trialRefs: [injection],
|
||
evidenceRefs: [`ev:${injection}`],
|
||
});
|
||
|
||
const outcome = await port.appendFinding(record);
|
||
|
||
expect(outcome).toEqual({
|
||
status: 'created',
|
||
id: 'finding-inj',
|
||
createdAt: FIXED_TS,
|
||
});
|
||
expect(fake.calls).toHaveLength(1);
|
||
const call = fake.calls[0]!;
|
||
expect(call.text).toContain('INSERT INTO findings');
|
||
expect(call.text).not.toContain('ON CONFLICT');
|
||
expect(call.text).toContain('RETURNING id, created_at');
|
||
expect(call.text).not.toContain(injection);
|
||
expect(call.text).not.toContain(';');
|
||
expect(call.params).toEqual([
|
||
'finding-inj',
|
||
'finding',
|
||
injection,
|
||
`summary ${injection}`,
|
||
'pending_review',
|
||
FIXED_TS,
|
||
[injection],
|
||
[`ev:${injection}`],
|
||
null,
|
||
]);
|
||
assertNoMutationOrReaderLimitSql(fake.calls);
|
||
});
|
||
|
||
test('keyed append uses partial-index ON CONFLICT DO NOTHING and returns created on 1 returned row', async () => {
|
||
const fake = createFakeExecutor([
|
||
{ id: 'finding-001', created_at: '2026-01-15T14:34:56.789+02:00' },
|
||
]);
|
||
const port = createPostgresFindingWritePort({ executor: fake.executor });
|
||
|
||
const outcome = await port.appendFinding(makeFiledRecord(), 'idem-key-1');
|
||
|
||
expect(outcome).toEqual({
|
||
status: 'created',
|
||
id: 'finding-001',
|
||
createdAt: FIXED_TS,
|
||
});
|
||
expect(fake.calls).toHaveLength(1);
|
||
const call = fake.calls[0]!;
|
||
expect(call.text).toContain(
|
||
'ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING'
|
||
);
|
||
expect(call.text).not.toContain('idem-key-1');
|
||
expect(call.params).toEqual([
|
||
'finding-001',
|
||
'finding',
|
||
'Momentum decays after 5 sessions',
|
||
'Cross-sectional rank IC turns negative past day 5.',
|
||
'pending_review',
|
||
FIXED_TS,
|
||
['101', '102'],
|
||
['snap:2026-01-15:ic'],
|
||
'idem-key-1',
|
||
]);
|
||
assertNoMutationOrReaderLimitSql(fake.calls);
|
||
});
|
||
|
||
test('keyed append reads winner in separate SELECT on 0 rows and returns replayed with stored metadata', async () => {
|
||
const fake = createSequenceExecutor((_text, _params, idx) => {
|
||
if (idx === 0) {
|
||
return { rows: [] };
|
||
}
|
||
return {
|
||
rows: [
|
||
makeRawReplayRow({
|
||
id: 'finding-original',
|
||
created_at: '2026-01-15T07:34:56.789999-05:00',
|
||
}),
|
||
],
|
||
};
|
||
});
|
||
const port = createPostgresFindingWritePort({ executor: fake.executor });
|
||
|
||
// Incoming call has a new id and createdAt, but identical comparable payload
|
||
const outcome = await port.appendFinding(
|
||
makeFiledRecord({
|
||
id: 'finding-retry-new-id',
|
||
createdAt: '2026-01-16T00:00:00.000Z',
|
||
}),
|
||
'idem-replay'
|
||
);
|
||
|
||
expect(outcome).toEqual({
|
||
status: 'replayed',
|
||
id: 'finding-original',
|
||
createdAt: FIXED_TS,
|
||
});
|
||
expect(fake.calls).toHaveLength(2);
|
||
expect(fake.calls[1]!.text).toContain('SELECT');
|
||
expect(fake.calls[1]!.text).toContain('WHERE idempotency_key = $1::text');
|
||
expect(fake.calls[1]!.params).toEqual(['idem-replay']);
|
||
assertNoMutationOrReaderLimitSql(fake.calls);
|
||
});
|
||
|
||
test('keyed append returns conflict when stored payload differs on any comparable field', async () => {
|
||
const diffs: readonly Partial<FiledFindingRecord>[] = [
|
||
{ kind: 'dead_end' },
|
||
{ title: 'Different title' },
|
||
{ summary: 'Different summary' },
|
||
{ trialRefs: ['101'] },
|
||
{ trialRefs: ['102', '101'] },
|
||
{ evidenceRefs: [] },
|
||
];
|
||
|
||
for (const diff of diffs) {
|
||
const fake = createSequenceExecutor((_text, _params, idx) =>
|
||
idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow()] }
|
||
);
|
||
const port = createPostgresFindingWritePort({ executor: fake.executor });
|
||
|
||
const outcome = await port.appendFinding(makeFiledRecord(diff), 'idem-conflict');
|
||
expect(outcome).toEqual({ status: 'conflict' });
|
||
expect(fake.calls).toHaveLength(2);
|
||
assertNoMutationOrReaderLimitSql(fake.calls);
|
||
}
|
||
});
|
||
|
||
test('keyed append resolves same-ID 23505 retry as replayed or conflict, and propagates unrelated 23505 or other errors', async () => {
|
||
const pkErr = Object.assign(new Error('duplicate key value violates unique constraint'), {
|
||
code: '23505',
|
||
});
|
||
|
||
// Same ID + identical payload -> replayed
|
||
const fakeReplay = createSequenceExecutor((_text, _params, idx) => {
|
||
if (idx === 0) {
|
||
throw pkErr;
|
||
}
|
||
return { rows: [makeRawReplayRow({ id: 'finding-001' })] };
|
||
});
|
||
const replayPort = createPostgresFindingWritePort({ executor: fakeReplay.executor });
|
||
expect(await replayPort.appendFinding(makeFiledRecord(), 'idem-same-id')).toEqual({
|
||
status: 'replayed',
|
||
id: 'finding-001',
|
||
createdAt: FIXED_TS,
|
||
});
|
||
expect(fakeReplay.calls).toHaveLength(2);
|
||
|
||
// Same ID + different payload -> conflict
|
||
const fakeConflict = createSequenceExecutor((_text, _params, idx) => {
|
||
if (idx === 0) {
|
||
throw pkErr;
|
||
}
|
||
return { rows: [makeRawReplayRow({ id: 'finding-001', title: 'Other title' })] };
|
||
});
|
||
const conflictPort = createPostgresFindingWritePort({ executor: fakeConflict.executor });
|
||
expect(await conflictPort.appendFinding(makeFiledRecord(), 'idem-same-id')).toEqual({
|
||
status: 'conflict',
|
||
});
|
||
|
||
// Unrelated PK collision: no stored row for idempotency_key -> propagate pkErr
|
||
const fakeMissing = createSequenceExecutor((_text, _params, idx) => {
|
||
if (idx === 0) {
|
||
throw pkErr;
|
||
}
|
||
return { rows: [] };
|
||
});
|
||
const missingPort = createPostgresFindingWritePort({ executor: fakeMissing.executor });
|
||
await expect(missingPort.appendFinding(makeFiledRecord(), 'idem-unrelated')).rejects.toBe(
|
||
pkErr
|
||
);
|
||
|
||
// Unrelated PK collision: stored row for idempotency_key has different ID -> propagate pkErr
|
||
const fakeDifferentId = createSequenceExecutor((_text, _params, idx) => {
|
||
if (idx === 0) {
|
||
throw pkErr;
|
||
}
|
||
return { rows: [makeRawReplayRow({ id: 'finding-other' })] };
|
||
});
|
||
const diffIdPort = createPostgresFindingWritePort({ executor: fakeDifferentId.executor });
|
||
await expect(diffIdPort.appendFinding(makeFiledRecord(), 'idem-other-id')).rejects.toBe(pkErr);
|
||
|
||
// Non-23505 error -> propagates immediately without SELECT
|
||
const checkErr = Object.assign(new Error('check violation'), { code: '23514' });
|
||
const fakeOther = createSequenceExecutor(() => {
|
||
throw checkErr;
|
||
});
|
||
const otherPort = createPostgresFindingWritePort({ executor: fakeOther.executor });
|
||
await expect(otherPort.appendFinding(makeFiledRecord(), 'idem-check')).rejects.toBe(checkErr);
|
||
expect(fakeOther.calls).toHaveLength(1);
|
||
|
||
// Unkeyed 23505 -> propagates immediately without SELECT
|
||
const fakeUnkeyed = createSequenceExecutor(() => {
|
||
throw pkErr;
|
||
});
|
||
const unkeyedPort = createPostgresFindingWritePort({ executor: fakeUnkeyed.executor });
|
||
await expect(unkeyedPort.appendFinding(makeFiledRecord())).rejects.toBe(pkErr);
|
||
expect(fakeUnkeyed.calls).toHaveLength(1);
|
||
});
|
||
|
||
test('quotes explicit schema on INSERT and replay SELECT, and omits prefix when unset', async () => {
|
||
const fakeScoped = createSequenceExecutor((_text, _params, idx) =>
|
||
idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow()] }
|
||
);
|
||
const scopedPort = createPostgresFindingWritePort({
|
||
executor: fakeScoped.executor,
|
||
schema: 'custom_research_1',
|
||
});
|
||
await scopedPort.appendFinding(makeFiledRecord(), 'idem-schema');
|
||
|
||
expect(fakeScoped.calls[0]!.text).toContain('INSERT INTO "custom_research_1".findings');
|
||
expect(fakeScoped.calls[1]!.text).toContain('FROM "custom_research_1".findings');
|
||
assertNoMutationOrReaderLimitSql(fakeScoped.calls);
|
||
});
|
||
});
|
||
|
||
describe('createPostgresKnowledgeReaders (fake executor)', () => {
|
||
test('listFindings binds exact id (taking precedence over query), escaped ILIKE query, and unfiltered queries with ORDER BY id ASC and no LIMIT', async () => {
|
||
const injection = "'; DELETE FROM findings; --";
|
||
const fake = createFakeExecutor([makeRawFindingRow()]);
|
||
const readers = createPostgresKnowledgeReaders({ executor: fake.executor });
|
||
|
||
// Unfiltered
|
||
const allRows = await readers.listFindings({});
|
||
expect(allRows).toEqual([
|
||
{
|
||
id: 'finding-001',
|
||
title: 'Momentum 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'],
|
||
},
|
||
]);
|
||
expect(fake.calls[0]!.text).not.toContain('WHERE');
|
||
expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY id ASC')).toBe(true);
|
||
expect(fake.calls[0]!.params).toEqual([]);
|
||
|
||
// Exact id takes precedence over query
|
||
await readers.listFindings({ id: injection, query: 'ignored' });
|
||
expect(fake.calls[1]!.text).toContain('WHERE id = $1::text');
|
||
expect(fake.calls[1]!.text).not.toContain('ILIKE');
|
||
expect(fake.calls[1]!.text).not.toContain(injection);
|
||
expect(fake.calls[1]!.params).toEqual([injection]);
|
||
|
||
// Escaped ILIKE query on title and summary (retaining non-ASCII stored rows as candidates)
|
||
await readers.listFindings({ query: '100% pure_wild\\path' });
|
||
expect(fake.calls[2]!.text).toContain(
|
||
"WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\' OR title ~ '[^\\x01-\\x7f]' OR summary ~ '[^\\x01-\\x7f]'"
|
||
);
|
||
expect(fake.calls[2]!.params).toEqual(['%100\\% pure\\_wild\\\\path%']);
|
||
|
||
assertNoMutationOrReaderLimitSql(fake.calls, true);
|
||
});
|
||
|
||
test('listProviderCaveats combines case-insensitive provider with id or escaped ILIKE query and no LIMIT', async () => {
|
||
const fake = createFakeExecutor([
|
||
makeRawCaveatRow({ created_at: '2026-01-15T12:34:56.789Z' }),
|
||
]);
|
||
const readers = createPostgresKnowledgeReaders({
|
||
executor: fake.executor,
|
||
schema: 'custom_research_2',
|
||
});
|
||
|
||
// Unfiltered
|
||
const rows = await readers.listProviderCaveats({});
|
||
expect(rows).toEqual([
|
||
{
|
||
id: 'caveat-001',
|
||
provider: 'EODHD',
|
||
dataset: 'eodIntraday1M',
|
||
caveat: 'Intraday 1m OHLCV is retroactively split-adjusted.',
|
||
createdAt: FIXED_TS,
|
||
},
|
||
]);
|
||
expect(fake.calls[0]!.text).toContain('FROM "custom_research_2".provider_caveats');
|
||
expect(fake.calls[0]!.text).not.toContain('WHERE');
|
||
expect(fake.calls[0]!.params).toEqual([]);
|
||
|
||
// Provider + exact id (id takes precedence over query)
|
||
await readers.listProviderCaveats({
|
||
provider: 'eodhd',
|
||
id: 'caveat-001',
|
||
query: 'ignored',
|
||
});
|
||
expect(fake.calls[1]!.text).toContain(
|
||
"WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]') AND id = $2::text"
|
||
);
|
||
expect(fake.calls[1]!.text).not.toContain('ILIKE');
|
||
expect(fake.calls[1]!.params).toEqual(['eodhd', 'caveat-001']);
|
||
|
||
// Provider + query with wildcards
|
||
await readers.listProviderCaveats({
|
||
provider: 'QuoteMedia',
|
||
query: '50%_ratio\\inv',
|
||
});
|
||
expect(fake.calls[2]!.text).toContain(
|
||
"WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]') AND (provider ILIKE $2::text ESCAPE '\\' OR dataset ILIKE $2::text ESCAPE '\\' OR caveat ILIKE $2::text ESCAPE '\\' OR provider ~ '[^\\x01-\\x7f]' OR dataset ~ '[^\\x01-\\x7f]' OR caveat ~ '[^\\x01-\\x7f]')"
|
||
);
|
||
expect(fake.calls[2]!.params).toEqual(['QuoteMedia', '%50\\%\\_ratio\\\\inv%']);
|
||
|
||
// Query only
|
||
await readers.listProviderCaveats({ query: 'split' });
|
||
expect(fake.calls[3]!.text).toContain(
|
||
"WHERE (provider ILIKE $1::text ESCAPE '\\' OR dataset ILIKE $1::text ESCAPE '\\' OR caveat ILIKE $1::text ESCAPE '\\' OR provider ~ '[^\\x01-\\x7f]' OR dataset ~ '[^\\x01-\\x7f]' OR caveat ~ '[^\\x01-\\x7f]')"
|
||
);
|
||
expect(fake.calls[3]!.params).toEqual(['%split%']);
|
||
|
||
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) OR provider ~ '[^\\x01-\\x7f]')"
|
||
);
|
||
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([]);
|
||
|
||
// ASCII query / ASCII provider against Unicode stored rows (e.g. BİST and K under C collation):
|
||
// SQL retains non-ASCII stored rows as candidates and JS .toLowerCase() filters out non-matches.
|
||
const asciiAgainstUnicodeFindingFake = createFakeExecutor([
|
||
makeRawFindingRow({
|
||
id: 'f-bist',
|
||
title: 'BİST exchange coverage',
|
||
summary: 'Turkish equities.',
|
||
}),
|
||
makeRawFindingRow({
|
||
id: 'f-other-unicode',
|
||
title: 'κόσμος',
|
||
summary: 'Unrelated Greek finding.',
|
||
}),
|
||
]);
|
||
const asciiFindingReaders = createPostgresKnowledgeReaders({
|
||
executor: asciiAgainstUnicodeFindingFake.executor,
|
||
});
|
||
expect((await asciiFindingReaders.listFindings({ query: 'bi' })).map(r => r.id)).toEqual([
|
||
'f-bist',
|
||
]);
|
||
|
||
const asciiAgainstUnicodeCaveatFake = createFakeExecutor([
|
||
makeRawCaveatRow({
|
||
id: 'c-kelvin',
|
||
provider: 'K',
|
||
dataset: 'ds',
|
||
caveat: 'BİST feed note.',
|
||
}),
|
||
makeRawCaveatRow({
|
||
id: 'c-other-unicode',
|
||
provider: 'κόσμος',
|
||
dataset: 'ds',
|
||
caveat: 'Unrelated.',
|
||
}),
|
||
]);
|
||
const asciiCaveatReaders = createPostgresKnowledgeReaders({
|
||
executor: asciiAgainstUnicodeCaveatFake.executor,
|
||
});
|
||
expect(
|
||
(await asciiCaveatReaders.listProviderCaveats({ provider: 'k', query: 'bi' })).map(r => r.id)
|
||
).toEqual(['c-kelvin']);
|
||
|
||
assertNoMutationOrReaderLimitSql(
|
||
[
|
||
...findingFake.calls,
|
||
...caveatFake.calls,
|
||
...nonAsciiProvFake.calls,
|
||
...asciiAgainstUnicodeFindingFake.calls,
|
||
...asciiAgainstUnicodeCaveatFake.calls,
|
||
],
|
||
true
|
||
);
|
||
});
|
||
});
|
||
|
||
describe('PostgreSQL findings adapter validation (fake executor)', () => {
|
||
test('rejects invalid executors and options with INVALID_EXECUTOR before any query', () => {
|
||
const invalidOptions: unknown[] = [
|
||
null,
|
||
undefined,
|
||
{},
|
||
{ executor: null },
|
||
{ executor: {} },
|
||
{ executor: { query: 'not-a-fn' } },
|
||
];
|
||
|
||
for (const opts of invalidOptions) {
|
||
for (const factory of [createPostgresFindingWritePort, createPostgresKnowledgeReaders]) {
|
||
let caught: unknown;
|
||
try {
|
||
factory(opts as Parameters<typeof createPostgresFindingWritePort>[0]);
|
||
} catch (err) {
|
||
caught = err;
|
||
}
|
||
expect(caught).toBeInstanceOf(PostgresFindingsError);
|
||
expect((caught as PostgresFindingsError).code).toBe('INVALID_EXECUTOR');
|
||
}
|
||
}
|
||
});
|
||
|
||
test('rejects invalid schema names with INVALID_SCHEMA before any query', () => {
|
||
const fake = createFakeExecutor([]);
|
||
const badSchemas: unknown[] = [
|
||
'',
|
||
'Public',
|
||
'1schema',
|
||
'bad-name',
|
||
'bad.name',
|
||
'public"; DROP TABLE findings; --',
|
||
'space name',
|
||
123,
|
||
null,
|
||
];
|
||
|
||
for (const schema of badSchemas) {
|
||
for (const factory of [createPostgresFindingWritePort, createPostgresKnowledgeReaders]) {
|
||
let caught: unknown;
|
||
try {
|
||
factory({ executor: fake.executor, schema: schema as string });
|
||
} catch (err) {
|
||
caught = err;
|
||
}
|
||
expect(caught).toBeInstanceOf(PostgresFindingsError);
|
||
expect((caught as PostgresFindingsError).code).toBe('INVALID_SCHEMA');
|
||
}
|
||
}
|
||
|
||
expect(fake.calls).toHaveLength(0);
|
||
});
|
||
|
||
test('accepts prototype-method executors', async () => {
|
||
class ProtoExecutor {
|
||
async query<Row = Record<string, unknown>>(): Promise<{ readonly rows: readonly Row[] }> {
|
||
return { rows: [makeRawFindingRow()] as unknown as readonly Row[] };
|
||
}
|
||
}
|
||
const readers = createPostgresKnowledgeReaders({ executor: new ProtoExecutor() });
|
||
const rows = await readers.listFindings({});
|
||
expect(rows).toHaveLength(1);
|
||
expect(rows[0]!.id).toBe('finding-001');
|
||
});
|
||
|
||
test('rejects invalid result envelopes and missing/duplicate receipt or winner rows with INVALID_ROW', async () => {
|
||
const badEnvelopeExecutor: PostgresFindingsExecutor = {
|
||
async query() {
|
||
return { rows: 'not-an-array' as unknown as readonly never[] };
|
||
},
|
||
};
|
||
const badWritePort = createPostgresFindingWritePort({ executor: badEnvelopeExecutor });
|
||
const badReaders = createPostgresKnowledgeReaders({ executor: badEnvelopeExecutor });
|
||
|
||
for (const op of [
|
||
() => badWritePort.appendFinding(makeFiledRecord()),
|
||
() => badWritePort.appendFinding(makeFiledRecord(), 'k1'),
|
||
() => badReaders.listFindings({}),
|
||
() => badReaders.listProviderCaveats({}),
|
||
]) {
|
||
let caught: unknown;
|
||
try {
|
||
await op();
|
||
} catch (err) {
|
||
caught = err;
|
||
}
|
||
expect(caught).toBeInstanceOf(PostgresFindingsError);
|
||
expect((caught as PostgresFindingsError).code).toBe('INVALID_ROW');
|
||
}
|
||
|
||
// Unkeyed insert returning 0 rows or 2 rows
|
||
for (const rows of [[], [{ id: 'a', created_at: FIXED_TS }, { id: 'b', created_at: FIXED_TS }]]) {
|
||
const port = createPostgresFindingWritePort({ executor: createFakeExecutor(rows).executor });
|
||
await expect(port.appendFinding(makeFiledRecord())).rejects.toMatchObject({
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
});
|
||
}
|
||
|
||
// Keyed insert returning 2 rows
|
||
const dupInsertPort = createPostgresFindingWritePort({
|
||
executor: createFakeExecutor([
|
||
{ id: 'a', created_at: FIXED_TS },
|
||
{ id: 'b', created_at: FIXED_TS },
|
||
]).executor,
|
||
});
|
||
await expect(dupInsertPort.appendFinding(makeFiledRecord(), 'k-dup')).rejects.toMatchObject({
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
});
|
||
|
||
// Keyed conflict lookup returning 0 rows or 2 rows
|
||
for (const lookupRows of [[], [makeRawReplayRow(), makeRawReplayRow({ id: 'finding-002' })]]) {
|
||
const fake = createSequenceExecutor((_t, _p, idx) =>
|
||
idx === 0 ? { rows: [] } : { rows: lookupRows }
|
||
);
|
||
const port = createPostgresFindingWritePort({ executor: fake.executor });
|
||
await expect(port.appendFinding(makeFiledRecord(), 'k-missing-or-dup')).rejects.toMatchObject(
|
||
{
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
}
|
||
);
|
||
}
|
||
|
||
// 23505 lookup returning 2 rows
|
||
const pkErr = Object.assign(new Error('dup'), { code: '23505' });
|
||
const fakeDup23505 = createSequenceExecutor((_t, _p, idx) => {
|
||
if (idx === 0) {
|
||
throw pkErr;
|
||
}
|
||
return { rows: [makeRawReplayRow(), makeRawReplayRow({ id: 'finding-002' })] };
|
||
});
|
||
const dup23505Port = createPostgresFindingWritePort({ executor: fakeDup23505.executor });
|
||
await expect(dup23505Port.appendFinding(makeFiledRecord(), 'k-dup-23505')).rejects.toMatchObject(
|
||
{
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
}
|
||
);
|
||
});
|
||
|
||
test('rejects malformed timestamps, invalid kinds on replay, and non-string or nested arrays with INVALID_ROW', async () => {
|
||
const badTimestamps: readonly unknown[] = [
|
||
null,
|
||
1700000000000,
|
||
new Date(Number.NaN),
|
||
'',
|
||
'2026-01-15',
|
||
'2026-01-15T12:34:56',
|
||
'2026-02-30T00:00:00Z',
|
||
'2026-01-15T24:00:00Z',
|
||
'2026-01-15T12:00:00+25:00',
|
||
'not-a-timestamp',
|
||
];
|
||
|
||
for (const badTs of badTimestamps) {
|
||
const findingReaders = createPostgresKnowledgeReaders({
|
||
executor: createFakeExecutor([makeRawFindingRow({ created_at: badTs })]).executor,
|
||
});
|
||
await expect(findingReaders.listFindings({})).rejects.toMatchObject({
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
});
|
||
|
||
const caveatReaders = createPostgresKnowledgeReaders({
|
||
executor: createFakeExecutor([makeRawCaveatRow({ created_at: badTs })]).executor,
|
||
});
|
||
await expect(caveatReaders.listProviderCaveats({})).rejects.toMatchObject({
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
});
|
||
}
|
||
|
||
// Invalid kind on replay
|
||
for (const badKind of ['hypothesis', 'FINDING', '', null, 42]) {
|
||
const fake = createSequenceExecutor((_t, _p, idx) =>
|
||
idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow({ kind: badKind })] }
|
||
);
|
||
const port = createPostgresFindingWritePort({ executor: fake.executor });
|
||
await expect(port.appendFinding(makeFiledRecord(), 'k-bad-kind')).rejects.toMatchObject({
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
});
|
||
}
|
||
|
||
// Invalid ref arrays (nested arrays, null elements, non-arrays)
|
||
const badArrays: readonly unknown[] = [null, '101', [101], ['101', null], [['101']]];
|
||
for (const badArr of badArrays) {
|
||
const readers = createPostgresKnowledgeReaders({
|
||
executor: createFakeExecutor([makeRawFindingRow({ trial_refs: badArr })]).executor,
|
||
});
|
||
await expect(readers.listFindings({})).rejects.toMatchObject({
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
});
|
||
|
||
const readersEv = createPostgresKnowledgeReaders({
|
||
executor: createFakeExecutor([makeRawFindingRow({ evidence_refs: badArr })]).executor,
|
||
});
|
||
await expect(readersEv.listFindings({})).rejects.toMatchObject({
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
});
|
||
}
|
||
|
||
// Non-object rows & blank strings
|
||
const badFindingRows: readonly unknown[] = [
|
||
null,
|
||
makeRawFindingRow({ id: ' ' }),
|
||
makeRawFindingRow({ title: '' }),
|
||
makeRawFindingRow({ status: null }),
|
||
makeRawFindingRow({ summary: '' }),
|
||
];
|
||
for (const badRow of badFindingRows) {
|
||
const readers = createPostgresKnowledgeReaders({
|
||
executor: createFakeExecutor([badRow as Record<string, unknown>]).executor,
|
||
});
|
||
await expect(readers.listFindings({})).rejects.toMatchObject({
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
});
|
||
}
|
||
|
||
const badCaveatRows: readonly unknown[] = [
|
||
null,
|
||
makeRawCaveatRow({ id: '' }),
|
||
makeRawCaveatRow({ provider: ' ' }),
|
||
makeRawCaveatRow({ dataset: '' }),
|
||
makeRawCaveatRow({ caveat: null }),
|
||
];
|
||
for (const badRow of badCaveatRows) {
|
||
const readers = createPostgresKnowledgeReaders({
|
||
executor: createFakeExecutor([badRow as Record<string, unknown>]).executor,
|
||
});
|
||
await expect(readers.listProviderCaveats({})).rejects.toMatchObject({
|
||
name: 'PostgresFindingsError',
|
||
code: 'INVALID_ROW',
|
||
});
|
||
}
|
||
});
|
||
});
|