stock-bot/libs/data/duckdb/test/duckdb-market-data-store.test.ts

1542 lines
64 KiB
TypeScript

import { afterEach, describe, expect, test } from 'bun:test';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
computeVaultCutoffTs,
MarketDataStoreValidationError,
VaultHoldoutFenceError,
type BarRecord,
} from '@stock-bot/research/market-data-store';
import {
createEventStudyTool,
createMcpServer,
type EventStudyResultPayload,
} from '@stock-bot/research/mcp';
import type { TrialLedgerExecutor } from '@stock-bot/research/trial-ledger';
import {
createNodeDuckDbExecutor,
openDuckDbMarketDataStore,
} from '../src/index';
const tempDirs: string[] = [];
afterEach(async () => {
while (tempDirs.length > 0) {
const dir = tempDirs.pop();
if (dir !== undefined) {
await rm(dir, { recursive: true, force: true });
}
}
});
async function buildCuratedFixture(): Promise<{
curatedRoot: string;
duckTempDir: string;
vaultCutoffTs: number;
}> {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-mds-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(join(curatedRoot, 'bars_1d', 'year=2024'), { recursive: true });
await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true });
await mkdir(join(curatedRoot, 'adj_factors'), { recursive: true });
await mkdir(join(curatedRoot, 'events', 'year=2024'), { recursive: true });
await mkdir(join(curatedRoot, 'shorts'), { recursive: true });
await mkdir(join(curatedRoot, 'fx_1d'), { recursive: true });
await mkdir(duckTempDir, { recursive: true });
// Max ingested = 2025-08-13 -> Vault cutoff = 2025-02-13T00:00:00.000Z
const vaultCutoffTs = computeVaultCutoffTs('2025-08-13');
const vaultCutoffMicros = vaultCutoffTs * 1000;
const asOfMicros = vaultCutoffMicros - 1;
const writer = await createNodeDuckDbExecutor();
try {
// 2024 bars (pre-Vault): listing 101 (USD, NVDA 10:1 split on 2024-06-10) + listing 202 (CAD)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, DATE '2024-06-07', TIMESTAMPTZ '2024-06-07 20:00:00+00', 1200.0::DOUBLE, 1220.0::DOUBLE, 1190.0::DOUBLE, 1208.88::DOUBLE, 41238600.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-07 20:00:00+00'),
(101::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 120.37::DOUBLE, 123.10::DOUBLE, 117.01::DOUBLE, 121.79::DOUBLE, 314162700.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00'),
(202::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 140.0::DOUBLE, 142.0::DOUBLE, 139.0::DOUBLE, 141.5::DOUBLE, 1200000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00')
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
) TO '${join(curatedRoot, 'bars_1d', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
`);
// 2025 bars: one pre-Vault bar (2025-02-12) and one Vault bar (2025-02-14)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, DATE '2025-02-12', TIMESTAMPTZ '2025-02-12 20:00:00+00', 130.0::DOUBLE, 132.0::DOUBLE, 129.0::DOUBLE, 131.0::DOUBLE, 200000000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-12 20:00:00+00'),
(101::INTEGER, DATE '2025-02-14', TIMESTAMPTZ '2025-02-14 20:00:00+00', 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 1.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-14 20:00:00+00')
) 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)
`);
// Point-in-time fenced adj_factors snapshot (10:1 split on 2024-06-10)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, DATE '2024-06-10', 10.0::DOUBLE, 10.05::DOUBLE, TIMESTAMPTZ '2024-06-10 00:00:00+00')
) AS t(listing_id, ex_date, cum_split_factor, cum_total_factor, known_at)
) TO '${join(curatedRoot, 'adj_factors', 'part.parquet')}' (
FORMAT PARQUET,
KV_METADATA {
'stock_bot.adj_factors.format_version': '1',
'stock_bot.adj_factors.snapshot_kind': 'point_in_time_fenced',
'stock_bot.adj_factors.as_of_micros': '${asOfMicros}',
'stock_bot.adj_factors.vault_cutoff_micros': '${vaultCutoffMicros}',
'stock_bot.adj_factors.rows_written': '1',
'stock_bot.adj_factors.snapshot_checksum': '0x0123456789abcdef'
}
)
`);
// Events (2024 filing)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(202::INTEGER, TIMESTAMPTZ '2024-06-05 14:30:00+00', TIMESTAMPTZ '2024-06-05 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, 'MD&A'::VARCHAR, '{"filing_id":"f1"}'::VARCHAR)
) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json)
) TO '${join(curatedRoot, 'events', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
`);
// Canadian shorts (+4 biz day known_at)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(202::INTEGER, DATE '2024-06-15', TIMESTAMPTZ '2024-06-21 21:00:00+00', 500000.0::DOUBLE, 25000.0::DOUBLE, NULL::DOUBLE, 'ceo_shorts'::VARCHAR)
) AS t(listing_id, report_date, known_at, shares_short, net_change, pct_float, source)
) TO '${join(curatedRoot, 'shorts', 'part.parquet')}' (FORMAT PARQUET)
`);
// FX 1d (USDCAD)
await writer.run(`
COPY (
SELECT * FROM (VALUES
('USDCAD'::VARCHAR, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 23:59:59.999999+00', 1.375::DOUBLE, 1.378::DOUBLE, 1.372::DOUBLE, 1.376::DOUBLE, 'eod_forex'::VARCHAR, TIMESTAMPTZ '2024-06-10 23:59:59.999999+00')
) AS t(pair, session_date, ts, open, high, low, close, source, known_at)
) TO '${join(curatedRoot, 'fx_1d', 'part.parquet')}' (FORMAT PARQUET)
`);
} finally {
await writer.close();
}
return { curatedRoot, duckTempDir, vaultCutoffTs };
}
describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => {
test('reads real Parquet bars (raw, split, total), events, shorts, fx, universe and enforces Vault fence', async () => {
const { curatedRoot, duckTempDir, vaultCutoffTs } = await buildCuratedFixture();
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 {
// 1. Raw bars: request through 2025-12-31 must clamp before Vault cutoff (2025-02-13) and never return 2025-02-14!
const rawBars: BarRecord[] = [];
for await (const batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2024-06-01',
to: '2025-12-31',
adjustment: 'raw',
})) {
rawBars.push(...batch.rows);
}
expect(rawBars.length).toBe(3);
expect(rawBars.every(r => r.ts < vaultCutoffTs)).toBe(true);
expect(rawBars[0]!.close).toBeCloseTo(1208.88, 6);
expect(rawBars[0]!.volume).toBeCloseTo(41_238_600, 1);
// 2. Vault rejection when from >= vaultCutoffTs
let rejected = false;
try {
for await (const _batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2025-02-13',
to: '2025-08-01',
adjustment: 'raw',
})) {
// should not yield
}
} catch (err) {
rejected = err instanceof VaultHoldoutFenceError;
}
expect(rejected).toBe(true);
// 3. Split-adjusted bars via pinned point_in_time_fenced adj_factors snapshot
const splitBars: BarRecord[] = [];
for await (const batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})) {
splitBars.push(...batch.rows);
}
expect(splitBars.length).toBe(2);
expect(splitBars[0]!.close).toBeCloseTo(120.888, 6);
expect(splitBars[0]!.volume).toBeCloseTo(412_386_000, 1);
expect(splitBars[1]!.close).toBeCloseTo(121.79, 6);
// 4. Total-return-adjusted bars (price divided by cum_total_factor, volume scaled by cum_split_factor)
const totalBars: BarRecord[] = [];
for await (const batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'total',
})) {
totalBars.push(...batch.rows);
}
expect(totalBars.length).toBe(2);
expect(totalBars[0]!.close).toBeCloseTo(1208.88 / 10.05, 6);
expect(totalBars[0]!.volume).toBeCloseTo(412_386_000, 1);
// 5. Events
const events = await opened.store.events({
kinds: ['filing'],
listingIds: [202],
from: '2024-06-01',
to: '2024-06-30',
});
expect(events.rows.length).toBe(1);
expect(events.rows[0]!.subtype).toBe('MD&A');
// 6. Shorts (known_at fence)
const shortsBeforeKnown = await opened.store.shortsAsOf({
listingIds: [202],
from: '2024-06-01',
to: '2024-06-30',
asOf: '2024-06-18',
});
expect(shortsBeforeKnown.rows.length).toBe(0);
const shortsAfterKnown = await opened.store.shortsAsOf({
listingIds: [202],
from: '2024-06-01',
to: '2024-06-30',
asOf: '2024-06-25',
});
expect(shortsAfterKnown.rows.length).toBe(1);
expect(shortsAfterKnown.rows[0]!.shares_short).toBe(500_000);
// 7. FX
const fx = await opened.store.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-30',
});
expect(fx.rows.length).toBe(1);
expect(fx.rows[0]!.close).toBeCloseTo(1.376, 6);
// 8. Universe
expect(await opened.store.universe({ ref: 'US_EQ', date: '2024-06-10' })).toEqual([101]);
expect(await opened.store.universe({ ref: 'CA_EQ', date: '2024-06-10' })).toEqual([202]);
expect(await opened.store.universe({ ref: 'US_CA_EQ', date: '2024-06-10' })).toEqual([
101, 202,
]);
} finally {
await opened.close();
}
});
test('fundamentalsAsOf enforces restatement non-overwrite, multi-year Hive glob, Vault microsecond fence, and allowEstimatedLag semantics', async () => {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2023'), { recursive: true });
await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2024'), { recursive: true });
await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2025'), { recursive: true });
await mkdir(duckTempDir, { recursive: true });
// Vault cutoff = 2025-02-13T00:00:00.000Z
const vaultCutoffTs = computeVaultCutoffTs('2025-08-13');
const s1KnownMs = Date.UTC(2024, 4, 1, 20, 0, 0, 0); // 2024-05-01T20:00:00Z
const s2KnownMs = Date.UTC(2024, 7, 1, 20, 0, 0, 0); // 2024-08-01T20:00:00Z
const s3KnownMs = Date.UTC(2024, 8, 15, 20, 0, 0, 0); // 2024-09-15T20:00:00Z
const writer = await createNodeDuckDbExecutor();
try {
// year=2023 partition: listing 50 (only exists in 2023 partition)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(
50::INTEGER,
TIMESTAMPTZ '2023-11-05 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2023-09-30',
'Q3'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2023-11-05 20:00:00+00',
80.0::DOUBLE,
8.0::DOUBLE,
12.0::DOUBLE,
500.0::DOUBLE,
250.0::DOUBLE,
10.0::DOUBLE,
DATE '2023-09-30',
'USD'::VARCHAR,
310.0::DOUBLE,
31.0::DOUBLE,
46.0::DOUBLE,
FALSE::BOOLEAN
)
) AS t(
listing_id, effective_known_at, known_at_source, has_estimated_lag,
period_end, fiscal_period, currency, period_known_at,
revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding,
ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag
)
) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2023', 'part.parquet')}' (FORMAT PARQUET)
`);
// year=2024 partition:
// - listing 101: S1 (Q1), S2 (Q2), S3 (Q1 restatement known after Q2 -> latest period stays Q2, TTM changes)
// - listing 201: older verified snapshot + newer estimated-lag snapshot (strict mode must omit without fallback)
// - listing 202: verified snapshot with estimated-lag TTM only (strict mode keeps row, nulls ttm_* + ttm_period_end + ttm_currency, preserves ttm_has_estimated_lag)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(
101::INTEGER,
TIMESTAMPTZ '2024-05-01 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-03-31',
'Q1'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2024-05-01 20:00:00+00',
100.0::DOUBLE,
10.0::DOUBLE,
15.0::DOUBLE,
1000.0::DOUBLE,
500.0::DOUBLE,
50.0::DOUBLE,
DATE '2024-03-31',
'USD'::VARCHAR,
380.0::DOUBLE,
38.0::DOUBLE,
55.0::DOUBLE,
FALSE::BOOLEAN
),
(
101::INTEGER,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-06-30',
'Q2'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
120.0::DOUBLE,
14.0::DOUBLE,
20.0::DOUBLE,
1050.0::DOUBLE,
520.0::DOUBLE,
50.0::DOUBLE,
DATE '2024-06-30',
'USD'::VARCHAR,
420.0::DOUBLE,
44.0::DOUBLE,
65.0::DOUBLE,
FALSE::BOOLEAN
),
(
101::INTEGER,
TIMESTAMPTZ '2024-09-15 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-06-30',
'Q2'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
120.0::DOUBLE,
14.0::DOUBLE,
20.0::DOUBLE,
1050.0::DOUBLE,
520.0::DOUBLE,
50.0::DOUBLE,
DATE '2024-06-30',
'USD'::VARCHAR,
415.0::DOUBLE,
42.0::DOUBLE,
63.0::DOUBLE,
FALSE::BOOLEAN
),
(
201::INTEGER,
TIMESTAMPTZ '2024-05-01 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-03-31',
'Q1'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2024-05-01 20:00:00+00',
50.0::DOUBLE,
5.0::DOUBLE,
7.0::DOUBLE,
400.0::DOUBLE,
200.0::DOUBLE,
20.0::DOUBLE,
DATE '2024-03-31',
'USD'::VARCHAR,
190.0::DOUBLE,
19.0::DOUBLE,
27.0::DOUBLE,
FALSE::BOOLEAN
),
(
201::INTEGER,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
'estimated_lag'::VARCHAR,
TRUE::BOOLEAN,
DATE '2024-06-30',
'Q2'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
60.0::DOUBLE,
6.0::DOUBLE,
8.0::DOUBLE,
420.0::DOUBLE,
210.0::DOUBLE,
20.0::DOUBLE,
DATE '2024-06-30',
'USD'::VARCHAR,
210.0::DOUBLE,
21.0::DOUBLE,
30.0::DOUBLE,
TRUE::BOOLEAN
),
(
202::INTEGER,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-06-30',
'Q2'::VARCHAR,
'CAD'::VARCHAR,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
75.0::DOUBLE,
9.0::DOUBLE,
11.0::DOUBLE,
600.0::DOUBLE,
300.0::DOUBLE,
30.0::DOUBLE,
DATE '2024-06-30',
'CAD'::VARCHAR,
300.0::DOUBLE,
30.0::DOUBLE,
45.0::DOUBLE,
TRUE::BOOLEAN
)
) AS t(
listing_id, effective_known_at, known_at_source, has_estimated_lag,
period_end, fiscal_period, currency, period_known_at,
revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding,
ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag
)
) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
`);
// year=2025 partition: Vault microsecond boundary rows
// - listing 102: 1 microsecond before cutoff (eligible), exact cutoff (excluded), post-cutoff (excluded)
// - listing 103: exact cutoff only (must return 0 rows)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(
102::INTEGER,
TIMESTAMPTZ '2025-02-12 23:59:59.999999+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-12-31',
'Q4'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2025-02-12 23:59:59.999999+00',
210.0::DOUBLE,
21.0::DOUBLE,
31.0::DOUBLE,
1500.0::DOUBLE,
750.0::DOUBLE,
60.0::DOUBLE,
DATE '2024-12-31',
'USD'::VARCHAR,
800.0::DOUBLE,
80.0::DOUBLE,
120.0::DOUBLE,
FALSE::BOOLEAN
),
(
102::INTEGER,
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-12-31',
'Q4'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
999.0::DOUBLE,
99.0::DOUBLE,
99.0::DOUBLE,
9999.0::DOUBLE,
4999.0::DOUBLE,
60.0::DOUBLE,
DATE '2024-12-31',
'USD'::VARCHAR,
9999.0::DOUBLE,
999.0::DOUBLE,
999.0::DOUBLE,
FALSE::BOOLEAN
),
(
102::INTEGER,
TIMESTAMPTZ '2025-02-14 12:00:00.000000+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2025-03-31',
'Q1'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2025-02-14 12:00:00.000000+00',
1111.0::DOUBLE,
111.0::DOUBLE,
111.0::DOUBLE,
11111.0::DOUBLE,
5555.0::DOUBLE,
60.0::DOUBLE,
DATE '2025-03-31',
'USD'::VARCHAR,
11111.0::DOUBLE,
1111.0::DOUBLE,
1111.0::DOUBLE,
FALSE::BOOLEAN
),
(
103::INTEGER,
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-12-31',
'Q4'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
777.0::DOUBLE,
77.0::DOUBLE,
77.0::DOUBLE,
7777.0::DOUBLE,
3333.0::DOUBLE,
40.0::DOUBLE,
DATE '2024-12-31',
'USD'::VARCHAR,
7777.0::DOUBLE,
777.0::DOUBLE,
777.0::DOUBLE,
FALSE::BOOLEAN
)
) AS t(
listing_id, effective_known_at, known_at_source, has_estimated_lag,
period_end, fiscal_period, currency, period_known_at,
revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding,
ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag
)
) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2025', 'part.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 {
// 1. Before S1: no row for listing 101
const beforeS1 = await opened.store.fundamentalsAsOf({
listingIds: [101],
fields: ['revenue', 'ttm_revenue'],
asOf: '2024-04-30T23:59:59Z',
});
expect(beforeS1.rows).toEqual([]);
// 2. Between S1 and S2: Q1 row (revenue 100, ttm_revenue 380)
const betweenS1S2 = await opened.store.fundamentalsAsOf({
listingIds: [101],
fields: ['revenue', 'ttm_revenue'],
asOf: '2024-06-15',
});
expect(betweenS1S2.rows).toHaveLength(1);
expect(betweenS1S2.rows[0]).toEqual({
listing_id: 101,
effective_known_at: s1KnownMs,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-03-31',
fiscal_period: 'Q1',
currency: 'USD',
period_known_at: s1KnownMs,
revenue: 100,
ttm_revenue: 380,
ttm_period_end: '2024-03-31',
ttm_currency: 'USD',
ttm_has_estimated_lag: false,
});
// 3. Between S2 and S3: Q2 baseline (revenue 120, period_known_at = S2, pre-restatement TTM 420)
const betweenS2S3 = await opened.store.fundamentalsAsOf({
listingIds: [101],
fields: ['revenue', 'ttm_revenue'],
asOf: '2024-08-15',
});
expect(betweenS2S3.rows).toHaveLength(1);
expect(betweenS2S3.rows[0]).toEqual({
listing_id: 101,
effective_known_at: s2KnownMs,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-06-30',
fiscal_period: 'Q2',
currency: 'USD',
period_known_at: s2KnownMs,
revenue: 120,
ttm_revenue: 420,
ttm_period_end: '2024-06-30',
ttm_currency: 'USD',
ttm_has_estimated_lag: false,
});
// 4. At and after S3 (Q1 restatement with known_at > Q2): Q2 period_end, revenue, and period_known_at stay fixed while ttm_revenue updates to 415
for (const asOf of ['2024-09-15T20:00:00Z', '2024-10-01']) {
const afterS3 = await opened.store.fundamentalsAsOf({
listingIds: [101],
fields: ['revenue', 'ttm_revenue'],
asOf,
});
expect(afterS3.rows).toHaveLength(1);
expect(afterS3.rows[0]).toEqual({
listing_id: 101,
effective_known_at: s3KnownMs,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-06-30',
fiscal_period: 'Q2',
currency: 'USD',
period_known_at: s2KnownMs,
revenue: 120,
ttm_revenue: 415,
ttm_period_end: '2024-06-30',
ttm_currency: 'USD',
ttm_has_estimated_lag: false,
});
}
// 5. Multi-partition glob (year=2023 + year=2024) sorted by listing_id ASC, with non-TTM projection omitting TTM metadata columns
const multiYear = await opened.store.fundamentalsAsOf({
listingIds: [101, 50],
fields: ['revenue'],
asOf: '2024-10-01',
});
expect(multiYear.columns).toEqual([
'listing_id',
'effective_known_at',
'known_at_source',
'has_estimated_lag',
'period_end',
'fiscal_period',
'currency',
'period_known_at',
'revenue',
]);
expect(multiYear.rows.map(r => r.listing_id)).toEqual([50, 101]);
expect(multiYear.rows[0]!.period_end).toBe('2023-09-30');
expect(multiYear.rows[0]!.revenue).toBe(80);
expect(multiYear.rows[1]!.revenue).toBe(120);
// 6. Vault microsecond fence: last pre-cutoff microsecond is eligible; exact cutoff and post-cutoff are excluded
for (const asOf of ['2025-02-13T00:00:00.000Z', '2025-06-01']) {
const fenced = await opened.store.fundamentalsAsOf({
listingIds: [103, 102],
fields: ['revenue'],
asOf,
});
expect(fenced.rows).toHaveLength(1);
expect(fenced.rows[0]!.listing_id).toBe(102);
expect(fenced.rows[0]!.revenue).toBe(210);
expect(fenced.rows[0]!.period_end).toBe('2024-12-31');
}
// 7. allowEstimatedLag default (true) vs strict (false):
// - listing 201 (has_estimated_lag = true on latest snapshot) returned by default, omitted in strict mode without falling back to older verified Q1 row
// - listing 202 (has_estimated_lag = false, ttm_has_estimated_lag = true) kept in strict mode with all ttm_* values + ttm_period_end + ttm_currency nulled and ttm_has_estimated_lag preserved
const lagAllowed = await opened.store.fundamentalsAsOf({
listingIds: [202, 201],
fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'],
asOf: '2024-09-01',
});
expect(lagAllowed.rows.map(r => r.listing_id)).toEqual([201, 202]);
expect(lagAllowed.rows[0]!.revenue).toBe(60);
expect(lagAllowed.rows[0]!.has_estimated_lag).toBe(true);
expect(lagAllowed.rows[1]!.revenue).toBe(75);
expect(lagAllowed.rows[1]!.ttm_revenue).toBe(300);
expect(lagAllowed.rows[1]!.ttm_net_income).toBe(30);
expect(lagAllowed.rows[1]!.ttm_operating_cash_flow).toBe(45);
expect(lagAllowed.rows[1]!.ttm_period_end).toBe('2024-06-30');
expect(lagAllowed.rows[1]!.ttm_currency).toBe('CAD');
expect(lagAllowed.rows[1]!.ttm_has_estimated_lag).toBe(true);
const lagStrict = await opened.store.fundamentalsAsOf({
listingIds: [202, 201],
fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'],
asOf: '2024-09-01',
allowEstimatedLag: false,
});
expect(lagStrict.rows).toHaveLength(1);
expect(lagStrict.rows[0]).toEqual({
listing_id: 202,
effective_known_at: s2KnownMs,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-06-30',
fiscal_period: 'Q2',
currency: 'CAD',
period_known_at: s2KnownMs,
revenue: 75,
ttm_revenue: null,
ttm_net_income: null,
ttm_operating_cash_flow: null,
ttm_period_end: null,
ttm_currency: null,
ttm_has_estimated_lag: true,
});
} finally {
await opened.close();
}
});
});
interface FundamentalsFixtureRow {
readonly listingId: number;
readonly effectiveKnownAt: string;
readonly hasEstimatedLag?: boolean;
readonly periodEnd: string;
readonly fiscalPeriod: string;
readonly periodKnownAt?: string;
readonly revenue: number | null;
readonly ttmRevenue: number | null;
readonly ttmHasEstimatedLag: boolean | null;
}
function fundamentalsRowSql(r: FundamentalsFixtureRow): string {
const num = (v: number | null): string => (v === null ? 'NULL::DOUBLE' : `${v}::DOUBLE`);
const bool = (v: boolean | null): string => (v === null ? 'NULL::BOOLEAN' : `${v ? 'TRUE' : 'FALSE'}::BOOLEAN`);
const ttmMissing = r.ttmRevenue === null;
return `(
${r.listingId}::INTEGER, TIMESTAMPTZ '${r.effectiveKnownAt}', 'filing_date'::VARCHAR, ${bool(r.hasEstimatedLag ?? false)},
DATE '${r.periodEnd}', '${r.fiscalPeriod}'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${r.periodKnownAt ?? r.effectiveKnownAt}',
${num(r.revenue)}, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE,
${ttmMissing ? 'NULL::DATE' : `DATE '${r.periodEnd}'`}, ${ttmMissing ? 'NULL::VARCHAR' : `'USD'::VARCHAR`},
${num(r.ttmRevenue)}, NULL::DOUBLE, NULL::DOUBLE, ${bool(r.ttmHasEstimatedLag)}
)`;
}
async function writeFundamentalsPartition(
curatedRoot: string,
year: number,
rows: readonly FundamentalsFixtureRow[]
): Promise<void> {
const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`);
await mkdir(dir, { recursive: true });
const writer = await createNodeDuckDbExecutor();
try {
await writer.run(`
COPY (
SELECT * FROM (VALUES ${rows.map(fundamentalsRowSql).join(', ')}) AS t(
listing_id, effective_known_at, known_at_source, has_estimated_lag,
period_end, fiscal_period, currency, period_known_at,
revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding,
ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag
)
) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET)
`);
} finally {
await writer.close();
}
}
describe('openDuckDbMarketDataStore fundamentalsAsOf edge cases (@duckdb/node-api)', () => {
async function openFundamentalsStore(): Promise<Awaited<ReturnType<typeof openDuckDbMarketDataStore>>> {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-edge-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(duckTempDir, { recursive: true });
// Partition directory does not drive ranking: listing 7's newest snapshot sits in
// year=2023 while its older one sits in year=2024; listing 8 is the reverse.
await writeFundamentalsPartition(curatedRoot, 2023, [
{ listingId: 7, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 70, ttmRevenue: 270, ttmHasEstimatedLag: false },
{ listingId: 8, effectiveKnownAt: '2023-11-01 12:00:00+00', periodEnd: '2023-09-30', fiscalPeriod: 'Q3', revenue: 80, ttmRevenue: 300, ttmHasEstimatedLag: false },
]);
await writeFundamentalsPartition(curatedRoot, 2024, [
{ listingId: 7, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 65, ttmRevenue: 260, ttmHasEstimatedLag: false },
{ listingId: 8, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 85, ttmRevenue: 310, ttmHasEstimatedLag: false },
// Sub-millisecond neighbours: only the microsecond distinguishes them.
{ listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000500+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 90, ttmRevenue: 360, ttmHasEstimatedLag: false },
{ listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000501+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 91, ttmRevenue: 361, ttmHasEstimatedLag: false },
// Verified Q1, then estimated Q2.
{ listingId: 10, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 100, ttmRevenue: 400, ttmHasEstimatedLag: false },
{ listingId: 10, effectiveKnownAt: '2024-08-01 12:00:00+00', hasEstimatedLag: true, periodEnd: '2024-06-30', fiscalPeriod: 'Q2', revenue: 110, ttmRevenue: 410, ttmHasEstimatedLag: true },
// TTM-only estimated lag.
{ listingId: 11, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 111, ttmRevenue: 444, ttmHasEstimatedLag: true },
// No TTM yet (fewer than four quarters): TTM values and flag are NULL.
{ listingId: 12, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 12, ttmRevenue: null, ttmHasEstimatedLag: null },
]);
return openDuckDbMarketDataStore({
curatedRoot,
vaultCutoffTs: computeVaultCutoffTs('2025-08-13'),
env: {
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
STOCK_BOT_DUCKDB_THREADS: '2',
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
},
});
}
test('selects the latest effective_known_at across Hive partitions regardless of partition directory', async () => {
const opened = await openFundamentalsStore();
try {
const result = await opened.store.fundamentalsAsOf({
listingIds: [8, 7],
fields: ['revenue'],
asOf: '2024-06-01',
});
expect(result.rows.map(r => [r.listing_id, r.fiscal_period, r.revenue])).toEqual([
[7, 'Q1', 70],
[8, 'Q4', 85],
]);
const earlier = await opened.store.fundamentalsAsOf({
listingIds: [7, 8],
fields: ['revenue'],
asOf: '2024-01-01',
});
expect(earlier.rows.map(r => [r.listing_id, r.fiscal_period])).toEqual([[8, 'Q3']]);
} finally {
await opened.close();
}
});
test('binds explicit sub-millisecond asOf so microsecond-adjacent snapshots are separated', async () => {
const opened = await openFundamentalsStore();
try {
const at = async (asOf: string): Promise<unknown[]> =>
(await opened.store.fundamentalsAsOf({ listingIds: [9], fields: ['revenue'], asOf })).rows.map(
r => r.revenue
);
expect(await at('2024-03-01T12:00:00.000499Z')).toEqual([]);
expect(await at('2024-03-01T12:00:00.000500Z')).toEqual([90]);
expect(await at('2024-03-01T14:00:00.000500+02:00')).toEqual([90]);
expect(await at('2024-03-01T12:00:00.000501Z')).toEqual([91]);
} finally {
await opened.close();
}
});
test('strict allowEstimatedLag returns the verified snapshot that was latest at an earlier asOf, and omits the listing once an estimated snapshot is latest', async () => {
const opened = await openFundamentalsStore();
try {
const beforeEstimate = await opened.store.fundamentalsAsOf({
listingIds: [10],
fields: ['revenue'],
asOf: '2024-07-31',
allowEstimatedLag: false,
});
expect(beforeEstimate.rows.map(r => [r.fiscal_period, r.revenue])).toEqual([['Q1', 100]]);
const afterEstimate = await opened.store.fundamentalsAsOf({
listingIds: [10],
fields: ['revenue'],
asOf: '2024-08-02',
allowEstimatedLag: false,
});
expect(afterEstimate.rows).toEqual([]);
} finally {
await opened.close();
}
});
test('strict mode keeps TTM-estimated rows without TTM columns when no ttm_* field is requested, and passes through NULL TTM flags', async () => {
const opened = await openFundamentalsStore();
try {
const noTtm = await opened.store.fundamentalsAsOf({
listingIds: [11],
fields: ['revenue'],
asOf: '2024-06-01',
allowEstimatedLag: false,
});
expect(noTtm.columns).not.toContain('ttm_has_estimated_lag');
expect(noTtm.rows).toEqual([
expect.objectContaining({ listing_id: 11, revenue: 111, has_estimated_lag: false }),
]);
expect(Object.keys(noTtm.rows[0]!)).toEqual(noTtm.columns as string[]);
const nullTtm = await opened.store.fundamentalsAsOf({
listingIds: [12, 11],
fields: ['ttm_revenue'],
asOf: '2024-06-01',
allowEstimatedLag: false,
});
expect(nullTtm.rows.map(r => [r.listing_id, r.ttm_revenue, r.ttm_period_end, r.ttm_currency, r.ttm_has_estimated_lag])).toEqual([
[11, null, null, null, true],
[12, null, null, null, null],
]);
} finally {
await opened.close();
}
});
test('returns only requested listings and is reproducible across repeated identical queries', async () => {
const opened = await openFundamentalsStore();
try {
const q = {
listingIds: [12, 999, 7],
fields: ['ttm_revenue', 'revenue'],
asOf: '2024-09-01T00:00:00.000001Z',
};
const first = await opened.store.fundamentalsAsOf(q);
const second = await opened.store.fundamentalsAsOf(q);
expect(first.rows.map(r => r.listing_id)).toEqual([7, 12]);
expect(second).toEqual(first);
} finally {
await opened.close();
}
});
});
function createInMemoryTrialLedger(): TrialLedgerExecutor {
const rows: Array<Record<string, unknown>> = [];
let nextTrialId = 1;
return {
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
const trimmed = text.trimStart();
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
const p = params ?? [];
const trialId = String(nextTrialId++);
const createdAt = new Date(Date.UTC(2024, 5, 20, 12, 0, nextTrialId));
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
const stored = {
trial_id: 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')) {
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 };
},
};
}
describe('co-published events (part.parquet + part-posts.parquet) via real DuckDB & MCP event_study', () => {
test('queries filing, earnings, and edited ceo_post together with PIT known_at anchoring and Vault isolation', async () => {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-events-copub-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(join(curatedRoot, 'bars_1d', 'year=2024'), { recursive: true });
await mkdir(join(curatedRoot, 'events', 'year=2024'), { recursive: true });
await mkdir(duckTempDir, { recursive: true });
// Max ingested = 2025-08-13 -> Vault cutoff = 2025-02-13T00:00:00.000Z
const vaultCutoffTs = computeVaultCutoffTs('2025-08-13');
const sessions = [
'2024-06-03',
'2024-06-04',
'2024-06-05',
'2024-06-06',
'2024-06-07',
'2024-06-10',
'2024-06-11',
'2024-06-12',
'2024-06-13',
'2024-06-14',
];
// Deterministic close paths:
// listing 101: +2% on 06-05 (filing), +3% on 06-07 (earnings), +1% on 06-11 (filing)
// listing 202: +4% on 06-06 (filing), +5% on 06-10 (earnings), 0% on 06-12 (posted_at), +10% on 06-13 (known_at anchor)
const closes101 = [100, 101, 103.02, 103.02, 106.1106, 106.1106, 107.171706, 107.171706, 107.171706, 107.171706];
const closes202 = [100, 100, 100, 104, 104, 109.2, 109.2, 109.2, 120.12, 120.12];
const barValues: string[] = [];
for (let i = 0; i < sessions.length; i += 1) {
const d = sessions[i]!;
const c1 = closes101[i]!;
const c2 = closes202[i]!;
barValues.push(
`(101::INTEGER, DATE '${d}', TIMESTAMPTZ '${d} 20:00:00+00', ${c1}::DOUBLE, ${c1}::DOUBLE, ${c1}::DOUBLE, ${c1}::DOUBLE, 100000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '${d} 20:00:00+00')`,
`(202::INTEGER, DATE '${d}', TIMESTAMPTZ '${d} 20:00:00+00', ${c2}::DOUBLE, ${c2}::DOUBLE, ${c2}::DOUBLE, ${c2}::DOUBLE, 100000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '${d} 20:00:00+00')`
);
}
const writer = await createNodeDuckDbExecutor();
try {
await writer.run(`
COPY (
SELECT * FROM (VALUES
${barValues.join(',\n ')}
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
) TO '${join(curatedRoot, 'bars_1d', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
`);
// Co-published filings & earnings in events/year=2024/part.parquet
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, TIMESTAMPTZ '2024-06-05 14:30:00+00', TIMESTAMPTZ '2024-06-05 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, '8-k'::VARCHAR, '{"filing_id":"f1"}'::VARCHAR),
(202::INTEGER, TIMESTAMPTZ '2024-06-06 14:30:00+00', TIMESTAMPTZ '2024-06-06 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, '8-k'::VARCHAR, '{"filing_id":"f2"}'::VARCHAR),
(101::INTEGER, TIMESTAMPTZ '2024-06-07 14:30:00+00', TIMESTAMPTZ '2024-06-07 14:30:00+00', 'filing_timestamp'::VARCHAR, 'earnings'::VARCHAR, 'bto'::VARCHAR, '{"quarter":"Q1"}'::VARCHAR),
(202::INTEGER, TIMESTAMPTZ '2024-06-10 14:30:00+00', TIMESTAMPTZ '2024-06-10 14:30:00+00', 'filing_timestamp'::VARCHAR, 'earnings'::VARCHAR, 'bto'::VARCHAR, '{"quarter":"Q1"}'::VARCHAR),
(101::INTEGER, TIMESTAMPTZ '2024-06-11 14:30:00+00', TIMESTAMPTZ '2024-06-11 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, 'md&a'::VARCHAR, '{"filing_id":"f3"}'::VARCHAR)
) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json)
) TO '${join(curatedRoot, 'events', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
`);
// Co-published ceoPosts in events/year=2024/part-posts.parquet:
// 1. Edited ceo_post: posted 2024-06-12 15:00 UTC (11:00 EDT, BEFORE 16:00 ET close),
// edited 2024-06-12 21:30 UTC (17:30 EDT, AFTER 16:00 ET close) -> anchors to 2024-06-13.
// 2. Post-cutoff Vault holdout row: ts in 2024, known_at = 2025-02-14 >= vaultCutoffTs.
await writer.run(`
COPY (
SELECT * FROM (VALUES
(202::INTEGER, TIMESTAMPTZ '2024-06-12 15:00:00+00', TIMESTAMPTZ '2024-06-12 21:30:00+00', 'post_edited'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"sp-edit-1","user_id":"u1","is_edited":true,"source":"ceo_posts","text":"edited after close"}'::VARCHAR),
(202::INTEGER, TIMESTAMPTZ '2024-12-30 15:00:00+00', TIMESTAMPTZ '2025-02-14 15:00:00+00', 'post_edited'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"sp-vault-1","user_id":"u2","is_edited":true,"source":"ceo_posts","text":"vault holdout"}'::VARCHAR)
) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json)
) TO '${join(curatedRoot, 'events', 'year=2024', 'part-posts.parquet')}' (FORMAT PARQUET)
`);
} finally {
await writer.close();
}
// Place dummy transient files (.tmp, .bak, .write.lock) to prove events/year=*/*.parquet ignores them.
await writeFile(join(curatedRoot, 'events', 'year=2024', 'part.parquet.99999-0.tmp'), 'not-parquet');
await writeFile(join(curatedRoot, 'events', 'year=2024', 'part.parquet.99999-0.bak'), 'not-parquet');
await writeFile(join(curatedRoot, 'events', '.write.lock'), '99999\n');
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 {
// 1. store.events with asOf < edited hides the edited ceo_post.
const beforeEdit = await opened.store.events({
kinds: ['filing', 'earnings', 'ceo_post'],
from: '2024-06-01',
to: '2024-12-31',
asOf: '2024-06-12T21:00:00Z',
});
expect(beforeEdit.rows.length).toBe(5);
expect(beforeEdit.rows.map(r => r.kind)).toEqual([
'filing',
'earnings',
'filing',
'filing',
'earnings',
]);
// 2. store.events with asOf >= edited returns filing, earnings, and edited ceo_post together,
// while excluding the post-cutoff Vault row (known_at = 2025-02-14 >= vaultCutoffTs).
const afterEdit = await opened.store.events({
kinds: ['filing', 'earnings', 'ceo_post'],
from: '2024-06-01',
to: '2024-12-31',
asOf: '2025-02-12T23:59:59Z',
});
expect(afterEdit.rows.length).toBe(6);
expect(afterEdit.rows.map(r => [r.listing_id, r.kind, r.known_at_source])).toEqual([
[101, 'filing', 'filing_timestamp'],
[101, 'earnings', 'filing_timestamp'],
[101, 'filing', 'filing_timestamp'],
[202, 'filing', 'filing_timestamp'],
[202, 'earnings', 'filing_timestamp'],
[202, 'ceo_post', 'post_edited'],
]);
const postRow = afterEdit.rows[5]!;
expect(postRow.ts).toBe(Date.parse('2024-06-12T15:00:00.000Z'));
expect(postRow.known_at).toBe(Date.parse('2024-06-12T21:30:00.000Z'));
expect(afterEdit.rows.some(r => String(r.payload_json).includes('sp-vault-1'))).toBe(false);
// 3. MCP event_study over real DuckDB store:
// - asOf < edited excludes the edited ceo_post (5 events, offset-0 AAR = 0.15 / 5 = 0.03)
// - asOf >= edited includes all 6 events and anchors the post-close edit to 2024-06-13
// (+10% return -> offset-0 AAR = 0.25 / 6, NOT 0.15 / 6 from 2024-06-12's 0% return).
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}T20:00:00.000Z`) })),
},
listingCalendarId: { 101: 'XTSE', 202: 'XTSE' },
}),
});
const server = createMcpServer({ name: 'test-copub-mcp', version: '0.1.0', tools: [tool] });
const runStudy = async (asOf: string, id: number): Promise<EventStudyResultPayload> => {
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id,
method: 'tools/call',
params: {
name: 'event_study',
arguments: {
listingIds: [101, 202],
from: '2024-06-03',
to: '2024-06-14',
asOf,
event: { kinds: ['filing', 'earnings', '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 };
};
expect(rpc.result.isError).not.toBe(true);
return JSON.parse(rpc.result.content[0]!.text) as EventStudyResultPayload;
};
const studyBeforeEdit = await runStudy('2024-06-12T21:00:00Z', 1);
expect(studyBeforeEdit.status).toBe('ok');
expect(studyBeforeEdit.eventCount).toBe(5);
expect(studyBeforeEdit.study.diagnostics.eventsUsed).toBe(5);
expect(studyBeforeEdit.study.clustered?.nDates).toBe(5);
const aar0Before = studyBeforeEdit.study.offsets.find(o => o.offset === 0)!.aar;
expect(aar0Before).toBeCloseTo(0.15 / 5, 10);
const studyAfterEdit = await runStudy('2024-06-14T23:59:59Z', 2);
expect(studyAfterEdit.status).toBe('ok');
expect(studyAfterEdit.eventCount).toBe(6);
expect(studyAfterEdit.study.diagnostics.eventsUsed).toBe(6);
expect(studyAfterEdit.study.clustered?.nDates).toBe(6);
const aar0After = studyAfterEdit.study.offsets.find(o => o.offset === 0)!.aar;
// Anchoring to 2024-06-13 (+10%) yields 0.25 / 6; anchoring to 2024-06-12 (0%) would yield 0.15 / 6.
expect(aar0After).toBeCloseTo(0.25 / 6, 10);
} finally {
await opened.close();
}
});
});
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();
}
});
});
describe('macroAsOf and crossSection via real DuckDB', () => {
test('macroAsOf enforces country/indicator/date filtering, known_at <= asOf lag, Vault fence, and fail-closed provenance', async () => {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-macro-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(join(curatedRoot, 'macro'), { recursive: true });
await mkdir(duckTempDir, { recursive: true });
const vaultCutoffTs = Date.UTC(2025, 4, 1, 0, 0, 0, 0); // 2025-05-01T00:00:00Z
const writer = await createNodeDuckDbExecutor();
try {
await writer.run(`
COPY (
SELECT * FROM (VALUES
('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-02-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.50::DOUBLE),
('US'::VARCHAR, 'cpi_yoy'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-03-07 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 3.00::DOUBLE),
('CA'::VARCHAR, 'gdp_qoq'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-04-06 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 1.80::DOUBLE),
('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-04-30', TIMESTAMPTZ '2025-05-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.25::DOUBLE)
) AS t(country_iso, indicator, period_date, known_at, known_at_source, value)
) TO '${join(curatedRoot, 'macro', 'part.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 {
// Early asOf sees +1d policy_rate, hides +35d cpi_yoy and +65d gdp_qoq.
const feb = await opened.store.macroAsOf({
countries: ['US', 'CA'],
indicators: ['policy_rate', 'cpi_yoy', 'gdp_qoq'],
from: '2025-01-01',
to: '2025-06-01',
asOf: '2025-02-15',
});
expect(feb.rows.map(r => `${r.country_iso}:${r.indicator}`)).toEqual(['US:policy_rate']);
// Post-cutoff to/asOf clamps strictly below 2025-05-01T00:00:00Z, hiding the at-cutoff row.
const clamped = await opened.store.macroAsOf({
countries: ['US', 'CA'],
indicators: ['policy_rate', 'cpi_yoy', 'gdp_qoq'],
from: '2025-01-01',
to: '2025-06-01',
asOf: '2025-06-01',
});
expect(clamped.rows.map(r => `${r.country_iso}:${r.indicator}:${r.period_date}`)).toEqual([
'CA:gdp_qoq:2025-01-31',
'US:cpi_yoy:2025-01-31',
'US:policy_rate:2025-01-31',
]);
// from >= vaultCutoffTs throws VaultHoldoutFenceError.
await expect(
opened.store.macroAsOf({
countries: ['US'],
indicators: ['policy_rate'],
from: '2025-05-01',
to: '2025-05-15',
})
).rejects.toBeInstanceOf(VaultHoldoutFenceError);
} finally {
await opened.close();
}
// Corrupt provenance row fails closed with MarketDataStoreValidationError.
const corruptRoot = join(root, 'corrupt-curated');
await mkdir(join(corruptRoot, 'macro'), { recursive: true });
const corruptWriter = await createNodeDuckDbExecutor();
try {
await corruptWriter.run(`
COPY (
SELECT * FROM (VALUES
('US'::VARCHAR, 'cpi_yoy'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-03-07 00:00:00+00', 'bad_source'::VARCHAR, 3.00::DOUBLE)
) AS t(country_iso, indicator, period_date, known_at, known_at_source, value)
) TO '${join(corruptRoot, 'macro', 'part.parquet')}' (FORMAT PARQUET)
`);
} finally {
await corruptWriter.close();
}
const corruptOpened = await openDuckDbMarketDataStore({
curatedRoot: corruptRoot,
vaultCutoffTs,
env: {
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
STOCK_BOT_DUCKDB_THREADS: '2',
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
},
});
try {
await expect(
corruptOpened.store.macroAsOf({
countries: ['US'],
indicators: ['cpi_yoy'],
from: '2025-01-01',
to: '2025-04-01',
})
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
} finally {
await corruptOpened.close();
}
});
test('crossSection joins versioned features to survivorship-free universe, null-fills missing/delayed rows, and enforces Vault fence', async () => {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-xsec-'));
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, 'features', 'ret_1d', 'v1', 'year=2025'), { recursive: true });
await mkdir(join(curatedRoot, 'features', 'rsi_14', 'v1', 'year=2025'), { recursive: true });
await mkdir(duckTempDir, { recursive: true });
const vaultCutoffTs = Date.UTC(2025, 4, 15, 0, 0, 0, 0); // 2025-05-15T00:00:00Z
const writer = await createNodeDuckDbExecutor();
try {
// Active on 2025-05-10: 101 (USD), 102 (USD), 201 (CAD). Delisted earlier: 103 (USD, 2025-04-01).
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 10.0::DOUBLE, 11.0::DOUBLE, 9.5::DOUBLE, 10.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00'),
(102::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 20.0::DOUBLE, 21.0::DOUBLE, 19.5::DOUBLE, 20.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00'),
(103::INTEGER, DATE '2025-04-01', TIMESTAMPTZ '2025-04-01 20:00:00+00', 5.0::DOUBLE, 5.5::DOUBLE, 4.5::DOUBLE, 5.0::DOUBLE, 500.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-04-01 20:00:00+00'),
(201::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 30.0::DOUBLE, 31.0::DOUBLE, 29.5::DOUBLE, 30.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00')
) 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)
`);
// ret_1d@v1: 101 known on 2025-05-09; 102 delayed until 2025-05-12; 201 known on 2025-05-09.
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', 0.02::DOUBLE),
(102::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-12 20:00:00+00', 0.05::DOUBLE),
(201::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', -0.01::DOUBLE)
) AS t(listing_id, ts, known_at, value)
) TO '${join(curatedRoot, 'features', 'ret_1d', 'v1', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
`);
// rsi_14@v1: only listing 101 present.
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', 62.5::DOUBLE)
) AS t(listing_id, ts, known_at, value)
) TO '${join(curatedRoot, 'features', 'rsi_14', 'v1', 'year=2025', 'part.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 {
// Omitted asOf defaults to q.date (2025-05-09) so 102's delayed ret_1d (known 2025-05-12) is NULL.
const usSameDay = await opened.store.crossSection({
features: ['ret_1d@v1', 'rsi_14@v1'],
date: '2025-05-09',
universe: 'US_EQ',
});
expect(usSameDay.columns).toEqual(['listing_id', 'ret_1d@v1', 'rsi_14@v1']);
expect(usSameDay.rows).toEqual([
{ listing_id: 101, 'ret_1d@v1': 0.02, 'rsi_14@v1': 62.5 },
{ listing_id: 102, 'ret_1d@v1': null, 'rsi_14@v1': null },
]);
// Explicit later asOf (2025-05-13) reveals 102's delayed ret_1d@v1 while US_CA_EQ includes 201.
const usCaLater = await opened.store.crossSection({
features: ['ret_1d@v1', 'rsi_14@v1'],
date: '2025-05-09',
universe: 'US_CA_EQ',
asOf: '2025-05-13',
});
expect(usCaLater.rows).toEqual([
{ listing_id: 101, 'ret_1d@v1': 0.02, 'rsi_14@v1': 62.5 },
{ listing_id: 102, 'ret_1d@v1': 0.05, 'rsi_14@v1': null },
{ listing_id: 201, 'ret_1d@v1': -0.01, 'rsi_14@v1': null },
]);
// Post-cutoff date throws VaultHoldoutFenceError.
await expect(
opened.store.crossSection({
features: ['ret_1d@v1'],
date: '2025-05-15',
universe: 'US_EQ',
})
).rejects.toBeInstanceOf(VaultHoldoutFenceError);
} finally {
await opened.close();
}
});
});