import { describe, expect, it } from 'bun:test'; import { type BarBatch, type BarRecord, type DuckDbExecutor, type DuckDbParam, type MarketDataStore, MarketDataStoreNotImplementedError, MarketDataStoreValidationError, type QuestDbQueryExecutor, type RoutedMarketDataStoreOptions, type Table, type TableRow, createDuckDbMarketDataStore, createQuestDbIntradayBarsReader, createRoutedMarketDataStore, } from '@stock-bot/research'; import { createQuestDbIntradayBarsReader as subpathCreateQuestDbIntradayBarsReader } from '@stock-bot/research/market-data-store-questdb'; import { createRoutedMarketDataStore as subpathCreateRoutedMarketDataStore } from '@stock-bot/research/market-data-store-routed'; import { type QueryDataResultPayload, createMcpServer, createQueryDataTool, } from '../src/mcp/index'; type BarsQuery = Parameters[0]; type CrossSectionQuery = Parameters[0]; type FundamentalsQuery = Parameters[0]; type EventsQuery = Parameters[0]; type ShortsQuery = Parameters[0]; type MacroQuery = Parameters[0]; type FxQuery = Parameters[0]; type UniverseQuery = Parameters[0]; const LISTING_ID = 42; const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z const VAULT_CUTOFF_US = VAULT_CUTOFF_TS * 1000; const CLAMPED_END_ISO = '2025-06-30T23:59:59.999Z'; const CURATED_ROOT = '/mnt/data/stockbot/curated'; function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { return { listingId, ts, open: close - 0.5, high: close + 0.5, low: close - 1, close, volume: 1_000, vwap: close, knownAt, }; } async function collectBatches(iterable: AsyncIterable): Promise { const batches: BarBatch[] = []; for await (const batch of iterable) { batches.push(batch); } return batches; } class PrototypeDailyStore implements MarketDataStore { readonly calls: { method: keyof MarketDataStore; arg: unknown }[] = []; readonly returnedPromises = new Map>(); readonly barsBatches: BarBatch[]; constructor(barsBatches: BarBatch[] = []) { this.barsBatches = barsBatches; } private assertReceiver(): void { if (!(this instanceof PrototypeDailyStore)) { throw new Error('Lost daily receiver (`this`).'); } } bars(q: BarsQuery): AsyncIterable { this.assertReceiver(); this.calls.push({ method: 'bars', arg: q }); const batches = this.barsBatches; return { async *[Symbol.asyncIterator]() { for (const batch of batches) { yield batch; } }, }; } crossSection(q: CrossSectionQuery): Promise { this.assertReceiver(); this.calls.push({ method: 'crossSection', arg: q }); const p = Promise.resolve
({ columns: ['listing_id'], rows: [{ listing_id: 42 }] }); this.returnedPromises.set('crossSection', p); return p; } fundamentalsAsOf(q: FundamentalsQuery): Promise
{ this.assertReceiver(); this.calls.push({ method: 'fundamentalsAsOf', arg: q }); const p = Promise.resolve
({ columns: ['listing_id', 'revenue'], rows: [] }); this.returnedPromises.set('fundamentalsAsOf', p); return p; } events(q: EventsQuery): Promise
{ this.assertReceiver(); this.calls.push({ method: 'events', arg: q }); const p = Promise.resolve
({ columns: ['listing_id', 'kind'], rows: [] }); this.returnedPromises.set('events', p); return p; } shortsAsOf(q: ShortsQuery): Promise
{ this.assertReceiver(); this.calls.push({ method: 'shortsAsOf', arg: q }); const p = Promise.resolve
({ columns: ['listing_id', 'shares_short'], rows: [] }); this.returnedPromises.set('shortsAsOf', p); return p; } macroAsOf(q: MacroQuery): Promise
{ this.assertReceiver(); this.calls.push({ method: 'macroAsOf', arg: q }); const p = Promise.resolve
({ columns: ['country', 'value'], rows: [] }); this.returnedPromises.set('macroAsOf', p); return p; } fx(q: FxQuery): Promise
{ this.assertReceiver(); this.calls.push({ method: 'fx', arg: q }); const p = Promise.resolve
({ columns: ['pair', 'close'], rows: [] }); this.returnedPromises.set('fx', p); return p; } universe(q: UniverseQuery): Promise { this.assertReceiver(); this.calls.push({ method: 'universe', arg: q }); const p = Promise.resolve([42, 101]); this.returnedPromises.set('universe', p); return p; } } class PrototypeIntradayReader implements Pick { readonly calls: BarsQuery[] = []; readonly barsBatches: BarBatch[]; constructor(barsBatches: BarBatch[] = []) { this.barsBatches = barsBatches; } bars(q: BarsQuery): AsyncIterable { if (!(this instanceof PrototypeIntradayReader)) { throw new Error('Lost intraday receiver (`this`).'); } this.calls.push(q); const batches = this.barsBatches; return { async *[Symbol.asyncIterator]() { for (const batch of batches) { yield batch; } }, }; } } interface QuestDbFixtureRow { readonly listing_id: string; readonly ts_us: number; readonly open: number; readonly high: number; readonly low: number; readonly close: number; readonly volume: number; readonly vwap: number | null; readonly known_at_us: number; } class PredicateAwareQuestDbExecutor implements QuestDbQueryExecutor { readonly calls: { readonly sql: string; readonly params: readonly unknown[] }[] = []; private readonly rows: readonly QuestDbFixtureRow[]; private readonly leaky: boolean; constructor(rows: readonly QuestDbFixtureRow[], options?: { leaky?: boolean }) { this.rows = rows; this.leaky = options?.leaky === true; } async query( sql: string, params: readonly unknown[] ): Promise<{ readonly rows: readonly Record[] }> { this.calls.push({ sql, params: [...params] }); if (this.leaky) { return { rows: this.rows as unknown as readonly Record[] }; } const fromUs = Date.parse(String(params[0])) * 1000; const toUs = Date.parse(String(params[1])) * 1000; const asOfUs = Date.parse(String(params[params.length - 1])) * 1000; const listingIds = new Set(params.slice(2, params.length - 1).map(String)); const filtered = this.rows.filter( row => row.ts_us >= fromUs && row.ts_us <= toUs && row.known_at_us <= asOfUs && listingIds.has(row.listing_id) ); return { rows: filtered as unknown as readonly Record[] }; } } class RecordingDuckDbExecutor implements DuckDbExecutor { readonly runCalls: string[] = []; readonly queryCalls: { readonly sql: string; readonly params: readonly DuckDbParam[] }[] = []; private readonly rows: readonly TableRow[]; constructor(rows: readonly TableRow[] = []) { this.rows = rows; } async run(sql: string): Promise { this.runCalls.push(sql); } async query(sql: string, params: readonly DuckDbParam[]): Promise { this.queryCalls.push({ sql, params: [...params] }); return this.rows; } } describe('package exports', () => { it('re-exports createRoutedMarketDataStore and createQuestDbIntradayBarsReader from root and subpaths', () => { expect(createRoutedMarketDataStore).toBe(subpathCreateRoutedMarketDataStore); expect(createQuestDbIntradayBarsReader).toBe(subpathCreateQuestDbIntradayBarsReader); }); }); describe('createRoutedMarketDataStore', () => { describe('constructor validation', () => { it('rejects null, primitives, arrays, and class instances for options', () => { const invalidOptions: unknown[] = [ null, undefined, 42, 'options', true, [], new Date(), new (class OptionsClass { daily = new PrototypeDailyStore(); intraday = new PrototypeIntradayReader(); })(), ]; for (const bad of invalidOptions) { let caught: unknown; try { createRoutedMarketDataStore(bad as RoutedMarketDataStoreOptions); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(MarketDataStoreValidationError); expect((caught as MarketDataStoreValidationError).field).toBe('options'); } }); it('accepts a null-prototype options object and prototype-backed delegates', () => { const options = Object.create(null) as { daily: MarketDataStore; intraday: Pick; }; options.daily = new PrototypeDailyStore(); options.intraday = new PrototypeIntradayReader(); const store = createRoutedMarketDataStore(options); expect(typeof store.bars).toBe('function'); }); it('rejects missing or malformed daily delegate and each missing daily method', () => { const intraday = new PrototypeIntradayReader(); for (const badDaily of [null, undefined, 'daily', 123, []]) { let caught: unknown; try { createRoutedMarketDataStore({ daily: badDaily as unknown as MarketDataStore, intraday, }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(MarketDataStoreValidationError); expect((caught as MarketDataStoreValidationError).field).toBe('daily'); } const requiredMethods: (keyof MarketDataStore)[] = [ 'bars', 'crossSection', 'fundamentalsAsOf', 'events', 'shortsAsOf', 'macroAsOf', 'fx', 'universe', ]; for (const missingMethod of requiredMethods) { const base = new PrototypeDailyStore(); const incomplete: Record = { bars: base.bars.bind(base), crossSection: base.crossSection.bind(base), fundamentalsAsOf: base.fundamentalsAsOf.bind(base), events: base.events.bind(base), shortsAsOf: base.shortsAsOf.bind(base), macroAsOf: base.macroAsOf.bind(base), fx: base.fx.bind(base), universe: base.universe.bind(base), }; delete incomplete[missingMethod]; let caughtMissing: unknown; try { createRoutedMarketDataStore({ daily: incomplete as unknown as MarketDataStore, intraday, }); } catch (err) { caughtMissing = err; } expect(caughtMissing).toBeInstanceOf(MarketDataStoreValidationError); expect((caughtMissing as MarketDataStoreValidationError).field).toBe( `daily.${missingMethod}` ); incomplete[missingMethod] = 'not-a-function'; let caughtNonFn: unknown; try { createRoutedMarketDataStore({ daily: incomplete as unknown as MarketDataStore, intraday, }); } catch (err) { caughtNonFn = err; } expect(caughtNonFn).toBeInstanceOf(MarketDataStoreValidationError); expect((caughtNonFn as MarketDataStoreValidationError).field).toBe( `daily.${missingMethod}` ); } }); it('rejects missing or non-callable intraday delegate and intraday.bars', () => { const daily = new PrototypeDailyStore(); for (const badIntraday of [null, undefined, 'intraday', 99, []]) { let caught: unknown; try { createRoutedMarketDataStore({ daily, intraday: badIntraday as unknown as Pick, }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(MarketDataStoreValidationError); expect((caught as MarketDataStoreValidationError).field).toBe('intraday'); } for (const badBars of [undefined, null, 'bars', 42, {}]) { let caught: unknown; try { createRoutedMarketDataStore({ daily, intraday: { bars: badBars } as unknown as Pick, }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(MarketDataStoreValidationError); expect((caught as MarketDataStoreValidationError).field).toBe('intraday.bars'); } }); }); describe('routing and delegation', () => { it('routes 1m bars exclusively to intraday and 1d bars exclusively to daily with exact query identity', async () => { const intradayBatch: BarBatch = { rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 101.25)], }; const dailyBatch: BarBatch = { rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 20, 0, 0), 102.5)], }; const daily = new PrototypeDailyStore([dailyBatch]); const intraday = new PrototypeIntradayReader([intradayBatch]); const store = createRoutedMarketDataStore({ daily, intraday }); const q1m: BarsQuery = { listingIds: [LISTING_ID], timeframe: '1m', from: '2025-06-30', to: '2025-06-30', adjustment: 'raw', }; const q1d: BarsQuery = { listingIds: [LISTING_ID], timeframe: '1d', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw', }; const intradayOut = await collectBatches(store.bars(q1m)); expect(intraday.calls).toHaveLength(1); expect(intraday.calls[0]).toBe(q1m); expect(daily.calls).toHaveLength(0); expect(intradayOut).toHaveLength(1); expect(intradayOut[0]).toBe(intradayBatch); const dailyOut = await collectBatches(store.bars(q1d)); expect(daily.calls).toHaveLength(1); expect(daily.calls[0]?.method).toBe('bars'); expect(daily.calls[0]?.arg).toBe(q1d); expect(intraday.calls).toHaveLength(1); expect(dailyOut).toHaveLength(1); expect(dailyOut[0]).toBe(dailyBatch); }); it('forwards invalid timeframe values and non-object inputs to daily unchanged', async () => { const daily = new PrototypeDailyStore(); const intraday = new PrototypeIntradayReader(); const store = createRoutedMarketDataStore({ daily, intraday }); const arrayWithTimeframe = Object.assign(['1m'], { timeframe: '1m' }); const malformedInputs: unknown[] = [ null, undefined, '1m', 42, ['1m'], arrayWithTimeframe, { listingIds: [42], timeframe: '2m', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, { listingIds: [42], timeframe: '', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, ]; for (const badInput of malformedInputs) { await collectBatches(store.bars(badInput as BarsQuery)); } expect(intraday.calls).toHaveLength(0); expect(daily.calls).toHaveLength(malformedInputs.length); for (let i = 0; i < malformedInputs.length; i += 1) { expect(daily.calls[i]?.method).toBe('bars'); expect(daily.calls[i]?.arg).toBe(malformedInputs[i]); } }); it('preserves DuckDB MarketDataStoreNotImplementedError for 5m and 1h with zero executor or intraday calls', async () => { const duckExecutor = new RecordingDuckDbExecutor(); const daily = createDuckDbMarketDataStore({ executor: duckExecutor, curatedRoot: CURATED_ROOT, vaultCutoffTs: VAULT_CUTOFF_TS, }); const intraday = new PrototypeIntradayReader(); const store = createRoutedMarketDataStore({ daily, intraday }); for (const timeframe of ['5m', '1h'] as const) { let caught: unknown; try { for await (const _batch of store.bars({ listingIds: [LISTING_ID], timeframe, from: '2025-06-01', to: '2025-06-30', adjustment: 'raw', })) { // unreachable } } catch (err) { caught = err; } expect(caught).toBeInstanceOf(MarketDataStoreNotImplementedError); } expect(duckExecutor.runCalls).toHaveLength(0); expect(duckExecutor.queryCalls).toHaveLength(0); expect(intraday.calls).toHaveLength(0); }); it('delegates all seven non-bars methods (including fx 1m) to daily with argument, receiver, and promise identity', async () => { const daily = new PrototypeDailyStore(); const intraday = new PrototypeIntradayReader(); const store = createRoutedMarketDataStore({ daily, intraday }); const crossSectionArg: CrossSectionQuery = { features: ['ret_1d@v1'], date: '2025-06-30', universe: 'US_EQ', }; const fundamentalsArg: FundamentalsQuery = { listingIds: [LISTING_ID], fields: ['revenue'], asOf: '2025-06-30', }; const eventsArg: EventsQuery = { kinds: ['filing'], listingIds: [LISTING_ID], from: '2025-06-01', to: '2025-06-30', }; const shortsArg: ShortsQuery = { listingIds: [LISTING_ID], from: '2025-06-01', to: '2025-06-30', }; const macroArg: MacroQuery = { countries: ['US'], indicators: ['CPI'], from: '2025-06-01', to: '2025-06-30', }; const fxArg: FxQuery = { pair: 'USD.CAD', timeframe: '1m', from: '2025-06-01', to: '2025-06-30', }; const universeArg: UniverseQuery = { ref: 'US_EQ', date: '2025-06-30', }; const pCrossSection = store.crossSection(crossSectionArg); const pFundamentals = store.fundamentalsAsOf(fundamentalsArg); const pEvents = store.events(eventsArg); const pShorts = store.shortsAsOf(shortsArg); const pMacro = store.macroAsOf(macroArg); const pFx = store.fx(fxArg); const pUniverse = store.universe(universeArg); expect(pCrossSection).toBe(daily.returnedPromises.get('crossSection') as Promise
); expect(pFundamentals).toBe(daily.returnedPromises.get('fundamentalsAsOf') as Promise
); expect(pEvents).toBe(daily.returnedPromises.get('events') as Promise
); expect(pShorts).toBe(daily.returnedPromises.get('shortsAsOf') as Promise
); expect(pMacro).toBe(daily.returnedPromises.get('macroAsOf') as Promise
); expect(pFx).toBe(daily.returnedPromises.get('fx') as Promise
); expect(pUniverse).toBe(daily.returnedPromises.get('universe') as Promise); await Promise.all([ pCrossSection, pFundamentals, pEvents, pShorts, pMacro, pFx, pUniverse, ]); expect(intraday.calls).toHaveLength(0); expect(daily.calls).toHaveLength(7); expect(daily.calls[0]).toEqual({ method: 'crossSection', arg: crossSectionArg }); expect(daily.calls[0]?.arg).toBe(crossSectionArg); expect(daily.calls[1]).toEqual({ method: 'fundamentalsAsOf', arg: fundamentalsArg }); expect(daily.calls[1]?.arg).toBe(fundamentalsArg); expect(daily.calls[2]).toEqual({ method: 'events', arg: eventsArg }); expect(daily.calls[2]?.arg).toBe(eventsArg); expect(daily.calls[3]).toEqual({ method: 'shortsAsOf', arg: shortsArg }); expect(daily.calls[3]?.arg).toBe(shortsArg); expect(daily.calls[4]).toEqual({ method: 'macroAsOf', arg: macroArg }); expect(daily.calls[4]?.arg).toBe(macroArg); expect(daily.calls[5]).toEqual({ method: 'fx', arg: fxArg }); expect(daily.calls[5]?.arg).toBe(fxArg); expect(daily.calls[6]).toEqual({ method: 'universe', arg: universeArg }); expect(daily.calls[6]?.arg).toBe(universeArg); }); }); describe('error propagation and lazy iteration', () => { it('propagates exact error instances for sync throws, promise rejections, and mid-iteration failures', async () => { const syncIntradayErr = new Error('sync intraday boom'); const syncDailyErr = new Error('sync daily boom'); const rejectedUniverseErr = new Error('async universe boom'); const iterErr = new Error('mid-iteration boom'); const baseDaily = new PrototypeDailyStore(); const firstBatch: BarBatch = { rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], }; const dailySyncStore = createRoutedMarketDataStore({ daily: { bars: () => { throw syncDailyErr; }, crossSection: baseDaily.crossSection.bind(baseDaily), fundamentalsAsOf: baseDaily.fundamentalsAsOf.bind(baseDaily), events: baseDaily.events.bind(baseDaily), shortsAsOf: baseDaily.shortsAsOf.bind(baseDaily), macroAsOf: baseDaily.macroAsOf.bind(baseDaily), fx: baseDaily.fx.bind(baseDaily), universe: () => Promise.reject(rejectedUniverseErr), }, intraday: { bars: () => { throw syncIntradayErr; }, }, }); let caughtSyncIntraday: unknown; try { dailySyncStore.bars({ listingIds: [LISTING_ID], timeframe: '1m', from: '2025-06-30', to: '2025-06-30', adjustment: 'raw', }); } catch (err) { caughtSyncIntraday = err; } expect(caughtSyncIntraday).toBe(syncIntradayErr); let caughtSyncDaily: unknown; try { dailySyncStore.bars({ listingIds: [LISTING_ID], timeframe: '1d', from: '2025-06-30', to: '2025-06-30', adjustment: 'raw', }); } catch (err) { caughtSyncDaily = err; } expect(caughtSyncDaily).toBe(syncDailyErr); let caughtRejected: unknown; try { await dailySyncStore.universe({ ref: 'US_EQ', date: '2025-06-30' }); } catch (err) { caughtRejected = err; } expect(caughtRejected).toBe(rejectedUniverseErr); const iterFailStore = createRoutedMarketDataStore({ daily: baseDaily, intraday: { bars() { return { async *[Symbol.asyncIterator]() { yield firstBatch; throw iterErr; }, }; }, }, }); const received: BarBatch[] = []; let caughtIter: unknown; try { for await (const batch of iterFailStore.bars({ listingIds: [LISTING_ID], timeframe: '1m', from: '2025-06-30', to: '2025-06-30', adjustment: 'raw', })) { received.push(batch); } } catch (err) { caughtIter = err; } expect(received).toHaveLength(1); expect(received[0]).toBe(firstBatch); expect(caughtIter).toBe(iterErr); }); it('preserves lazy iteration and closes the delegate iterator on early exit', async () => { const batch1: BarBatch = { rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], }; const batch2: BarBatch = { rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 31, 0), 101)], }; let nextCalls = 0; let returnCalls = 0; const store = createRoutedMarketDataStore({ daily: new PrototypeDailyStore(), intraday: { bars() { return { [Symbol.asyncIterator]() { const batches = [batch1, batch2]; return { async next() { const idx = nextCalls; nextCalls += 1; const value = batches[idx]; if (value === undefined) { return { done: true as const, value: undefined }; } return { done: false as const, value }; }, async return() { returnCalls += 1; return { done: true as const, value: undefined }; }, }; }, }; }, }, }); const consumed: BarBatch[] = []; for await (const batch of store.bars({ listingIds: [LISTING_ID], timeframe: '1m', from: '2025-06-30', to: '2025-06-30', adjustment: 'raw', })) { consumed.push(batch); break; } expect(consumed).toHaveLength(1); expect(consumed[0]).toBe(batch1); expect(nextCalls).toBe(1); expect(returnCalls).toBe(1); }); }); describe('QuestDB intraday reader integration and Vault fence', () => { const preCutoffTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; const preCutoffTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; const fixtureRows: readonly QuestDbFixtureRow[] = [ { listing_id: String(LISTING_ID), ts_us: preCutoffTs1Us, open: 100.0, high: 101.0, low: 99.5, close: 100.5, volume: 500, vwap: 100.25, known_at_us: preCutoffTs1Us + 60_000_000, }, { listing_id: String(LISTING_ID), ts_us: preCutoffTs2Us, open: 100.5, high: 101.5, low: 100.25, close: 101.25, volume: 750, vwap: 101.0, known_at_us: preCutoffTs2Us + 60_000_000, }, // Row with ts exactly at Vault cutoff (must be excluded by fence) { listing_id: String(LISTING_ID), ts_us: VAULT_CUTOFF_US, open: 102.0, high: 103.0, low: 101.5, close: 102.5, volume: 900, vwap: 102.25, known_at_us: preCutoffTs2Us + 60_000_000, }, // Row with known_at exactly at Vault cutoff (must be excluded by fence) { listing_id: String(LISTING_ID), ts_us: preCutoffTs2Us + 60_000_000, open: 101.25, high: 102.0, low: 101.0, close: 101.75, volume: 600, vwap: 101.5, known_at_us: VAULT_CUTOFF_US, }, ]; const straddlingQuery: BarsQuery = { listingIds: [LISTING_ID], timeframe: '1m', from: '2025-06-30T13:30:00Z', to: '2025-07-05T20:00:00Z', adjustment: 'raw', asOf: '2025-07-10T00:00:00Z', }; it('streams batches unchanged from createQuestDbIntradayBarsReader and clamps to/asOf strictly below vaultCutoffTs', async () => { const directExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); const directReader = createQuestDbIntradayBarsReader({ executor: directExecutor, vaultCutoffTs: VAULT_CUTOFF_TS, vaultOperatorAuthorized: false, batchSize: 1, }); const routedExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); const underlyingIntraday = createQuestDbIntradayBarsReader({ executor: routedExecutor, vaultCutoffTs: VAULT_CUTOFF_TS, vaultOperatorAuthorized: false, batchSize: 1, }); const yieldedByIntraday: BarBatch[] = []; const recordingIntraday: Pick = { bars(q) { const inner = underlyingIntraday.bars(q); return { async *[Symbol.asyncIterator]() { for await (const batch of inner) { yieldedByIntraday.push(batch); yield batch; } }, }; }, }; const daily = new PrototypeDailyStore(); const store = createRoutedMarketDataStore({ daily, intraday: recordingIntraday }); const directBatches = await collectBatches(directReader.bars(straddlingQuery)); const routedBatches = await collectBatches(store.bars(straddlingQuery)); expect(daily.calls).toHaveLength(0); expect(routedExecutor.calls).toHaveLength(1); expect(routedExecutor.calls[0]?.params[1]).toBe(CLAMPED_END_ISO); expect(routedExecutor.calls[0]?.params[3]).toBe(CLAMPED_END_ISO); expect(routedBatches).toEqual(directBatches); expect(routedBatches).toHaveLength(2); expect(routedBatches[0]).toBe(yieldedByIntraday[0]); expect(routedBatches[1]).toBe(yieldedByIntraday[1]); for (const batch of routedBatches) { for (const row of batch.rows) { expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); } } }); it('rejects a leaky QuestDB executor returning a row with ts or known_at at vaultCutoffTs before yielding any batch', async () => { const tsCutoffRow = fixtureRows[2] as QuestDbFixtureRow; const knownAtCutoffRow = fixtureRows[3] as QuestDbFixtureRow; const preCutoffRow = fixtureRows[0] as QuestDbFixtureRow; for (const leakyRows of [ [preCutoffRow, tsCutoffRow], [preCutoffRow, knownAtCutoffRow], ]) { const leakyExecutor = new PredicateAwareQuestDbExecutor(leakyRows, { leaky: true }); const intraday = createQuestDbIntradayBarsReader({ executor: leakyExecutor, vaultCutoffTs: VAULT_CUTOFF_TS, vaultOperatorAuthorized: false, batchSize: 1, }); const store = createRoutedMarketDataStore({ daily: new PrototypeDailyStore(), intraday, }); const yielded: BarBatch[] = []; let caught: unknown; try { for await (const batch of store.bars(straddlingQuery)) { yielded.push(batch); } } catch (err) { caught = err; } expect(caught).toBeInstanceOf(MarketDataStoreValidationError); expect(yielded).toHaveLength(0); } }); }); describe('MCP query_data end-to-end over routed store', () => { it('routes 1m calls to fake QuestDB and 1d calls to fake DuckDB, enforcing the Vault cutoff deterministically', async () => { const intradayTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; const intradayTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; const questDbRows: readonly QuestDbFixtureRow[] = [ { listing_id: String(LISTING_ID), ts_us: intradayTs1Us, open: 100.0, high: 100.75, low: 99.5, close: 100.5, volume: 1_200, vwap: 100.2, known_at_us: intradayTs1Us + 60_000_000, }, { listing_id: String(LISTING_ID), ts_us: intradayTs2Us, open: 100.5, high: 101.25, low: 100.25, close: 101.0, volume: 1_500, vwap: 100.8, known_at_us: intradayTs2Us + 60_000_000, }, // Out-of-fence rows at exact cutoff (filtered by predicate-aware executor) { listing_id: String(LISTING_ID), ts_us: VAULT_CUTOFF_US, open: 105.0, high: 106.0, low: 104.0, close: 105.5, volume: 2_000, vwap: 105.2, known_at_us: intradayTs2Us + 60_000_000, }, { listing_id: String(LISTING_ID), ts_us: intradayTs2Us + 60_000_000, open: 101.0, high: 101.5, low: 100.75, close: 101.25, volume: 1_100, vwap: 101.1, known_at_us: VAULT_CUTOFF_US, }, ]; const dailyBarTs = Date.UTC(2025, 5, 30, 20, 0, 0, 0); const duckDbRows: readonly TableRow[] = [ { listing_id: LISTING_ID, ts: dailyBarTs, open: 99.0, high: 102.0, low: 98.5, close: 101.5, volume: 250_000, vwap: 100.75, known_at: dailyBarTs, }, ]; const questExecutor = new PredicateAwareQuestDbExecutor(questDbRows); const duckExecutor = new RecordingDuckDbExecutor(duckDbRows); const daily = createDuckDbMarketDataStore({ executor: duckExecutor, curatedRoot: CURATED_ROOT, vaultCutoffTs: VAULT_CUTOFF_TS, vaultOperatorAuthorized: false, }); const intraday = createQuestDbIntradayBarsReader({ executor: questExecutor, vaultCutoffTs: VAULT_CUTOFF_TS, vaultOperatorAuthorized: false, }); const routedStore = createRoutedMarketDataStore({ daily, intraday }); const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createQueryDataTool({ store: routedStore, vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS, }, }), ], }); const direct1mBatches = await collectBatches( createQuestDbIntradayBarsReader({ executor: new PredicateAwareQuestDbExecutor(questDbRows), vaultCutoffTs: VAULT_CUTOFF_TS, vaultOperatorAuthorized: false, }).bars({ listingIds: [LISTING_ID], timeframe: '1m', from: '2025-06-30', to: '2025-07-05', adjustment: 'raw', }) ); const expected1mRows = direct1mBatches.flatMap(b => b.rows); const req1m = JSON.stringify({ jsonrpc: '2.0', id: 'mcp-1m', method: 'tools/call', params: { name: 'query_data', arguments: { listingIds: [LISTING_ID], from: '2025-06-30', to: '2025-07-05', timeframe: '1m', adjustment: 'raw', }, }, }); const raw1mFirst = await server.handleMessage(req1m); const raw1mSecond = await server.handleMessage(req1m); expect(raw1mFirst).not.toBeNull(); expect(raw1mSecond).toBe(raw1mFirst); expect(questExecutor.calls).toHaveLength(2); expect(duckExecutor.queryCalls).toHaveLength(0); expect(duckExecutor.runCalls).toHaveLength(0); const resp1m = JSON.parse(raw1mFirst as string) as { result: { isError?: boolean; content: { type: string; text: string }[] }; }; expect(resp1m.result.isError).toBeUndefined(); const payload1m = JSON.parse(resp1m.result.content[0]?.text ?? '') as QueryDataResultPayload; expect(payload1m.rows).toEqual(expected1mRows); expect(payload1m.rows).toHaveLength(2); for (const row of payload1m.rows) { expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); } const direct1dBatches = await collectBatches( createDuckDbMarketDataStore({ executor: new RecordingDuckDbExecutor(duckDbRows), curatedRoot: CURATED_ROOT, vaultCutoffTs: VAULT_CUTOFF_TS, vaultOperatorAuthorized: false, }).bars({ listingIds: [LISTING_ID], timeframe: '1d', from: '2025-06-25', to: '2025-07-05', adjustment: 'raw', }) ); const expected1dRows = direct1dBatches.flatMap(b => b.rows); const req1d = JSON.stringify({ jsonrpc: '2.0', id: 'mcp-1d', method: 'tools/call', params: { name: 'query_data', arguments: { listingIds: [LISTING_ID], from: '2025-06-25', to: '2025-07-05', timeframe: '1d', adjustment: 'raw', }, }, }); const raw1dFirst = await server.handleMessage(req1d); const raw1dSecond = await server.handleMessage(req1d); expect(raw1dFirst).not.toBeNull(); expect(raw1dSecond).toBe(raw1dFirst); expect(questExecutor.calls).toHaveLength(2); expect(duckExecutor.queryCalls).toHaveLength(2); const resp1d = JSON.parse(raw1dFirst as string) as { result: { isError?: boolean; content: { type: string; text: string }[] }; }; expect(resp1d.result.isError).toBeUndefined(); const payload1d = JSON.parse(resp1d.result.content[0]?.text ?? '') as QueryDataResultPayload; expect(payload1d.rows).toEqual(expected1dRows); expect(payload1d.rows).toHaveLength(1); for (const row of payload1d.rows) { expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); } }); }); });