T-209: tests

This commit is contained in:
Studio 2026-12-04 14:38:13 -05:00
parent 1eddd86850
commit e6bc956e49
2 changed files with 169 additions and 0 deletions

View file

@ -1198,3 +1198,136 @@ describe('co-published events (part.parquet + part-posts.parquet) via real DuckD
} }
}); });
}); });
describe('co-published ceo_post Vault boundary via real DuckDB (store.events + MCP event_study)', () => {
test('posts-only partition is read; known_at/ts at the cutoff are fenced; from >= cutoff is rejected', async () => {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-events-vault-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true });
await mkdir(join(curatedRoot, 'events', 'year=2025'), { recursive: true });
await mkdir(duckTempDir, { recursive: true });
// Vault cutoff = 2025-02-13T00:00:00.000Z
const vaultCutoffTs = computeVaultCutoffTs('2025-08-13');
expect(vaultCutoffTs).toBe(Date.parse('2025-02-13T00:00:00.000Z'));
const sessions = ['2025-02-06', '2025-02-07', '2025-02-10', '2025-02-11', '2025-02-12'];
const writer = await createNodeDuckDbExecutor();
try {
const barValues = sessions.map(
d =>
`(303::INTEGER, DATE '${d}', TIMESTAMPTZ '${d} 21:00:00+00', 10.0::DOUBLE, 10.0::DOUBLE, 10.0::DOUBLE, 10.0::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '${d} 21:00:00+00')`
);
await writer.run(`
COPY (
SELECT * FROM (VALUES ${barValues.join(',')}) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
`);
// Posts-only year partition: no events/year=2025/part.parquet exists at all.
await writer.run(`
COPY (
SELECT * FROM (VALUES
(303::INTEGER, TIMESTAMPTZ '2025-02-10 15:00:00+00', TIMESTAMPTZ '2025-02-10 15:00:00+00', 'post_timestamp'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"in-1"}'::VARCHAR),
(303::INTEGER, TIMESTAMPTZ '2025-02-12 15:00:00+00', TIMESTAMPTZ '2025-02-12 23:59:59.999+00', 'post_edited'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"edge-in"}'::VARCHAR),
(303::INTEGER, TIMESTAMPTZ '2025-02-12 16:00:00+00', TIMESTAMPTZ '2025-02-13 00:00:00+00', 'post_edited'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"edge-known-at-cutoff"}'::VARCHAR),
(303::INTEGER, TIMESTAMPTZ '2025-02-13 00:00:00+00', TIMESTAMPTZ '2025-02-13 00:00:00+00', 'post_timestamp'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"edge-ts-at-cutoff"}'::VARCHAR)
) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json)
) TO '${join(curatedRoot, 'events', 'year=2025', 'part-posts.parquet')}' (FORMAT PARQUET)
`);
} finally {
await writer.close();
}
const opened = await openDuckDbMarketDataStore({
curatedRoot,
vaultCutoffTs,
env: {
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
STOCK_BOT_DUCKDB_THREADS: '2',
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
},
});
try {
// asOf and to both beyond the cutoff: the fence clamps them to cutoff - 1 ms, so only rows with
// ts < cutoff AND known_at < cutoff survive (the edit landing exactly on the cutoff is hidden).
const clamped = await opened.store.events({
kinds: ['ceo_post'],
from: '2025-01-01',
to: '2025-12-31',
asOf: '2025-08-01T00:00:00Z',
});
expect(
clamped.rows.map(r => (JSON.parse(String(r.payload_json)) as { spiel_id: string }).spiel_id)
).toEqual(['in-1', 'edge-in']);
expect(clamped.rows.every(r => r.ts < vaultCutoffTs && r.known_at < vaultCutoffTs)).toBe(true);
// Omitted asOf behaves the same way (defaults to cutoff - 1 ms).
const defaulted = await opened.store.events({
kinds: ['ceo_post', 'filing', 'earnings'],
from: '2025-01-01',
to: '2025-12-31',
});
expect(defaulted.rows.length).toBe(2);
// Requests starting at the cutoff are rejected, not silently empty.
let rejectedError: unknown;
try {
await opened.store.events({ kinds: ['ceo_post'], from: '2025-02-13', to: '2025-03-01' });
} catch (err) {
rejectedError = err;
}
expect(rejectedError).toBeInstanceOf(VaultHoldoutFenceError);
const tool = createEventStudyTool({
store: opened.store,
ledger: createInMemoryTrialLedger(),
vaultContext: { vaultCutoffTs },
principalId: 'agent:11111111-2222-4333-8444-555555555555',
resolveExchangeCalendars: q => ({
calendars: {
XTSE: sessions
.filter(date => date >= q.fromDate && date <= q.toDate)
.map(date => ({ date, closeTs: Date.parse(`${date}T21:00:00.000Z`) })),
},
listingCalendarId: { 303: 'XTSE' },
}),
});
const server = createMcpServer({ name: 'test-vault-mcp', version: '0.1.0', tools: [tool] });
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'event_study',
arguments: {
listingIds: [303],
from: '2025-02-13',
to: '2025-03-01',
event: { kinds: ['ceo_post'] },
preDays: 1,
postDays: 1,
benchmark: 'none',
adjustment: 'raw',
universeMarket: 'CA_EQ',
horizonBucket: 'swing_1_10d',
},
},
})
);
const rpc = JSON.parse(raw!) as {
result?: { content: Array<{ type: string; text: string }>; isError?: boolean };
error?: { message: string };
};
// MCP must refuse a study window that starts inside the Vault (JSON-RPC error or tool error),
// never return an 'ok' study, and never leak the at-cutoff post.
expect(rpc.error !== undefined || rpc.result?.isError === true).toBe(true);
expect(raw!).not.toContain('edge-ts-at-cutoff');
expect(raw!).not.toContain('edge-known-at-cutoff');
} finally {
await opened.close();
}
});
});

