934 lines
34 KiB
TypeScript
934 lines
34 KiB
TypeScript
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 PoolClient, 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) {
|
||
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(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 queryable.query(
|
||
text,
|
||
params === undefined ? undefined : [...params]
|
||
) as unknown as Promise<{ readonly rows: readonly Row[] }>;
|
||
},
|
||
};
|
||
}
|
||
|
||
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);
|
||
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('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', () => {
|
||
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 pinned connections observe committed winner via fresh snapshot for identical and differing payloads', async () => {
|
||
const f = await createIsolatedFixture();
|
||
|
||
const runPinnedRace = async (
|
||
key: string,
|
||
winnerRecord: FiledFindingRecord,
|
||
loserRecord: FiledFindingRecord
|
||
) => {
|
||
const winnerClient = await f.pool.connect();
|
||
let winnerOpen = false;
|
||
cleanup.push(async () => {
|
||
if (winnerOpen) {
|
||
await winnerClient.query('ROLLBACK').catch(() => {});
|
||
}
|
||
winnerClient.release();
|
||
});
|
||
const loserClient = await f.pool.connect();
|
||
cleanup.push(() => {
|
||
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 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 }>(
|
||
'SELECT id FROM findings WHERE idempotency_key = $1',
|
||
['idem-race-same']
|
||
)
|
||
).rows;
|
||
expect(storedSame).toEqual([{ id: recA.id }]);
|
||
|
||
// Concurrent differing payloads: loser's separate READ COMMITTED lookup sees winner -> conflict
|
||
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 diffRace = await runPinnedRace('idem-race-diff', diffA, diffB);
|
||
expect(diffRace.loserOutcome).toEqual({ status: 'conflict' });
|
||
|
||
const storedDiff = (
|
||
await f.pool.query<{ id: string }>(
|
||
'SELECT id FROM findings WHERE idempotency_key = $1',
|
||
['idem-race-diff']
|
||
)
|
||
).rows;
|
||
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 () => {
|
||
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);
|
||
|
||
// 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');
|
||
});
|
||
|
||
test('matches ASCII queries and providers against Unicode stored text under PostgreSQL C collation through MCP', async () => {
|
||
const f = await createIsolatedFixture();
|
||
|
||
// Force C collation on text columns to reproduce the C-collation casing mismatch
|
||
// regardless of the host test database's default collation.
|
||
await f.pool.query(`
|
||
ALTER TABLE findings
|
||
ALTER COLUMN title TYPE TEXT COLLATE "C",
|
||
ALTER COLUMN summary TYPE TEXT COLLATE "C";
|
||
ALTER TABLE provider_caveats
|
||
ALTER COLUMN provider TYPE TEXT COLLATE "C",
|
||
ALTER COLUMN dataset TYPE TEXT COLLATE "C",
|
||
ALTER COLUMN caveat TYPE TEXT COLLATE "C";
|
||
`);
|
||
|
||
// Prove PostgreSQL C collation itself fails both direct SQL casing comparisons.
|
||
const pgCheck = (
|
||
await f.pool.query<{ ilike_match: boolean; lower_match: boolean }>(
|
||
`SELECT
|
||
('BİST exchange coverage' COLLATE "C" ILIKE '%bi%') AS ilike_match,
|
||
(lower('K' COLLATE "C") = lower('k' COLLATE "C")) AS lower_match`
|
||
)
|
||
).rows[0]!;
|
||
expect(pgCheck.ilike_match).toBe(false);
|
||
expect(pgCheck.lower_match).toBe(false);
|
||
|
||
const executor = createPgExecutor(f.pool);
|
||
const writePort = createPostgresFindingWritePort({ executor });
|
||
const readers = createPostgresKnowledgeReaders({ executor });
|
||
|
||
let idSeq = 0;
|
||
const server = createMcpServer({
|
||
name: 'stock-bot-research',
|
||
version: '0.1.0',
|
||
tools: [
|
||
createFileFindingTool({
|
||
port: writePort,
|
||
trialLookup: {
|
||
hasResearchVisibleTrial(ref) {
|
||
return ref === '101';
|
||
},
|
||
},
|
||
newId: () => {
|
||
idSeq += 1;
|
||
return `finding-c-coll-${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-c-coll-${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 Unicode finding 'BİST exchange coverage' and an unrelated Unicode finding 'κόσμος'
|
||
const bistFileRes = await callTool('file_finding', {
|
||
kind: 'finding',
|
||
title: 'BİST exchange coverage',
|
||
summary: 'Turkish equities universe check.',
|
||
trialRefs: ['101'],
|
||
evidenceRefs: [],
|
||
});
|
||
expect(bistFileRes.isError).toBeUndefined();
|
||
const bistReceipt = JSON.parse(bistFileRes.content[0]!.text) as FileFindingResultPayload;
|
||
|
||
const unrelatedFileRes = await callTool('file_finding', {
|
||
kind: 'finding',
|
||
title: 'κόσμος',
|
||
summary: 'Unrelated Greek finding.',
|
||
trialRefs: ['101'],
|
||
evidenceRefs: [],
|
||
});
|
||
expect(unrelatedFileRes.isError).toBeUndefined();
|
||
|
||
// ASCII query 'bi' must match 'BİST exchange coverage' and exclude 'κόσμος'
|
||
const bistReadRes = await callTool('read_knowledge', {
|
||
source: 'findings',
|
||
query: 'bi',
|
||
});
|
||
expect(bistReadRes.isError).toBeUndefined();
|
||
const bistKnowledge = JSON.parse(
|
||
bistReadRes.content[0]!.text
|
||
) as ReadKnowledgeResultPayload;
|
||
expect(bistKnowledge.rowCount).toBe(1);
|
||
expect(bistKnowledge.rows[0]?.id).toBe(bistReceipt.id);
|
||
|
||
// Provider caveats: ASCII query against 'BİST' text, and ASCII provider 'k' against 'K' (U+212A)
|
||
await f.pool.query(
|
||
`INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at)
|
||
VALUES
|
||
('caveat-c-bist', 'EODHD', 'eodPrices', 'BİST intraday feed caveat.', $1::timestamptz),
|
||
('caveat-c-kelvin', 'K', 'kelvinBars', 'Kelvin sign provider caveat.', $1::timestamptz),
|
||
('caveat-c-greek', 'EODHD', 'eodPrices', 'Unrelated κόσμος caveat.', $1::timestamptz)`,
|
||
[FIXED_TS]
|
||
);
|
||
|
||
const bistCaveatRes = await callTool('read_knowledge', {
|
||
source: 'provider_caveats',
|
||
provider: 'eodhd',
|
||
query: 'bi',
|
||
});
|
||
expect(bistCaveatRes.isError).toBeUndefined();
|
||
const bistCaveats = JSON.parse(
|
||
bistCaveatRes.content[0]!.text
|
||
) as ReadKnowledgeResultPayload;
|
||
expect(bistCaveats.rowCount).toBe(1);
|
||
expect(bistCaveats.rows[0]?.id).toBe('caveat-c-bist');
|
||
|
||
const kelvinCaveatRes = await callTool('read_knowledge', {
|
||
source: 'provider_caveats',
|
||
provider: 'k',
|
||
});
|
||
expect(kelvinCaveatRes.isError).toBeUndefined();
|
||
const kelvinCaveats = JSON.parse(
|
||
kelvinCaveatRes.content[0]!.text
|
||
) as ReadKnowledgeResultPayload;
|
||
expect(kelvinCaveats.rowCount).toBe(1);
|
||
expect(kelvinCaveats.rows[0]?.id).toBe('caveat-c-kelvin');
|
||
});
|
||
});
|
||
|
||
// QA (T-161): seeded differential check that the adapter's SQL pushdown plus JS
|
||
// post-filter never drops or adds a row relative to read_knowledge's JS matching
|
||
// rules, against real PostgreSQL under both the database default and "C" collation.
|
||
function qaMulberry32(seed: number): () => number {
|
||
let a = seed >>> 0;
|
||
return () => {
|
||
a = (a + 0x6d2b79f5) >>> 0;
|
||
let t = a;
|
||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||
};
|
||
}
|
||
|
||
const QA_ALPHABET = ['a', 'B', 'i', 'I', 's', 'S', 'k', '%', '_', '\\', ' ', 'İ', 'ı', 'Σ', 'ς', 'K', 'é', 'ß'];
|
||
|
||
function qaText(rand: () => number, min: number, max: number): string {
|
||
const len = min + Math.floor(rand() * (max - min + 1));
|
||
let out = '';
|
||
for (let i = 0; i < len; i += 1) {
|
||
out += QA_ALPHABET[Math.floor(rand() * QA_ALPHABET.length)];
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function qaQuery(rand: () => number, corpus: readonly string[]): string {
|
||
if (rand() < 0.5) {
|
||
const source = corpus[Math.floor(rand() * corpus.length)]!;
|
||
const start = Math.floor(rand() * source.length);
|
||
const end = Math.min(source.length, start + 1 + Math.floor(rand() * 3));
|
||
let q = '';
|
||
for (const ch of source.slice(start, end)) {
|
||
q += rand() < 0.5 ? ch.toUpperCase() : ch.toLowerCase();
|
||
}
|
||
return q.length > 0 ? q : 'a';
|
||
}
|
||
return qaText(rand, 1, 2);
|
||
}
|
||
|
||
describe.skipIf(!url)('PostgreSQL findings readers QA differential vs read_knowledge matching', () => {
|
||
for (const forceCCollation of [false, true]) {
|
||
test(`seeded corpus/query fuzz agrees with JS matching (${forceCCollation ? 'C' : 'default'} collation)`, async () => {
|
||
const f = await createIsolatedFixture();
|
||
if (forceCCollation) {
|
||
await f.pool.query(`
|
||
ALTER TABLE findings
|
||
ALTER COLUMN title TYPE TEXT COLLATE "C",
|
||
ALTER COLUMN summary TYPE TEXT COLLATE "C";
|
||
ALTER TABLE provider_caveats
|
||
ALTER COLUMN provider TYPE TEXT COLLATE "C",
|
||
ALTER COLUMN dataset TYPE TEXT COLLATE "C",
|
||
ALTER COLUMN caveat TYPE TEXT COLLATE "C";
|
||
`);
|
||
}
|
||
const executor = createPgExecutor(f.pool);
|
||
const writePort = createPostgresFindingWritePort({ executor });
|
||
const readers = createPostgresKnowledgeReaders({ executor });
|
||
const rand = qaMulberry32(forceCCollation ? 4242 : 161);
|
||
|
||
const findings = Array.from({ length: 30 }, (_, i) => ({
|
||
id: `qa-f-${String(i).padStart(3, '0')}`,
|
||
title: `T${qaText(rand, 2, 6)}`,
|
||
summary: `S${qaText(rand, 2, 6)}`,
|
||
}));
|
||
for (const row of findings) {
|
||
const outcome = await writePort.appendFinding(
|
||
makeFinding({ id: row.id, title: row.title, summary: row.summary })
|
||
);
|
||
expect(outcome.status).toBe('created');
|
||
}
|
||
|
||
const providers = ['EODHD', 'eodhd', 'K', 'kelvin', 'İBK', 'ibk', 'ΣΙΣ', 'σις'];
|
||
const caveats = Array.from({ length: 30 }, (_, i) => ({
|
||
id: `qa-c-${String(i).padStart(3, '0')}`,
|
||
provider: providers[Math.floor(rand() * providers.length)]!,
|
||
dataset: `D${qaText(rand, 2, 5)}`,
|
||
caveat: `C${qaText(rand, 2, 6)}`,
|
||
}));
|
||
for (const row of caveats) {
|
||
await f.pool.query(
|
||
`INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at)
|
||
VALUES ($1, $2, $3, $4, $5::timestamptz)`,
|
||
[row.id, row.provider, row.dataset, row.caveat, FIXED_TS]
|
||
);
|
||
}
|
||
|
||
const findingCorpus = findings.flatMap(r => [r.title, r.summary]);
|
||
for (let n = 0; n < 60; n += 1) {
|
||
const query = qaQuery(rand, findingCorpus);
|
||
const lower = query.toLowerCase();
|
||
const expected = findings
|
||
.filter(
|
||
r => r.title.toLowerCase().includes(lower) || r.summary.toLowerCase().includes(lower)
|
||
)
|
||
.map(r => r.id);
|
||
const actual = (await readers.listFindings({ query })).map(r => r.id);
|
||
expect({ query, ids: actual }).toEqual({ query, ids: expected });
|
||
}
|
||
|
||
const caveatCorpus = caveats.flatMap(r => [r.provider, r.dataset, r.caveat]);
|
||
for (let n = 0; n < 60; n += 1) {
|
||
const provider =
|
||
rand() < 0.6
|
||
? providers[Math.floor(rand() * providers.length)]!.toUpperCase()
|
||
: undefined;
|
||
const query = rand() < 0.7 ? qaQuery(rand, caveatCorpus) : undefined;
|
||
const lowerProvider = provider?.toLowerCase();
|
||
const lowerQuery = query?.toLowerCase();
|
||
const expected = caveats
|
||
.filter(r => lowerProvider === undefined || r.provider.toLowerCase() === lowerProvider)
|
||
.filter(
|
||
r =>
|
||
lowerQuery === undefined ||
|
||
r.provider.toLowerCase().includes(lowerQuery) ||
|
||
r.dataset.toLowerCase().includes(lowerQuery) ||
|
||
r.caveat.toLowerCase().includes(lowerQuery)
|
||
)
|
||
.map(r => r.id);
|
||
const actual = (
|
||
await readers.listProviderCaveats({
|
||
...(provider !== undefined ? { provider } : {}),
|
||
...(query !== undefined ? { query } : {}),
|
||
})
|
||
).map(r => r.id);
|
||
expect({ provider, query, ids: actual }).toEqual({ provider, query, ids: expected });
|
||
}
|
||
}, 30_000);
|
||
}
|
||
});
|