3403 lines
127 KiB
TypeScript
3403 lines
127 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import {
|
|
type BarBatch,
|
|
type BarRecord,
|
|
type MarketDataStore,
|
|
MarketDataStoreValidationError,
|
|
type Table,
|
|
type TableRow,
|
|
VaultScopeNotAuthorizedError,
|
|
} from '../src/market-data-store';
|
|
import {
|
|
type BarsQuery,
|
|
FUNDAMENTALS_PIT_VALUE_FIELDS,
|
|
type FundamentalsAsOfQuery,
|
|
MarketDataStoreNotImplementedError,
|
|
type ShortsAsOfQuery,
|
|
type UniverseQuery,
|
|
} from '../src/market-data-store-duckdb';
|
|
import {
|
|
ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS,
|
|
ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS,
|
|
ANALYZE_SIGNAL_MAX_LISTING_IDS,
|
|
ANALYZE_SIGNAL_MAX_SERIES_POINTS,
|
|
type AnalyzeSignalResultPayload,
|
|
createAnalyzeSignalTool,
|
|
createMcpServer,
|
|
createQueryDataTool,
|
|
} from '../src/mcp/index';
|
|
import {
|
|
type SignalObservation,
|
|
buildForwardReturnPanel,
|
|
shortsTableToSignalRows,
|
|
} from '../src/signal-panel';
|
|
import { analyzeSignal } from '../src/signal-study';
|
|
import { type TrialLedgerExecutor, canonicalExpressionHash } from '../src/trial-ledger';
|
|
|
|
const SEED = 20261129;
|
|
const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
|
const CAMPAIGN_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
|
const HYPOTHESIS_UUID = '12345678-1234-4123-8123-123456789abc';
|
|
|
|
function createSeededRng(seed: number): () => number {
|
|
let state = seed >>> 0;
|
|
return () => {
|
|
state = (state + 0x6d2b79f5) >>> 0;
|
|
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
|
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
|
};
|
|
}
|
|
|
|
function makeBusinessDates(startDate: string, count: number): string[] {
|
|
const out: string[] = new Array(count);
|
|
const current = new Date(`${startDate}T00:00:00.000Z`);
|
|
let written = 0;
|
|
while (written < count) {
|
|
const day = current.getUTCDay();
|
|
if (day !== 0 && day !== 6) {
|
|
out[written] = current.toISOString().slice(0, 10);
|
|
written += 1;
|
|
}
|
|
current.setUTCDate(current.getUTCDate() + 1);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function makeUtcMs(date: string, hourUtc: number): number {
|
|
const [y, m, d] = date.split('-').map(Number);
|
|
return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0);
|
|
}
|
|
|
|
interface StoredTrialRow {
|
|
readonly trial_id: string;
|
|
readonly created_at: Date;
|
|
readonly principal_id: string;
|
|
readonly campaign_id: string | null;
|
|
readonly stage: string;
|
|
readonly universe_market: string;
|
|
readonly horizon_bucket: string;
|
|
readonly hypothesis_id: string | null;
|
|
readonly expression_hash: string;
|
|
readonly sample_start: string;
|
|
readonly sample_end: string;
|
|
readonly n_obs: number;
|
|
readonly sharpe_unann: number;
|
|
readonly skewness: number;
|
|
readonly kurtosis: number;
|
|
readonly daily_series: readonly number[];
|
|
}
|
|
|
|
function createFakeTrialLedger(options?: {
|
|
insertError?: Error;
|
|
dsrReadError?: Error;
|
|
}): {
|
|
executor: TrialLedgerExecutor;
|
|
rows: StoredTrialRow[];
|
|
insertCalls: number;
|
|
selectCalls: number;
|
|
} {
|
|
const rows: StoredTrialRow[] = [];
|
|
let nextTrialId = 1;
|
|
const state = {
|
|
rows,
|
|
insertCalls: 0,
|
|
selectCalls: 0,
|
|
executor: null as unknown as TrialLedgerExecutor,
|
|
};
|
|
|
|
state.executor = {
|
|
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
|
const trimmed = text.trimStart();
|
|
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
|
state.insertCalls += 1;
|
|
if (options?.insertError !== undefined) {
|
|
throw options.insertError;
|
|
}
|
|
const p = params ?? [];
|
|
const trialId = nextTrialId++;
|
|
const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId));
|
|
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
|
const stored: StoredTrialRow = {
|
|
trial_id: String(trialId),
|
|
created_at: createdAt,
|
|
principal_id: p[0] as string,
|
|
campaign_id: (p[1] as string | null) ?? null,
|
|
stage: p[2] as string,
|
|
universe_market: p[3] as string,
|
|
horizon_bucket: p[4] as string,
|
|
hypothesis_id: (p[5] as string | null) ?? null,
|
|
expression_hash: p[6] as string,
|
|
sample_start: p[7] as string,
|
|
sample_end: p[8] as string,
|
|
n_obs: p[9] as number,
|
|
sharpe_unann: p[10] as number,
|
|
skewness: p[11] as number,
|
|
kurtosis: p[12] as number,
|
|
daily_series: dailySeries,
|
|
};
|
|
rows.push(stored);
|
|
return {
|
|
rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row],
|
|
rowCount: 1,
|
|
};
|
|
}
|
|
|
|
if (trimmed.startsWith('SELECT')) {
|
|
state.selectCalls += 1;
|
|
if (options?.dsrReadError !== undefined) {
|
|
throw options.dsrReadError;
|
|
}
|
|
if (text.includes('WHERE trial_id = $1::bigint')) {
|
|
const targetId = String(params?.[0]);
|
|
const matched = rows.filter(r => r.trial_id === targetId);
|
|
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
|
}
|
|
if (text.includes('WHERE universe_market = $1')) {
|
|
const market = params?.[0] as string;
|
|
const bucket = params?.[1] as string;
|
|
const matched = rows.filter(
|
|
r => r.universe_market === market && r.horizon_bucket === bucket
|
|
);
|
|
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
|
}
|
|
}
|
|
|
|
return { rows: [], rowCount: 0 };
|
|
},
|
|
};
|
|
|
|
return state;
|
|
}
|
|
|
|
interface CeoShortsFixture {
|
|
readonly listingIds: number[];
|
|
readonly allDates: string[];
|
|
readonly vaultCutoffDate: string;
|
|
readonly vaultCutoffTs: number;
|
|
readonly bars: BarRecord[];
|
|
readonly shortsTable: Table;
|
|
}
|
|
|
|
const SHORTS_COLUMNS = [
|
|
'listing_id',
|
|
'report_date',
|
|
'known_at',
|
|
'shares_short',
|
|
'net_change',
|
|
'pct_float',
|
|
'source',
|
|
] as const;
|
|
|
|
function buildCeoShortsFixture(options?: {
|
|
preCutoffSessions?: number;
|
|
postCutoffSessions?: number;
|
|
listingCount?: number;
|
|
poisonPostCutoff?: boolean;
|
|
}): CeoShortsFixture {
|
|
const rand = createSeededRng(SEED);
|
|
const listingCount = options?.listingCount ?? 28;
|
|
const preCutoffSessions = options?.preCutoffSessions ?? 140;
|
|
const postCutoffSessions = options?.postCutoffSessions ?? 10;
|
|
const poisonPostCutoff = options?.poisonPostCutoff ?? false;
|
|
|
|
const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions);
|
|
const vaultCutoffDate = allDates[preCutoffSessions]!;
|
|
const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0);
|
|
|
|
const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i);
|
|
const bars: BarRecord[] = [];
|
|
const shortsRows: TableRow[] = [];
|
|
|
|
const PUBLICATION_LAG_SESSIONS = 4;
|
|
const activeNetChange = new Float64Array(listingCount);
|
|
const pendingByPublishIdx = new Map<number, (number | null)[]>();
|
|
const prices = new Float64Array(listingCount);
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
prices[l] = 10 + l * 1.5;
|
|
}
|
|
|
|
for (let t = 0; t < allDates.length; t += 1) {
|
|
const date = allDates[t]!;
|
|
const closeTs = makeUtcMs(date, 21); // 16:00 ET close
|
|
|
|
const released = pendingByPublishIdx.get(t - 1);
|
|
if (released !== undefined) {
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
const v = released[l];
|
|
if (v !== null && v !== undefined) {
|
|
activeNetChange[l] = v / 20_000;
|
|
}
|
|
}
|
|
}
|
|
|
|
const publishIdx = t + PUBLICATION_LAG_SESSIONS;
|
|
if (t % 10 === 0 && publishIdx < allDates.length) {
|
|
const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+4
|
|
const pending: (number | null)[] = [];
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
const isNullCell = t > 0 && (t + l) % 19 === 0;
|
|
const netChange = isNullCell ? null : Math.round((rand() * 2 - 1) * 20_000);
|
|
pending.push(netChange);
|
|
shortsRows.push({
|
|
listing_id: listingIds[l]!,
|
|
report_date: date,
|
|
known_at: reportKnownAt,
|
|
shares_short: 100_000 + l * 5_000 + Math.round(rand() * 10_000),
|
|
net_change: netChange,
|
|
pct_float: isNullCell ? null : Number((0.02 + rand() * 0.08).toFixed(4)),
|
|
source: 'ceoShorts',
|
|
});
|
|
}
|
|
pendingByPublishIdx.set(publishIdx, pending);
|
|
}
|
|
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
const dailyRet = -0.004 * activeNetChange[l]! + (rand() * 2 - 1) * 0.008;
|
|
prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet));
|
|
const isPostCutoff = date >= vaultCutoffDate;
|
|
const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6));
|
|
bars.push({
|
|
listingId: listingIds[l]!,
|
|
ts: closeTs,
|
|
open: closeVal,
|
|
high: closeVal,
|
|
low: closeVal,
|
|
close: closeVal,
|
|
volume: 50_000,
|
|
vwap: closeVal,
|
|
knownAt: closeTs,
|
|
});
|
|
}
|
|
}
|
|
|
|
return {
|
|
listingIds,
|
|
allDates,
|
|
vaultCutoffDate,
|
|
vaultCutoffTs,
|
|
bars,
|
|
shortsTable: {
|
|
columns: SHORTS_COLUMNS,
|
|
rows: shortsRows,
|
|
},
|
|
};
|
|
}
|
|
|
|
interface FakeStoreState {
|
|
readonly barsCalls: BarsQuery[];
|
|
readonly shortsCalls: ShortsAsOfQuery[];
|
|
readonly fundamentalsCalls: FundamentalsAsOfQuery[];
|
|
readonly universeCalls: UniverseQuery[];
|
|
readonly store: MarketDataStore;
|
|
}
|
|
|
|
function createFakeStore(options?: {
|
|
bars?: readonly BarRecord[];
|
|
shortsTable?: Table;
|
|
fundamentalsResolver?: (q: FundamentalsAsOfQuery) => Table | Promise<Table>;
|
|
universeIds?: readonly number[];
|
|
universeResolver?: (q: UniverseQuery) => number[];
|
|
leaky?: boolean;
|
|
barsError?: Error;
|
|
shortsError?: Error;
|
|
fundamentalsError?: Error;
|
|
universeError?: Error;
|
|
}): FakeStoreState {
|
|
const barsCalls: BarsQuery[] = [];
|
|
const shortsCalls: ShortsAsOfQuery[] = [];
|
|
const fundamentalsCalls: FundamentalsAsOfQuery[] = [];
|
|
const universeCalls: UniverseQuery[] = [];
|
|
|
|
const allBars = options?.bars ?? [];
|
|
const allShorts = options?.shortsTable ?? { columns: SHORTS_COLUMNS, rows: [] };
|
|
const leaky = options?.leaky ?? false;
|
|
|
|
const store: MarketDataStore = {
|
|
bars(q: BarsQuery): AsyncIterable<BarBatch> {
|
|
barsCalls.push(q);
|
|
if (options?.barsError !== undefined) {
|
|
const err = options.barsError;
|
|
return {
|
|
[Symbol.asyncIterator]() {
|
|
return {
|
|
next() {
|
|
return Promise.reject(err);
|
|
},
|
|
};
|
|
},
|
|
};
|
|
}
|
|
|
|
const idSet = new Set(q.listingIds);
|
|
const fromMs = Date.parse(q.from.length === 10 ? `${q.from}T00:00:00.000Z` : q.from);
|
|
const toMs = Date.parse(q.to.length === 10 ? `${q.to}T23:59:59.999Z` : q.to);
|
|
const asOfMs =
|
|
q.asOf !== undefined
|
|
? Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf)
|
|
: Number.POSITIVE_INFINITY;
|
|
|
|
const filtered = leaky
|
|
? [...allBars]
|
|
: allBars.filter(
|
|
row =>
|
|
idSet.has(row.listingId) &&
|
|
row.ts >= fromMs &&
|
|
row.ts <= toMs &&
|
|
row.ts <= asOfMs &&
|
|
row.knownAt <= asOfMs
|
|
);
|
|
|
|
return {
|
|
async *[Symbol.asyncIterator]() {
|
|
yield { rows: filtered };
|
|
},
|
|
};
|
|
},
|
|
|
|
async shortsAsOf(q: ShortsAsOfQuery): Promise<Table> {
|
|
shortsCalls.push(q);
|
|
if (options?.shortsError !== undefined) {
|
|
throw options.shortsError;
|
|
}
|
|
|
|
if (leaky) {
|
|
return {
|
|
columns: allShorts.columns,
|
|
rows: [...allShorts.rows],
|
|
};
|
|
}
|
|
|
|
const idSet = new Set(q.listingIds);
|
|
const fromDate = q.from.slice(0, 10);
|
|
const toDate = q.to.slice(0, 10);
|
|
const asOfMs =
|
|
q.asOf !== undefined
|
|
? Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf)
|
|
: Number.POSITIVE_INFINITY;
|
|
|
|
const rows = allShorts.rows.filter(row => {
|
|
const lid = row.listing_id as number;
|
|
const reportDate = row.report_date as string | undefined;
|
|
const knownAt = row.known_at as number;
|
|
const inDateRange =
|
|
reportDate === undefined || (reportDate >= fromDate && reportDate <= toDate);
|
|
return idSet.has(lid) && inDateRange && knownAt <= asOfMs;
|
|
});
|
|
|
|
return {
|
|
columns: allShorts.columns,
|
|
rows,
|
|
};
|
|
},
|
|
|
|
async universe(q: UniverseQuery): Promise<number[]> {
|
|
universeCalls.push(q);
|
|
if (options?.universeError !== undefined) {
|
|
throw options.universeError;
|
|
}
|
|
if (options?.universeResolver !== undefined) {
|
|
return options.universeResolver(q);
|
|
}
|
|
return [...(options?.universeIds ?? [])];
|
|
},
|
|
|
|
crossSection() {
|
|
throw new MarketDataStoreNotImplementedError('crossSection');
|
|
},
|
|
async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise<Table> {
|
|
fundamentalsCalls.push(q);
|
|
if (options?.fundamentalsError !== undefined) {
|
|
throw options.fundamentalsError;
|
|
}
|
|
if (options?.fundamentalsResolver !== undefined) {
|
|
return options.fundamentalsResolver(q);
|
|
}
|
|
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
|
|
},
|
|
events() {
|
|
throw new MarketDataStoreNotImplementedError('events');
|
|
},
|
|
macroAsOf() {
|
|
throw new MarketDataStoreNotImplementedError('macroAsOf');
|
|
},
|
|
fx() {
|
|
throw new MarketDataStoreNotImplementedError('fx');
|
|
},
|
|
};
|
|
|
|
return { barsCalls, shortsCalls, fundamentalsCalls, universeCalls, store };
|
|
}
|
|
|
|
async function callAnalyzeSignal(params: {
|
|
store: MarketDataStore;
|
|
ledger: TrialLedgerExecutor;
|
|
vaultCutoffTs: number;
|
|
principalId?: string;
|
|
args: Record<string, unknown>;
|
|
}): Promise<{
|
|
rawResponse: string;
|
|
isError: boolean;
|
|
text: string;
|
|
}> {
|
|
const tool = createAnalyzeSignalTool({
|
|
store: params.store,
|
|
ledger: params.ledger,
|
|
vaultContext: { vaultCutoffTs: params.vaultCutoffTs },
|
|
principalId: params.principalId ?? AGENT_PRINCIPAL,
|
|
});
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [tool],
|
|
});
|
|
|
|
const rawResponse = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'as-1',
|
|
method: 'tools/call',
|
|
params: {
|
|
name: 'analyze_signal',
|
|
arguments: params.args,
|
|
},
|
|
})
|
|
);
|
|
|
|
expect(rawResponse).not.toBeNull();
|
|
const parsed = JSON.parse(rawResponse as string) as {
|
|
result: {
|
|
isError?: boolean;
|
|
content: { type: string; text: string }[];
|
|
};
|
|
};
|
|
return {
|
|
rawResponse: rawResponse as string,
|
|
isError: parsed.result.isError === true,
|
|
text: parsed.result.content[0]?.text ?? '',
|
|
};
|
|
}
|
|
|
|
describe('MCP analyze_signal tool', () => {
|
|
test('tools/list advertises query_data and analyze_signal and omits server-controlled fields from analyze_signal schema', async () => {
|
|
const fixture = buildCeoShortsFixture({ preCutoffSessions: 20, postCutoffSessions: 5, listingCount: 6 });
|
|
const fakeStore = createFakeStore({ bars: fixture.bars, shortsTable: fixture.shortsTable });
|
|
const fakeLedger = createFakeTrialLedger();
|
|
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [
|
|
createQueryDataTool({
|
|
store: fakeStore.store,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
}),
|
|
createAnalyzeSignalTool({
|
|
store: fakeStore.store,
|
|
ledger: fakeLedger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'list-1',
|
|
method: 'tools/list',
|
|
})
|
|
);
|
|
|
|
const parsed = JSON.parse(raw as string) as {
|
|
result: {
|
|
tools: {
|
|
name: string;
|
|
description: string;
|
|
inputSchema: {
|
|
type: string;
|
|
properties: Record<string, { additionalProperties?: boolean; properties?: Record<string, unknown> }>;
|
|
required?: string[];
|
|
additionalProperties: boolean;
|
|
};
|
|
}[];
|
|
};
|
|
};
|
|
|
|
const names = parsed.result.tools.map(t => t.name);
|
|
expect(names).toEqual(['query_data', 'analyze_signal']);
|
|
|
|
const analyzeTool = parsed.result.tools.find(t => t.name === 'analyze_signal');
|
|
expect(analyzeTool).toBeDefined();
|
|
expect(analyzeTool?.inputSchema.type).toBe('object');
|
|
expect(analyzeTool?.inputSchema.additionalProperties).toBe(false);
|
|
expect(analyzeTool?.inputSchema.properties.signal?.additionalProperties).toBe(false);
|
|
|
|
const propKeys = Object.keys(analyzeTool?.inputSchema.properties ?? {});
|
|
expect(propKeys).toContain('listingIds');
|
|
expect(propKeys).toContain('universe');
|
|
expect(propKeys).toContain('from');
|
|
expect(propKeys).toContain('to');
|
|
expect(propKeys).toContain('signal');
|
|
expect(propKeys).toContain('horizonSessions');
|
|
expect(propKeys).toContain('universeMarket');
|
|
expect(propKeys).toContain('horizonBucket');
|
|
|
|
for (const forbidden of ['scope', 'vault_evaluation_only', 'principalId', 'vaultCutoffDate']) {
|
|
expect(propKeys).not.toContain(forbidden);
|
|
expect(analyzeTool?.inputSchema.required ?? []).not.toContain(forbidden);
|
|
}
|
|
});
|
|
|
|
test('executes seeded ceoShorts fixture with parity to direct analyzeSignal and writes exactly one trial row under injected principal', async () => {
|
|
const fixture = buildCeoShortsFixture();
|
|
const fakeStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
});
|
|
const mcpLedger = createFakeTrialLedger();
|
|
|
|
const from = fixture.allDates[0]!;
|
|
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
|
|
|
const res = await callAnalyzeSignal({
|
|
store: fakeStore.store,
|
|
ledger: mcpLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
principalId: AGENT_PRINCIPAL,
|
|
args: {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
campaignId: CAMPAIGN_UUID,
|
|
hypothesisId: HYPOTHESIS_UUID,
|
|
},
|
|
});
|
|
|
|
expect(res.isError).toBe(false);
|
|
const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload;
|
|
expect(payload.status).toBe('ok');
|
|
if (payload.status !== 'ok') {
|
|
return;
|
|
}
|
|
|
|
// Run direct research pipeline on the same pre-cutoff bars/shorts with a fresh isolated ledger
|
|
const directLedger = createFakeTrialLedger();
|
|
const preCutoffBars = fixture.bars.filter(b => b.ts < fixture.vaultCutoffTs);
|
|
const preCutoffShorts: Table = {
|
|
columns: fixture.shortsTable.columns,
|
|
rows: fixture.shortsTable.rows.filter(
|
|
r => (r.report_date as string) < fixture.vaultCutoffDate && (r.known_at as number) < fixture.vaultCutoffTs
|
|
),
|
|
};
|
|
const directSignals = shortsTableToSignalRows(preCutoffShorts, 'net_change');
|
|
const directBuilt = buildForwardReturnPanel({
|
|
bars: preCutoffBars,
|
|
signals: directSignals,
|
|
horizonSessions: 5,
|
|
vaultCutoffDate: fixture.vaultCutoffDate,
|
|
});
|
|
const directStudy = await analyzeSignal(directLedger.executor, {
|
|
principalId: AGENT_PRINCIPAL,
|
|
campaignId: CAMPAIGN_UUID,
|
|
hypothesisId: HYPOTHESIS_UUID,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
expression: {
|
|
expression: 'direct_reference',
|
|
params: { field: 'net_change', horizonSessions: 5 },
|
|
universe: fixture.listingIds,
|
|
horizon: '5d',
|
|
},
|
|
panel: directBuilt.panel,
|
|
vaultCutoffDate: fixture.vaultCutoffDate,
|
|
});
|
|
|
|
expect(directStudy.status).toBe('ok');
|
|
if (directStudy.status !== 'ok') {
|
|
return;
|
|
}
|
|
|
|
// Parity between MCP payload and direct research pipeline
|
|
expect(payload.scope).toBe('vault_fenced');
|
|
expect(payload.vaultCutoffTs).toBe(fixture.vaultCutoffTs);
|
|
expect(payload.vaultCutoffDate).toBe(fixture.vaultCutoffDate);
|
|
expect(payload.panelDiagnostics).toEqual(directBuilt.diagnostics);
|
|
expect(payload.analysis.rankIc).toEqual(directStudy.analysis.rankIc);
|
|
expect(payload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc);
|
|
expect(payload.analysis.quantiles.spreadSummary).toEqual(
|
|
directStudy.analysis.quantiles.spreadSummary
|
|
);
|
|
expect(payload.analysis.turnover.meanTopTurnover).toBe(
|
|
directStudy.analysis.turnover.meanTopTurnover
|
|
);
|
|
expect(payload.analysis.recency).toEqual(directStudy.analysis.recency);
|
|
expect(payload.analysis.diagnostics).toEqual(directStudy.analysis.diagnostics);
|
|
expect(payload.trial.sampleStart).toBe(directStudy.trial.sampleStart);
|
|
expect(payload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd);
|
|
expect(payload.trial.sampleEnd < fixture.vaultCutoffDate).toBe(true);
|
|
expect(payload.trial.nObs).toBe(directStudy.trial.nObs);
|
|
expect(payload.trial.expressionHash).toMatch(/^[0-9a-f]{64}$/);
|
|
expect(payload.deflatedSharpe).toEqual(directStudy.deflatedSharpe);
|
|
|
|
// Bounded series preview: >100 observations truncated to latest 100 while study & ledger keep full sample
|
|
expect(payload.analysis.ledgerSeries.series).toBe('rank_ic');
|
|
expect(payload.analysis.ledgerSeries.totalCount).toBe(directStudy.trial.nObs);
|
|
expect(payload.analysis.ledgerSeries.totalCount).toBeGreaterThan(ANALYZE_SIGNAL_MAX_SERIES_POINTS);
|
|
expect(payload.analysis.ledgerSeries.truncated).toBe(true);
|
|
expect(payload.analysis.ledgerSeries.points).toHaveLength(ANALYZE_SIGNAL_MAX_SERIES_POINTS);
|
|
const lastPoint = payload.analysis.ledgerSeries.points[ANALYZE_SIGNAL_MAX_SERIES_POINTS - 1];
|
|
expect(lastPoint?.date).toBe(directStudy.trial.sampleEnd);
|
|
|
|
// Exactly one trial_ledger row written with injected principalId and full daily_series
|
|
expect(mcpLedger.rows).toHaveLength(1);
|
|
const stored = mcpLedger.rows[0]!;
|
|
expect(stored.stage).toBe('signal_ic');
|
|
expect(stored.principal_id).toBe(AGENT_PRINCIPAL);
|
|
expect(stored.campaign_id).toBe(CAMPAIGN_UUID);
|
|
expect(stored.hypothesis_id).toBe(HYPOTHESIS_UUID);
|
|
expect(stored.universe_market).toBe('CA_EQ');
|
|
expect(stored.horizon_bucket).toBe('swing_1_10d');
|
|
expect(stored.n_obs).toBe(directStudy.trial.nObs);
|
|
expect(stored.daily_series).toHaveLength(directStudy.trial.nObs);
|
|
});
|
|
|
|
test('identical requests and reordered/duplicate listingIds produce the same expressionHash; changing field, horizon, or ledgerSeries changes it', async () => {
|
|
const fixture = buildCeoShortsFixture();
|
|
const from = fixture.allDates[0]!;
|
|
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
|
|
|
async function runWithArgs(args: Record<string, unknown>) {
|
|
const store = createFakeStore({ bars: fixture.bars, shortsTable: fixture.shortsTable });
|
|
const ledger = createFakeTrialLedger();
|
|
const res = await callAnalyzeSignal({
|
|
store: store.store,
|
|
ledger: ledger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args,
|
|
});
|
|
expect(res.isError).toBe(false);
|
|
const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload;
|
|
expect(payload.status).toBe('ok');
|
|
if (payload.status !== 'ok') {
|
|
throw new Error('Expected ok status');
|
|
}
|
|
return { payload, ledger };
|
|
}
|
|
|
|
const baseArgs = {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const run1 = await runWithArgs(baseArgs);
|
|
const run2 = await runWithArgs(baseArgs);
|
|
expect(run1.payload.trial.expressionHash).toBe(run2.payload.trial.expressionHash);
|
|
|
|
// Reordered and duplicated listingIds canonicalize to the exact same expressionHash
|
|
const reorderedIds = [...fixture.listingIds].reverse();
|
|
reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[3]!);
|
|
const runReordered = await runWithArgs({ ...baseArgs, listingIds: reorderedIds });
|
|
expect(runReordered.payload.trial.expressionHash).toBe(run1.payload.trial.expressionHash);
|
|
|
|
// Different signal.field -> different expressionHash
|
|
const runOtherField = await runWithArgs({
|
|
...baseArgs,
|
|
signal: { source: 'shorts', field: 'pct_float' },
|
|
});
|
|
expect(runOtherField.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash);
|
|
|
|
// Different horizonSessions -> different expressionHash (including position_10d_plus bucket for 11d)
|
|
const runOtherHorizon = await runWithArgs({
|
|
...baseArgs,
|
|
horizonSessions: 11,
|
|
horizonBucket: 'position_10d_plus',
|
|
});
|
|
expect(runOtherHorizon.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash);
|
|
expect(runOtherHorizon.ledger.rows[0]?.horizon_bucket).toBe('position_10d_plus');
|
|
|
|
// Equivalent date/timestamp/offset forms canonicalize to identical effective microsecond bounds & expressionHash
|
|
const midDate = fixture.allDates[120]!;
|
|
const runDateForm = await runWithArgs({
|
|
...baseArgs,
|
|
from,
|
|
to: midDate,
|
|
asOf: midDate,
|
|
});
|
|
const runIsoMicrosForm = await runWithArgs({
|
|
...baseArgs,
|
|
from: `${from}T00:00:00.000000Z`,
|
|
to: `${midDate}T23:59:59.999999Z`,
|
|
asOf: `${midDate}T23:59:59.999999Z`,
|
|
});
|
|
const runOffsetForm = await runWithArgs({
|
|
...baseArgs,
|
|
from: '2022-08-31T19:00:00.000000-05:00',
|
|
to: `${midDate}T18:59:59.999999-05:00`,
|
|
asOf: `${midDate}T18:59:59.999999-05:00`,
|
|
});
|
|
expect(runDateForm.payload.effectiveFrom).toBe(`${from}T00:00:00.000Z`);
|
|
expect(runDateForm.payload.effectiveTo).toBe(`${midDate}T23:59:59.999999Z`);
|
|
expect(runDateForm.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999999Z`);
|
|
expect(runIsoMicrosForm.payload.effectiveFrom).toBe(runDateForm.payload.effectiveFrom);
|
|
expect(runIsoMicrosForm.payload.effectiveTo).toBe(runDateForm.payload.effectiveTo);
|
|
expect(runIsoMicrosForm.payload.effectiveAsOf).toBe(runDateForm.payload.effectiveAsOf);
|
|
expect(runIsoMicrosForm.payload.trial.expressionHash).toBe(
|
|
runDateForm.payload.trial.expressionHash
|
|
);
|
|
expect(runOffsetForm.payload.trial.expressionHash).toBe(
|
|
runDateForm.payload.trial.expressionHash
|
|
);
|
|
|
|
// Distinct sub-millisecond effective bounds produce different expressionHash even with identical sampleStart/sampleEnd
|
|
const runAsOfZeroMicros = await runWithArgs({
|
|
...baseArgs,
|
|
from,
|
|
to: midDate,
|
|
asOf: `${midDate}T23:59:59.999000Z`,
|
|
});
|
|
expect(runAsOfZeroMicros.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999Z`);
|
|
expect(runAsOfZeroMicros.payload.trial.sampleStart).toBe(runDateForm.payload.trial.sampleStart);
|
|
expect(runAsOfZeroMicros.payload.trial.sampleEnd).toBe(runDateForm.payload.trial.sampleEnd);
|
|
expect(runAsOfZeroMicros.payload.trial.expressionHash).not.toBe(
|
|
runDateForm.payload.trial.expressionHash
|
|
);
|
|
|
|
const runToZeroMicros = await runWithArgs({
|
|
...baseArgs,
|
|
from,
|
|
to: `${midDate}T23:59:59.999000Z`,
|
|
asOf: midDate,
|
|
});
|
|
expect(runToZeroMicros.payload.effectiveTo).toBe(`${midDate}T23:59:59.999Z`);
|
|
expect(runToZeroMicros.payload.trial.expressionHash).not.toBe(
|
|
runDateForm.payload.trial.expressionHash
|
|
);
|
|
|
|
const runFromOneMicro = await runWithArgs({
|
|
...baseArgs,
|
|
from: `${from}T00:00:00.000001Z`,
|
|
to: midDate,
|
|
asOf: midDate,
|
|
});
|
|
expect(runFromOneMicro.payload.effectiveFrom).toBe(`${from}T00:00:00.000001Z`);
|
|
expect(runFromOneMicro.payload.trial.expressionHash).not.toBe(
|
|
runDateForm.payload.trial.expressionHash
|
|
);
|
|
|
|
// quantile_spread ledgerSeries works, truncates preview to 100 while preserving full count, and hashes distinctly
|
|
const runSpread = await runWithArgs({ ...baseArgs, ledgerSeries: 'quantile_spread' });
|
|
expect(runSpread.payload.analysis.ledgerSeries.series).toBe('quantile_spread');
|
|
expect(runSpread.payload.analysis.ledgerSeries.totalCount).toBe(runSpread.payload.trial.nObs);
|
|
expect(runSpread.payload.analysis.ledgerSeries.truncated).toBe(true);
|
|
expect(runSpread.payload.analysis.ledgerSeries.points).toHaveLength(
|
|
ANALYZE_SIGNAL_MAX_SERIES_POINTS
|
|
);
|
|
expect(runSpread.ledger.rows[0]?.daily_series).toHaveLength(runSpread.payload.trial.nObs);
|
|
expect(runSpread.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash);
|
|
});
|
|
|
|
test('clamps to/asOf strictly below midnight and intraday Vault cutoffs and blocks cutoff-day leakage from a leaky store', async () => {
|
|
const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false });
|
|
const poisonedFixture = buildCeoShortsFixture({ poisonPostCutoff: true });
|
|
const from = cleanFixture.allDates[0]!;
|
|
const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!;
|
|
const horizonSessions = 5;
|
|
|
|
// 1. Clamping test with to and asOf after Vault cutoff (midnight cutoff)
|
|
const clampLedger = createFakeTrialLedger();
|
|
const clampStore = createFakeStore({
|
|
bars: cleanFixture.bars,
|
|
shortsTable: cleanFixture.shortsTable,
|
|
});
|
|
const clampRes = await callAnalyzeSignal({
|
|
store: clampStore.store,
|
|
ledger: clampLedger.executor,
|
|
vaultCutoffTs: cleanFixture.vaultCutoffTs,
|
|
args: {
|
|
listingIds: cleanFixture.listingIds,
|
|
from,
|
|
to: postCutoffDate,
|
|
asOf: postCutoffDate,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
|
|
expect(clampRes.isError).toBe(false);
|
|
const clampPayload = JSON.parse(clampRes.text) as AnalyzeSignalResultPayload;
|
|
expect(clampPayload.status).toBe('ok');
|
|
expect(clampPayload.clampedTo).toBe(true);
|
|
expect(clampPayload.clampedAsOf).toBe(true);
|
|
expect(clampPayload.toMs).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
expect(clampPayload.asOfMs).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
|
|
// Store received fenced to and asOf strictly below vaultCutoffTs
|
|
expect(clampStore.barsCalls).toHaveLength(1);
|
|
expect(clampStore.barsCalls[0]?.scope).toBe('vault_fenced');
|
|
expect(Date.parse(clampStore.barsCalls[0]?.to ?? '')).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
expect(Date.parse(clampStore.barsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
expect(clampStore.shortsCalls).toHaveLength(1);
|
|
expect(Date.parse(clampStore.shortsCalls[0]?.to ?? '')).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
expect(Date.parse(clampStore.shortsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
if (clampPayload.status === 'ok') {
|
|
expect(clampPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true);
|
|
const endIdx = cleanFixture.allDates.indexOf(clampPayload.trial.sampleEnd);
|
|
const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!;
|
|
expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true);
|
|
}
|
|
|
|
// 2. Intraday Vault cutoff (12:00 UTC on vaultCutoffDate) with asOf beyond cutoff and leaky store
|
|
// injecting rows on vaultCutoffDate before cutoff, at exact cutoff timestamp, and after cutoff.
|
|
const intradayCutoffTs = makeUtcMs(cleanFixture.vaultCutoffDate, 12);
|
|
const cleanPreCutoffBars = cleanFixture.bars.filter(
|
|
b => new Date(b.ts).toISOString().slice(0, 10) < cleanFixture.vaultCutoffDate
|
|
);
|
|
const cleanPreCutoffShorts: Table = {
|
|
columns: cleanFixture.shortsTable.columns,
|
|
rows: cleanFixture.shortsTable.rows.filter(
|
|
r =>
|
|
(r.report_date as string) < cleanFixture.vaultCutoffDate &&
|
|
(r.known_at as number) < intradayCutoffTs
|
|
),
|
|
};
|
|
const cleanIntradayStore = createFakeStore({
|
|
bars: cleanPreCutoffBars,
|
|
shortsTable: cleanPreCutoffShorts,
|
|
leaky: false,
|
|
});
|
|
const leakyIntradayStore = createFakeStore({
|
|
bars: [
|
|
...poisonedFixture.bars,
|
|
// Cutoff-day bars BEFORE intradayCutoffTs (10:00 UTC) for every listing
|
|
...poisonedFixture.listingIds.map(listingId => ({
|
|
listingId,
|
|
ts: makeUtcMs(poisonedFixture.vaultCutoffDate, 10),
|
|
open: 888_888,
|
|
high: 888_888,
|
|
low: 888_888,
|
|
close: 888_888,
|
|
volume: 100,
|
|
vwap: 888_888,
|
|
knownAt: makeUtcMs(poisonedFixture.vaultCutoffDate, 10),
|
|
})),
|
|
// Bar at EXACT intradayCutoffTs (12:00 UTC)
|
|
{
|
|
listingId: poisonedFixture.listingIds[0]!,
|
|
ts: intradayCutoffTs,
|
|
open: 777_777,
|
|
high: 777_777,
|
|
low: 777_777,
|
|
close: 777_777,
|
|
volume: 100,
|
|
vwap: 777_777,
|
|
knownAt: intradayCutoffTs,
|
|
},
|
|
],
|
|
shortsTable: {
|
|
columns: poisonedFixture.shortsTable.columns,
|
|
rows: [
|
|
...poisonedFixture.shortsTable.rows,
|
|
// Shorts row on vaultCutoffDate with known_at before intradayCutoffTs
|
|
{
|
|
listing_id: poisonedFixture.listingIds[0]!,
|
|
report_date: poisonedFixture.vaultCutoffDate,
|
|
known_at: makeUtcMs(poisonedFixture.vaultCutoffDate, 9),
|
|
shares_short: 9_999_999,
|
|
net_change: 9_999_999,
|
|
pct_float: 0.99,
|
|
source: 'ceoShorts',
|
|
},
|
|
// Shorts row with report_date before cutoff but known_at at exact intradayCutoffTs
|
|
{
|
|
listing_id: poisonedFixture.listingIds[1]!,
|
|
report_date: cleanFixture.allDates[100]!,
|
|
known_at: intradayCutoffTs,
|
|
shares_short: 8_888_888,
|
|
net_change: 8_888_888,
|
|
pct_float: 0.88,
|
|
source: 'ceoShorts',
|
|
},
|
|
],
|
|
},
|
|
leaky: true,
|
|
});
|
|
|
|
const cleanIntradayLedger = createFakeTrialLedger();
|
|
const leakyIntradayLedger = createFakeTrialLedger();
|
|
const intradayArgs = {
|
|
listingIds: cleanFixture.listingIds,
|
|
from,
|
|
to: postCutoffDate,
|
|
asOf: postCutoffDate,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const cleanIntradayRes = await callAnalyzeSignal({
|
|
store: cleanIntradayStore.store,
|
|
ledger: cleanIntradayLedger.executor,
|
|
vaultCutoffTs: intradayCutoffTs,
|
|
args: intradayArgs,
|
|
});
|
|
const leakyIntradayRes = await callAnalyzeSignal({
|
|
store: leakyIntradayStore.store,
|
|
ledger: leakyIntradayLedger.executor,
|
|
vaultCutoffTs: intradayCutoffTs,
|
|
args: intradayArgs,
|
|
});
|
|
|
|
expect(cleanIntradayRes.isError).toBe(false);
|
|
expect(leakyIntradayRes.isError).toBe(false);
|
|
expect(leakyIntradayRes.text).toBe(cleanIntradayRes.text);
|
|
expect(leakyIntradayLedger.rows).toEqual(cleanIntradayLedger.rows);
|
|
|
|
const intradayPayload = JSON.parse(leakyIntradayRes.text) as AnalyzeSignalResultPayload;
|
|
expect(intradayPayload.status).toBe('ok');
|
|
expect(intradayPayload.clampedTo).toBe(true);
|
|
expect(intradayPayload.clampedAsOf).toBe(true);
|
|
expect(intradayPayload.toMs).toBe(intradayCutoffTs - 1);
|
|
expect(intradayPayload.asOfMs).toBe(intradayCutoffTs - 1);
|
|
if (intradayPayload.status === 'ok') {
|
|
expect(intradayPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true);
|
|
const endIdx = cleanFixture.allDates.indexOf(intradayPayload.trial.sampleEnd);
|
|
const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!;
|
|
expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true);
|
|
}
|
|
});
|
|
|
|
test('earlier explicit asOf excludes bars with ts > asOf or knownAt > asOf independently from a leaky store and matches clean replay', async () => {
|
|
const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false });
|
|
const from = cleanFixture.allDates[0]!;
|
|
const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!;
|
|
const horizonSessions = 5;
|
|
|
|
// Set asOf to noon UTC on session 100 while `to` extends past cutoff
|
|
const asOfSessionIdx = 100;
|
|
const asOfDate = cleanFixture.allDates[asOfSessionIdx]!;
|
|
const asOfIso = `${asOfDate}T12:00:00.000Z`;
|
|
const asOfMs = makeUtcMs(asOfDate, 12);
|
|
|
|
// Clean replay store filters strictly by ts <= asOfMs && knownAt <= asOfMs
|
|
const cleanStore = createFakeStore({
|
|
bars: cleanFixture.bars,
|
|
shortsTable: cleanFixture.shortsTable,
|
|
leaky: false,
|
|
});
|
|
|
|
// Leaky store injects two independent bar leaks + a delayed shorts row:
|
|
// (a) Closing bars on `asOfDate` stamped at 21:00 UTC (> noon asOf) with knownAt at 00:00 UTC (<= noon asOf) and poisoned close
|
|
// (b) Delayed bars on session 95 (ts <= noon asOf) with knownAt at 15:00 UTC on `asOfDate` (> noon asOf) and poisoned close
|
|
const delayedBarDate = cleanFixture.allDates[95]!;
|
|
const leakyBars: BarRecord[] = cleanFixture.bars.map(bar => {
|
|
if (bar.ts === makeUtcMs(asOfDate, 21)) {
|
|
return {
|
|
...bar,
|
|
open: 666_666,
|
|
high: 666_666,
|
|
low: 666_666,
|
|
close: 666_666,
|
|
vwap: 666_666,
|
|
knownAt: makeUtcMs(asOfDate, 0), // earlier than noon asOf, while ts (21:00 UTC) > noon asOf
|
|
};
|
|
}
|
|
return bar;
|
|
});
|
|
// Also inject a bar with ts <= asOfMs but knownAt > asOfMs for listing 0 on session 95 (replace clean bar? No, add extra listing or poisoned bar on a date not in clean? Better: inject on a date after clean or with a listing that has a delayed knownAt!)
|
|
// Specifically: take a clean bar on session 95 for listing 0 and verify a delayed-knownAt poison bar on session 100-1 (where ts <= asOfMs and knownAt > asOfMs) is dropped.
|
|
// Even stronger: add a synthetic bar on `delayedBarDate` at 10:00 UTC (ts <= asOfMs) with knownAt = 15:00 UTC on `asOfDate` (> asOfMs) and poisoned close 555_555.
|
|
// If knownAt filter regresses, buildForwardReturnPanel will throw duplicate_bar (conflicting close on delayedBarDate)!
|
|
leakyBars.push({
|
|
listingId: cleanFixture.listingIds[0]!,
|
|
ts: makeUtcMs(delayedBarDate, 10),
|
|
open: 555_555,
|
|
high: 555_555,
|
|
low: 555_555,
|
|
close: 555_555,
|
|
volume: 100,
|
|
vwap: 555_555,
|
|
knownAt: makeUtcMs(asOfDate, 15), // > noon asOf, while ts <= noon asOf
|
|
});
|
|
|
|
const leakyStore = createFakeStore({
|
|
bars: leakyBars,
|
|
shortsTable: {
|
|
columns: cleanFixture.shortsTable.columns,
|
|
rows: [
|
|
...cleanFixture.shortsTable.rows,
|
|
{
|
|
listing_id: cleanFixture.listingIds[1]!,
|
|
report_date: cleanFixture.allDates[50]!,
|
|
known_at: makeUtcMs(asOfDate, 15), // > noon asOf
|
|
shares_short: 7_777_777,
|
|
net_change: 7_777_777,
|
|
pct_float: 0.77,
|
|
source: 'ceoShorts',
|
|
},
|
|
],
|
|
},
|
|
leaky: true,
|
|
});
|
|
|
|
const cleanLedger = createFakeTrialLedger();
|
|
const leakyLedger = createFakeTrialLedger();
|
|
const args = {
|
|
listingIds: cleanFixture.listingIds,
|
|
from,
|
|
to: postCutoffDate,
|
|
asOf: asOfIso,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const cleanRes = await callAnalyzeSignal({
|
|
store: cleanStore.store,
|
|
ledger: cleanLedger.executor,
|
|
vaultCutoffTs: cleanFixture.vaultCutoffTs,
|
|
args,
|
|
});
|
|
const leakyRes = await callAnalyzeSignal({
|
|
store: leakyStore.store,
|
|
ledger: leakyLedger.executor,
|
|
vaultCutoffTs: cleanFixture.vaultCutoffTs,
|
|
args,
|
|
});
|
|
|
|
expect(cleanRes.isError).toBe(false);
|
|
expect(leakyRes.isError).toBe(false);
|
|
expect(leakyRes.text).toBe(cleanRes.text);
|
|
expect(leakyLedger.rows).toEqual(cleanLedger.rows);
|
|
|
|
const payload = JSON.parse(leakyRes.text) as AnalyzeSignalResultPayload;
|
|
expect(payload.status).toBe('ok');
|
|
expect(payload.clampedAsOf).toBe(false);
|
|
expect(payload.asOfMs).toBe(asOfMs);
|
|
if (payload.status === 'ok') {
|
|
const endIdx = cleanFixture.allDates.indexOf(payload.trial.sampleEnd);
|
|
const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!;
|
|
// Closing bar on asOfDate (21:00 UTC) was excluded by ts > asOfMs, so last forward endpoint must precede asOfDate
|
|
expect(lastForwardEndpoint < asOfDate).toBe(true);
|
|
}
|
|
});
|
|
|
|
test('request wholly inside Vault holdout returns fixed VaultHoldoutFenceError with zero store and ledger calls', async () => {
|
|
const fixture = buildCeoShortsFixture();
|
|
const fakeStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
});
|
|
const fakeLedger = createFakeTrialLedger();
|
|
|
|
const res = await callAnalyzeSignal({
|
|
store: fakeStore.store,
|
|
ledger: fakeLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: {
|
|
listingIds: fixture.listingIds,
|
|
from: fixture.vaultCutoffDate,
|
|
to: fixture.allDates[fixture.allDates.length - 1]!,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
|
|
expect(res.isError).toBe(true);
|
|
expect(res.text).toBe(
|
|
'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.'
|
|
);
|
|
expect(fakeStore.barsCalls).toHaveLength(0);
|
|
expect(fakeStore.shortsCalls).toHaveLength(0);
|
|
expect(fakeStore.universeCalls).toHaveLength(0);
|
|
expect(fakeLedger.insertCalls).toBe(0);
|
|
expect(fakeLedger.rows).toHaveLength(0);
|
|
});
|
|
|
|
test('named universe resolves strictly before study start and respects earlier/intraday asOf', async () => {
|
|
const fixture = buildCeoShortsFixture();
|
|
const from = fixture.allDates[0]!; // 2022-09-01
|
|
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
|
|
|
const fakeStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
universeIds: [...fixture.listingIds].reverse(),
|
|
});
|
|
const fakeLedger = createFakeTrialLedger();
|
|
|
|
const res = await callAnalyzeSignal({
|
|
store: fakeStore.store,
|
|
ledger: fakeLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: {
|
|
universe: 'CA_EQ',
|
|
from,
|
|
to,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
|
|
expect(res.isError).toBe(false);
|
|
// Study starts 2022-09-01 -> universe must be resolved on 2022-08-31 (strictly before study start)
|
|
expect(fakeStore.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-31' }]);
|
|
// Sorted listingIds passed to bars and shortsAsOf
|
|
expect(fakeStore.barsCalls[0]?.listingIds).toEqual(fixture.listingIds);
|
|
expect(fakeStore.shortsCalls[0]?.listingIds).toEqual(fixture.listingIds);
|
|
|
|
// Earlier intraday asOf (2022-08-15T12:00:00Z) -> universe resolved on completed UTC date 2022-08-14
|
|
const earlyStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
universeIds: fixture.listingIds,
|
|
});
|
|
const earlyLedger = createFakeTrialLedger();
|
|
await callAnalyzeSignal({
|
|
store: earlyStore.store,
|
|
ledger: earlyLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: {
|
|
universe: 'CA_EQ',
|
|
from,
|
|
to,
|
|
asOf: '2022-08-15T12:00:00Z',
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(earlyStore.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-14' }]);
|
|
});
|
|
|
|
test('insufficient-data cases (empty universe, empty panel, undersized panel, zero-variance series) return reason with zero ledger writes', async () => {
|
|
const cutoffDate = '2025-03-31';
|
|
const cutoffTs = makeUtcMs(cutoffDate, 0);
|
|
|
|
// 1. Empty resolved universe -> zero bars/shorts calls, zero ledger rows
|
|
const emptyUniStore = createFakeStore({ universeIds: [] });
|
|
const emptyUniLedger = createFakeTrialLedger();
|
|
const emptyUniRes = await callAnalyzeSignal({
|
|
store: emptyUniStore.store,
|
|
ledger: emptyUniLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args: {
|
|
universe: 'CA_EQ',
|
|
from: '2025-01-01',
|
|
to: '2025-03-20',
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(emptyUniRes.isError).toBe(false);
|
|
const emptyUniPayload = JSON.parse(emptyUniRes.text) as AnalyzeSignalResultPayload;
|
|
expect(emptyUniPayload.status).toBe('insufficient_data');
|
|
if (emptyUniPayload.status === 'insufficient_data') {
|
|
expect(emptyUniPayload.reason).toBe('too_few_observations');
|
|
}
|
|
expect(emptyUniStore.barsCalls).toHaveLength(0);
|
|
expect(emptyUniStore.shortsCalls).toHaveLength(0);
|
|
expect(emptyUniLedger.rows).toHaveLength(0);
|
|
|
|
// 2. Empty panel (bars exist but no shorts signals)
|
|
const dates = makeBusinessDates('2025-01-02', 6);
|
|
const barsForSixDays: BarRecord[] = [];
|
|
for (let d = 0; d < dates.length; d += 1) {
|
|
const ts = makeUtcMs(dates[d]!, 21);
|
|
for (let id = 1; id <= 6; id += 1) {
|
|
barsForSixDays.push({
|
|
listingId: id,
|
|
ts,
|
|
open: 100 + d,
|
|
high: 101 + d,
|
|
low: 99 + d,
|
|
close: 100 + d + id * 0.1,
|
|
volume: 1000,
|
|
vwap: 100 + d,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
}
|
|
const emptyPanelStore = createFakeStore({
|
|
bars: barsForSixDays,
|
|
shortsTable: { columns: SHORTS_COLUMNS, rows: [] },
|
|
});
|
|
const emptyPanelLedger = createFakeTrialLedger();
|
|
const emptyPanelRes = await callAnalyzeSignal({
|
|
store: emptyPanelStore.store,
|
|
ledger: emptyPanelLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args: {
|
|
listingIds: [1, 2, 3, 4, 5, 6],
|
|
from: dates[0]!,
|
|
to: dates[dates.length - 1]!,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(emptyPanelRes.isError).toBe(false);
|
|
const emptyPanelPayload = JSON.parse(emptyPanelRes.text) as AnalyzeSignalResultPayload;
|
|
expect(emptyPanelPayload.status).toBe('insufficient_data');
|
|
if (emptyPanelPayload.status === 'insufficient_data') {
|
|
expect(emptyPanelPayload.reason).toBe('too_few_observations');
|
|
}
|
|
expect(emptyPanelLedger.rows).toHaveLength(0);
|
|
|
|
// 3. Undersized non-empty panel (only 1 date with forward return -> too_few_observations)
|
|
const twoDayBars = barsForSixDays.filter(b => b.ts <= makeUtcMs(dates[1]!, 21));
|
|
const singleSignalRows: TableRow[] = [1, 2, 3, 4, 5, 6].map(id => ({
|
|
listing_id: id,
|
|
report_date: dates[0]!,
|
|
known_at: makeUtcMs(dates[0]!, 10),
|
|
shares_short: 1000 * id,
|
|
net_change: 100 * id,
|
|
pct_float: 0.01 * id,
|
|
source: 'ceoShorts',
|
|
}));
|
|
const undersizedStore = createFakeStore({
|
|
bars: twoDayBars,
|
|
shortsTable: { columns: SHORTS_COLUMNS, rows: singleSignalRows },
|
|
});
|
|
const undersizedLedger = createFakeTrialLedger();
|
|
const undersizedRes = await callAnalyzeSignal({
|
|
store: undersizedStore.store,
|
|
ledger: undersizedLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args: {
|
|
listingIds: [1, 2, 3, 4, 5, 6],
|
|
from: dates[0]!,
|
|
to: dates[1]!,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(undersizedRes.isError).toBe(false);
|
|
const undersizedPayload = JSON.parse(undersizedRes.text) as AnalyzeSignalResultPayload;
|
|
expect(undersizedPayload.status).toBe('insufficient_data');
|
|
if (undersizedPayload.status === 'insufficient_data') {
|
|
expect(undersizedPayload.reason).toBe('too_few_observations');
|
|
}
|
|
expect(undersizedLedger.rows).toHaveLength(0);
|
|
|
|
// 4. Zero-variance rank_ic series (identical strictly monotone rank ordering every day -> rank_ic = 1.0 on every date)
|
|
const monotoneBars: BarRecord[] = [];
|
|
for (let d = 0; d < dates.length; d += 1) {
|
|
const ts = makeUtcMs(dates[d]!, 21);
|
|
for (let id = 1; id <= 6; id += 1) {
|
|
const close = 100 * Math.pow(1 + 0.01 * id, d);
|
|
monotoneBars.push({
|
|
listingId: id,
|
|
ts,
|
|
open: close,
|
|
high: close,
|
|
low: close,
|
|
close,
|
|
volume: 1000,
|
|
vwap: close,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
}
|
|
const zeroVarStore = createFakeStore({
|
|
bars: monotoneBars,
|
|
shortsTable: { columns: SHORTS_COLUMNS, rows: singleSignalRows },
|
|
});
|
|
const zeroVarLedger = createFakeTrialLedger();
|
|
const zeroVarRes = await callAnalyzeSignal({
|
|
store: zeroVarStore.store,
|
|
ledger: zeroVarLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args: {
|
|
listingIds: [1, 2, 3, 4, 5, 6],
|
|
from: dates[0]!,
|
|
to: dates[dates.length - 1]!,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(zeroVarRes.isError).toBe(false);
|
|
const zeroVarPayload = JSON.parse(zeroVarRes.text) as AnalyzeSignalResultPayload;
|
|
expect(zeroVarPayload.status).toBe('insufficient_data');
|
|
if (zeroVarPayload.status === 'insufficient_data') {
|
|
expect(zeroVarPayload.reason).toBe('zero_variance_series');
|
|
}
|
|
expect(zeroVarLedger.rows).toHaveLength(0);
|
|
});
|
|
|
|
test('strict schema rejects forbidden keys, unknown keys, bad selectors, invalid dates/UUIDs, INT32/limit/horizon violations with zero store or ledger calls', async () => {
|
|
const cutoffTs = makeUtcMs('2025-03-31', 0);
|
|
const validBase = {
|
|
listingIds: [101, 102],
|
|
from: '2025-01-02',
|
|
to: '2025-03-20',
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const invalidCases: readonly [string, Record<string, unknown>][] = [
|
|
['scope vault_evaluation_only', { ...validBase, scope: 'vault_evaluation_only' }],
|
|
['scope vault_fenced', { ...validBase, scope: 'vault_fenced' }],
|
|
['vault_evaluation_only flag', { ...validBase, vault_evaluation_only: true }],
|
|
['principalId override', { ...validBase, principalId: 'operator' }],
|
|
['vaultCutoffDate override', { ...validBase, vaultCutoffDate: '2026-01-01' }],
|
|
['unknown top-level key', { ...validBase, extraFlag: true }],
|
|
[
|
|
'unknown nested signal key',
|
|
{ ...validBase, signal: { source: 'shorts', field: 'net_change', extra: 1 } },
|
|
],
|
|
['both listingIds and universe', { ...validBase, universe: 'CA_EQ' }],
|
|
[
|
|
'neither listingIds nor universe',
|
|
{
|
|
from: validBase.from,
|
|
to: validBase.to,
|
|
signal: validBase.signal,
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
],
|
|
['unknown signal.source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }],
|
|
['unknown signal.field', { ...validBase, signal: { source: 'shorts', field: 'unknown_col' } }],
|
|
['invalid calendar date from', { ...validBase, from: '2025-02-30' }],
|
|
['invalid string date to', { ...validBase, to: 'not-a-date' }],
|
|
['naive timestamp without offset in asOf', { ...validBase, asOf: '2025-02-01T12:00:00' }],
|
|
['invalid campaignId UUID', { ...validBase, campaignId: 'not-a-uuid' }],
|
|
['invalid hypothesisId UUID', { ...validBase, hypothesisId: '12345' }],
|
|
['INT32 overflow listingId', { ...validBase, listingIds: [2_147_483_648] }],
|
|
['INT32 underflow listingId', { ...validBase, listingIds: [-2_147_483_649] }],
|
|
['non-integer listingId', { ...validBase, listingIds: [101.5] }],
|
|
['empty listingIds', { ...validBase, listingIds: [] }],
|
|
[
|
|
'more than 500 explicit listingIds',
|
|
{
|
|
...validBase,
|
|
listingIds: Array.from({ length: ANALYZE_SIGNAL_MAX_LISTING_IDS + 1 }, (_, i) => i + 1),
|
|
},
|
|
],
|
|
['horizonSessions 0', { ...validBase, horizonSessions: 0 }],
|
|
['horizonSessions negative', { ...validBase, horizonSessions: -3 }],
|
|
[
|
|
'horizonSessions above max',
|
|
{ ...validBase, horizonSessions: ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS + 1 },
|
|
],
|
|
['horizonSessions float', { ...validBase, horizonSessions: 2.5 }],
|
|
['negative maxSignalAgeSessions', { ...validBase, maxSignalAgeSessions: -1 }],
|
|
['mismatched horizonBucket intraday for 5d daily horizon', { ...validBase, horizonSessions: 5, horizonBucket: 'intraday' }],
|
|
[
|
|
'mismatched horizonBucket position_10d_plus for 5d daily horizon',
|
|
{ ...validBase, horizonSessions: 5, horizonBucket: 'position_10d_plus' },
|
|
],
|
|
[
|
|
'mismatched horizonBucket swing_1_10d for 11d daily horizon',
|
|
{ ...validBase, horizonSessions: 11, horizonBucket: 'swing_1_10d' },
|
|
],
|
|
[
|
|
'mismatched horizonBucket intraday for 15d daily horizon',
|
|
{ ...validBase, horizonSessions: 15, horizonBucket: 'intraday' },
|
|
],
|
|
[
|
|
'named universe CA_EQ with mismatched universeMarket FX',
|
|
{
|
|
from: validBase.from,
|
|
to: validBase.to,
|
|
signal: validBase.signal,
|
|
horizonSessions: 5,
|
|
universe: 'CA_EQ',
|
|
universeMarket: 'FX',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
],
|
|
[
|
|
'named universe CA_EQ with mismatched universeMarket US_EQ',
|
|
{
|
|
from: validBase.from,
|
|
to: validBase.to,
|
|
signal: validBase.signal,
|
|
horizonSessions: 5,
|
|
universe: 'CA_EQ',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
],
|
|
[
|
|
'named universe US_CA_EQ with mismatched universeMarket US_EQ',
|
|
{
|
|
from: validBase.from,
|
|
to: validBase.to,
|
|
signal: validBase.signal,
|
|
horizonSessions: 5,
|
|
universe: 'US_CA_EQ',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
],
|
|
['shorts study with FX universeMarket and listingIds', { ...validBase, universeMarket: 'FX' }],
|
|
];
|
|
|
|
for (const [_label, args] of invalidCases) {
|
|
const fakeStore = createFakeStore();
|
|
const fakeLedger = createFakeTrialLedger();
|
|
const res = await callAnalyzeSignal({
|
|
store: fakeStore.store,
|
|
ledger: fakeLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args,
|
|
});
|
|
|
|
expect(res.isError).toBe(true);
|
|
expect(res.text).toContain('Invalid arguments for tool "analyze_signal":');
|
|
expect(fakeStore.barsCalls).toHaveLength(0);
|
|
expect(fakeStore.shortsCalls).toHaveLength(0);
|
|
expect(fakeStore.universeCalls).toHaveLength(0);
|
|
expect(fakeLedger.insertCalls).toBe(0);
|
|
}
|
|
|
|
// Raw JSON own __proto__ key rejected with zero store or ledger calls
|
|
const protoStore = createFakeStore();
|
|
const protoLedger = createFakeTrialLedger();
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [
|
|
createAnalyzeSignalTool({
|
|
store: protoStore.store,
|
|
ledger: protoLedger.executor,
|
|
vaultContext: { vaultCutoffTs: cutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
}),
|
|
],
|
|
});
|
|
const rawProto =
|
|
'{"jsonrpc":"2.0","id":"proto-1","method":"tools/call","params":{"name":"analyze_signal","arguments":{"listingIds":[101],"from":"2025-01-02","to":"2025-03-20","signal":{"source":"shorts","field":"net_change"},"horizonSessions":5,"universeMarket":"CA_EQ","horizonBucket":"swing_1_10d","__proto__":{"principalId":"operator"}}}}';
|
|
const protoResp = JSON.parse((await server.handleMessage(rawProto)) as string) as {
|
|
result: { isError?: boolean; content: { type: string; text: string }[] };
|
|
};
|
|
expect(protoResp.result.isError).toBe(true);
|
|
expect(protoStore.barsCalls).toHaveLength(0);
|
|
expect(protoLedger.insertCalls).toBe(0);
|
|
});
|
|
|
|
test('sanitizes store, panel, ledger insert, and DSR read failures without leaking SQL, paths, or connection URIs', async () => {
|
|
const fixture = buildCeoShortsFixture();
|
|
const from = fixture.allDates[0]!;
|
|
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
|
const validArgs = {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const sensitiveDetail =
|
|
'SELECT * FROM trial_ledger WHERE secret=1 at /mnt/data/stockbot/curated/shorts/part.parquet via postgres://user:pass@host:5432/trading_bot';
|
|
|
|
function assertNoLeak(rawResponse: string): void {
|
|
expect(rawResponse).not.toContain('SELECT * FROM trial_ledger');
|
|
expect(rawResponse).not.toContain('/mnt/data/stockbot');
|
|
expect(rawResponse).not.toContain('part.parquet');
|
|
expect(rawResponse).not.toContain('postgres://user:pass@host');
|
|
}
|
|
|
|
// 1. Store domain & unexpected errors
|
|
const storeErrors: readonly [Error, string][] = [
|
|
[new VaultScopeNotAuthorizedError(sensitiveDetail), 'VaultScopeNotAuthorizedError'],
|
|
[new MarketDataStoreValidationError(sensitiveDetail, 'curatedRoot'), 'MarketDataStoreValidationError'],
|
|
[new MarketDataStoreNotImplementedError('shortsAsOf', sensitiveDetail), 'MarketDataStoreNotImplementedError'],
|
|
[new Error(sensitiveDetail), 'Error: Tool execution failed.'],
|
|
];
|
|
for (const [err, expectedSnippet] of storeErrors) {
|
|
const store = createFakeStore({ shortsError: err, bars: fixture.bars });
|
|
const ledger = createFakeTrialLedger();
|
|
const res = await callAnalyzeSignal({
|
|
store: store.store,
|
|
ledger: ledger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: validArgs,
|
|
});
|
|
expect(res.isError).toBe(true);
|
|
expect(res.text).toContain(expectedSnippet);
|
|
assertNoLeak(res.rawResponse);
|
|
expect(ledger.rows).toHaveLength(0);
|
|
}
|
|
|
|
// 2. Malformed shorts table -> SignalPanelError mapped cleanly
|
|
const badTableStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: { columns: ['listing_id'], rows: [] },
|
|
});
|
|
const badTableLedger = createFakeTrialLedger();
|
|
const badTableRes = await callAnalyzeSignal({
|
|
store: badTableStore.store,
|
|
ledger: badTableLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: validArgs,
|
|
});
|
|
expect(badTableRes.isError).toBe(true);
|
|
expect(badTableRes.text).toContain('SignalPanelError:');
|
|
expect(badTableLedger.rows).toHaveLength(0);
|
|
|
|
// 3. Ledger INSERT failure -> isError: true, no leak, zero trial rows written
|
|
const insertFailStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
});
|
|
const insertFailLedger = createFakeTrialLedger({
|
|
insertError: new Error(sensitiveDetail),
|
|
});
|
|
const insertFailRes = await callAnalyzeSignal({
|
|
store: insertFailStore.store,
|
|
ledger: insertFailLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: validArgs,
|
|
});
|
|
expect(insertFailRes.isError).toBe(true);
|
|
expect(insertFailRes.text).toBe('Error: Tool execution failed.');
|
|
assertNoLeak(insertFailRes.rawResponse);
|
|
expect(insertFailLedger.insertCalls).toBe(1);
|
|
expect(insertFailLedger.rows).toHaveLength(0);
|
|
|
|
// 4. DSR read failure after INSERT -> isError: true, fixed SignalStudyError, no leak, exactly 1 insert (never retried)
|
|
const dsrFailStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
});
|
|
const dsrFailLedger = createFakeTrialLedger({
|
|
dsrReadError: new Error(sensitiveDetail),
|
|
});
|
|
const dsrFailRes = await callAnalyzeSignal({
|
|
store: dsrFailStore.store,
|
|
ledger: dsrFailLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: validArgs,
|
|
});
|
|
expect(dsrFailRes.isError).toBe(true);
|
|
expect(dsrFailRes.text).toBe(
|
|
'SignalStudyError: Trial was recorded, but cluster deflated Sharpe evaluation failed.'
|
|
);
|
|
assertNoLeak(dsrFailRes.rawResponse);
|
|
expect(dsrFailLedger.insertCalls).toBe(1);
|
|
expect(dsrFailLedger.rows).toHaveLength(1);
|
|
});
|
|
});
|
|
|
|
interface FundamentalsPitFixtureRow {
|
|
readonly listing_id: number;
|
|
readonly effective_known_at: number;
|
|
readonly known_at_source: string;
|
|
readonly has_estimated_lag: boolean;
|
|
readonly period_end: string;
|
|
readonly fiscal_period: string;
|
|
readonly currency: string;
|
|
readonly period_known_at: number;
|
|
readonly revenue: number | null;
|
|
readonly net_income: number | null;
|
|
readonly operating_cash_flow: number | null;
|
|
readonly total_assets: number | null;
|
|
readonly total_equity: number | null;
|
|
readonly shares_outstanding: number | null;
|
|
readonly ttm_revenue: number | null;
|
|
readonly ttm_net_income: number | null;
|
|
readonly ttm_operating_cash_flow: number | null;
|
|
readonly ttm_period_end: string | null;
|
|
readonly ttm_currency: string | null;
|
|
readonly ttm_has_estimated_lag: boolean;
|
|
}
|
|
|
|
const FUNDAMENTALS_TTM_FIELDS = new Set<string>([
|
|
'ttm_revenue',
|
|
'ttm_net_income',
|
|
'ttm_operating_cash_flow',
|
|
]);
|
|
|
|
function queryFundamentalsFixtureRows(
|
|
rows: readonly FundamentalsPitFixtureRow[],
|
|
q: FundamentalsAsOfQuery
|
|
): Table {
|
|
const idSet = new Set(q.listingIds);
|
|
const asOfMs = Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf);
|
|
const allowEstimatedLag = q.allowEstimatedLag ?? false;
|
|
|
|
const latestByListing = new Map<number, FundamentalsPitFixtureRow>();
|
|
for (const row of rows) {
|
|
if (!idSet.has(row.listing_id) || row.effective_known_at > asOfMs) {
|
|
continue;
|
|
}
|
|
const prev = latestByListing.get(row.listing_id);
|
|
if (prev === undefined || row.effective_known_at > prev.effective_known_at) {
|
|
latestByListing.set(row.listing_id, row);
|
|
}
|
|
}
|
|
|
|
const hasTtm = q.fields.some(f => FUNDAMENTALS_TTM_FIELDS.has(f));
|
|
const columns: string[] = [
|
|
'listing_id',
|
|
'effective_known_at',
|
|
'known_at_source',
|
|
'has_estimated_lag',
|
|
'period_end',
|
|
'fiscal_period',
|
|
'currency',
|
|
'period_known_at',
|
|
...q.fields,
|
|
...(hasTtm ? ['ttm_period_end', 'ttm_currency', 'ttm_has_estimated_lag'] : []),
|
|
];
|
|
|
|
const outRows: TableRow[] = [];
|
|
const sortedIds = [...latestByListing.keys()].sort((a, b) => a - b);
|
|
for (const lid of sortedIds) {
|
|
const selected = latestByListing.get(lid)!;
|
|
if (!allowEstimatedLag && selected.has_estimated_lag) {
|
|
continue;
|
|
}
|
|
const projected: Record<string, string | number | boolean | null> = {
|
|
listing_id: selected.listing_id,
|
|
effective_known_at: selected.effective_known_at,
|
|
known_at_source: selected.known_at_source,
|
|
has_estimated_lag: selected.has_estimated_lag,
|
|
period_end: selected.period_end,
|
|
fiscal_period: selected.fiscal_period,
|
|
currency: selected.currency,
|
|
period_known_at: selected.period_known_at,
|
|
};
|
|
for (const field of q.fields) {
|
|
const val = selected[field as keyof FundamentalsPitFixtureRow] as number | null;
|
|
if (FUNDAMENTALS_TTM_FIELDS.has(field)) {
|
|
projected[field] = allowEstimatedLag || !selected.ttm_has_estimated_lag ? val : null;
|
|
} else {
|
|
projected[field] = val;
|
|
}
|
|
}
|
|
if (hasTtm) {
|
|
projected.ttm_period_end =
|
|
allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_period_end : null;
|
|
projected.ttm_currency =
|
|
allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_currency : null;
|
|
projected.ttm_has_estimated_lag = selected.ttm_has_estimated_lag;
|
|
}
|
|
outRows.push(projected);
|
|
}
|
|
|
|
return { columns, rows: outRows };
|
|
}
|
|
|
|
function makeFundamentalsRow(params: {
|
|
listingId: number;
|
|
effectiveKnownAt: number;
|
|
periodEnd: string;
|
|
fiscalPeriod: string;
|
|
revenue: number;
|
|
ttmRevenue: number;
|
|
hasEstimatedLag?: boolean;
|
|
ttmHasEstimatedLag?: boolean;
|
|
}): FundamentalsPitFixtureRow {
|
|
const hasEstimatedLag = params.hasEstimatedLag ?? false;
|
|
const ttmHasEstimatedLag = params.ttmHasEstimatedLag ?? false;
|
|
return {
|
|
listing_id: params.listingId,
|
|
effective_known_at: params.effectiveKnownAt,
|
|
known_at_source: hasEstimatedLag ? 'estimated_lag' : 'sec_edgar_filing',
|
|
has_estimated_lag: hasEstimatedLag,
|
|
period_end: params.periodEnd,
|
|
fiscal_period: params.fiscalPeriod,
|
|
currency: 'USD',
|
|
period_known_at: params.effectiveKnownAt,
|
|
revenue: params.revenue,
|
|
net_income: Number((params.revenue * 0.15).toFixed(2)),
|
|
operating_cash_flow: Number((params.revenue * 0.2).toFixed(2)),
|
|
total_assets: Number((params.revenue * 4.0).toFixed(2)),
|
|
total_equity: Number((params.revenue * 1.8).toFixed(2)),
|
|
shares_outstanding: 10_000_000,
|
|
ttm_revenue: params.ttmRevenue,
|
|
ttm_net_income: Number((params.ttmRevenue * 0.15).toFixed(2)),
|
|
ttm_operating_cash_flow: Number((params.ttmRevenue * 0.2).toFixed(2)),
|
|
ttm_period_end: params.periodEnd,
|
|
ttm_currency: 'USD',
|
|
ttm_has_estimated_lag: ttmHasEstimatedLag,
|
|
};
|
|
}
|
|
|
|
// Seeded fundamentals study fixture metadata (pinned for reproducibility):
|
|
// - Dataset ID: `synthetic:mcp-analyze-signal-fundamentals:seed-20261202:v1`
|
|
// - Tool version: `mcp:analyze_signal:v1`
|
|
// - Seed: `20261202` (Mulberry32 PRNG)
|
|
// - Universe: 12 synthetic US equity listings (`70001..70012`, USD, 21:00 UTC close)
|
|
// - Pre-Vault window: 2023-01-02..2023-06-30 (130 business sessions), Vault cutoff: 2023-07-03T00:00:00.000Z
|
|
// - Adjustment: `raw`, horizon: `5` sessions, modeled execution/transaction costs: `0`
|
|
// - Ownership: Quant research owns evidence; Director owns adoption.
|
|
const FUNDAMENTALS_FIXTURE_SEED = 20261202;
|
|
|
|
function buildFundamentalsStudyFixture(): {
|
|
readonly listingIds: number[];
|
|
readonly allDates: string[];
|
|
readonly preCutoffSessions: number;
|
|
readonly vaultCutoffDate: string;
|
|
readonly vaultCutoffTs: number;
|
|
readonly bars: BarRecord[];
|
|
readonly fundamentalsRows: FundamentalsPitFixtureRow[];
|
|
} {
|
|
const rand = createSeededRng(FUNDAMENTALS_FIXTURE_SEED);
|
|
const listingCount = 12;
|
|
const preCutoffSessions = 130;
|
|
const postCutoffSessions = 10;
|
|
const allDates = makeBusinessDates('2023-01-02', preCutoffSessions + postCutoffSessions);
|
|
const vaultCutoffDate = allDates[preCutoffSessions]!;
|
|
const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0);
|
|
const listingIds = Array.from({ length: listingCount }, (_, i) => 70_001 + i);
|
|
|
|
const fundamentalsRows: FundamentalsPitFixtureRow[] = [];
|
|
// Monthly PIT releases across 6 pre-cutoff months + 1 post-cutoff release
|
|
const releaseDates = [
|
|
{ date: '2023-01-10', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' },
|
|
{ date: '2023-02-15', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' },
|
|
{ date: '2023-04-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' },
|
|
{ date: '2023-05-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' },
|
|
{ date: vaultCutoffDate, periodEnd: '2023-06-30', fiscalPeriod: 'Q2' },
|
|
];
|
|
|
|
const activeScore = new Float64Array(listingCount);
|
|
for (let rIdx = 0; rIdx < releaseDates.length; rIdx += 1) {
|
|
const rel = releaseDates[rIdx]!;
|
|
const knownAt = makeUtcMs(rel.date, 13); // 08:00 ET pre-close
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
const rev = 100 + l * 25 + rIdx * 10 + Math.round((rand() * 2 - 1) * 40);
|
|
const ttm = rev * 4 + (l % 3) * 15;
|
|
fundamentalsRows.push(
|
|
makeFundamentalsRow({
|
|
listingId: listingIds[l]!,
|
|
effectiveKnownAt: knownAt,
|
|
periodEnd: rel.periodEnd,
|
|
fiscalPeriod: rel.fiscalPeriod,
|
|
revenue: rev,
|
|
ttmRevenue: ttm,
|
|
})
|
|
);
|
|
}
|
|
}
|
|
|
|
const prices = new Float64Array(listingCount);
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
prices[l] = 20 + l * 3;
|
|
}
|
|
|
|
const bars: BarRecord[] = [];
|
|
for (let t = 0; t < allDates.length; t += 1) {
|
|
const date = allDates[t]!;
|
|
const closeTs = makeUtcMs(date, 21);
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
activeScore[l] = (l - listingCount / 2) / listingCount;
|
|
const dailyRet = 0.002 * activeScore[l]! + (rand() * 2 - 1) * 0.01;
|
|
prices[l] = Math.max(1.0, prices[l]! * (1 + dailyRet));
|
|
const close = Number(prices[l]!.toFixed(6));
|
|
bars.push({
|
|
listingId: listingIds[l]!,
|
|
ts: closeTs,
|
|
open: close,
|
|
high: close,
|
|
low: close,
|
|
close,
|
|
volume: 80_000,
|
|
vwap: close,
|
|
knownAt: closeTs,
|
|
});
|
|
}
|
|
}
|
|
|
|
return {
|
|
listingIds,
|
|
allDates,
|
|
preCutoffSessions,
|
|
vaultCutoffDate,
|
|
vaultCutoffTs,
|
|
bars,
|
|
fundamentalsRows,
|
|
};
|
|
}
|
|
|
|
describe('MCP analyze_signal tool — fundamentals source', () => {
|
|
test('tools/list advertises strict signal discriminated branches and rejects invalid fundamentals inputs with zero store/ledger calls', async () => {
|
|
const cutoffTs = makeUtcMs('2025-03-31', 0);
|
|
const fakeStore = createFakeStore();
|
|
const fakeLedger = createFakeTrialLedger();
|
|
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [
|
|
createAnalyzeSignalTool({
|
|
store: fakeStore.store,
|
|
ledger: fakeLedger.executor,
|
|
vaultContext: { vaultCutoffTs: cutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const listRaw = await server.handleMessage(
|
|
JSON.stringify({ jsonrpc: '2.0', id: 'list-fund', method: 'tools/list' })
|
|
);
|
|
const listParsed = JSON.parse(listRaw as string) as {
|
|
result: {
|
|
tools: {
|
|
name: string;
|
|
description: string;
|
|
inputSchema: {
|
|
properties: {
|
|
signal: {
|
|
type: string;
|
|
additionalProperties: boolean;
|
|
properties: Record<string, unknown>;
|
|
anyOf: {
|
|
additionalProperties: boolean;
|
|
properties: Record<string, { const?: string; enum?: string[]; default?: unknown }>;
|
|
}[];
|
|
};
|
|
};
|
|
};
|
|
}[];
|
|
};
|
|
};
|
|
|
|
const tool = listParsed.result.tools[0]!;
|
|
expect(tool.description).toContain('fundamentals');
|
|
expect(tool.description).toContain('short-interest');
|
|
|
|
const signalSchema = tool.inputSchema.properties.signal;
|
|
expect(signalSchema.type).toBe('object');
|
|
expect(signalSchema.additionalProperties).toBe(false);
|
|
expect(Object.keys(signalSchema.properties).sort()).toEqual([
|
|
'allowEstimatedLag',
|
|
'field',
|
|
'source',
|
|
]);
|
|
expect(signalSchema.anyOf).toHaveLength(2);
|
|
expect(signalSchema.anyOf[0]?.additionalProperties).toBe(false);
|
|
expect(signalSchema.anyOf[0]?.properties.source?.const).toBe('shorts');
|
|
expect(signalSchema.anyOf[1]?.additionalProperties).toBe(false);
|
|
expect(signalSchema.anyOf[1]?.properties.source?.const).toBe('fundamentals');
|
|
expect(signalSchema.anyOf[1]?.properties.field?.enum).toEqual([...FUNDAMENTALS_PIT_VALUE_FIELDS]);
|
|
expect(signalSchema.anyOf[1]?.properties.allowEstimatedLag?.default).toBe(false);
|
|
|
|
const validBase = {
|
|
listingIds: [70_001, 70_002],
|
|
from: '2023-01-02',
|
|
to: '2023-06-30',
|
|
signal: { source: 'fundamentals', field: 'ttm_revenue' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const invalidCases: readonly [string, Record<string, unknown>][] = [
|
|
['unknown fundamentals field', { ...validBase, signal: { source: 'fundamentals', field: 'ebitda_fake' } }],
|
|
['shorts field on fundamentals source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }],
|
|
['fundamentals field on shorts source', { ...validBase, signal: { source: 'shorts', field: 'ttm_revenue' } }],
|
|
['unknown signal.source', { ...validBase, signal: { source: 'macro', field: 'ttm_revenue' } }],
|
|
[
|
|
'unknown nested key in fundamentals signal',
|
|
{ ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', extraKey: true } },
|
|
],
|
|
[
|
|
'allowEstimatedLag on shorts source',
|
|
{ ...validBase, signal: { source: 'shorts', field: 'net_change', allowEstimatedLag: false } },
|
|
],
|
|
[
|
|
'non-boolean allowEstimatedLag string',
|
|
{ ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 'true' } },
|
|
],
|
|
[
|
|
'non-boolean allowEstimatedLag number',
|
|
{ ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 1 } },
|
|
],
|
|
['fundamentals study with FX universeMarket', { ...validBase, universeMarket: 'FX' }],
|
|
];
|
|
|
|
for (const [_label, args] of invalidCases) {
|
|
const store = createFakeStore();
|
|
const ledger = createFakeTrialLedger();
|
|
const res = await callAnalyzeSignal({
|
|
store: store.store,
|
|
ledger: ledger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args,
|
|
});
|
|
expect(res.isError).toBe(true);
|
|
expect(res.text).toContain('Invalid arguments for tool "analyze_signal":');
|
|
expect(store.barsCalls).toHaveLength(0);
|
|
expect(store.shortsCalls).toHaveLength(0);
|
|
expect(store.fundamentalsCalls).toHaveLength(0);
|
|
expect(store.universeCalls).toHaveLength(0);
|
|
expect(ledger.insertCalls).toBe(0);
|
|
}
|
|
});
|
|
|
|
test('executes fundamentals study, records canonical fundamentals expressionHash, forwards allowEstimatedLag verbatim, and preserves identity on append-only retry', async () => {
|
|
const fixture = buildFundamentalsStudyFixture();
|
|
const from = fixture.allDates[0]!;
|
|
const to = fixture.allDates[fixture.preCutoffSessions - 1]!;
|
|
|
|
const store = createFakeStore({
|
|
bars: fixture.bars,
|
|
fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q),
|
|
});
|
|
const sharedLedger = createFakeTrialLedger();
|
|
|
|
const baseArgs = {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to,
|
|
signal: { source: 'fundamentals', field: 'ttm_revenue' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
campaignId: CAMPAIGN_UUID,
|
|
hypothesisId: HYPOTHESIS_UUID,
|
|
};
|
|
|
|
const res1 = await callAnalyzeSignal({
|
|
store: store.store,
|
|
ledger: sharedLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
principalId: AGENT_PRINCIPAL,
|
|
args: baseArgs,
|
|
});
|
|
expect(res1.isError).toBe(false);
|
|
const payload1 = JSON.parse(res1.text) as AnalyzeSignalResultPayload;
|
|
expect(payload1.status).toBe('ok');
|
|
if (payload1.status !== 'ok') {
|
|
return;
|
|
}
|
|
|
|
expect(payload1.signal).toEqual({
|
|
source: 'fundamentals',
|
|
field: 'ttm_revenue',
|
|
allowEstimatedLag: false,
|
|
});
|
|
expect(sharedLedger.rows).toHaveLength(1);
|
|
expect(sharedLedger.rows[0]?.stage).toBe('signal_ic');
|
|
expect(sharedLedger.rows[0]?.principal_id).toBe(AGENT_PRINCIPAL);
|
|
|
|
// Verify canonical expression prefix `mcp:analyze_signal:v1:fundamentals:` via canonicalExpressionHash
|
|
const expectedHash = canonicalExpressionHash({
|
|
expression: 'mcp:analyze_signal:v1:fundamentals:ttm_revenue',
|
|
params: {
|
|
version: 1,
|
|
signalSource: 'fundamentals',
|
|
signalField: 'ttm_revenue',
|
|
allowEstimatedLag: false,
|
|
horizonSessions: 5,
|
|
maxSignalAgeSessions: null,
|
|
adjustment: 'raw',
|
|
ledgerSeries: 'rank_ic',
|
|
effectiveFrom: payload1.effectiveFrom,
|
|
effectiveTo: payload1.effectiveTo,
|
|
effectiveAsOf: payload1.effectiveAsOf,
|
|
},
|
|
universe: {
|
|
kind: 'listingIds',
|
|
listingIds: fixture.listingIds,
|
|
},
|
|
horizon: '5d',
|
|
sampleStart: payload1.trial.sampleStart,
|
|
sampleEnd: payload1.trial.sampleEnd,
|
|
});
|
|
expect(payload1.trial.expressionHash).toBe(expectedHash);
|
|
expect(sharedLedger.rows[0]?.expression_hash).toBe(expectedHash);
|
|
|
|
// Default allowEstimatedLag === false forwarded verbatim to every fundamentalsAsOf call
|
|
expect(store.fundamentalsCalls.length).toBeGreaterThan(0);
|
|
expect(store.shortsCalls).toHaveLength(0);
|
|
for (const call of store.fundamentalsCalls) {
|
|
expect(call.fields).toEqual(['ttm_revenue']);
|
|
expect(call.allowEstimatedLag).toBe(false);
|
|
}
|
|
|
|
// Re-running identical request against the SAME ledger appends under append-only rules with one distinct expression_hash
|
|
const res2 = await callAnalyzeSignal({
|
|
store: store.store,
|
|
ledger: sharedLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
principalId: AGENT_PRINCIPAL,
|
|
args: baseArgs,
|
|
});
|
|
expect(res2.isError).toBe(false);
|
|
const payload2 = JSON.parse(res2.text) as AnalyzeSignalResultPayload;
|
|
expect(payload2.status).toBe('ok');
|
|
if (payload2.status !== 'ok') {
|
|
return;
|
|
}
|
|
expect(payload2.trial.expressionHash).toBe(payload1.trial.expressionHash);
|
|
expect(new Set(sharedLedger.rows.map(r => r.expression_hash)).size).toBe(1);
|
|
|
|
// Explicit allowEstimatedLag: false and reordered/duplicated listingIds preserve identity
|
|
const explicitFalseStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q),
|
|
});
|
|
const explicitFalseLedger = createFakeTrialLedger();
|
|
const reorderedIds = [...fixture.listingIds].reverse();
|
|
reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[2]!);
|
|
const resExplicitFalse = await callAnalyzeSignal({
|
|
store: explicitFalseStore.store,
|
|
ledger: explicitFalseLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: {
|
|
...baseArgs,
|
|
listingIds: reorderedIds,
|
|
signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: false },
|
|
},
|
|
});
|
|
const payloadExplicitFalse = JSON.parse(resExplicitFalse.text) as AnalyzeSignalResultPayload;
|
|
expect(payloadExplicitFalse.status).toBe('ok');
|
|
if (payloadExplicitFalse.status === 'ok') {
|
|
expect(payloadExplicitFalse.trial.expressionHash).toBe(payload1.trial.expressionHash);
|
|
}
|
|
expect(explicitFalseStore.fundamentalsCalls.every(c => c.allowEstimatedLag === false)).toBe(true);
|
|
|
|
// allowEstimatedLag: true forwards true verbatim and changes expressionHash
|
|
const lagTrueStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q),
|
|
});
|
|
const lagTrueLedger = createFakeTrialLedger();
|
|
const resLagTrue = await callAnalyzeSignal({
|
|
store: lagTrueStore.store,
|
|
ledger: lagTrueLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: {
|
|
...baseArgs,
|
|
signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true },
|
|
},
|
|
});
|
|
const payloadLagTrue = JSON.parse(resLagTrue.text) as AnalyzeSignalResultPayload;
|
|
expect(payloadLagTrue.status).toBe('ok');
|
|
if (payloadLagTrue.status === 'ok') {
|
|
expect(payloadLagTrue.signal).toEqual({
|
|
source: 'fundamentals',
|
|
field: 'ttm_revenue',
|
|
allowEstimatedLag: true,
|
|
});
|
|
expect(payloadLagTrue.trial.expressionHash).not.toBe(payload1.trial.expressionHash);
|
|
}
|
|
expect(lagTrueStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true);
|
|
|
|
// Different field changes expressionHash
|
|
const otherFieldStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q),
|
|
});
|
|
const otherFieldLedger = createFakeTrialLedger();
|
|
const resOtherField = await callAnalyzeSignal({
|
|
store: otherFieldStore.store,
|
|
ledger: otherFieldLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: {
|
|
...baseArgs,
|
|
signal: { source: 'fundamentals', field: 'revenue' },
|
|
},
|
|
});
|
|
const payloadOtherField = JSON.parse(resOtherField.text) as AnalyzeSignalResultPayload;
|
|
expect(payloadOtherField.status).toBe('ok');
|
|
if (payloadOtherField.status === 'ok') {
|
|
expect(payloadOtherField.trial.expressionHash).not.toBe(payload1.trial.expressionHash);
|
|
}
|
|
|
|
// Shorts study over the same window/listings produces a distinct expressionHash
|
|
const shortsRows: TableRow[] = fixture.listingIds.map((lid, i) => ({
|
|
listing_id: lid,
|
|
report_date: from,
|
|
known_at: makeUtcMs(from, 12),
|
|
shares_short: 100_000 + i * 5_000,
|
|
net_change: (i - 5) * 1_000,
|
|
pct_float: 0.03 + i * 0.005,
|
|
source: 'ceoShorts',
|
|
}));
|
|
const shortsStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: { columns: SHORTS_COLUMNS, rows: shortsRows },
|
|
});
|
|
const shortsLedger = createFakeTrialLedger();
|
|
const resShorts = await callAnalyzeSignal({
|
|
store: shortsStore.store,
|
|
ledger: shortsLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: {
|
|
...baseArgs,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
},
|
|
});
|
|
const payloadShorts = JSON.parse(resShorts.text) as AnalyzeSignalResultPayload;
|
|
expect(payloadShorts.status).toBe('ok');
|
|
if (payloadShorts.status === 'ok') {
|
|
expect(payloadShorts.trial.expressionHash).not.toBe(payload1.trial.expressionHash);
|
|
}
|
|
});
|
|
|
|
test('queries month-end snapshots in ascending order from unsorted bars, preserves earlier explicit asOf, enforces 120-snapshot cap, and handles empty bars', async () => {
|
|
// 1. Unsorted bars spanning 3 UTC months (2 full + 1 partial final month) with earlier intraday asOf
|
|
const janDates = ['2023-01-10', '2023-01-31'];
|
|
const febDates = ['2023-02-14', '2023-02-28'];
|
|
const marDates = ['2023-03-08', '2023-03-15'];
|
|
const unsortedDates = [...marDates, ...janDates, ...febDates].reverse();
|
|
const bars: BarRecord[] = [];
|
|
for (const date of unsortedDates) {
|
|
const ts = makeUtcMs(date, 21);
|
|
for (const lid of [101, 102]) {
|
|
bars.push({
|
|
listingId: lid,
|
|
ts,
|
|
open: 10,
|
|
high: 10,
|
|
low: 10,
|
|
close: 10,
|
|
volume: 100,
|
|
vwap: 10,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
}
|
|
|
|
const cutoffTs = makeUtcMs('2023-04-01', 0);
|
|
const preWindowKnownAt = makeUtcMs('2022-12-15', 13);
|
|
const storeOrder = createFakeStore({
|
|
bars,
|
|
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();
|
|
|
|
// Earlier explicit asOf on 2023-03-15T22:30:00.123456Z (after 21:00 bar close, before day end)
|
|
const explicitAsOf = '2023-03-15T22:30:00.123456Z';
|
|
const orderRes = await callAnalyzeSignal({
|
|
store: storeOrder.store,
|
|
ledger: ledgerOrder.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args: {
|
|
listingIds: [102, 101],
|
|
from: '2023-01-01',
|
|
to: '2023-03-31',
|
|
asOf: explicitAsOf,
|
|
signal: { source: 'fundamentals', field: 'revenue' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(orderRes.isError).toBe(false);
|
|
expect(storeOrder.fundamentalsCalls.map(c => c.asOf)).toEqual([
|
|
'2023-01-31T23:59:59.999999Z',
|
|
'2023-02-28T23:59:59.999999Z',
|
|
explicitAsOf,
|
|
]);
|
|
expect(storeOrder.fundamentalsCalls.every(c => c.listingIds[0] === 101 && c.listingIds[1] === 102)).toBe(true);
|
|
|
|
// 2. Empty eligible bar sample -> 0 fundamentalsAsOf calls, insufficient_data, 0 ledger writes
|
|
const emptyBarsStore = createFakeStore({
|
|
bars: [],
|
|
fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }),
|
|
});
|
|
const emptyBarsLedger = createFakeTrialLedger();
|
|
const emptyRes = await callAnalyzeSignal({
|
|
store: emptyBarsStore.store,
|
|
ledger: emptyBarsLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args: {
|
|
listingIds: [101, 102],
|
|
from: '2023-01-01',
|
|
to: '2023-03-31',
|
|
signal: { source: 'fundamentals', field: 'revenue' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(emptyRes.isError).toBe(false);
|
|
const emptyPayload = JSON.parse(emptyRes.text) as AnalyzeSignalResultPayload;
|
|
expect(emptyPayload.status).toBe('insufficient_data');
|
|
if (emptyPayload.status === 'insufficient_data') {
|
|
expect(emptyPayload.reason).toBe('too_few_observations');
|
|
}
|
|
expect(emptyBarsStore.fundamentalsCalls).toHaveLength(0);
|
|
expect(emptyBarsLedger.rows).toHaveLength(0);
|
|
|
|
// 3. Exactly 120 eligible UTC months is accepted; 121 is rejected with 0 fundamentals calls and 0 ledger inserts
|
|
function makeMonthlyBars(monthCount: number): BarRecord[] {
|
|
const out: BarRecord[] = [];
|
|
for (let m = 0; m < monthCount; m += 1) {
|
|
const year = 2010 + Math.floor(m / 12);
|
|
const month = (m % 12) + 1;
|
|
const date = `${year}-${String(month).padStart(2, '0')}-15`;
|
|
const ts = makeUtcMs(date, 21);
|
|
out.push({
|
|
listingId: 101,
|
|
ts,
|
|
open: 10,
|
|
high: 10,
|
|
low: 10,
|
|
close: 10,
|
|
volume: 100,
|
|
vwap: 10,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
return out;
|
|
}
|
|
|
|
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: 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({
|
|
store: exactCapStore.store,
|
|
ledger: exactCapLedger.executor,
|
|
vaultCutoffTs: capCutoffTs,
|
|
args: {
|
|
listingIds: [101],
|
|
from: '2010-01-01',
|
|
to: '2024-12-31',
|
|
signal: { source: 'fundamentals', field: 'revenue' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(exactCapRes.isError).toBe(false);
|
|
expect(exactCapStore.fundamentalsCalls).toHaveLength(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS);
|
|
|
|
const overCapStore = createFakeStore({
|
|
bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS + 1),
|
|
fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }),
|
|
});
|
|
const overCapLedger = createFakeTrialLedger();
|
|
const overCapRes = await callAnalyzeSignal({
|
|
store: overCapStore.store,
|
|
ledger: overCapLedger.executor,
|
|
vaultCutoffTs: capCutoffTs,
|
|
args: {
|
|
listingIds: [101],
|
|
from: '2010-01-01',
|
|
to: '2024-12-31',
|
|
signal: { source: 'fundamentals', field: 'revenue' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(overCapRes.isError).toBe(true);
|
|
expect(overCapRes.text).toBe(
|
|
`Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.`
|
|
);
|
|
expect(overCapStore.fundamentalsCalls).toHaveLength(0);
|
|
expect(overCapLedger.insertCalls).toBe(0);
|
|
expect(overCapLedger.rows).toHaveLength(0);
|
|
});
|
|
|
|
test('restatement replay prevents look-ahead: dates before Q1 restatement use originally known values and appending a future revision leaves prior output unchanged', async () => {
|
|
// Explicit deterministic restatement fixture:
|
|
// - 6 listings across 2023-01-02..2023-05-31 (108 sessions), Vault cutoff 2023-06-01T00:00:00Z
|
|
// - Original Q1 known 2023-01-12T13:00Z (period_end 2022-12-31)
|
|
// - Original Q2 known 2023-02-15T13:00Z (period_end 2023-01-31)
|
|
// - Q1 restatement known 2023-04-12T13:00Z (AFTER Q2!): period_end stays 2023-01-31 (Q2),
|
|
// while ttm_revenue flips cross-sectional ordering for listings 0..5.
|
|
// - Unchanged months (March, May) re-emit identical (listing_id, effective_known_at) -> deduped cleanly.
|
|
const listingIds = [80_001, 80_002, 80_003, 80_004, 80_005, 80_006];
|
|
const allDates = makeBusinessDates('2023-01-02', 112);
|
|
const preCutoffDates = allDates.filter(d => d < '2023-06-01');
|
|
const vaultCutoffDate = '2023-06-01';
|
|
const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0);
|
|
|
|
const q1KnownAt = makeUtcMs('2023-01-12', 13);
|
|
const q2KnownAt = makeUtcMs('2023-02-15', 13);
|
|
const q1RestatedKnownAt = makeUtcMs('2023-04-12', 13);
|
|
const futureRevisionKnownAt = makeUtcMs('2023-06-15', 13); // post-cutoff
|
|
|
|
const rand = createSeededRng(20261203);
|
|
const bars: BarRecord[] = [];
|
|
const prices = new Float64Array(listingIds.length).fill(50);
|
|
for (let t = 0; t < preCutoffDates.length; t += 1) {
|
|
const date = preCutoffDates[t]!;
|
|
const closeTs = makeUtcMs(date, 21);
|
|
for (let l = 0; l < listingIds.length; l += 1) {
|
|
const ret = (l - 2.5) * 0.0015 + (rand() * 2 - 1) * 0.008;
|
|
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: 25_000,
|
|
vwap: close,
|
|
knownAt: closeTs,
|
|
});
|
|
}
|
|
}
|
|
|
|
const basePitRows: FundamentalsPitFixtureRow[] = [];
|
|
const expectedDirectObs: SignalObservation[] = [];
|
|
|
|
for (let l = 0; l < listingIds.length; l += 1) {
|
|
const lid = listingIds[l]!;
|
|
const q1Val = 100 + l * 20;
|
|
const q2Val = 120 + l * 25;
|
|
// Restatement reverses cross-sectional rank ordering after 2023-04-12
|
|
const restatedVal = 300 - l * 30;
|
|
|
|
basePitRows.push(
|
|
makeFundamentalsRow({
|
|
listingId: lid,
|
|
effectiveKnownAt: q1KnownAt,
|
|
periodEnd: '2022-12-31',
|
|
fiscalPeriod: 'Q1',
|
|
revenue: q1Val / 4,
|
|
ttmRevenue: q1Val,
|
|
}),
|
|
makeFundamentalsRow({
|
|
listingId: lid,
|
|
effectiveKnownAt: q2KnownAt,
|
|
periodEnd: '2023-01-31',
|
|
fiscalPeriod: 'Q2',
|
|
revenue: q2Val / 4,
|
|
ttmRevenue: q2Val,
|
|
}),
|
|
makeFundamentalsRow({
|
|
listingId: lid,
|
|
effectiveKnownAt: q1RestatedKnownAt,
|
|
periodEnd: '2023-01-31',
|
|
fiscalPeriod: 'Q2',
|
|
revenue: q2Val / 4,
|
|
ttmRevenue: restatedVal,
|
|
})
|
|
);
|
|
|
|
expectedDirectObs.push(
|
|
{ listingId: lid, knownAt: q1KnownAt, value: q1Val },
|
|
{ listingId: lid, knownAt: q2KnownAt, value: q2Val },
|
|
{ listingId: lid, knownAt: q1RestatedKnownAt, value: restatedVal }
|
|
);
|
|
}
|
|
|
|
// 1. Direct baseline using independently specified eligible observations
|
|
const directLedger = createFakeTrialLedger();
|
|
const directBuilt = buildForwardReturnPanel({
|
|
bars,
|
|
signals: expectedDirectObs,
|
|
horizonSessions: 5,
|
|
vaultCutoffDate,
|
|
});
|
|
const directStudy = await analyzeSignal(directLedger.executor, {
|
|
principalId: AGENT_PRINCIPAL,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
expression: {
|
|
expression: 'direct_restatement_baseline',
|
|
params: { field: 'ttm_revenue', horizonSessions: 5 },
|
|
universe: listingIds,
|
|
horizon: '5d',
|
|
},
|
|
panel: directBuilt.panel,
|
|
vaultCutoffDate,
|
|
});
|
|
expect(directStudy.status).toBe('ok');
|
|
if (directStudy.status !== 'ok') {
|
|
return;
|
|
}
|
|
|
|
// 2. MCP handler run on base rows (before future revision is appended)
|
|
const args = {
|
|
listingIds,
|
|
from: preCutoffDates[0]!,
|
|
to: preCutoffDates[preCutoffDates.length - 1]!,
|
|
signal: { source: 'fundamentals', field: 'ttm_revenue' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const mcpStore = createFakeStore({
|
|
bars,
|
|
fundamentalsResolver: q => queryFundamentalsFixtureRows(basePitRows, q),
|
|
});
|
|
const mcpLedger = createFakeTrialLedger();
|
|
const mcpRes = await callAnalyzeSignal({
|
|
store: mcpStore.store,
|
|
ledger: mcpLedger.executor,
|
|
vaultCutoffTs,
|
|
args,
|
|
});
|
|
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 between MCP handler and direct baseline (dates, rankIc, ledger daily_series)
|
|
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);
|
|
expect(mcpPayload.trial.sampleStart).toBe(directStudy.trial.sampleStart);
|
|
expect(mcpPayload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd);
|
|
// Forward return endpoint remains strictly before vaultCutoffDate
|
|
const sampleEndIdx = preCutoffDates.indexOf(mcpPayload.trial.sampleEnd);
|
|
expect(sampleEndIdx).toBeGreaterThanOrEqual(0);
|
|
expect(sampleEndIdx + 5).toBeLessThan(preCutoffDates.length);
|
|
expect(preCutoffDates[sampleEndIdx + 5]! < vaultCutoffDate).toBe(true);
|
|
|
|
// Confirm pre-restatement dates (between 2023-02-15 and 2023-04-11) actually differ from a look-ahead study
|
|
// that wrongly substitutes the restated values onto Q2's earlier known_at!
|
|
const lookAheadObs = expectedDirectObs.map(o =>
|
|
o.knownAt === q2KnownAt
|
|
? { ...o, value: 300 - (o.listingId - 80_001) * 30 }
|
|
: o
|
|
);
|
|
const lookAheadBuilt = buildForwardReturnPanel({
|
|
bars,
|
|
signals: lookAheadObs,
|
|
horizonSessions: 5,
|
|
vaultCutoffDate,
|
|
});
|
|
const lookAheadLedger = createFakeTrialLedger();
|
|
const lookAheadStudy = await analyzeSignal(lookAheadLedger.executor, {
|
|
principalId: AGENT_PRINCIPAL,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
expression: {
|
|
expression: 'look_ahead_counterfactual',
|
|
params: { field: 'ttm_revenue', horizonSessions: 5 },
|
|
universe: listingIds,
|
|
horizon: '5d',
|
|
},
|
|
panel: lookAheadBuilt.panel,
|
|
vaultCutoffDate,
|
|
});
|
|
expect(lookAheadStudy.status).toBe('ok');
|
|
expect(mcpLedger.rows[0]?.daily_series).not.toEqual(lookAheadLedger.rows[0]?.daily_series);
|
|
|
|
// 3. Append a future revision (post-cutoff) and verify all prior dated outputs & ledger rows remain bit-identical
|
|
const rowsWithFutureRevision: FundamentalsPitFixtureRow[] = [
|
|
...basePitRows,
|
|
...listingIds.map((lid, l) =>
|
|
makeFundamentalsRow({
|
|
listingId: lid,
|
|
effectiveKnownAt: futureRevisionKnownAt,
|
|
periodEnd: '2023-01-31',
|
|
fiscalPeriod: 'Q2',
|
|
revenue: 999,
|
|
ttmRevenue: 9_999 + l,
|
|
})
|
|
),
|
|
];
|
|
const futureStore = createFakeStore({
|
|
bars,
|
|
fundamentalsResolver: q => queryFundamentalsFixtureRows(rowsWithFutureRevision, q),
|
|
});
|
|
const futureLedger = createFakeTrialLedger();
|
|
const futureRes = await callAnalyzeSignal({
|
|
store: futureStore.store,
|
|
ledger: futureLedger.executor,
|
|
vaultCutoffTs,
|
|
args,
|
|
});
|
|
expect(futureRes.isError).toBe(false);
|
|
expect(futureRes.text).toBe(mcpRes.text);
|
|
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('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);
|
|
|
|
// 6. Stale March null row for an omitted listing must not suppress April omission backfill;
|
|
// exact payload and ledger rows must match the clean run.
|
|
const staleNullKnownAt = makeUtcMs('2023-03-20', 13);
|
|
const staleNullStore = createFakeStore({
|
|
bars,
|
|
fundamentalsResolver: q => {
|
|
const cleanTable = queryFundamentalsFixtureRows(pitRows, q);
|
|
const returnedIds = new Set(cleanTable.rows.map(r => r.listing_id));
|
|
const injected: TableRow[] = [];
|
|
for (const omittedTarget of [listingIds[1]!, listingIds[5]!]) {
|
|
if (q.listingIds.includes(omittedTarget) && !returnedIds.has(omittedTarget)) {
|
|
injected.push({
|
|
listing_id: omittedTarget,
|
|
effective_known_at: staleNullKnownAt,
|
|
known_at_source: 'sec_edgar_filing',
|
|
has_estimated_lag: false,
|
|
period_end: '2022-12-31',
|
|
fiscal_period: 'Q1',
|
|
currency: 'USD',
|
|
period_known_at: staleNullKnownAt,
|
|
ttm_revenue: null,
|
|
ttm_period_end: null,
|
|
ttm_currency: null,
|
|
ttm_has_estimated_lag: false,
|
|
});
|
|
}
|
|
}
|
|
return {
|
|
columns: cleanTable.columns,
|
|
rows: [...cleanTable.rows, ...injected],
|
|
};
|
|
},
|
|
});
|
|
const staleNullLedger = createFakeTrialLedger();
|
|
const staleNullRes = await callAnalyzeSignal({
|
|
store: staleNullStore.store,
|
|
ledger: staleNullLedger.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(staleNullRes.isError).toBe(false);
|
|
expect(staleNullRes.text).toBe(mcpRes.text);
|
|
expect(staleNullLedger.rows).toEqual(mcpLedger.rows);
|
|
for (const call of staleNullStore.fundamentalsCalls) {
|
|
expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs);
|
|
expect(call.allowEstimatedLag).toBe(false);
|
|
}
|
|
|
|
// 7. Genuinely null latest field with allowEstimatedLag: true must still probe earlier
|
|
// eligible closes and recover the valid April 5 release.
|
|
const nullLatestPitRows: FundamentalsPitFixtureRow[] = pitRows.map(row =>
|
|
row.effective_known_at === aprEstimatedLagKnownAt ? { ...row, ttm_revenue: null } : row
|
|
);
|
|
const nullLatestAllowLagStore = createFakeStore({
|
|
bars,
|
|
fundamentalsResolver: q => queryFundamentalsFixtureRows(nullLatestPitRows, q),
|
|
});
|
|
const nullLatestAllowLagLedger = createFakeTrialLedger();
|
|
const nullLatestAllowLagRes = await callAnalyzeSignal({
|
|
store: nullLatestAllowLagStore.store,
|
|
ledger: nullLatestAllowLagLedger.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(nullLatestAllowLagRes.isError).toBe(false);
|
|
const nullLatestAllowLagPayload = JSON.parse(
|
|
nullLatestAllowLagRes.text
|
|
) as AnalyzeSignalResultPayload;
|
|
expect(nullLatestAllowLagPayload.status).toBe('ok');
|
|
if (nullLatestAllowLagPayload.status === 'ok') {
|
|
expect(nullLatestAllowLagPayload.analysis.rankIc).toEqual(
|
|
directVerifiedStudy.analysis.rankIc
|
|
);
|
|
expect(nullLatestAllowLagPayload.analysis.pearsonIc).toEqual(
|
|
directVerifiedStudy.analysis.pearsonIc
|
|
);
|
|
expect(nullLatestAllowLagLedger.rows[0]?.daily_series).toEqual(
|
|
directVerifiedLedger.rows[0]?.daily_series
|
|
);
|
|
const recoveredByDate = new Map(
|
|
nullLatestAllowLagPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])
|
|
);
|
|
let recoveredAprilDiffCount = 0;
|
|
for (const d of aprilPreEstimatedDates) {
|
|
if (recoveredByDate.get(d) !== brokenByDate.get(d)) {
|
|
recoveredAprilDiffCount += 1;
|
|
}
|
|
}
|
|
expect(recoveredAprilDiffCount).toBeGreaterThan(0);
|
|
}
|
|
expect(nullLatestAllowLagStore.fundamentalsCalls.length).toBeGreaterThan(0);
|
|
for (const call of nullLatestAllowLagStore.fundamentalsCalls) {
|
|
expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs);
|
|
expect(call.allowEstimatedLag).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]!;
|
|
const postCutoffDate = fixture.allDates[fixture.allDates.length - 1]!;
|
|
|
|
const cleanStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q),
|
|
});
|
|
const leakyStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
leaky: true,
|
|
fundamentalsResolver: q => {
|
|
const cleanTable = queryFundamentalsFixtureRows(fixture.fundamentalsRows, q);
|
|
const snapAsOfMs = Date.parse(q.asOf);
|
|
const poisonedRows: TableRow[] = [
|
|
// 1. effective_known_at strictly after individual snapshot asOf (but before vaultCutoffTs)
|
|
{
|
|
listing_id: fixture.listingIds[0]!,
|
|
effective_known_at: snapAsOfMs + 60_000,
|
|
ttm_revenue: 999_999,
|
|
},
|
|
// 2. effective_known_at at exact vaultCutoffTs
|
|
{
|
|
listing_id: fixture.listingIds[1]!,
|
|
effective_known_at: fixture.vaultCutoffTs,
|
|
ttm_revenue: 888_888,
|
|
},
|
|
// 3. effective_known_at after vaultCutoffTs
|
|
{
|
|
listing_id: fixture.listingIds[2]!,
|
|
effective_known_at: fixture.vaultCutoffTs + 86_400_000,
|
|
ttm_revenue: 777_777,
|
|
},
|
|
// 4. unrequested listing_id
|
|
{
|
|
listing_id: 999_999,
|
|
effective_known_at: makeUtcMs(from, 12),
|
|
ttm_revenue: 666_666,
|
|
},
|
|
// 5. non-safe-integer effective_known_at (float & NaN)
|
|
{
|
|
listing_id: fixture.listingIds[3]!,
|
|
effective_known_at: makeUtcMs(from, 12) + 0.5,
|
|
ttm_revenue: 555_555,
|
|
},
|
|
{
|
|
listing_id: fixture.listingIds[3]!,
|
|
effective_known_at: Number.NaN,
|
|
ttm_revenue: 555_555,
|
|
},
|
|
// 6. null, NaN, and Infinity field values
|
|
{
|
|
listing_id: fixture.listingIds[4]!,
|
|
effective_known_at: makeUtcMs(from, 12),
|
|
ttm_revenue: null,
|
|
},
|
|
{
|
|
listing_id: fixture.listingIds[4]!,
|
|
effective_known_at: makeUtcMs(from, 12) + 1_000,
|
|
ttm_revenue: Number.NaN,
|
|
},
|
|
{
|
|
listing_id: fixture.listingIds[4]!,
|
|
effective_known_at: makeUtcMs(from, 12) + 2_000,
|
|
ttm_revenue: Number.POSITIVE_INFINITY,
|
|
},
|
|
];
|
|
return {
|
|
columns: cleanTable.columns,
|
|
rows: [...cleanTable.rows, ...poisonedRows],
|
|
};
|
|
},
|
|
});
|
|
|
|
const cleanLedger = createFakeTrialLedger();
|
|
const leakyLedger = createFakeTrialLedger();
|
|
const args = {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to: postCutoffDate,
|
|
asOf: postCutoffDate,
|
|
signal: { source: 'fundamentals', field: 'ttm_revenue' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const cleanRes = await callAnalyzeSignal({
|
|
store: cleanStore.store,
|
|
ledger: cleanLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args,
|
|
});
|
|
const leakyRes = await callAnalyzeSignal({
|
|
store: leakyStore.store,
|
|
ledger: leakyLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args,
|
|
});
|
|
|
|
expect(cleanRes.isError).toBe(false);
|
|
expect(leakyRes.isError).toBe(false);
|
|
expect(leakyRes.text).toBe(cleanRes.text);
|
|
expect(leakyLedger.rows).toEqual(cleanLedger.rows);
|
|
|
|
// Every fundamentalsAsOf call's asOf is strictly before vaultCutoffTs
|
|
expect(cleanStore.fundamentalsCalls.length).toBeGreaterThan(0);
|
|
for (const call of [...cleanStore.fundamentalsCalls, ...leakyStore.fundamentalsCalls]) {
|
|
expect(Date.parse(call.asOf)).toBeLessThan(fixture.vaultCutoffTs);
|
|
}
|
|
|
|
// Malformed fundamentals table -> sanitized SignalPanelError with zero ledger writes
|
|
const badTableStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
fundamentalsResolver: () => ({ columns: null, rows: null } as unknown as Table),
|
|
});
|
|
const badTableLedger = createFakeTrialLedger();
|
|
const badTableRes = await callAnalyzeSignal({
|
|
store: badTableStore.store,
|
|
ledger: badTableLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args,
|
|
});
|
|
expect(badTableRes.isError).toBe(true);
|
|
expect(badTableRes.text).toBe('SignalPanelError: Invalid signal panel input.');
|
|
expect(badTableLedger.rows).toHaveLength(0);
|
|
});
|
|
});
|