From bec64c5ec6f6c37e7e9baa134f8800171e72f2dc Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:30:22 -0500 Subject: [PATCH] =?UTF-8?q?T-149:=20M2.1h=20=E2=80=94=20MCP=20copilot=20`a?= =?UTF-8?q?nalyze=5Fsignal`:=20add=20a=20Vault-fenced=20`fundamentals`=20s?= =?UTF-8?q?ignal=20source=20(point-in-time=20`fundamentalsAsOf`=20month-en?= =?UTF-8?q?d=20snapshots=20=E2=86=92=20`SignalObservation`s)=20+=20extend?= =?UTF-8?q?=20the=20headless=20stdio=20end-to-end=20test=20to=20run=20a=20?= =?UTF-8?q?fundamental=20AND=20a=20shorts=20study=20(pure,=20injected=20po?= =?UTF-8?q?rts,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/analyze-signal.ts | 162 ++++++++++- libs/research/test/mcp-analyze-signal.test.ts | 259 ++++++++++++++++++ 2 files changed, 418 insertions(+), 3 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index 8a803e12..ef4ca71c 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -579,6 +579,69 @@ function resolveSnapshotAsOf( }; } +function buildBarTimestampsByListing(bars: readonly BarRecord[]): Map { + const byListing = new Map(); + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i]; + if ( + typeof bar !== 'object' || + bar === null || + typeof bar.listingId !== 'number' || + !Number.isSafeInteger(bar.listingId) || + typeof bar.ts !== 'number' || + !Number.isFinite(bar.ts) + ) { + continue; + } + let list = byListing.get(bar.listingId); + if (list === undefined) { + list = []; + byListing.set(bar.listingId, list); + } + list.push(bar.ts); + } + for (const [lid, list] of byListing) { + list.sort((a, b) => a - b); + let write = 0; + for (let i = 0; i < list.length; i += 1) { + const ts = list[i] as number; + if (write === 0 || list[write - 1] !== ts) { + list[write] = ts; + write += 1; + } + } + list.length = write; + byListing.set(lid, list); + } + return byListing; +} + +function findLatestBarBefore( + sortedTs: readonly number[] | undefined, + upperExclusiveMs: number, + lowerExclusiveMs: number +): number | null { + if (sortedTs === undefined || sortedTs.length === 0) { + return null; + } + let lo = 0; + let hi = sortedTs.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if ((sortedTs[mid] as number) < upperExclusiveMs) { + lo = mid + 1; + } else { + hi = mid; + } + } + const idx = lo - 1; + if (idx < 0) { + return null; + } + const candidate = sortedTs[idx] as number; + return candidate > lowerExclusiveMs ? candidate : null; +} + function appendEligibleFundamentalsObservations(params: { readonly table: Table; readonly field: FundamentalsPitValueField; @@ -588,7 +651,7 @@ function appendEligibleFundamentalsObservations(params: { readonly vaultCutoffTs: number; readonly seenKeys: Set; readonly out: SignalObservation[]; -}): void { +}): Map { const { table, field, @@ -612,6 +675,8 @@ function appendEligibleFundamentalsObservations(params: { ); } + const latestKnownAtByListing = new Map(); + for (let i = 0; i < table.rows.length; i += 1) { const row = table.rows[i]; if (typeof row !== 'object' || row === null) { @@ -640,12 +705,22 @@ function appendEligibleFundamentalsObservations(params: { } const rawValue = row[field]; - if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { + const isFiniteValue = typeof rawValue === 'number' && Number.isFinite(rawValue); + if (!isFiniteValue && rawValue !== null) { continue; } const normalizedListingId = listingId === 0 ? 0 : listingId; const normalizedKnownAt = knownAt === 0 ? 0 : knownAt; + const prevLatest = latestKnownAtByListing.get(normalizedListingId); + if (prevLatest === undefined || normalizedKnownAt > prevLatest) { + latestKnownAtByListing.set(normalizedListingId, normalizedKnownAt); + } + + if (!isFiniteValue) { + continue; + } + const normalizedValue = rawValue === 0 ? 0 : rawValue; const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; if (seenKeys.has(dedupeKey)) { @@ -658,6 +733,8 @@ function appendEligibleFundamentalsObservations(params: { value: normalizedValue, }); } + + return latestKnownAtByListing; } function buildCanonicalStudyExpression(params: { @@ -940,6 +1017,9 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT signals = []; const seenKeys = new Set(); + const barTimestampsByListing = buildBarTimestampsByListing(eligibleBars); + let windowFloorMs = Number.NEGATIVE_INFINITY; + for (const snapshotDate of snapshotDates) { const snapshot = resolveSnapshotAsOf( snapshotDate, @@ -952,7 +1032,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT asOf: snapshot.asOf, allowEstimatedLag: input.signal.allowEstimatedLag, }); - appendEligibleFundamentalsObservations({ + const latestKnownByListing = appendEligibleFundamentalsObservations({ table: rawTable, field: input.signal.field, listingIdSet, @@ -962,6 +1042,82 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT seenKeys, out: signals, }); + + // Backfill vintages superseded earlier within this month (or prior + // to the first eligible bar for the initial month) by stepping to + // the latest uncovered eligible bar strictly before each returned + // vintage. Listings sharing a target bar timestamp are batched. + const pendingByBarTs = new Map(); + const enqueueBackfill = ( + knownByListing: ReadonlyMap, + upperBoundExclusiveMs?: number + ): void => { + for (const [lid, knownAt] of knownByListing) { + const upperExclusive = + upperBoundExclusiveMs !== undefined + ? Math.min(knownAt, upperBoundExclusiveMs) + : knownAt; + const prevBarTs = findLatestBarBefore( + barTimestampsByListing.get(lid), + upperExclusive, + windowFloorMs + ); + if (prevBarTs !== null) { + let bucket = pendingByBarTs.get(prevBarTs); + if (bucket === undefined) { + bucket = []; + pendingByBarTs.set(prevBarTs, bucket); + } + bucket.push(lid); + } + } + }; + + enqueueBackfill(latestKnownByListing); + + while (pendingByBarTs.size > 0) { + // Pop the highest bar timestamp first so earlier buckets merge + // newly discovered listings landing on the same session. + let nextBarTs = Number.NEGATIVE_INFINITY; + for (const ts of pendingByBarTs.keys()) { + if (ts > nextBarTs) { + nextBarTs = ts; + } + } + const batchListingIds = sortAndDedupeListingIds(pendingByBarTs.get(nextBarTs) ?? []); + pendingByBarTs.delete(nextBarTs); + if (batchListingIds.length === 0) { + continue; + } + + const batchAsOfMs = Math.min(nextBarTs, fenced.asOfMs); + const batchAsOf = + batchAsOfMs === fenced.asOfMs + ? fenced.canonicalAsOf + : formatUtcIsoWithMicros(batchAsOfMs, 0); + const batchListingIdSet = new Set(batchListingIds); + + const backfillTable = await store.fundamentalsAsOf({ + listingIds: batchListingIds, + fields: [input.signal.field], + asOf: batchAsOf, + allowEstimatedLag: input.signal.allowEstimatedLag, + }); + const backfillKnownByListing = appendEligibleFundamentalsObservations({ + table: backfillTable, + field: input.signal.field, + listingIdSet: batchListingIdSet, + snapshotAsOfMs: batchAsOfMs, + fencedAsOfMs: fenced.asOfMs, + vaultCutoffTs, + seenKeys, + out: signals, + }); + + enqueueBackfill(backfillKnownByListing, nextBarTs); + } + + windowFloorMs = snapshot.asOfMs; } } diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index 40c52efd..8176615e 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -2537,6 +2537,265 @@ describe('MCP analyze_signal tool — fundamentals source', () => { expect(futureLedger.rows).toEqual(mcpLedger.rows); }); + test('same-month restatement replay retains earlier intra-month vintage through the day before the amendment', async () => { + // Regression fixture for intra-month superseded vintages: + // - Dataset ID: `synthetic:mcp-analyze-signal-same-month-restatement:seed-20261204:v1` + // - 6 listings across 2023-03-01..2023-05-12 (53 sessions), Vault cutoff 2023-05-15T00:00:00Z + // - March 10: initial Q1 release (listings 0..4 only; listing 5 has NO prior release before April 5) + // - April 5: Q2 release for all 6 listings (strictly ascending ttm_revenue across listings) + // - April 18: Q1 restatement (SAME month as Q2!) keeping Q2 as latest period while reversing + // ttm_revenue cross-sectional ordering. + // Under latest-only month-end reads, the April 30 snapshot returns only the April 18 vintage + // and erases April 5 from April 5..17 (falling back to March for listings 0..4 and dropping + // listing 5 completely). With intra-month backfill, April 5..17 uses the original April 5 Q2 + // values and April 18+ uses the restated values. + const listingIds = [81_001, 81_002, 81_003, 81_004, 81_005, 81_006]; + const allDates = makeBusinessDates('2023-03-01', 53); + const vaultCutoffDate = '2023-05-15'; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const marKnownAt = makeUtcMs('2023-03-10', 13); + const aprQ2KnownAt = makeUtcMs('2023-04-05', 13); + const aprRestatedKnownAt = makeUtcMs('2023-04-18', 13); + + const rand = createSeededRng(20261204); + const bars: BarRecord[] = []; + const prices = new Float64Array(listingIds.length).fill(40); + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingIds.length; l += 1) { + const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 30_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + const pitRows: FundamentalsPitFixtureRow[] = []; + const expectedAllVintagesObs: SignalObservation[] = []; + const brokenMonthEndOnlyObs: SignalObservation[] = []; + + for (let l = 0; l < listingIds.length; l += 1) { + const lid = listingIds[l]!; + // March ordering: alternating/scrambled; April 5 Q2: strictly ascending; April 18 restated: strictly descending + const marVal = 200 + ((l * 3) % listingIds.length) * 25; + const aprQ2Val = 100 + l * 40; + const aprRestatedVal = 400 - l * 45; + + if (l < 5) { + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: marKnownAt, + periodEnd: '2022-12-31', + fiscalPeriod: 'Q1', + revenue: marVal / 4, + ttmRevenue: marVal, + }) + ); + expectedAllVintagesObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + brokenMonthEndOnlyObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + } + + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprQ2KnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprQ2Val / 4, + ttmRevenue: aprQ2Val, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprRestatedKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprQ2Val / 4, + ttmRevenue: aprRestatedVal, + }) + ); + + expectedAllVintagesObs.push( + { listingId: lid, knownAt: aprQ2KnownAt, value: aprQ2Val }, + { listingId: lid, knownAt: aprRestatedKnownAt, value: aprRestatedVal } + ); + // Month-end-only baseline misses the April 5 vintage completely + brokenMonthEndOnlyObs.push({ listingId: lid, knownAt: aprRestatedKnownAt, value: aprRestatedVal }); + } + + // 1. Direct baseline with all eligible vintages (including April 5 Q2) + const directBuilt = buildForwardReturnPanel({ + bars, + signals: expectedAllVintagesObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const directLedger = createFakeTrialLedger(); + const directStudy = await analyzeSignal(directLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_same_month_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3 }, + universe: listingIds, + horizon: '3d', + }, + panel: directBuilt.panel, + vaultCutoffDate, + }); + expect(directStudy.status).toBe('ok'); + if (directStudy.status !== 'ok') { + return; + } + + // 2. Broken month-end-only counterfactual (omits April 5 Q2) + const brokenBuilt = buildForwardReturnPanel({ + bars, + signals: brokenMonthEndOnlyObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const brokenLedger = createFakeTrialLedger(); + const brokenStudy = await analyzeSignal(brokenLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'broken_month_end_only_counterfactual', + params: { field: 'ttm_revenue', horizonSessions: 3 }, + universe: listingIds, + horizon: '3d', + }, + panel: brokenBuilt.panel, + vaultCutoffDate, + }); + expect(brokenStudy.status).toBe('ok'); + + // 3. MCP handler over multi-month window (March..May) + const mcpStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const mcpLedger = createFakeTrialLedger(); + const mcpRes = await callAnalyzeSignal({ + store: mcpStore.store, + ledger: mcpLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(mcpRes.isError).toBe(false); + const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; + expect(mcpPayload.status).toBe('ok'); + if (mcpPayload.status !== 'ok') { + return; + } + + // Exact parity with the full-vintage direct baseline across all dates (including April 5..17) + expect(mcpPayload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); + expect(mcpPayload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); + expect(mcpLedger.rows[0]?.daily_series).toEqual(directLedger.rows[0]?.daily_series); + + // Specifically verify April 5..17 dated points match direct baseline and differ from month-end-only + const aprilPreAmendmentDates = mcpPayload.analysis.ledgerSeries.points + .filter(p => p.date >= '2023-04-05' && p.date <= '2023-04-17') + .map(p => p.date); + expect(aprilPreAmendmentDates.length).toBeGreaterThan(0); + expect(aprilPreAmendmentDates[0]).toBe('2023-04-05'); + expect(aprilPreAmendmentDates[aprilPreAmendmentDates.length - 1]).toBe('2023-04-17'); + + const mcpByDate = new Map(mcpPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])); + const brokenByDate = new Map( + brokenStudy.analysis.dates.map((d, idx) => [d, brokenStudy.analysis.rankIcSeries[idx]!]) + ); + let aprilDiffCount = 0; + for (const d of aprilPreAmendmentDates) { + if (mcpByDate.get(d) !== brokenByDate.get(d)) { + aprilDiffCount += 1; + } + } + expect(aprilDiffCount).toBeGreaterThan(0); + + // Every fundamentalsAsOf call (month-end + backfill) stays strictly below Vault cutoff and forwards allowEstimatedLag + for (const call of mcpStore.fundamentalsCalls) { + expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); + expect(call.allowEstimatedLag).toBe(false); + } + + // 4. Single-month window starting in April (2023-04-03..2023-04-28): + // must retain March prior (for Apr 3..4), April 5 Q2 (for Apr 5..17), and April 18 restatement (Apr 18..28). + const aprilOnlyBars = bars.filter(b => b.ts >= makeUtcMs('2023-04-03', 0) && b.ts <= makeUtcMs('2023-04-28', 23)); + const aprilDirectBuilt = buildForwardReturnPanel({ + bars: aprilOnlyBars, + signals: expectedAllVintagesObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const aprilDirectLedger = createFakeTrialLedger(); + const aprilDirectStudy = await analyzeSignal(aprilDirectLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_april_only_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3 }, + universe: listingIds, + horizon: '3d', + }, + panel: aprilDirectBuilt.panel, + vaultCutoffDate, + }); + expect(aprilDirectStudy.status).toBe('ok'); + + const aprilMcpStore = createFakeStore({ + bars: aprilOnlyBars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const aprilMcpLedger = createFakeTrialLedger(); + const aprilMcpRes = await callAnalyzeSignal({ + store: aprilMcpStore.store, + ledger: aprilMcpLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: '2023-04-03', + to: '2023-04-28', + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(aprilMcpRes.isError).toBe(false); + const aprilMcpPayload = JSON.parse(aprilMcpRes.text) as AnalyzeSignalResultPayload; + expect(aprilMcpPayload.status).toBe('ok'); + if (aprilMcpPayload.status === 'ok' && aprilDirectStudy.status === 'ok') { + expect(aprilMcpPayload.analysis.rankIc).toEqual(aprilDirectStudy.analysis.rankIc); + expect(aprilMcpLedger.rows[0]?.daily_series).toEqual(aprilDirectLedger.rows[0]?.daily_series); + expect(aprilMcpPayload.trial.sampleStart).toBe('2023-04-03'); + } + }); + test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { const fixture = buildFundamentalsStudyFixture(); const from = fixture.allDates[0]!;