T-134: tests
This commit is contained in:
parent
4c810cb249
commit
c6bd028dcc
1 changed files with 354 additions and 0 deletions
354
libs/research/test/mcp-search-symbols-qa.test.ts
Normal file
354
libs/research/test/mcp-search-symbols-qa.test.ts
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
createMcpServer,
|
||||
createSearchSymbolsTool,
|
||||
SEARCH_SYMBOLS_MAX_QUERY_LENGTH,
|
||||
type SearchSymbolsResultPayload,
|
||||
type SymbolSearchPort,
|
||||
type SymbolSearchQuery,
|
||||
type SymbolSearchRow,
|
||||
} from '../src/mcp/index';
|
||||
|
||||
// QA fixture: deterministic in-memory security-master port (no network, no
|
||||
// Postgres, no MongoDB). Cutoffs are pinned epoch-ms values; no wall clock.
|
||||
const MIDDAY_CUTOFF_TS = Date.UTC(2025, 2, 31, 15, 30, 0, 0); // 2025-03-31T15:30Z
|
||||
const LAST_MS_CUTOFF_TS = Date.UTC(2025, 2, 31, 23, 59, 59, 999); // 2025-03-31T23:59:59.999Z
|
||||
const CUTOFF_DATE = '2025-03-31';
|
||||
|
||||
function row(
|
||||
overrides: Partial<SymbolSearchRow> & { readonly listingId: number }
|
||||
): SymbolSearchRow {
|
||||
return {
|
||||
instrumentId: overrides.listingId * 10,
|
||||
ticker: `T${overrides.listingId}`,
|
||||
classSuffix: null,
|
||||
name: `Company ${overrides.listingId}`,
|
||||
mic: 'XNAS',
|
||||
currency: 'USD',
|
||||
isin: null,
|
||||
firstBarDate: '2020-01-02',
|
||||
lastBarDate: '2025-03-28',
|
||||
delistedAt: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function fakePort(impl: (q: SymbolSearchQuery) => Promise<unknown> | unknown): {
|
||||
readonly calls: SymbolSearchQuery[];
|
||||
readonly port: SymbolSearchPort;
|
||||
} {
|
||||
const calls: SymbolSearchQuery[] = [];
|
||||
return {
|
||||
calls,
|
||||
port: {
|
||||
async searchSymbols(q) {
|
||||
calls.push({ ...q });
|
||||
return (await impl(q)) as readonly SymbolSearchRow[];
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function call(
|
||||
port: SymbolSearchPort,
|
||||
args: Record<string, unknown>,
|
||||
vaultCutoffTs: number
|
||||
): Promise<{ isError: boolean; text: string; payload: SearchSymbolsResultPayload | null }> {
|
||||
const server = createMcpServer({
|
||||
name: 'stock-bot-research',
|
||||
version: '0.1.0',
|
||||
tools: [createSearchSymbolsTool({ port, vaultContext: { vaultCutoffTs } })],
|
||||
});
|
||||
const raw = await server.handleMessage(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 7,
|
||||
method: 'tools/call',
|
||||
params: { name: 'search_symbols', arguments: args },
|
||||
})
|
||||
);
|
||||
const parsed = JSON.parse(raw as string) as {
|
||||
result: { isError?: boolean; content: { text: string }[] };
|
||||
};
|
||||
const isError = parsed.result.isError === true;
|
||||
const text = parsed.result.content[0]?.text ?? '';
|
||||
return {
|
||||
isError,
|
||||
text,
|
||||
payload: isError ? null : (JSON.parse(text) as SearchSymbolsResultPayload),
|
||||
};
|
||||
}
|
||||
|
||||
describe('MCP search_symbols QA', () => {
|
||||
test('intraday cutoff fences against the cutoff UTC calendar date (equal kept, next day dropped/clamped/masked)', async () => {
|
||||
const rows = [
|
||||
row({
|
||||
listingId: 1,
|
||||
ticker: 'QQ',
|
||||
firstBarDate: CUTOFF_DATE,
|
||||
lastBarDate: '2025-04-01',
|
||||
delistedAt: '2025-04-01',
|
||||
}),
|
||||
row({ listingId: 2, ticker: 'QQ', firstBarDate: '2025-04-01', lastBarDate: '2025-04-02' }),
|
||||
row({ listingId: 3, ticker: 'QQ', lastBarDate: CUTOFF_DATE, delistedAt: CUTOFF_DATE }),
|
||||
];
|
||||
for (const cutoff of [MIDDAY_CUTOFF_TS, LAST_MS_CUTOFF_TS]) {
|
||||
const { port } = fakePort(() => rows);
|
||||
const res = await call(port, { query: 'QQ' }, cutoff);
|
||||
expect(res.isError).toBe(false);
|
||||
expect(res.payload?.vaultCutoffTs).toBe(cutoff);
|
||||
expect(
|
||||
res.payload?.rows.map(r => [r.listingId, r.firstBarDate, r.lastBarDate, r.delistedAt])
|
||||
).toEqual([
|
||||
[1, CUTOFF_DATE, CUTOFF_DATE, null],
|
||||
[3, '2020-01-02', CUTOFF_DATE, CUTOFF_DATE],
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
test('cutoff one ms before midnight UTC uses the previous calendar date', async () => {
|
||||
const cutoff = Date.UTC(2025, 2, 31, 0, 0, 0, 0) - 1; // 2025-03-30T23:59:59.999Z
|
||||
const { port } = fakePort(() => [
|
||||
row({ listingId: 1, ticker: 'EDGE', firstBarDate: CUTOFF_DATE }),
|
||||
row({ listingId: 2, ticker: 'EDGE', lastBarDate: CUTOFF_DATE, delistedAt: CUTOFF_DATE }),
|
||||
]);
|
||||
const res = await call(port, { query: 'EDGE' }, cutoff);
|
||||
expect(res.payload?.rows).toHaveLength(1);
|
||||
expect(res.payload?.rows[0]).toMatchObject({
|
||||
listingId: 2,
|
||||
lastBarDate: '2025-03-30',
|
||||
delistedAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
test('a future delisting changes neither membership nor ranking relative to a never-delisted listing', async () => {
|
||||
const base = [
|
||||
row({ listingId: 9, ticker: 'MSFT', name: 'Microsoft Corp' }),
|
||||
row({ listingId: 4, ticker: 'MSFTX', name: 'Microsoft Tracker' }),
|
||||
row({ listingId: 7, ticker: 'ZZZ', name: 'Old msft Holdings' }),
|
||||
];
|
||||
const withFutureDelisting = base.map(r =>
|
||||
r.listingId === 4 ? { ...r, delistedAt: '2026-01-15', lastBarDate: '2026-01-14' } : r
|
||||
);
|
||||
for (const includeDelisted of [true, false]) {
|
||||
const a = await call(
|
||||
fakePort(() => base).port,
|
||||
{ query: 'msft', includeDelisted },
|
||||
MIDDAY_CUTOFF_TS
|
||||
);
|
||||
const b = await call(
|
||||
fakePort(() => withFutureDelisting).port,
|
||||
{ query: 'msft', includeDelisted },
|
||||
MIDDAY_CUTOFF_TS
|
||||
);
|
||||
expect(a.payload?.rows.map(r => r.listingId)).toEqual([9, 4, 7]);
|
||||
expect(b.payload?.rows.map(r => r.listingId)).toEqual([9, 4, 7]);
|
||||
expect(b.payload?.rows[1]).toMatchObject({ delistedAt: null, lastBarDate: CUTOFF_DATE });
|
||||
}
|
||||
});
|
||||
|
||||
test('truncation with includeDelisted: true ignores post-cutoff rows placed ahead of eligible matches', async () => {
|
||||
const rows = [
|
||||
row({ listingId: 1, ticker: 'NEW', firstBarDate: '2025-06-01' }),
|
||||
row({ listingId: 2, ticker: 'NEW', firstBarDate: '2025-04-01' }),
|
||||
row({ listingId: 3, ticker: 'NEWA' }),
|
||||
row({ listingId: 4, ticker: 'NEWB', delistedAt: '2021-05-05', lastBarDate: '2021-05-04' }),
|
||||
];
|
||||
const fit = await call(fakePort(() => rows).port, { query: 'new', limit: 2 }, MIDDAY_CUTOFF_TS);
|
||||
expect(fit.payload).toMatchObject({ rowCount: 2, truncated: false });
|
||||
expect(fit.payload?.rows.map(r => r.listingId)).toEqual([3, 4]);
|
||||
|
||||
const over = await call(
|
||||
fakePort(() => rows).port,
|
||||
{ query: 'new', limit: 1 },
|
||||
MIDDAY_CUTOFF_TS
|
||||
);
|
||||
expect(over.payload).toMatchObject({ rowCount: 1, truncated: true });
|
||||
expect(over.payload?.rows.map(r => r.listingId)).toEqual([3]);
|
||||
});
|
||||
|
||||
test('a row matching both ticker prefix and name ranks by its best (ticker) match; name match is literal substring', async () => {
|
||||
const rows = [
|
||||
row({ listingId: 1, ticker: 'ZED', name: 'A.B Industries' }),
|
||||
row({ listingId: 2, ticker: 'A.BX', name: 'A.B Prefix Co' }),
|
||||
row({ listingId: 3, ticker: 'AXB', name: 'Regex Bait AXB' }),
|
||||
row({ listingId: 4, ticker: 'A.B', name: 'Exact Dot' }),
|
||||
];
|
||||
const res = await call(fakePort(() => rows).port, { query: 'a.b' }, MIDDAY_CUTOFF_TS);
|
||||
// "a.b" must not behave like a regex: AXB (3) is not a match.
|
||||
expect(res.payload?.rows.map(r => r.listingId)).toEqual([4, 2, 1]);
|
||||
});
|
||||
|
||||
test('repeated calls on shuffled inputs give byte-identical payloads', async () => {
|
||||
const rows = Array.from({ length: 30 }, (_, i) =>
|
||||
row({ listingId: 1000 - i * 7, ticker: i % 3 === 0 ? 'RY' : `RY${i}`, name: `Royal ${i}` })
|
||||
);
|
||||
// Deterministic Fisher-Yates with a fixed LCG seed.
|
||||
let seed = 12345;
|
||||
const shuffled = [...rows];
|
||||
for (let i = shuffled.length - 1; i > 0; i -= 1) {
|
||||
seed = (seed * 1103515245 + 12345) % 2147483648;
|
||||
const j = seed % (i + 1);
|
||||
[shuffled[i], shuffled[j]] = [shuffled[j] as SymbolSearchRow, shuffled[i] as SymbolSearchRow];
|
||||
}
|
||||
const a = await call(fakePort(() => rows).port, { query: 'RY', limit: 12 }, MIDDAY_CUTOFF_TS);
|
||||
const b = await call(
|
||||
fakePort(() => shuffled).port,
|
||||
{ query: 'RY', limit: 12 },
|
||||
MIDDAY_CUTOFF_TS
|
||||
);
|
||||
expect(a.text).toBe(b.text);
|
||||
const ids = a.payload?.rows.map(r => r.listingId) ?? [];
|
||||
const exact = ids.slice(0, 10);
|
||||
expect([...exact].sort((x, y) => x - y)).toEqual(exact); // 10 exact RY matches ascending
|
||||
expect(a.payload?.truncated).toBe(true);
|
||||
});
|
||||
|
||||
test('query of exactly 64 chars (and 64 chars after trimming) is accepted; whitespace is trimmed before the length check', async () => {
|
||||
const q = 'B'.repeat(SEARCH_SYMBOLS_MAX_QUERY_LENGTH);
|
||||
const fake = fakePort(() => []);
|
||||
const exact = await call(fake.port, { query: q }, MIDDAY_CUTOFF_TS);
|
||||
const padded = await call(fake.port, { query: ` ${q} ` }, MIDDAY_CUTOFF_TS);
|
||||
expect(exact.isError).toBe(false);
|
||||
expect(padded.isError).toBe(false);
|
||||
expect(fake.calls.map(c => c.query)).toEqual([q, q]);
|
||||
});
|
||||
|
||||
test('limit 1 and 100 accepted and forwarded as hints; non-number limit, null and non-boolean includeDelisted rejected without port call', async () => {
|
||||
const fake = fakePort(() => []);
|
||||
expect((await call(fake.port, { query: 'X', limit: 1 }, MIDDAY_CUTOFF_TS)).isError).toBe(false);
|
||||
expect(
|
||||
(await call(fake.port, { query: 'X', limit: 100, country: 'US' }, MIDDAY_CUTOFF_TS)).isError
|
||||
).toBe(false);
|
||||
expect(fake.calls).toEqual([
|
||||
{ query: 'X', limit: 1, includeDelisted: true, vaultCutoffTs: MIDDAY_CUTOFF_TS },
|
||||
{
|
||||
query: 'X',
|
||||
limit: 100,
|
||||
country: 'US',
|
||||
includeDelisted: true,
|
||||
vaultCutoffTs: MIDDAY_CUTOFF_TS,
|
||||
},
|
||||
]);
|
||||
|
||||
const bad = fakePort(() => []);
|
||||
for (const args of [
|
||||
{ query: 'X', limit: '20' },
|
||||
{ query: 'X', limit: null },
|
||||
{ query: 'X', limit: Number.NaN },
|
||||
{ query: 42 },
|
||||
{ query: 'X', country: null },
|
||||
{ query: 'X', includeDelisted: 0 },
|
||||
{ query: 'X', vaultCutoffTs: Date.UTC(2030, 0, 1) },
|
||||
]) {
|
||||
const res = await call(bad.port, args, MIDDAY_CUTOFF_TS);
|
||||
expect(res.isError).toBe(true);
|
||||
}
|
||||
expect(bad.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('malformed port responses yield a sanitized isError result', async () => {
|
||||
const malformed: unknown[] = [
|
||||
null,
|
||||
{ rows: [] },
|
||||
'not-an-array',
|
||||
[null],
|
||||
['row'],
|
||||
[{ ...row({ listingId: 1, ticker: 'M' }), listingId: '1' }],
|
||||
[{ ...row({ listingId: 1, ticker: 'M' }), listingId: 1.5 }],
|
||||
[{ ...row({ listingId: 1, ticker: 'M' }), instrumentId: undefined }],
|
||||
[{ ...row({ listingId: 1, ticker: 'M' }), ticker: null }],
|
||||
[{ ...row({ listingId: 1, ticker: 'M' }), name: undefined }],
|
||||
[{ ...row({ listingId: 1, ticker: 'M' }), mic: 5 }],
|
||||
[{ ...row({ listingId: 1, ticker: 'M' }), isin: 123 }],
|
||||
[{ ...row({ listingId: 1, ticker: 'M' }), classSuffix: undefined }],
|
||||
[{ ...row({ listingId: 1, ticker: 'M' }), firstBarDate: undefined }],
|
||||
];
|
||||
for (const response of malformed) {
|
||||
const res = await call(fakePort(() => response).port, { query: 'M' }, MIDDAY_CUTOFF_TS);
|
||||
expect(res.isError).toBe(true);
|
||||
expect(res.text).toBe('Error: Tool execution failed.');
|
||||
}
|
||||
});
|
||||
|
||||
test('non-Error port rejections are sanitized', async () => {
|
||||
for (const thrown of ['password=hunter2', { secret: 'x' }, 42]) {
|
||||
const res = await call(
|
||||
fakePort(() => {
|
||||
throw thrown;
|
||||
}).port,
|
||||
{ query: 'AAPL' },
|
||||
MIDDAY_CUTOFF_TS
|
||||
);
|
||||
expect(res.isError).toBe(true);
|
||||
expect(res.text).toBe('Error: Tool execution failed.');
|
||||
expect(res.text).not.toContain('hunter2');
|
||||
}
|
||||
});
|
||||
|
||||
test('returned rows are fresh projections: mutating port objects after the call does not alter output, and port input is not mutated', async () => {
|
||||
const source = row({ listingId: 5, ticker: 'FRZ', lastBarDate: '2025-05-05' });
|
||||
const snapshot = JSON.stringify(source);
|
||||
const server = createMcpServer({
|
||||
name: 'stock-bot-research',
|
||||
version: '0.1.0',
|
||||
tools: [
|
||||
createSearchSymbolsTool({
|
||||
port: { searchSymbols: async () => [source] },
|
||||
vaultContext: { vaultCutoffTs: MIDDAY_CUTOFF_TS },
|
||||
}),
|
||||
],
|
||||
});
|
||||
const raw = await server.handleMessage(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'tools/call',
|
||||
params: { name: 'search_symbols', arguments: { query: 'FRZ' } },
|
||||
})
|
||||
);
|
||||
expect(JSON.stringify(source)).toBe(snapshot); // clamping did not write back to the port row
|
||||
const payload = JSON.parse(
|
||||
(JSON.parse(raw as string) as { result: { content: { text: string }[] } }).result.content[0]
|
||||
?.text ?? ''
|
||||
) as SearchSymbolsResultPayload;
|
||||
expect(payload.rows[0]?.lastBarDate).toBe(CUTOFF_DATE);
|
||||
});
|
||||
|
||||
test('concurrent calls are independent and each respects its own arguments', async () => {
|
||||
const rows = [
|
||||
row({ listingId: 1, ticker: 'TD', mic: 'XTSE', currency: 'CAD' }),
|
||||
row({ listingId: 2, ticker: 'TD', mic: 'XNYS' }),
|
||||
row({ listingId: 3, ticker: 'TDX', delistedAt: '2022-02-02', lastBarDate: '2022-02-01' }),
|
||||
];
|
||||
const fake = fakePort(q =>
|
||||
q.country === undefined ? rows : rows.filter(r => (q.country === 'CA') === (r.mic === 'XTSE'))
|
||||
);
|
||||
const [all, ca, active] = await Promise.all([
|
||||
call(fake.port, { query: 'TD' }, MIDDAY_CUTOFF_TS),
|
||||
call(fake.port, { query: 'TD', country: 'CA' }, MIDDAY_CUTOFF_TS),
|
||||
call(fake.port, { query: 'TD', includeDelisted: false, limit: 1 }, MIDDAY_CUTOFF_TS),
|
||||
]);
|
||||
expect(all.payload?.rows.map(r => r.listingId)).toEqual([1, 2, 3]);
|
||||
expect(ca.payload?.rows.map(r => r.listingId)).toEqual([1]);
|
||||
expect(active.payload).toMatchObject({ rowCount: 1, truncated: true });
|
||||
expect(active.payload?.rows.map(r => r.listingId)).toEqual([1]);
|
||||
});
|
||||
|
||||
test('pre-1970 cutoff fences correctly', async () => {
|
||||
const cutoff = Date.UTC(1965, 5, 30, 12, 0, 0, 0);
|
||||
const rows = [
|
||||
row({
|
||||
listingId: 1,
|
||||
ticker: 'IBM',
|
||||
firstBarDate: '1962-01-02',
|
||||
lastBarDate: '2025-03-28',
|
||||
delistedAt: null,
|
||||
}),
|
||||
row({ listingId: 2, ticker: 'IBM', firstBarDate: '1970-01-02' }),
|
||||
];
|
||||
const res = await call(fakePort(() => rows).port, { query: 'IBM' }, cutoff);
|
||||
expect(res.payload?.rows).toHaveLength(1);
|
||||
expect(res.payload?.rows[0]).toMatchObject({ listingId: 1, lastBarDate: '1965-06-30' });
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue