feat(research): add owner-aware ledger and intraday storage

Implement reviewed F02/D02: exact owner accounting, atomic funding checks, idempotent receipts and ledger checkpoints; connect existing EOD intraday storage through validated research admission without active financial-engine cutover.
This commit is contained in:
Boki 2026-10-22 21:16:53 -04:00
parent b4af840d4e
commit b65acccd91
15 changed files with 2704 additions and 104 deletions

View file

@ -0,0 +1,416 @@
import { describe, expect, spyOn, test } from 'bun:test';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import type { MongoDBClient, QuestDBClient } from '@stock-bot/services';
import { fetchIntraday } from '../../apps/stock/data-ingestion/src/handlers/eod/actions/intraday';
import type { EodHandler } from '../../apps/stock/data-ingestion/src/handlers/eod/eod.handler';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import {
loadDataset,
validateDataset,
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
import {
createDatasetV2,
validateDatasetV2,
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import {
HistoricalStorageError,
StorageService,
type HistoricalStorageProvider,
} from '../../apps/stock/orchestrator/src/services/StorageService';
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
import { end, identity, intradayResponse, metadata, start } from '../fixtures/intraday/eod';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('intraday-storage-test');
type StoredBar = ReturnType<typeof intradayResponse>[number] & typeof identity & { source: string };
/** Only HTTP and Mongo transport are replaced. Ingestion mapping and research admission are real. */
function memoryStore() {
const documents: StoredBar[] = [];
const reads: { collection: string; filter: unknown; options: unknown }[] = [];
const mongodb = {
connected: true,
collection(name: string) {
expect(name).toBe('eodSymbols');
return {
async findOne(filter: unknown) {
expect(filter).toEqual({ eodSearchCode: identity.eodSearchCode });
return {
Code: identity.symbol,
Exchange: 'VENUE-METADATA',
eodExchange: identity.exchange,
};
},
};
},
async batchUpsert(collection: string, rows: StoredBar[], keys: string[]) {
expect(collection).toBe('eodIntraday5M');
expect(keys).toEqual(['timestamp', 'eodSearchCode']);
for (const row of rows) {
const index = documents.findIndex(
old => old.timestamp === row.timestamp && old.eodSearchCode === row.eodSearchCode
);
if (index < 0) {
documents.push(structuredClone(row));
} else {
documents[index] = structuredClone(row);
}
}
return { insertedCount: rows.length };
},
async find(
collection: string,
filter: { eodSearchCode: string; timestamp: { $gte: number; $lt: number } },
options: unknown
) {
reads.push({ collection, filter, options });
return documents
.filter(
row =>
row.eodSearchCode === filter.eodSearchCode &&
row.timestamp >= filter.timestamp.$gte &&
row.timestamp < filter.timestamp.$lt
)
.sort((a, b) => a.timestamp - b.timestamp);
},
} as unknown as MongoDBClient;
return { mongodb, documents, reads };
}
async function ingest(mongodb: MongoDBClient, bars = intradayResponse()) {
const fakeFetch = async (input: Parameters<typeof fetch>[0]) => {
const url = new URL(String(input));
// Do not print URLs: production writer includes its existing provider credentials.
expect(url.origin).toBe('https://eodhd.com');
expect(url.pathname).toBe(`/api/intraday/${identity.eodSearchCode}`);
expect(url.searchParams.get('interval')).toBe('5m');
expect(url.searchParams.get('from')).toBe(String(start.getTime() / 1000));
expect(url.searchParams.get('to')).toBe(String(end.getTime() / 1000));
return Response.json(bars);
};
const request = spyOn(globalThis, 'fetch').mockImplementation(
Object.assign(fakeFetch, { preconnect: globalThis.fetch.preconnect })
);
try {
return await fetchIntraday.call({ mongodb, logger } as unknown as EodHandler, {
eodSearchCode: identity.eodSearchCode,
interval: '5m',
fromDate: start,
toDate: end,
});
} finally {
request.mockRestore();
}
}
const config = () =>
BacktestConfigSchema.parse({
mode: 'backtest',
symbols: [identity.eodSearchCode],
strategy: 'sma-crossover',
startDate: start.toISOString(),
endDate: end.toISOString(),
initialCapital: 100_000,
dataFrequency: '5m',
commission: 0,
slippage: 0,
config: { fastPeriod: 3, slowPeriod: 7 },
});
describe('EOD intraday ingestion → research storage', () => {
test('ingest_5m_freeze_replay: real writer/admission, v2 freeze and legacy native replay', async () => {
const store = memoryStore();
const response = intradayResponse();
expect(await ingest(store.mongodb, response)).toEqual({
success: true,
recordsSaved: 78,
recordsFetched: 78,
});
const storage = new StorageService({ logger }, store.mongodb, null, null);
const bars = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m');
const economicRows = bars.map(({ timestamp, open, high, low, close, volume }) => ({
timestamp: timestamp.getTime(),
open,
high,
low,
close,
volume,
}));
const expected = response.map(({ timestamp, open, high, low, close, volume }) => ({
timestamp: timestamp * 1000,
open,
high,
low,
close,
volume,
}));
expect(economicRows).toEqual(expected);
expect(bars.every(bar => bar.source === 'eod' && bar.vwap === undefined)).toBe(true);
const freeze = (rows: typeof expected) =>
createDatasetV2({
metadata: metadata(),
bars: rows.map((row, sourceSequence) => ({
...row,
seriesId: 'fixture-5m',
sourceSequence,
})),
});
const dataset = freeze(economicRows);
expect(dataset.manifest.hash).toBe(freeze(expected).manifest.hash);
expect(dataset.manifest.barCount).toBe(response.length);
expect(dataset.manifest.eligibility).toBe('exploratory');
expect(dataset.bars[0]?.intervalStart).toBe(start.getTime());
expect(dataset.bars.at(-1)?.intervalEnd).toBe(end.getTime());
expect(
dataset.bars.every(bar => bar.vwap === null && bar.availableAt === bar.intervalEnd)
).toBe(true);
expect(validateDatasetV2(JSON.parse(JSON.stringify(dataset)))).toEqual(dataset);
// V1 runtime stays V1. This checks storage compatibility, not future F06 replay correctness.
const legacy = await loadDataset(storage, config());
expect(
legacy.bars.map(({ timestamp, open, high, low, close, volume }) => ({
timestamp,
open,
high,
low,
close,
volume,
}))
).toEqual(expected);
expect(validateDataset(JSON.parse(JSON.stringify(legacy))).manifest.hash).toBe(
legacy.manifest.hash
);
const engine = new RustBacktestAdapter({ logger, storage });
try {
const first = await engine.runBacktest(config(), async () => legacy);
const second = await engine.runBacktest(config(), async () => legacy);
expect(first.status).toBe('completed');
expect(first.ohlcData[identity.eodSearchCode]).toHaveLength(78);
expect(first.ohlcData[identity.eodSearchCode]?.[0]?.timestamp).toBe(start.getTime());
expect(first.trades.length).toBeGreaterThan(0);
expect(first.trades).toEqual(second.trades);
expect(first.equity).toEqual(second.equity);
expect(first.metrics).toEqual(second.metrics);
} finally {
await engine.shutdown();
}
});
test('supported collections, UTC seconds and half-open fractional boundaries', async () => {
const store = memoryStore();
await ingest(
store.mongodb,
intradayResponse()
.slice(0, 3)
.map(row => ({ ...row, gmtoffset: -14_400, datetime: 'untrusted local label' }))
);
const storage = new StorageService({ logger }, store.mongodb, null, null);
for (const [interval, collection] of [
['1m', 'eodIntraday1M'],
['5m', 'eodIntraday5M'],
['1h', 'eodIntraday1H'],
]) {
const bars = await storage.getHistoricalBars(
identity.eodSearchCode,
new Date(start.getTime() + 1),
new Date(start.getTime() + 600_000),
interval
);
expect(bars.map(bar => bar.timestamp.getTime())).toEqual([start.getTime() + 300_000]);
expect(store.reads.at(-1)?.collection).toBe(collection);
expect(store.reads.at(-1)?.filter).toEqual({
eodSearchCode: identity.eodSearchCode,
timestamp: { $gte: (start.getTime() + 1) / 1000, $lt: (start.getTime() + 600_000) / 1000 },
});
}
});
test('capabilities report configured connectivity and supported intervals, never stored coverage', () => {
const store = memoryStore();
const storage = new StorageService({ logger }, store.mongodb, null, {
connected: false,
} as QuestDBClient);
expect(storage.getHistoricalCapabilities()).toEqual([
{
provider: 'questdb',
configured: true,
connected: false,
intervals: ['1m', '5m', '15m', '1h', '1d'],
},
{ provider: 'eod', configured: true, connected: true, intervals: ['1m', '5m', '1h', '1d'] },
]);
expect(
new StorageService({ logger }, null, null, null)
.getHistoricalCapabilities()
.every(capability => !capability.configured && !capability.connected)
).toBe(true);
});
test('unsupported_interval and provider reject explicitly without queries or synthetic fallback', async () => {
const store = memoryStore();
const storage = new StorageService({ logger }, store.mongodb, null, null, {
allowSyntheticData: true,
});
for (const interval of ['15m', '2m']) {
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, interval)
).rejects.toMatchObject({ name: 'HistoricalStorageError', code: 'unsupported-interval' });
}
await expect(
storage.getHistoricalBars(
identity.eodSearchCode,
start,
end,
'5m',
undefined,
undefined,
'qm' as HistoricalStorageProvider
)
).rejects.toMatchObject({ code: 'unsupported-provider' });
expect(store.reads).toHaveLength(0);
const absent = new StorageService({ logger }, null, null, null, { allowSyntheticData: true });
for (const provider of ['eod', 'questdb'] as const) {
await expect(
absent.getHistoricalBars(
identity.eodSearchCode,
start,
end,
'5m',
undefined,
undefined,
provider
)
).rejects.toMatchObject({ code: 'provider-unavailable', provider });
}
});
test('missing_range is typed; selecting a real provider never falls back to synthetic data', async () => {
const store = memoryStore();
const storage = new StorageService({ logger }, store.mongodb, null, null, {
allowSyntheticData: true,
});
try {
await storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m');
throw new Error('Expected rejection');
} catch (error) {
expect(error).toBeInstanceOf(HistoricalStorageError);
expect(error).toMatchObject({ code: 'missing-range', provider: 'eod' });
}
expect(store.reads.map(read => read.collection)).toEqual(['eodIntraday5M']);
});
test('provider_priority selects QuestDB once; empty/error never falls through, explicit EOD is available', async () => {
const store = memoryStore();
await ingest(store.mongodb);
let fail = false;
const failure = new Error('Transport unavailable');
let questReads = 0;
const questdb = {
async query() {
questReads++;
if (fail) {
throw failure;
}
return { rows: [] };
},
} as unknown as QuestDBClient;
const storage = new StorageService({ logger }, store.mongodb, null, questdb);
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')
).rejects.toMatchObject({ code: 'missing-range', provider: 'questdb' });
fail = true;
await expect(storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')).rejects.toBe(
failure
);
expect(store.reads).toHaveLength(0);
expect(
await storage.getHistoricalBars(
identity.eodSearchCode,
start,
end,
'5m',
undefined,
undefined,
'eod'
)
).toHaveLength(78);
expect(questReads).toBe(2);
});
test('invalid seconds, OHLCV, duplicate timestamps and incomplete listing identity fail admission', async () => {
const row = { ...intradayResponse()[0]!, ...identity, source: 'eod' };
let records: unknown[] = [row];
const mongodb = {
async find() {
return records;
},
} as unknown as MongoDBClient;
const storage = new StorageService({ logger }, mongodb, null, null);
for (const timestamp of [
String(row.timestamp),
row.timestamp + 0.5,
NaN,
Infinity,
Number.MAX_SAFE_INTEGER,
8_640_000_000_001,
]) {
records = [{ ...row, timestamp }];
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')
).rejects.toThrow('Unix-seconds timestamp');
}
for (const changed of [
{ symbol: 'OTHER' },
{ exchange: 'VENUE-METADATA' },
{ exchange: undefined },
{ eodSearchCode: 'FIXTURE.OTHER' },
]) {
records = [{ ...row, ...changed }];
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')
).rejects.toThrow('identity mismatch');
}
records = [{ ...row, low: -1 }];
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')
).rejects.toThrow('Invalid historical OHLCV');
records = [row, row];
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')
).rejects.toThrow('Duplicate historical timestamps');
records = [row];
await expect(storage.getHistoricalBars('FIXTURE', start, end, '5m')).rejects.toThrow(
'exchange-qualified'
);
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m', {
adjustment: 'provider-adjusted',
timestamp: 'utc-instant',
})
).rejects.toThrow('Provider-adjusted prices unavailable');
});
test('cancellation before and after a read never publishes late bars', async () => {
let reads = 0;
const before = new AbortController();
before.abort(new Error('cancelled before query'));
const after = new AbortController();
const mongodb = {
async find() {
reads++;
after.abort(new Error('cancelled during query'));
return [{ ...intradayResponse()[0]!, ...identity }];
},
} as unknown as MongoDBClient;
const storage = new StorageService({ logger }, mongodb, null, null);
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m', undefined, before.signal)
).rejects.toThrow('cancelled before query');
expect(reads).toBe(0);
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m', undefined, after.signal)
).rejects.toThrow('cancelled during query');
expect(reads).toBe(1);
});
});