T-158: M2.1k — PostgreSQL security-master adapter for the MCP copilot search_symbols tool: SymbolSearchPort over an injected executor in libs/research/src/mcp/adapters/postgres-symbol-search.ts (as-of-cutoff ticker resolution, parameterized SQL, no new deps)

This commit is contained in:
Studio 2026-12-02 08:56:23 -05:00
parent 4e4be190df
commit c6fcc341b9

View file

@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { Client, Pool, type PoolConfig } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
@ -46,21 +46,45 @@ function createPgExecutor(pool: Pool): SymbolSearchExecutor {
};
}
async function createIsolatedFixture() {
const safeUrl = assertSafetyDatabaseUrl(url);
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({
connectionString: safeUrl,
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
});
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)}`
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
@ -95,7 +119,7 @@ async function seedFixture(pool: Pool): Promise<void> {
INSERT INTO instrument (instrument_id, primary_isin, canonical_name, security_type, issuer_country)
OVERRIDING SYSTEM VALUE
VALUES
(101, 'US1010000001', 'Renamed Holdings Inc', 'common', 'US'),
(101, 'CA1010000001', 'Alpha Oldco Canada', 'common', 'CA'),
(102, 'US1020000002', 'Gap Rename Corp', 'common', 'US'),
(103, 'US1030000003', 'Stealth Future Ventures', 'common', 'US'),
(104, 'CA1040000004', 'No History Metals', 'common', 'CA'),
@ -108,7 +132,7 @@ async function seedFixture(pool: Pool): Promise<void> {
(111, 'US1110000011', 'Delist Boundary Future', 'common', 'US'),
(112, 'US1120000012', '100% Pure_Wild\\Co', 'common', 'US'),
(113, 'US1130000013', 'Second Oldco Group', 'common', 'US'),
(114, 'CA1140000014', 'Alpha Oldco Canada', 'common', 'CA')
(114, 'US1140000014', 'Renamed Holdings Inc', 'common', 'US')
`);
await client.query(`
@ -118,7 +142,7 @@ async function seedFixture(pool: Pool): Promise<void> {
)
OVERRIDING SYSTEM VALUE
VALUES
(101, 101, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active'),
(101, 101, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active'),
(102, 102, 'XNYS', 'GAPNEW', '', 'USD', '2019-01-01', '2024-12-31', 'active'),
(103, 103, 'XNAS', 'FUTROOT', '', 'USD', '2020-01-01', NULL, NULL),
(104, 104, 'XTSE', 'NOHIST', 'A', 'CAD', '2021-03-15', '2024-06-28', 'active'),
@ -131,14 +155,14 @@ async function seedFixture(pool: Pool): Promise<void> {
(111, 111, 'XNAS', 'DLST4', '', 'USD', '2015-01-01', '2024-09-15', 'bankruptcy_cancelled'),
(112, 112, 'XNYS', 'WILD', '', 'USD', '2020-01-01', '2024-06-28', 'active'),
(113, 113, 'XNAS', 'OLDCO2', '', 'USD', '2020-01-01', '2024-06-28', 'active'),
(114, 114, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active')
(114, 114, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active')
`);
await client.query(`
INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source)
VALUES
(101, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'),
(101, 'NEWCO', '2024-07-01', NULL, 'eod'),
(114, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'),
(114, 'NEWCO', '2024-07-01', NULL, 'eod'),
(102, 'GAPOLD', '2019-01-01', '2024-05-31', 'eod'),
(102, 'GAPNEW', '2024-07-01', NULL, 'eod'),
(103, 'FUTROOT', '2024-07-15', NULL, 'eod'),
@ -169,6 +193,22 @@ describe('PostgreSQL symbol search safety guard', () => {
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');
});
test('preserves isolated schema search_path precedence over URL startup options', () => {
const schema = 'stock_bot_safety_fixture_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 symbol search adapter', () => {
@ -184,15 +224,15 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => {
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(oldcoRows.map(r => r.listingId)).toEqual([101, 113, 114]);
expect(oldcoRows[0]).toEqual({
listingId: 101,
instrumentId: 101,
expect(oldcoRows[2]).toEqual({
listingId: 114,
instrumentId: 114,
ticker: 'OLDCO',
classSuffix: null,
name: 'Renamed Holdings Inc',
mic: 'XNAS',
currency: 'USD',
isin: 'US1010000001',
isin: 'US1140000014',
firstBarDate: '2018-01-02',
lastBarDate: '2024-12-31',
delistedAt: null,
@ -325,7 +365,7 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => {
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([
{ id: 114, mic: 'XTSE' },
{ id: 101, mic: 'XTSE' },
]);
// (e) Case-insensitive exact ISIN match with partial-ISIN negative
@ -421,14 +461,15 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => {
return JSON.parse(parsed.result.content[0]!.text) as SearchSymbolsResultPayload;
};
// Ranking & truncation: exact ticker OLDCO (101) > prefix OLDCO2 (113) > name Alpha Oldco Canada (114)
// Ranking & truncation: adapter returns ascending listing_id [101 (name), 113 (prefix), 114 (exact)];
// MCP tool must re-rank to exact ticker OLDCO (114) > prefix OLDCO2 (113) and drop name match ZOLD (101)
const oldcoPayload = await callTool({ query: 'OLDCO', limit: 2 });
expect(oldcoPayload.scope).toBe('vault_fenced');
expect(oldcoPayload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS);
expect(oldcoPayload.truncated).toBe(true);
expect(oldcoPayload.rowCount).toBe(2);
expect(oldcoPayload.rows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([
{ id: 101, ticker: 'OLDCO' },
{ id: 114, ticker: 'OLDCO' },
{ id: 113, ticker: 'OLDCO2' },
]);
// Post-cutoff lastBarDate (2024-12-31) is clamped to vaultCutoffDate (2024-06-30)
@ -444,4 +485,24 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => {
expect(futureDelistPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE);
expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull();
});
test('isolates fixture schema even when the safety database URL includes startup options', async () => {
const parsed = new URL(assertSafetyDatabaseUrl(url));
parsed.searchParams.set('options', '-c statement_timeout=30000 -c search_path=public');
const f = await createIsolatedFixture(parsed.toString());
const { rows } = await f.pool.query<{ current_schema: string | null }>(
'SELECT current_schema() AS current_schema'
);
expect(rows[0]?.current_schema).toBe(f.schema);
const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) });
const matches = await port.searchSymbols({
query: 'OLDCO',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(matches.map(r => r.listingId)).toEqual([101, 113, 114]);
});
});