T-182: tests
This commit is contained in:
parent
c9b20584de
commit
02cc44e70b
1 changed files with 496 additions and 0 deletions
496
libs/research/test/mcp-stdio-host-qa.test.ts
Normal file
496
libs/research/test/mcp-stdio-host-qa.test.ts
Normal file
|
|
@ -0,0 +1,496 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import type { BarBatch, BarQuery, MarketDataStore, Table } from '../src/market-data-store';
|
||||
import {
|
||||
EVENTS_COLUMNS,
|
||||
MarketDataStoreNotImplementedError,
|
||||
} from '../src/market-data-store-duckdb';
|
||||
import {
|
||||
type PostgresResearchCopilotExecutor,
|
||||
type ResearchCopilotStdioHostDeps,
|
||||
ResearchCopilotHostConfigError,
|
||||
type StdioInput,
|
||||
type StdioOutput,
|
||||
parseResearchCopilotHostConfig,
|
||||
runResearchCopilotStdioHost,
|
||||
} from '../src/mcp/index';
|
||||
|
||||
// QA fixtures: synthetic in-memory factories and stdio only. No Postgres,
|
||||
// DuckDB, filesystem, or network. Protocol/wiring checks; no strategy claims.
|
||||
const FAKE_DECODED_PASSWORD = 'qa+p@ss w0rd/=?';
|
||||
const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD);
|
||||
const FAKE_POSTGRES_URL = `postgresql://qa_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`;
|
||||
const CUTOFF_ISO = '2025-06-01T00:00:00Z';
|
||||
const CUTOFF_MS = Date.UTC(2025, 5, 1);
|
||||
const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12);
|
||||
|
||||
function buildEnv(
|
||||
overrides: Readonly<Record<string, string | undefined>> = {}
|
||||
): Record<string, string | undefined> {
|
||||
return {
|
||||
RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL,
|
||||
RESEARCH_MCP_CURATED_ROOT: '/qa/curated',
|
||||
RESEARCH_MCP_VAULT_CUTOFF_TS: CUTOFF_ISO,
|
||||
RESEARCH_MCP_PRINCIPAL_ID: 'operator',
|
||||
RESEARCH_MCP_LIBRARY_ROOT: '/qa/library',
|
||||
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101, 102] }),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function memoryOutput(): { readonly output: StdioOutput; readonly chunks: string[] } {
|
||||
const chunks: string[] = [];
|
||||
return {
|
||||
chunks,
|
||||
output: {
|
||||
write(chunk: string): boolean {
|
||||
chunks.push(chunk);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function trackingInput(messages: readonly unknown[]): {
|
||||
readonly input: StdioInput;
|
||||
readonly pulled: () => number;
|
||||
} {
|
||||
let count = 0;
|
||||
return {
|
||||
pulled: () => count,
|
||||
input: {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const msg of messages) {
|
||||
count += 1;
|
||||
yield `${JSON.stringify(msg)}\n`;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function recordingStore(): { readonly store: MarketDataStore; readonly barQueries: BarQuery[] } {
|
||||
const barQueries: BarQuery[] = [];
|
||||
const emptyEvents: Table = { columns: [...EVENTS_COLUMNS], rows: [] };
|
||||
const store: MarketDataStore = {
|
||||
async *bars(q: BarQuery): AsyncIterable<BarBatch> {
|
||||
barQueries.push(q);
|
||||
yield { listingId: q.listingIds[0] ?? 0, timeframe: q.timeframe, rows: [] };
|
||||
},
|
||||
async events() {
|
||||
return emptyEvents;
|
||||
},
|
||||
async universe() {
|
||||
return [];
|
||||
},
|
||||
async crossSection() {
|
||||
throw new MarketDataStoreNotImplementedError('crossSection');
|
||||
},
|
||||
async fundamentalsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
|
||||
},
|
||||
async shortsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('shortsAsOf');
|
||||
},
|
||||
async macroAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('macroAsOf');
|
||||
},
|
||||
async fx() {
|
||||
throw new MarketDataStoreNotImplementedError('fx');
|
||||
},
|
||||
};
|
||||
return { store, barQueries };
|
||||
}
|
||||
|
||||
function calendarExecutor(): {
|
||||
readonly executor: PostgresResearchCopilotExecutor;
|
||||
readonly sql: string[];
|
||||
} {
|
||||
const sql: string[] = [];
|
||||
const executor: PostgresResearchCopilotExecutor = {
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }> {
|
||||
sql.push(text);
|
||||
if (text.includes('calendar_code AS calendar_code')) {
|
||||
const ids = (params?.[0] as readonly number[] | undefined) ?? [];
|
||||
return {
|
||||
rows: ids.map(id => ({ listing_id: id, calendar_code: 'XNYS' }) as unknown as Row),
|
||||
};
|
||||
}
|
||||
return { rows: [] };
|
||||
},
|
||||
};
|
||||
return { executor, sql };
|
||||
}
|
||||
|
||||
function baseDeps(
|
||||
overrides: Partial<ResearchCopilotStdioHostDeps> = {}
|
||||
): ResearchCopilotStdioHostDeps {
|
||||
return {
|
||||
config: parseResearchCopilotHostConfig(buildEnv()),
|
||||
openExecutor: () => ({ executor: calendarExecutor().executor, close: () => {} }),
|
||||
openStore: () => ({ store: recordingStore().store, close: () => {} }),
|
||||
createLibraryCardReader: () => ({ listLibraryCards: async () => [] }),
|
||||
newId: () => 'qa-id',
|
||||
now: () => FIXED_NOW_MS,
|
||||
stdio: { input: trackingInput([]).input, output: memoryOutput().output },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function captureRejection(run: () => Promise<unknown>): Promise<unknown> {
|
||||
try {
|
||||
await run();
|
||||
} catch (err) {
|
||||
return err;
|
||||
}
|
||||
throw new Error('expected rejection');
|
||||
}
|
||||
|
||||
function expectNoSecret(error: unknown): void {
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
const err = error as Error & { cause?: unknown };
|
||||
for (const text of [err.message, err.stack ?? '']) {
|
||||
expect(text).not.toContain(FAKE_POSTGRES_URL);
|
||||
expect(text).not.toContain(FAKE_ENCODED_PASSWORD);
|
||||
expect(text).not.toContain(FAKE_DECODED_PASSWORD);
|
||||
}
|
||||
expect(err.cause).toBeUndefined();
|
||||
}
|
||||
|
||||
describe('runResearchCopilotStdioHost QA: session-date wiring', () => {
|
||||
test('event_study derives session dates from the configured reference listings on the opened store, clamped below the env cutoff', async () => {
|
||||
const { store, barQueries } = recordingStore();
|
||||
const { executor } = calendarExecutor();
|
||||
const sink = memoryOutput();
|
||||
const { input } = trackingInput([
|
||||
{
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'event_study',
|
||||
arguments: {
|
||||
listingIds: [555],
|
||||
from: '2025-05-01',
|
||||
to: '2025-06-20',
|
||||
event: { kinds: ['filing'] },
|
||||
preDays: 2,
|
||||
postDays: 3,
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
benchmark: 'none',
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
await runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => ({ executor, close: () => {} }),
|
||||
openStore: () => ({ store, close: () => {} }),
|
||||
stdio: { input, output: sink.output },
|
||||
})
|
||||
);
|
||||
|
||||
expect(sink.chunks).toHaveLength(1);
|
||||
const studyQuery = barQueries.find(q => q.listingIds.includes(555));
|
||||
expect(studyQuery?.scope).toBe('vault_fenced');
|
||||
|
||||
const sessionQueries = barQueries.filter(q => !q.listingIds.includes(555));
|
||||
expect(sessionQueries).toHaveLength(1);
|
||||
const sessionQuery = sessionQueries[0]!;
|
||||
expect([...sessionQuery.listingIds]).toEqual([101, 102]);
|
||||
expect(sessionQuery.timeframe).toBe('1d');
|
||||
expect(sessionQuery.scope).not.toBe('vault_evaluation_only');
|
||||
expect(sessionQuery.to < '2025-06-01').toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runResearchCopilotStdioHost QA: lifecycle edge cases', () => {
|
||||
test('supports synchronous factories and synchronously throwing close(), closing in reverse order once each', async () => {
|
||||
const events: string[] = [];
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => {
|
||||
events.push('open:executor');
|
||||
return {
|
||||
executor: calendarExecutor().executor,
|
||||
close: () => {
|
||||
events.push('close:executor');
|
||||
},
|
||||
};
|
||||
},
|
||||
openStore: () => {
|
||||
events.push('open:store');
|
||||
return {
|
||||
store: recordingStore().store,
|
||||
close: () => {
|
||||
events.push('close:store');
|
||||
throw new Error('sync store close failure');
|
||||
},
|
||||
};
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
expect((err as Error).message).toBe('sync store close failure');
|
||||
expect(events).toEqual(['open:executor', 'open:store', 'close:store', 'close:executor']);
|
||||
});
|
||||
|
||||
test('synchronous throw from openStore is the rethrown original and the executor is still closed', async () => {
|
||||
const storeError = new Error('sync store open failure');
|
||||
let execCloses = 0;
|
||||
const sink = memoryOutput();
|
||||
const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
||||
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => ({
|
||||
executor: calendarExecutor().executor,
|
||||
close: () => {
|
||||
execCloses += 1;
|
||||
},
|
||||
}),
|
||||
openStore: () => {
|
||||
throw storeError;
|
||||
},
|
||||
stdio: { input: tracker.input, output: sink.output },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
expect(err).toBe(storeError);
|
||||
expect(execCloses).toBe(1);
|
||||
expect(sink.chunks).toEqual([]);
|
||||
expect(tracker.pulled()).toBe(0);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['null', null],
|
||||
['missing close()', { executor: {} }],
|
||||
] as const)('invalid executor handle (%s) fails closed with no store open and no stdio', async (_label, handle) => {
|
||||
let storeOpened = false;
|
||||
const sink = memoryOutput();
|
||||
const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
||||
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => handle as never,
|
||||
openStore: () => {
|
||||
storeOpened = true;
|
||||
return { store: recordingStore().store, close: () => {} };
|
||||
},
|
||||
stdio: { input: tracker.input, output: sink.output },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(storeOpened).toBe(false);
|
||||
expect(sink.chunks).toEqual([]);
|
||||
expect(tracker.pulled()).toBe(0);
|
||||
});
|
||||
|
||||
test('invalid store handle closes the executor and serves nothing', async () => {
|
||||
let execCloses = 0;
|
||||
const sink = memoryOutput();
|
||||
const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
||||
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => ({
|
||||
executor: calendarExecutor().executor,
|
||||
close: () => {
|
||||
execCloses += 1;
|
||||
},
|
||||
}),
|
||||
openStore: () => ({ store: recordingStore().store }) as never,
|
||||
stdio: { input: tracker.input, output: sink.output },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(execCloses).toBe(1);
|
||||
expect(sink.chunks).toEqual([]);
|
||||
expect(tracker.pulled()).toBe(0);
|
||||
});
|
||||
|
||||
test('library reader without listLibraryCards closes store then executor and serves nothing', async () => {
|
||||
const closes: string[] = [];
|
||||
const sink = memoryOutput();
|
||||
const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
||||
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => ({
|
||||
executor: calendarExecutor().executor,
|
||||
close: () => {
|
||||
closes.push('executor');
|
||||
},
|
||||
}),
|
||||
openStore: () => ({
|
||||
store: recordingStore().store,
|
||||
close: () => {
|
||||
closes.push('store');
|
||||
},
|
||||
}),
|
||||
createLibraryCardReader: () => ({}) as never,
|
||||
stdio: { input: tracker.input, output: sink.output },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(closes).toEqual(['store', 'executor']);
|
||||
expect(sink.chunks).toEqual([]);
|
||||
expect(tracker.pulled()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runResearchCopilotStdioHost QA: credential redaction', () => {
|
||||
test('replaces a safe-message error whose cause chain carries the DSN', async () => {
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => {
|
||||
throw new Error('connect failed', {
|
||||
cause: new Error('inner', { cause: new Error(`dsn=${FAKE_POSTGRES_URL}`) }),
|
||||
});
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
expectNoSecret(err);
|
||||
expect((err as Error).message).toContain('PostgreSQL executor');
|
||||
});
|
||||
|
||||
test('replaces an error carrying only the URL-encoded password', async () => {
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
createLibraryCardReader: () => {
|
||||
throw new Error(`bad token ${FAKE_ENCODED_PASSWORD}`);
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
expectNoSecret(err);
|
||||
expect((err as Error).message).toContain('library card reader');
|
||||
});
|
||||
|
||||
test('replaces an error whose message getter throws (uninspectable)', async () => {
|
||||
const hostile = new Error('placeholder');
|
||||
Object.defineProperty(hostile, 'message', {
|
||||
get() {
|
||||
throw new Error(FAKE_DECODED_PASSWORD);
|
||||
},
|
||||
});
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openStore: () => {
|
||||
throw hostile;
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(err).not.toBe(hostile);
|
||||
expectNoSecret(err);
|
||||
expect((err as Error).message).toContain('market data store');
|
||||
});
|
||||
|
||||
test('redacts a query-parameter password containing "+" in both decoded forms', async () => {
|
||||
const config = parseResearchCopilotHostConfig(
|
||||
buildEnv({
|
||||
RESEARCH_MCP_POSTGRES_URL: 'postgresql://qa_ro@127.0.0.1:5433/db?password=a+b%2Bc',
|
||||
})
|
||||
);
|
||||
for (const leaked of ['a b+c', 'a+b+c', 'a+b%2Bc']) {
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
config,
|
||||
openExecutor: () => {
|
||||
throw new Error(`auth failed: ${leaked}`);
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
expect((err as Error).message).not.toContain(leaked);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseResearchCopilotHostConfig QA: edge cases', () => {
|
||||
test('keeps a "__proto__" calendar code as an own data property without prototype pollution', () => {
|
||||
const config = parseResearchCopilotHostConfig(
|
||||
buildEnv({
|
||||
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: '{"__proto__":[7],"XNYS":[101]}',
|
||||
})
|
||||
);
|
||||
|
||||
expect(Object.keys(config.referenceListingIds).sort()).toEqual(['XNYS', '__proto__']);
|
||||
expect(Object.getOwnPropertyDescriptor(config.referenceListingIds, '__proto__')?.value).toEqual([7]);
|
||||
expect(Object.getPrototypeOf(config.referenceListingIds)).toBe(Object.prototype);
|
||||
});
|
||||
|
||||
test('ignores undefined prefixed keys and differently cased look-alike keys', () => {
|
||||
const config = parseResearchCopilotHostConfig(
|
||||
buildEnv({
|
||||
RESEARCH_MCP_NOT_SET: undefined,
|
||||
research_mcp_extra: 'x',
|
||||
Research_Mcp_Extra: 'y',
|
||||
})
|
||||
);
|
||||
expect(config.principalId).toBe('operator');
|
||||
});
|
||||
|
||||
test('accepts boundary early-close values (minute 1/960, dates 1976-01-01 and 2030-12-31)', () => {
|
||||
const config = parseResearchCopilotHostConfig(
|
||||
buildEnv({
|
||||
RESEARCH_MCP_EARLY_CLOSES: JSON.stringify({
|
||||
XNYS: { '1976-01-01': 1, '2030-12-31': 960 },
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(config.earlyCloses).toEqual({ XNYS: { '1976-01-01': 1, '2030-12-31': 960 } });
|
||||
});
|
||||
|
||||
test('accepts INT32 max listing id and rejects a two-digit-year cutoff that Date.UTC would remap', () => {
|
||||
expect(
|
||||
parseResearchCopilotHostConfig(
|
||||
buildEnv({ RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: '{"XNYS":[2147483647]}' })
|
||||
).referenceListingIds
|
||||
).toEqual({ XNYS: [2147483647] });
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
parseResearchCopilotHostConfig(
|
||||
buildEnv({ RESEARCH_MCP_VAULT_CUTOFF_TS: '0050-01-01T00:00:00Z' })
|
||||
);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
// Must never silently become 1950-01-01 (a different, earlier cutoff).
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
||||
expect((caught as ResearchCopilotHostConfigError).variable).toBe(
|
||||
'RESEARCH_MCP_VAULT_CUTOFF_TS'
|
||||
);
|
||||
});
|
||||
|
||||
test('parses the cutoff once and repeated parses of the same env are deterministic', () => {
|
||||
const a = parseResearchCopilotHostConfig(buildEnv());
|
||||
const b = parseResearchCopilotHostConfig(buildEnv());
|
||||
expect(a).toEqual(b);
|
||||
expect(a.vaultCutoffTs).toBe(CUTOFF_MS);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue