refactor(orchestrator): narrow historical storage to reads (CL17)

This commit is contained in:
Boki 2026-10-26 20:30:40 -04:00
parent 03518c8ae4
commit 984dc1a9cc
17 changed files with 88 additions and 232 deletions

View file

@ -218,7 +218,7 @@ describe('historical dataset preparation', () => {
return { rows: rows('A.US', 5) };
},
} as unknown as QuestDBClient;
const storage = new StorageService({ logger }, null, null, questdb);
const storage = new StorageService(logger, null, questdb);
expect(
await storage.getHistoricalBars(
'A.US',
@ -247,7 +247,7 @@ describe('historical dataset preparation', () => {
}));
},
} as unknown as MongoDBClient;
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
const read = () =>
storage.getHistoricalBars('A.US', new Date(config.startDate), new Date(config.endDate), '1d');
expect(await read()).toHaveLength(5);

View file

@ -94,7 +94,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
};
},
} as unknown as QuestDBClient;
const storage = new StorageService({ logger }, null, null, questdb);
const storage = new StorageService(logger, null, questdb);
const bars = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m');
expect(bars[0]?.timestamp.toISOString()).toBe('2024-01-01T15:00:00.000Z');
timestamp = '2024-01-01T10:00:00';
@ -113,7 +113,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
await persistEodPrices(mongodb, listing, [fixture[0]!]);
expect(documents[0]?.exchange).toBe('NASDAQ');
expect((documents[0] as unknown as { providerExchange: string }).providerExchange).toBe('US');
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
expect(
(await storage.getHistoricalBars(listing.eodSearchCode, start, end, '1d'))[0]?.symbol
).toBe('FIXTURE.US');
@ -129,7 +129,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
await persistEodPrices(mongodb, other, [
{ ...fixture[0]!, open: 200, high: 201, low: 199, close: 200 },
]);
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
expect(
(await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d'))[0]?.close
).toBe(fixture[0]!.close);
@ -159,7 +159,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
{ ...fixture[1]!, open: 50, high: 55, low: 45, close: 50, adjusted_close: 49, volume: 2000 },
];
await persistEodPrices(mongodb, identity, prices);
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
const raw = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d');
const adjusted = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d', {
adjustment: 'provider-adjusted',
@ -181,7 +181,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
test('explicit source requests reach storage and cannot silently reuse another provider', async () => {
const { mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, fixture);
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
const providers: unknown[] = [];
const selected = await loadDataset(
{
@ -205,7 +205,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
test('missing provider factors cannot silently turn adjusted requests into raw data', async () => {
const { mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, [fixture[0]!]);
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d', {
adjustment: 'provider-adjusted',
@ -223,7 +223,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
test('daily timestamps are UTC session labels with aligned, exclusive ranges', async () => {
const { mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, fixture.slice(0, 3));
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
const bars = await storage.getHistoricalBars(
identity.eodSearchCode,
start,
@ -248,7 +248,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
test('dataset hashes survive JSON key reordering and reject tampering or mismatched requests', async () => {
const { mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, fixture);
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
const first = await loadDataset(storage, datasetConfig());
const reordered = JSON.parse(JSON.stringify(first), (_key, value) =>
value && !Array.isArray(value) && typeof value === 'object'
@ -273,7 +273,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
expect(documents).toHaveLength(fixture.length);
expect(documents.every(row => row.source === 'eod')).toBe(true);
const services = { logger, mongodb };
const storage = new StorageService(services, mongodb, null, null);
const storage = new StorageService(services.logger, mongodb, null);
const config = BacktestConfigSchema.parse({
mode: 'backtest',
name: 'Fixed replay',
@ -304,7 +304,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
symbols: [identity.eodSearchCode, other.eodSearchCode],
config: { fastPeriod: 3, slowPeriod: 7 },
};
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
const first = await loadDataset(storage, config);
const second = await loadDataset(storage, config);
for (const id of config.symbols) {
@ -324,14 +324,14 @@ describe('deterministic ingestion → storage → native backtest', () => {
});
test('missing storage never silently produces synthetic prices', async () => {
const storage = new StorageService({ logger }, null, null, null);
const storage = new StorageService(logger, null, null);
await expect(storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).rejects.toThrow(
'explicit opt-in'
);
});
test('explicit synthetic fixtures use a stable seed', async () => {
const storage = new StorageService({ logger }, null, null, null, {
const storage = new StorageService(logger, null, null, {
allowSyntheticData: true,
syntheticSeed: 7,
});

View file

@ -126,7 +126,7 @@ describe('EOD intraday ingestion → research storage', () => {
recordsSaved: 78,
recordsFetched: 78,
});
const storage = new StorageService({ logger }, store.mongodb, null, null);
const storage = new StorageService(logger, store.mongodb, null);
const bars = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m');
const economicRows = bars.map(({ timestamp, open, high, low, close, volume }) => ({
timestamp: timestamp.getTime(),
@ -157,6 +157,10 @@ describe('EOD intraday ingestion → research storage', () => {
});
const dataset = freeze(economicRows);
expect(dataset.manifest.hash).toBe(freeze(expected).manifest.hash);
// Pinned before CL17: dropping write/lifecycle responsibilities cannot alter retained bytes.
expect(dataset.manifest.hash).toBe(
'828cff0ac7ac555f82e69540b90f529ed237de07bab4bbd96a734068d75cfed1'
);
expect(dataset.manifest.barCount).toBe(response.length);
expect(dataset.manifest.eligibility).toBe('exploratory');
expect(dataset.bars[0]?.intervalStart).toBe(start.getTime());
@ -168,6 +172,9 @@ describe('EOD intraday ingestion → research storage', () => {
// Historical V1 payloads remain readable; production execution requires V2 admission.
const legacy = await loadDataset(storage, config());
expect(legacy.manifest.hash).toBe(
'094e1002f551d4a9ec31d7f89afae5cb32ca82b4b6ff1ca6778c8c281f5392eb'
);
expect(
legacy.bars.map(({ timestamp, open, high, low, close, volume }) => ({
timestamp,
@ -196,7 +203,7 @@ describe('EOD intraday ingestion → research storage', () => {
.slice(0, 3)
.map(row => ({ ...row, gmtoffset: -14_400, datetime: 'untrusted local label' }))
);
const storage = new StorageService({ logger }, store.mongodb, null, null);
const storage = new StorageService(logger, store.mongodb, null);
for (const [interval, collection] of [
['1m', 'eodIntraday1M'],
['5m', 'eodIntraday5M'],
@ -219,7 +226,7 @@ describe('EOD intraday ingestion → research storage', () => {
test('capabilities report configured connectivity and supported intervals, never stored coverage', () => {
const store = memoryStore();
const storage = new StorageService({ logger }, store.mongodb, null, {
const storage = new StorageService(logger, store.mongodb, {
connected: false,
} as QuestDBClient);
expect(storage.getHistoricalCapabilities()).toEqual([
@ -232,7 +239,7 @@ describe('EOD intraday ingestion → research storage', () => {
{ provider: 'eod', configured: true, connected: true, intervals: ['1m', '5m', '1h', '1d'] },
]);
expect(
new StorageService({ logger }, null, null, null)
new StorageService(logger, null, null)
.getHistoricalCapabilities()
.every(capability => !capability.configured && !capability.connected)
).toBe(true);
@ -240,7 +247,7 @@ describe('EOD intraday ingestion → research storage', () => {
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, {
const storage = new StorageService(logger, store.mongodb, null, {
allowSyntheticData: true,
});
for (const interval of ['15m', '2m']) {
@ -260,7 +267,7 @@ describe('EOD intraday ingestion → research storage', () => {
)
).rejects.toMatchObject({ code: 'unsupported-provider' });
expect(store.reads).toHaveLength(0);
const absent = new StorageService({ logger }, null, null, null, { allowSyntheticData: true });
const absent = new StorageService(logger, null, null, { allowSyntheticData: true });
for (const provider of ['eod', 'questdb'] as const) {
await expect(
absent.getHistoricalBars(
@ -278,7 +285,7 @@ describe('EOD intraday ingestion → research storage', () => {
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, {
const storage = new StorageService(logger, store.mongodb, null, {
allowSyntheticData: true,
});
try {
@ -306,7 +313,7 @@ describe('EOD intraday ingestion → research storage', () => {
return { rows: [] };
},
} as unknown as QuestDBClient;
const storage = new StorageService({ logger }, store.mongodb, null, questdb);
const storage = new StorageService(logger, store.mongodb, questdb);
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')
).rejects.toMatchObject({ code: 'missing-range', provider: 'questdb' });
@ -337,7 +344,7 @@ describe('EOD intraday ingestion → research storage', () => {
return records;
},
} as unknown as MongoDBClient;
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
for (const timestamp of [
String(row.timestamp),
row.timestamp + 0.5,
@ -362,6 +369,12 @@ describe('EOD intraday ingestion → research storage', () => {
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')
).rejects.toThrow('identity mismatch');
}
for (const volume of [null, undefined, '', ' ', NaN, Infinity, -1]) {
records = [{ ...row, volume }];
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')
).rejects.toThrow('Invalid historical OHLCV');
}
records = [{ ...row, low: -1 }];
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')
@ -394,7 +407,7 @@ describe('EOD intraday ingestion → research storage', () => {
return [{ ...intradayResponse()[0]!, ...identity }];
},
} as unknown as MongoDBClient;
const storage = new StorageService({ logger }, mongodb, null, null);
const storage = new StorageService(logger, mongodb, null);
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m', undefined, before.signal)
).rejects.toThrow('cancelled before query');

View file

@ -13,6 +13,9 @@ function fixture(failAt?: string) {
const record = async (step: string) => {
calls.push(step);
const [service, operation] = step.split('.');
if (!service || !operation) {
throw new Error('Invalid lifecycle fixture step');
}
if (operation === 'shutdown') {
resources.delete(service);
} else {
@ -28,10 +31,6 @@ function fixture(failAt?: string) {
initialize: () => record('execution.initialize'),
shutdown: () => record('execution.shutdown'),
},
storage: {
initialize: () => record('storage.initialize'),
shutdown: () => record('storage.shutdown'),
},
strategies: {
restoreStrategies: () => record('strategies.restore'),
shutdown: () => record('strategies.shutdown'),
@ -48,23 +47,17 @@ describe('explicit mode lifecycle dependencies', () => {
test('paper recovery completes before the feed starts; shutdown drains the feed before strategies and execution', async () => {
const f = fixture();
await f.mode.initializeMode({ mode: 'paper', startingCapital: 10000 });
expect(f.calls).toEqual([
'execution.initialize',
'storage.initialize',
'strategies.restore',
'market.initialize',
]);
expect(f.calls).toEqual(['execution.initialize', 'strategies.restore', 'market.initialize']);
await f.mode.shutdown();
expect(f.calls.slice(4)).toEqual([
expect(f.calls.slice(3)).toEqual([
'market.shutdown',
'strategies.shutdown',
'execution.shutdown',
'storage.shutdown',
]);
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
expect(f.mode.getConfig()).toBeNull();
await f.mode.shutdown();
expect(f.calls).toHaveLength(8);
expect(f.calls).toHaveLength(6);
});
test('backtest mode replaces the current engine without restoring paper strategies', async () => {
@ -75,51 +68,37 @@ describe('explicit mode lifecycle dependencies', () => {
expect(f.mode.getTradingEngine()).not.toBe(prior);
expect(f.calls).toEqual([
'execution.initialize',
'storage.initialize',
'market.initialize',
'market.shutdown',
'strategies.shutdown',
'execution.shutdown',
'storage.shutdown',
'execution.initialize',
'storage.initialize',
'market.initialize',
]);
await f.mode.shutdown();
});
test.each(['market.shutdown', 'strategies.shutdown', 'execution.shutdown', 'storage.shutdown'])(
test.each(['market.shutdown', 'strategies.shutdown', 'execution.shutdown'])(
'%s failure still closes every other dependency and clears the mode engine',
async failAt => {
const f = fixture(failAt);
await f.mode.initializeMode(config);
await expect(f.mode.shutdown()).rejects.toBe(f.failure);
expect(f.calls.slice(3)).toEqual([
expect(f.calls.slice(2)).toEqual([
'market.shutdown',
'strategies.shutdown',
'execution.shutdown',
'storage.shutdown',
]);
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
expect(f.mode.getConfig()).toBeNull();
await f.mode.shutdown();
expect(f.calls).toHaveLength(7);
expect(f.calls).toHaveLength(5);
}
);
const paper = { mode: 'paper' as const, startingCapital: 10000 };
const initialization = [
'execution.initialize',
'storage.initialize',
'strategies.restore',
'market.initialize',
];
const cleanup = [
'market.shutdown',
'strategies.shutdown',
'execution.shutdown',
'storage.shutdown',
];
const initialization = ['execution.initialize', 'strategies.restore', 'market.initialize'];
const cleanup = ['market.shutdown', 'strategies.shutdown', 'execution.shutdown'];
test.each(initialization)(
'partial acquisition in %s cleans up attempted stages and allows retry without a success event',
@ -175,7 +154,7 @@ describe('explicit mode lifecycle dependencies', () => {
const f = fixture();
await f.mode.initializeMode(config);
const prior = f.mode.getTradingEngine();
f.failures.set('storage.initialize', f.failure);
f.failures.set('strategies.restore', f.failure);
await expect(f.mode.initializeMode(paper)).rejects.toBe(f.failure);
expect(f.mode.getConfig()).toBeNull();
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');

View file

@ -179,7 +179,6 @@ describe('one simulation execution gateway', () => {
logger,
marketData: lifecycle,
execution,
storage: lifecycle,
strategies: { restoreStrategies: async () => {}, shutdown: async () => {} },
});
await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
@ -207,7 +206,7 @@ describe('one simulation execution gateway', () => {
}
const market: MarketDataService = new MarketDataService({
logger,
storage: new StorageService({ logger }, null, null, null),
storage: new StorageService(logger, null, null),
drainStrategies: () => manager.drain(),
});
const manager: StrategyManager = new StrategyManager({

View file

@ -120,7 +120,7 @@ function fixture(
read,
query,
questdb,
storage: new StorageService(container, mongodb, null, questdb),
storage: new StorageService(container.logger, mongodb, questdb),
container,
};
}

View file

@ -265,7 +265,7 @@ describe('explicit strategy contracts and shared planning', () => {
test('the TypeScript backend rejects invalid settings before calling a dataset resolver', async () => {
const f = await runtime();
const storage = new StorageService({ logger }, null, null, null);
const storage = new StorageService(logger, null, null);
const backend = new BacktestEngine({
logger,
execution: f.execution,

View file

@ -31,7 +31,7 @@ afterEach(async () => {
});
async function fixture() {
const services: OrchestratorServices = { logger };
const storage = new StorageService(services, null, null, null, {
const storage = new StorageService(services.logger, null, null, {
allowSyntheticData: true,
syntheticSeed: 42,
});
@ -52,7 +52,6 @@ async function fixture() {
logger,
marketData: market,
execution,
storage,
strategies: manager,
});
const backend = new BacktestEngine({