From ee826bdef4bab9873e9d01d34505470b1044f8b3 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:39:37 -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 | 41 +- libs/research/test/mcp-analyze-signal.test.ts | 368 +++++++++++++++++- 2 files changed, 392 insertions(+), 17 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index ef4ca71c..eaa43c40 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -1002,6 +1002,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT ); signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); } else { + const { field: fundamentalsField, allowEstimatedLag } = input.signal; const snapshotDates = deriveMonthlySnapshotDates(eligibleBars); if (snapshotDates.length > ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS) { return { @@ -1028,13 +1029,13 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT ); const rawTable = await store.fundamentalsAsOf({ listingIds, - fields: [input.signal.field], + fields: [fundamentalsField], asOf: snapshot.asOf, - allowEstimatedLag: input.signal.allowEstimatedLag, + allowEstimatedLag, }); const latestKnownByListing = appendEligibleFundamentalsObservations({ table: rawTable, - field: input.signal.field, + field: fundamentalsField, listingIdSet, snapshotAsOfMs: snapshot.asOfMs, fencedAsOfMs: fenced.asOfMs, @@ -1046,17 +1047,27 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT // 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. + // vintage. When `allowEstimatedLag` is false, DuckDB omits listings + // whose latest vintage uses estimated publication lag, so treat + // omitted listings as unresolved intervals and probe earlier + // eligible closes in the month. Listings sharing a target bar + // timestamp are batched. const pendingByBarTs = new Map(); const enqueueBackfill = ( + queriedListingIds: readonly number[], knownByListing: ReadonlyMap, - upperBoundExclusiveMs?: number + upperBoundExclusiveMs: number ): void => { - for (const [lid, knownAt] of knownByListing) { - const upperExclusive = - upperBoundExclusiveMs !== undefined - ? Math.min(knownAt, upperBoundExclusiveMs) - : knownAt; + for (const lid of queriedListingIds) { + const knownAt = knownByListing.get(lid); + let upperExclusive: number; + if (knownAt !== undefined) { + upperExclusive = Math.min(knownAt, upperBoundExclusiveMs); + } else if (!allowEstimatedLag) { + upperExclusive = upperBoundExclusiveMs; + } else { + continue; + } const prevBarTs = findLatestBarBefore( barTimestampsByListing.get(lid), upperExclusive, @@ -1073,7 +1084,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT } }; - enqueueBackfill(latestKnownByListing); + enqueueBackfill(listingIds, latestKnownByListing, snapshot.asOfMs); while (pendingByBarTs.size > 0) { // Pop the highest bar timestamp first so earlier buckets merge @@ -1099,13 +1110,13 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT const backfillTable = await store.fundamentalsAsOf({ listingIds: batchListingIds, - fields: [input.signal.field], + fields: [fundamentalsField], asOf: batchAsOf, - allowEstimatedLag: input.signal.allowEstimatedLag, + allowEstimatedLag, }); const backfillKnownByListing = appendEligibleFundamentalsObservations({ table: backfillTable, - field: input.signal.field, + field: fundamentalsField, listingIdSet: batchListingIdSet, snapshotAsOfMs: batchAsOfMs, fencedAsOfMs: fenced.asOfMs, @@ -1114,7 +1125,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT out: signals, }); - enqueueBackfill(backfillKnownByListing, nextBarTs); + enqueueBackfill(batchListingIds, 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 8176615e..41ee7c95 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -2189,9 +2189,17 @@ describe('MCP analyze_signal tool — fundamentals source', () => { } const cutoffTs = makeUtcMs('2023-04-01', 0); + const preWindowKnownAt = makeUtcMs('2022-12-15', 13); const storeOrder = createFakeStore({ bars, - fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + fundamentalsResolver: q => ({ + columns: ['listing_id', 'effective_known_at', 'revenue'], + rows: q.listingIds.map(lid => ({ + listing_id: lid, + effective_known_at: preWindowKnownAt, + revenue: 100, + })), + }), }); const ledgerOrder = createFakeTrialLedger(); @@ -2273,9 +2281,17 @@ describe('MCP analyze_signal tool — fundamentals source', () => { } const capCutoffTs = makeUtcMs('2025-01-01', 0); + const capPreWindowKnownAt = makeUtcMs('2009-12-15', 13); const exactCapStore = createFakeStore({ bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS), - fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + fundamentalsResolver: q => ({ + columns: ['listing_id', 'effective_known_at', 'revenue'], + rows: q.listingIds.map(lid => ({ + listing_id: lid, + effective_known_at: capPreWindowKnownAt, + revenue: 100, + })), + }), }); const exactCapLedger = createFakeTrialLedger(); const exactCapRes = await callAnalyzeSignal({ @@ -2796,6 +2812,354 @@ describe('MCP analyze_signal tool — fundamentals source', () => { } }); + test('estimated-lag omission backfill recovers earlier verified intra-month vintages when allowEstimatedLag is false', async () => { + // Regression fixture for DuckDB estimated-lag omission under allowEstimatedLag: false: + // - Dataset ID: `synthetic:mcp-analyze-signal-estimated-lag-omission:seed-20261205:v1` + // - 6 listings across 2023-03-01..2023-05-12 (53 sessions), Vault cutoff 2023-05-15T00:00:00Z + // - March 10: verified Q1 release (listings 0..4 only; listing 5 has no March prior) + // - April 5: verified Q2 release (`has_estimated_lag: false`) for all 6 listings + // - April 18: estimated-lag update (`has_estimated_lag: true`) for all 6 listings, so + // DuckDB's `fundamentalsAsOf(..., allowEstimatedLag: false)` omits listings 1..5 + // at April month-end and omits listing 0 at intermediate backfill probes. + // - April 25: verified update (`has_estimated_lag: false`) for listing 0 only (exercises + // sandwiched omission during backfill after a later verified release). + const listingIds = [82_001, 82_002, 82_003, 82_004, 82_005, 82_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 aprVerifiedKnownAt = makeUtcMs('2023-04-05', 13); + const aprEstimatedLagKnownAt = makeUtcMs('2023-04-18', 13); + const aprLateVerifiedKnownAt = makeUtcMs('2023-04-25', 13); + + const rand = createSeededRng(20261205); + const bars: BarRecord[] = []; + const prices = new Float64Array(listingIds.length).fill(45); + 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 expectedVerifiedObs: SignalObservation[] = []; + const expectedAllowLagObs: SignalObservation[] = []; + const brokenOmittedAprilObs: SignalObservation[] = []; + + for (let l = 0; l < listingIds.length; l += 1) { + const lid = listingIds[l]!; + const marVal = 200 + ((l * 3) % listingIds.length) * 25; + const aprVerifiedVal = 100 + l * 40; + const aprEstimatedVal = 400 - l * 45; + const aprLateVerifiedVal = 150; + + if (l < 5) { + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: marKnownAt, + periodEnd: '2022-12-31', + fiscalPeriod: 'Q1', + revenue: marVal / 4, + ttmRevenue: marVal, + hasEstimatedLag: false, + }) + ); + expectedVerifiedObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + expectedAllowLagObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + brokenOmittedAprilObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + } + + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprVerifiedKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprVerifiedVal / 4, + ttmRevenue: aprVerifiedVal, + hasEstimatedLag: false, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprEstimatedLagKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprEstimatedVal / 4, + ttmRevenue: aprEstimatedVal, + hasEstimatedLag: true, + }) + ); + + expectedVerifiedObs.push({ + listingId: lid, + knownAt: aprVerifiedKnownAt, + value: aprVerifiedVal, + }); + expectedAllowLagObs.push( + { listingId: lid, knownAt: aprVerifiedKnownAt, value: aprVerifiedVal }, + { listingId: lid, knownAt: aprEstimatedLagKnownAt, value: aprEstimatedVal } + ); + + if (l === 0) { + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprLateVerifiedKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprLateVerifiedVal / 4, + ttmRevenue: aprLateVerifiedVal, + hasEstimatedLag: false, + }) + ); + expectedVerifiedObs.push({ + listingId: lid, + knownAt: aprLateVerifiedKnownAt, + value: aprLateVerifiedVal, + }); + expectedAllowLagObs.push({ + listingId: lid, + knownAt: aprLateVerifiedKnownAt, + value: aprLateVerifiedVal, + }); + brokenOmittedAprilObs.push({ + listingId: lid, + knownAt: aprLateVerifiedKnownAt, + value: aprLateVerifiedVal, + }); + } + } + + // 1. Direct verified-only baseline (includes April 5 verified release; excludes April 18 estimated lag) + const directVerifiedBuilt = buildForwardReturnPanel({ + bars, + signals: expectedVerifiedObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const directVerifiedLedger = createFakeTrialLedger(); + const directVerifiedStudy = await analyzeSignal(directVerifiedLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_estimated_lag_omission_verified_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, + universe: listingIds, + horizon: '3d', + }, + panel: directVerifiedBuilt.panel, + vaultCutoffDate, + }); + expect(directVerifiedStudy.status).toBe('ok'); + if (directVerifiedStudy.status !== 'ok') { + return; + } + + // 2. Broken counterfactual without omission backfill (loses April 5 for all omitted listings) + const brokenBuilt = buildForwardReturnPanel({ + bars, + signals: brokenOmittedAprilObs, + 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_estimated_lag_omission_counterfactual', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, + universe: listingIds, + horizon: '3d', + }, + panel: brokenBuilt.panel, + vaultCutoffDate, + }); + expect(brokenStudy.status).toBe('ok'); + + // 3. MCP handler with allowEstimatedLag: false (default) over 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 verified-only direct baseline across all dates (including April 5..17) + expect(mcpPayload.analysis.rankIc).toEqual(directVerifiedStudy.analysis.rankIc); + expect(mcpPayload.analysis.pearsonIc).toEqual(directVerifiedStudy.analysis.pearsonIc); + expect(mcpLedger.rows[0]?.daily_series).toEqual(directVerifiedLedger.rows[0]?.daily_series); + + const aprilPreEstimatedDates = mcpPayload.analysis.ledgerSeries.points + .filter(p => p.date >= '2023-04-05' && p.date <= '2023-04-17') + .map(p => p.date); + expect(aprilPreEstimatedDates[0]).toBe('2023-04-05'); + expect(aprilPreEstimatedDates[aprilPreEstimatedDates.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 aprilPreEstimatedDates) { + if (mcpByDate.get(d) !== brokenByDate.get(d)) { + aprilDiffCount += 1; + } + } + expect(aprilDiffCount).toBeGreaterThan(0); + + // Every fundamentalsAsOf call stays strictly below Vault cutoff and forwards allowEstimatedLag: false + for (const call of mcpStore.fundamentalsCalls) { + expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); + expect(call.allowEstimatedLag).toBe(false); + } + + // 4. Single-month April-only window (2023-04-03..2023-04-28) with allowEstimatedLag: false + 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: expectedVerifiedObs, + 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_estimated_lag_april_only_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, + 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); + } + + // 5. With allowEstimatedLag: true, April 18 estimated-lag update is included alongside April 5 + const allowLagDirectBuilt = buildForwardReturnPanel({ + bars, + signals: expectedAllowLagObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const allowLagDirectLedger = createFakeTrialLedger(); + const allowLagDirectStudy = await analyzeSignal(allowLagDirectLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_estimated_lag_allowed_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: true }, + universe: listingIds, + horizon: '3d', + }, + panel: allowLagDirectBuilt.panel, + vaultCutoffDate, + }); + expect(allowLagDirectStudy.status).toBe('ok'); + + const allowLagStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const allowLagLedger = createFakeTrialLedger(); + const allowLagRes = await callAnalyzeSignal({ + store: allowLagStore.store, + ledger: allowLagLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(allowLagRes.isError).toBe(false); + const allowLagPayload = JSON.parse(allowLagRes.text) as AnalyzeSignalResultPayload; + expect(allowLagPayload.status).toBe('ok'); + if (allowLagPayload.status === 'ok' && allowLagDirectStudy.status === 'ok') { + expect(allowLagPayload.analysis.rankIc).toEqual(allowLagDirectStudy.analysis.rankIc); + expect(allowLagLedger.rows[0]?.daily_series).toEqual( + allowLagDirectLedger.rows[0]?.daily_series + ); + expect(allowLagLedger.rows[0]?.daily_series).not.toEqual(mcpLedger.rows[0]?.daily_series); + } + expect(allowLagStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); + }); + 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]!;