View file

@ -816,3 +816,39 @@ fn post_2200_timestamp_is_preserved_by_adapter_and_rejected_by_writer() {
); );
assert!(!dir.path().join("events/year=2201").exists()); assert!(!dir.path().join("events/year=2201").exists());
} }
/// Regression for T-209: the curated `ceoPosts` kind must be one of the `EventKind` values the
/// downstream TypeScript and Python readers accept. With the old `"post"` label every curated post
/// was unreachable through `store.events` / MCP `event_study` because `validateEventKinds` rejects
/// unknown kinds and no reader can request `"post"`.
#[test]
fn event_kind_post_is_accepted_by_ts_and_python_event_kind_contracts() {
const TS_READER: &str = include_str!("../../../libs/research/src/market-data-store-duckdb.ts");
const TS_CONTRACT: &str = include_str!("../../../libs/research/src/market-data-store.ts");
const PY_READER: &str = include_str!("../../../python/stockbot/data.py");
let ts_kinds_line = TS_READER
.lines()
.find(|l| l.starts_with("export const EVENT_KINDS"))
.expect("EVENT_KINDS declaration in market-data-store-duckdb.ts");
let ts_type_line = TS_CONTRACT
.lines()
.find(|l| l.starts_with("export type EventKind"))
.expect("EventKind type in market-data-store.ts");
let py_line = PY_READER
.lines()
.find(|l| l.starts_with("EventKind = Literal["))
.expect("EventKind Literal in python/stockbot/data.py");
let quoted_single = format!("'{EVENT_KIND_POST}'");
let quoted_double = format!("\"{EVENT_KIND_POST}\"");
assert!(ts_kinds_line.contains(&quoted_single), "TS EVENT_KINDS lacks {quoted_single}: {ts_kinds_line}");
assert!(ts_type_line.contains(&quoted_single), "TS EventKind lacks {quoted_single}: {ts_type_line}");
assert!(py_line.contains(&quoted_double), "Python EventKind lacks {quoted_double}: {py_line}");
// Both readers must glob every `.parquet` sibling in a year partition so the posts file
// (`part-posts.parquet`) is read alongside filings/earnings (`part.parquet`).
assert!(TS_READER.contains("'events/year=*/*.parquet'"));
assert!(PY_READER.contains("/events/year=*/*.parquet"));
assert!(!PY_READER.contains("/events/year=*/part.parquet"));
}