From f0f55acef2b45ee40fa478e0e1b69a2bf18dd943 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 00:56:58 -0500 Subject: [PATCH] T-133: tests --- libs/research/test/mcp-event-study-qa.test.ts | 297 ++++++++++++++++++ 1 file changed, 297 insertions(+) diff --git a/libs/research/test/mcp-event-study-qa.test.ts b/libs/research/test/mcp-event-study-qa.test.ts index e45ec584..fca76a34 100644 --- a/libs/research/test/mcp-event-study-qa.test.ts +++ b/libs/research/test/mcp-event-study-qa.test.ts @@ -817,3 +817,300 @@ describe('MCP event_study QA edge cases', () => { expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series); }); }); + +// --------------------------------------------------------------------------- +// Quant QA additions (T-133): exact benchmark economics, late-revised bars, +// subtype-filter accounting, resolver contract edges, and microsecond upper bounds. +// Fixture "qa-t133-v1": 6 listings, weekday sessions, flat prices except +// explicit jump days; gross close-to-close returns, raw adjustment, no costs. +// --------------------------------------------------------------------------- + +const QA_LISTINGS = [701, 702, 703, 704, 705, 706]; + +function qaXnysResolver(dates: readonly string[]) { + const calls: EventStudyExchangeCalendarQuery[] = []; + const resolve = (q: EventStudyExchangeCalendarQuery): EventStudyExchangeCalendars => { + calls.push(q); + const sessions = dates + .filter(d => d >= q.fromDate && d <= q.toDate) + .map(date => ({ date, closeTs: utcMs(date, 21) })); + const listingCalendarId = new Map(); + for (const id of q.listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; + }; + return { calls, resolve }; +} + +/** Flat 100 prices; `jumps` maps `${listingIndex}:${dayIndex}` -> daily return. */ +function qaBars(dates: readonly string[], days: number, jumps: ReadonlyMap) { + const bars: BarRecord[] = []; + for (let l = 0; l < QA_LISTINGS.length; l += 1) { + let price = 100; + for (let t = 0; t < days; t += 1) { + price = Number((price * (1 + (jumps.get(`${l}:${t}`) ?? 0))).toFixed(6)); + const ts = utcMs(dates[t]!, 21); + bars.push({ + listingId: QA_LISTINGS[l]!, + ts, + open: price, + high: price, + low: price, + close: price, + volume: 1_000, + knownAt: ts, + }); + } + } + return bars; +} + +function qaEvent(l: number, ts: number, extra?: Partial): TableRow { + return { + listing_id: QA_LISTINGS[l]!, + ts, + known_at: ts, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + ...extra, + }; +} + +function qaServer(params: { + bars: readonly BarRecord[]; + rows: readonly TableRow[]; + vaultCutoffTs: number; + resolveExchangeCalendars: ( + q: EventStudyExchangeCalendarQuery + ) => EventStudyExchangeCalendars | Promise; +}) { + const ledger = createFakeLedger(); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: createPassThroughStore({ + bars: params.bars, + eventsTable: { columns: [...EVENTS_COLUMNS], rows: [...params.rows] }, + }), + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: params.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: params.resolveExchangeCalendars, + }), + ], + }); + return { server, ledger }; +} + +describe('MCP event_study QA additions', () => { + // Day 6: listings 0-2 get +10% with events; day 12: listings 3-5 get +20% with events. + // Other listings are flat, so the equal-weight benchmark on day 6 is 0.05 and on day 12 is 0.10. + const dates = makeBusinessDates('2023-03-01', 22); + const vaultCutoffTs = utcMs(dates[21]!, 0); + const jumps = new Map([ + ['0:6', 0.1], + ['1:6', 0.1], + ['2:6', 0.1], + ['3:12', 0.2], + ['4:12', 0.2], + ['5:12', 0.2], + ]); + const bars = qaBars(dates, 21, jumps); + const eventRows: TableRow[] = [ + ...[0, 1, 2].map(l => qaEvent(l, utcMs(dates[6]!, 14))), + ...[3, 4, 5].map(l => qaEvent(l, utcMs(dates[12]!, 14))), + ]; + const baseArgs = { + listingIds: QA_LISTINGS, + from: dates[0]!, + to: dates[20]!, + event: { kinds: ['filing'] }, + preDays: 1, + postDays: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + test('benchmark "none" reports raw event-day returns and "equal_weight" subtracts the cross-sectional mean', async () => { + const none = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + const ew = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + + const resNone = await invoke(none.server, { ...baseArgs, benchmark: 'none' }); + const resEw = await invoke(ew.server, { ...baseArgs, benchmark: 'equal_weight' }); + + if (resNone.payload?.status !== 'ok' || resEw.payload?.status !== 'ok') { + throw new Error(`Expected ok payloads: ${resNone.text} | ${resEw.text}`); + } + const at = (p: typeof resNone.payload, offset: number) => + p.study.offsets.find(o => o.offset === offset)!; + + // none: mean(+10% x3, +20% x3) = 0.15; flat neighbours. + expect(at(resNone.payload, 0).aar).toBeCloseTo(0.15, 10); + expect(at(resNone.payload, -1).aar).toBeCloseTo(0, 10); + expect(at(resNone.payload, 1).aar).toBeCloseTo(0, 10); + // equal_weight: mean(0.10-0.05 x3, 0.20-0.10 x3) = 0.075. + expect(at(resEw.payload, 0).aar).toBeCloseTo(0.075, 10); + expect(at(resEw.payload, 0).n).toBe(6); + expect(resNone.payload.study.hasBenchmark).toBe(false); + expect(resEw.payload.study.hasBenchmark).toBe(true); + expect(none.ledger.insertCalls).toBe(1); + expect(ew.ledger.insertCalls).toBe(1); + expect(resNone.payload.trial.expressionHash).not.toBe(resEw.payload.trial.expressionHash); + }); + + test('a late-revised bar (knownAt > asOf) leaked by the store is dropped before the panel', async () => { + const asOfIso = `${dates[18]!}T21:00:00.000Z`; + // Same (listing, ts) as an original bar but a different close and knownAt after asOf. + // If admitted, the panel would throw duplicate_bar or change returns. + const revised: BarRecord = { + ...bars.find(b => b.listingId === QA_LISTINGS[0] && b.ts === utcMs(dates[6]!, 21))!, + close: 999, + open: 999, + high: 999, + low: 999, + knownAt: utcMs(dates[19]!, 12), + }; + const clean = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + const leaky = qaServer({ + bars: [...bars, revised], + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + + const resClean = await invoke(clean.server, { ...baseArgs, asOf: asOfIso, benchmark: 'none' }); + const resLeaky = await invoke(leaky.server, { ...baseArgs, asOf: asOfIso, benchmark: 'none' }); + + expect(resLeaky.isError).toBeUndefined(); + if (resLeaky.payload?.status !== 'ok' || resClean.payload?.status !== 'ok') { + throw new Error(`Expected ok payloads: ${resLeaky.text}`); + } + expect(resLeaky.payload.study.offsets).toEqual(resClean.payload.study.offsets); + expect(resLeaky.payload.panelDiagnostics).toEqual(resClean.payload.panelDiagnostics); + expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series); + }); + + test('subtype filter drops null and non-matching subtypes (even in the Vault) without counting Vault exclusions', async () => { + const noise: TableRow[] = [ + qaEvent(0, utcMs(dates[9]!, 14), { subtype: null }), + qaEvent(1, utcMs(dates[9]!, 14), { subtype: '10-Q' }), + // Non-matching subtype on the cutoff day: filtered as unrequested, not as a Vault exclusion. + qaEvent(2, utcMs(dates[21]!, 14), { subtype: '10-K' }), + // Matching subtype on the cutoff day: a genuine Vault exclusion. + qaEvent(3, utcMs(dates[21]!, 14)), + ]; + const { server, ledger } = qaServer({ + bars, + rows: [...eventRows, ...noise], + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + + const res = await invoke(server, { + ...baseArgs, + event: { kinds: ['filing'], subtypes: ['8-K'] }, + benchmark: 'none', + }); + + if (res.payload?.status !== 'ok') { + throw new Error(`Expected ok: ${res.text}`); + } + expect(res.payload.eventCount).toBe(6); + expect(res.payload.vaultExcludedEvents).toBe(1); + expect(res.payload.event.subtypes).toEqual(['8-K']); + expect(res.payload.study.offsets.find(o => o.offset === 0)!.aar).toBeCloseTo(0.15, 10); + expect(ledger.insertCalls).toBe(1); + }); + + test('synchronous calendar resolver is accepted and a non-Error throw maps to the fixed resolver message', async () => { + const sync = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + const syncRes = await invoke(sync.server, { ...baseArgs, benchmark: 'none' }); + expect(syncRes.payload?.status).toBe('ok'); + + const SECRET = 'SECRET_CAL_DSN_55120'; + const failing = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: () => { + throw `postgres://calendar:${SECRET}@db/cal`; + }, + }); + const failRes = await invoke(failing.server, { ...baseArgs, benchmark: 'none' }); + expect(failRes.isError).toBe(true); + expect(failRes.text).toBe('Error: Exchange calendar resolution failed.'); + expect(failRes.text).not.toContain(SECRET); + expect(failing.ledger.insertCalls).toBe(0); + + const rejecting = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: () => Promise.reject(new TypeError(`/srv/cal/${SECRET}.parquet`)), + }); + const rejectRes = await invoke(rejecting.server, { ...baseArgs, benchmark: 'none' }); + expect(rejectRes.isError).toBe(true); + expect(rejectRes.text).toBe('Error: Exchange calendar resolution failed.'); + expect(rejectRes.text).not.toContain(SECRET); + }); + + test('microsecond-precision to/asOf keep rows at the boundary millisecond and drop the next millisecond', async () => { + // to/asOf at dates[14] 15:00:00.123456Z. Base events (days 6, 12) are inside the window. + const boundaryIso = `${dates[14]!}T15:00:00.123456Z`; + const boundaryMs = Date.parse(`${dates[14]!}T15:00:00.123Z`); + const extra: TableRow[] = [ + qaEvent(0, boundaryMs), // ts == toMs, known_at == asOfMs (.123 <= .123456) -> kept + qaEvent(1, boundaryMs + 1), // .124 > .123456 -> dropped + qaEvent(2, utcMs(dates[10]!, 14), { known_at: boundaryMs + 1 }), // known after asOf -> dropped + ]; + const { server } = qaServer({ + bars, + rows: [...eventRows, ...extra], + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + + const res = await invoke(server, { + ...baseArgs, + to: boundaryIso, + asOf: boundaryIso, + benchmark: 'none', + }); + + expect(res.isError).toBeUndefined(); + expect(res.payload?.effectiveTo).toBe(boundaryIso); + expect(res.payload?.effectiveAsOf).toBe(boundaryIso); + // The boundary-ms event passes the defensive filter and reaches the panel, which drops it + // as after-last-session (its dates[14] close is after asOf). The .124 rows never reach the + // panel: if they did, droppedAfterLastSession would be > 1 or eventCount would change. + expect(res.payload?.panelDiagnostics.droppedAfterLastSession).toBe(1); + expect(res.payload?.eventCount).toBe(6); + expect(res.payload?.study.diagnostics.eventsUsed).toBe(6); + expect(res.payload?.vaultExcludedEvents).toBe(0); + }); +});