From 984dc1a9ccede63efdb51fae280afc9c99d470ce Mon Sep 17 00:00:00 2001 From: Boki Date: Mon, 26 Oct 2026 20:30:40 -0400 Subject: [PATCH] refactor(orchestrator): narrow historical storage to reads (CL17) --- .../orchestrator/examples/example-runtime.ts | 3 +- apps/stock/orchestrator/src/container.ts | 3 +- .../orchestrator/src/core/ModeManager.ts | 7 +- .../src/services/StorageService.ts | 154 +----------------- .../web-api/src/routes/datasets.routes.ts | 2 +- docs/development/backlog/README.md | 2 +- docs/development/backlog/manifest.json | 21 ++- .../orchestrator-engine-cleanup.md | 9 + test/integration/dataset-preparation.test.ts | 4 +- test/integration/ingestion-backtest.test.ts | 24 +-- test/integration/intraday-storage.test.ts | 33 ++-- test/integration/mode-lifecycle.test.ts | 45 ++--- test/integration/order-execution.test.ts | 3 +- .../stored-dataset-preparation.test.ts | 2 +- test/integration/strategy-contracts.test.ts | 2 +- test/integration/typescript-backtest.test.ts | 3 +- test/postgres/strategy-recovery.test.ts | 3 +- 17 files changed, 88 insertions(+), 232 deletions(-) diff --git a/apps/stock/orchestrator/examples/example-runtime.ts b/apps/stock/orchestrator/examples/example-runtime.ts index a346f19e..f7628106 100644 --- a/apps/stock/orchestrator/examples/example-runtime.ts +++ b/apps/stock/orchestrator/examples/example-runtime.ts @@ -21,7 +21,7 @@ export async function createExampleRuntime() { }) .build(); const container = di.resolve('serviceContainer') as OrchestratorServices; - const storageService = new StorageService(container, null, null, null, { + const storageService = new StorageService(container.logger, null, null, { allowSyntheticData: true, syntheticSeed: 42, }); @@ -45,7 +45,6 @@ export async function createExampleRuntime() { logger: container.logger, marketData: marketDataService, execution: executionService, - storage: storageService, strategies: strategyManager, }); const custom = container.custom ?? {}; diff --git a/apps/stock/orchestrator/src/container.ts b/apps/stock/orchestrator/src/container.ts index 62d34cb2..394bcb0f 100644 --- a/apps/stock/orchestrator/src/container.ts +++ b/apps/stock/orchestrator/src/container.ts @@ -123,9 +123,8 @@ export async function registerOrchestratorServices( // Create storage service first as it's needed by other services const storageService = new StorageService( - services, + services.logger, services.mongodb, - services.postgres, services.questdb || null, options ); diff --git a/apps/stock/orchestrator/src/core/ModeManager.ts b/apps/stock/orchestrator/src/core/ModeManager.ts index f50aece4..d2b34ed0 100644 --- a/apps/stock/orchestrator/src/core/ModeManager.ts +++ b/apps/stock/orchestrator/src/core/ModeManager.ts @@ -4,7 +4,6 @@ import { defined } from '@stock-bot/invariants'; import type { Logger } from '@stock-bot/services'; import type { ExecutionService } from '../services/ExecutionService'; import type { MarketDataService } from '../services/MarketDataService'; -import type { StorageService } from '../services/StorageService'; import type { StrategyManager } from '../strategies/StrategyManager'; import { BacktestConfigSchema, @@ -13,7 +12,7 @@ import { type TradingMode, } from '../types'; -const shutdownOrder = ['marketData', 'strategies', 'execution', 'storage'] as const; +const shutdownOrder = ['marketData', 'strategies', 'execution'] as const; type LifecycleService = (typeof shutdownOrder)[number]; export class ModeManager extends EventEmitter { @@ -27,7 +26,6 @@ export class ModeManager extends EventEmitter { logger: Pick; marketData: Pick; execution: Pick; - storage: Pick; strategies: Pick; } ) { @@ -132,9 +130,6 @@ export class ModeManager extends EventEmitter { attempted.add('execution'); await this.dependencies.execution.initialize(config, defined(this.tradingEngine)); - // Configure storage - attempted.add('storage'); - await this.dependencies.storage.initialize(config); if (config.mode === 'paper') { attempted.add('strategies'); await this.dependencies.strategies.restoreStrategies(); diff --git a/apps/stock/orchestrator/src/services/StorageService.ts b/apps/stock/orchestrator/src/services/StorageService.ts index 6f9491d5..9f4843c6 100644 --- a/apps/stock/orchestrator/src/services/StorageService.ts +++ b/apps/stock/orchestrator/src/services/StorageService.ts @@ -1,12 +1,6 @@ -import type { - IServiceContainer, - MongoDBClient, - PostgresClient, - QuestDBClient, -} from '@stock-bot/services'; +import type { Logger, MongoDBClient, QuestDBClient } from '@stock-bot/services'; import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types'; import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation'; -import type { MarketData, ModeConfig, PerformanceMetrics } from '../types'; export interface HistoricalBar { symbol: string; @@ -48,151 +42,21 @@ const eodIntradayCollections: Readonly> = { '1h': 'eodIntraday1H', }; +/** Historical reads over borrowed adapters; ingestion and migrations own all writes. */ export class StorageService { - private questdb: QuestDBClient | null = null; - private postgres: PostgresClient | null = null; - private mongodb: MongoDBClient | null = null; - private mode: 'backtest' | 'paper' | 'live' = 'paper'; - private container: IServiceContainer; + private readonly questdb: QuestDBClient | null; + private readonly mongodb: MongoDBClient | null; constructor( - container: IServiceContainer, + private readonly logger: Pick, mongoClient: MongoDBClient | null | undefined, - postgresClient: PostgresClient | null | undefined, questdbClient: QuestDBClient | null, private readonly options: { allowSyntheticData?: boolean; syntheticSeed?: number } = {} ) { - this.container = container; this.mongodb = mongoClient ?? null; - this.postgres = postgresClient ?? null; this.questdb = questdbClient; } - async initialize(config: ModeConfig): Promise { - this.mode = config.mode; - // Clients are already injected via DI - if (config.mode !== 'backtest') { - await this.createTables(); - } - } - - private async createTables(): Promise { - // Create tables if they don't exist - if (this.postgres) { - // Strategy performance table - await this.postgres.query(` - CREATE TABLE IF NOT EXISTS strategy_performance ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - strategy_id VARCHAR(255) NOT NULL, - timestamp TIMESTAMP NOT NULL, - total_return DECIMAL(20, 8), - sharpe_ratio DECIMAL(20, 8), - max_drawdown DECIMAL(20, 8), - win_rate DECIMAL(20, 8), - total_trades INTEGER, - mode VARCHAR(10) NOT NULL - ) - `); - } - } - - private async insertTimeSeries(table: string, data: Record): Promise { - if (!this.questdb) { - throw new Error('QuestDB is unavailable'); - } - if (!/^[a-z0-9_]+$/.test(table)) { - throw new Error('Invalid time-series table'); - } - const columns = Object.keys(data); - const placeholders = columns.map((_, i) => '$' + (i + 1)); - await this.questdb.query( - `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`, - Object.values(data) - ); - } - - async storeMarketData(data: MarketData[]): Promise { - if (!this.questdb) { - return; - } - - for (const item of data) { - try { - parseInstrumentId(item.data.symbol); - switch (item.type) { - case 'quote': - await this.insertTimeSeries('quotes', { - symbol: item.data.symbol, - bid: item.data.bid, - ask: item.data.ask, - bid_size: item.data.bidSize, - ask_size: item.data.askSize, - timestamp: new Date(item.data.timestamp), - }); - break; - - case 'trade': - await this.insertTimeSeries('trades', { - symbol: item.data.symbol, - price: item.data.price, - size: item.data.size, - side: item.data.side, - timestamp: new Date(item.data.timestamp), - }); - break; - - case 'bar': { - const interval = '1m'; // Would be determined from context - await this.insertTimeSeries(`bars_${interval}`, { - symbol: item.data.symbol, - open: item.data.open, - high: item.data.high, - low: item.data.low, - close: item.data.close, - volume: item.data.volume, - vwap: item.data.vwap || null, - timestamp: new Date(item.data.timestamp), - }); - break; - } - } - } catch (error) { - this.container.logger.error('Error storing market data:', error); - } - } - } - - async storeStrategyPerformance( - strategyId: string, - metrics: Pick< - PerformanceMetrics, - 'totalReturn' | 'sharpeRatio' | 'maxDrawdown' | 'winRate' | 'totalTrades' - > - ): Promise { - if (!this.postgres) { - return; - } - - await this.postgres.query( - ` - INSERT INTO strategy_performance ( - strategy_id, timestamp, total_return, sharpe_ratio, - max_drawdown, win_rate, total_trades, mode - ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) - `, - [ - strategyId, - new Date(), - metrics.totalReturn, - metrics.sharpeRatio, - metrics.maxDrawdown, - metrics.winRate, - metrics.totalTrades, - this.mode, - ] - ); - } - /** Adapter support and current connectivity, not evidence of stored range coverage. */ getHistoricalCapabilities() { return [ @@ -602,9 +466,7 @@ export class StorageService { currentTime = new Date(currentTime.getTime() + msPerInterval); } - this.container.logger.info( - `Generated ${bars.length} mock bars for ${symbol} with seed ${seed}` - ); + this.logger.info(`Generated ${bars.length} mock bars for ${symbol} with seed ${seed}`); return bars; } @@ -625,8 +487,4 @@ export class StorageService { return 60 * 1000; // Default to 1 minute } } - - async shutdown(): Promise { - // All adapters are borrowed from DI. Only their lifecycle owner may close them. - } } diff --git a/apps/stock/web-api/src/routes/datasets.routes.ts b/apps/stock/web-api/src/routes/datasets.routes.ts index 80bc249c..ac8329a0 100644 --- a/apps/stock/web-api/src/routes/datasets.routes.ts +++ b/apps/stock/web-api/src/routes/datasets.routes.ts @@ -33,7 +33,7 @@ export function createDatasetRoutes(container: IServiceContainer) { try { const body = await readBody(c.req.raw); // Request-local read adapter: no initialization, mode changes or shared trading runtime. - const storage = new StorageService(container, container.mongodb, null, null); + const storage = new StorageService(container.logger, container.mongodb, null); const prepared = await prepareStoredDataset(body, storage, c.req.raw.signal); c.req.raw.signal.throwIfAborted(); return c.json(prepared); diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index b1f3fa91..86715ec2 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -144,7 +144,7 @@ R06/R08/R09 and the R07 comparison/measurement are complete. The default support ## E11 — Orchestrator and engine cleanup -Owner authorized planning and per-task implementation commits. [Execution plan and validation](../orchestrator-engine-cleanup.md). First wave CL14/CL15/CL16 is completed and committed. CL17–CL20 are ready; CL21 remains conditional. Earlier cleanup reviews and the six original conditional tasks remain unchanged. +Owner authorized planning and per-task implementation commits. [Execution plan and validation](../orchestrator-engine-cleanup.md). First wave CL14/CL15/CL16 is completed and committed. CL17/CL18 are completed; CL19/CL20 are in progress; CL21 remains conditional. Earlier cleanup reviews and the six original conditional tasks remain unchanged. | Task | Priority | Dependencies | | --- | --- | --- | diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index d5b0b0ef..88c84e36 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,6 +1,6 @@ { "schema_version": 1, - "plan_revision": "2026-10-26.82", + "plan_revision": "2026-10-26.83", "repository_base": "b7aeca4", "plan_status": "orchestrator_engine_cleanup_remaining_wave", "execution_authorized": true, @@ -2854,7 +2854,7 @@ "epic": "E11", "priority": "P2", "severity": "Medium", - "status": "in_progress", + "status": "done", "dependencies": [ "CL14" ], @@ -2880,9 +2880,15 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "integration_state": "implementing", + "integration_state": "validated_pending_commit", "integration_base": "580a6de7", - "completion_evidence": "orchestrator-engine-cleanup.md" + "completion_evidence": "orchestrator-engine-cleanup.md", + "reviewer": "/root", + "validation": { + "integration": "Root 60 passed, 519 assertions; implementer expanded103 plus architecture17", + "postgres": "12 passed, 92 assertions: stored preparation and strategy recovery on disposable database", + "review": "Root independently accepted; normalization bodies and baseline frozen hashes unchanged" + } }, { "id": "CL18", @@ -2914,10 +2920,10 @@ ], "assignment": "/root/implement_cl18", "branch": "cleanup/cl18-native-helpers", - "completed_commit": null, + "completed_commit": "03518c8a", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_commit", + "integration_state": "validated_committed", "integration_base": "580a6de7", "completion_evidence": "orchestrator-engine-cleanup.md", "reviewer": "/root/review_cl18", @@ -2925,7 +2931,8 @@ "rust": "150 passed, 4 existing ignored", "native": "28 passed, 227 assertions; rebuilt integrated addon", "review": "Accepted by /root/review_cl18; root integration checks passed" - } + }, + "implementation_commit": "03518c8a" }, { "id": "CL19", diff --git a/docs/development/orchestrator-engine-cleanup.md b/docs/development/orchestrator-engine-cleanup.md index d185a1e8..c1343c3d 100644 --- a/docs/development/orchestrator-engine-cleanup.md +++ b/docs/development/orchestrator-engine-cleanup.md @@ -57,3 +57,12 @@ CL16 implementation commit: `8546fce4`. Disposable test containers were stopped/ Replay and paper hosts now share private strict parsing and financial-view helpers. Host identities/errors stay separate; required nullable fields, reservation ordering, and paper intermediate versus final admission revisions are preserved. No financial kernel, wire version or economic policy changed. Implemented by `/root/implement_cl18`, independently accepted by `/root/review_cl18`, integrated by `/root`. Local and root Rust gates: 150 passed, 4 existing ignored. Root rebuilt the integrated addon and ran native-bindings/native-replay/native-replay-report: 28 passed, 227 assertions. Added replay-to-paper checkpoint/view parity at each fixture boundary and nested/missing/null negatives. Explicit authored-test types, lint, format and diff checks passed. Sandbox-blocked child-worker test was stopped; the authorized rerun passed. Logs: `/tmp/stock-bot-engine-cleanup-20261026/cl18-root-{build,tests-accepted,cargo}.log`. Combined repository gate follows integration of the remaining independent stories. + + +CL18 implementation commit: `03518c8a`. + +### CL17 — accepted + +Historical storage now borrows only its logger, MongoDB and QuestDB readers. Removed uncalled market/performance writes, ad hoc DDL, PostgreSQL injection, mode state and empty shutdown; retained ModeManager/examples no longer give this reader a resource lifecycle. Provider routing, decoding, validation and synthetic calculations stay unchanged. Pinned baseline V1/V2 hashes and malformed-volume negatives protect retained data semantics. + +Implemented by `/root/implement_cl17`, independently reviewed/integrated by `/root`. Root scoped historical/dataset/mode suite: 60 passed, 519 assertions; application types passed. Expanded implementer suite: 103 passed, 895 assertions; architecture rerun: 17 passed. Root disposable stored-dataset preparation plus strategy recovery: 12 passed, 92 assertions. Authored-test types/lint and diff checks passed. Three obsolete parameterized storage-lifecycle cases were removed with the nonexistent stages; actual execution/feed/strategy rollback cases remain. Initial worktree browser bundling read errors cleared on architecture rerun. Nine pre-existing lint findings in other historical test bodies and the already-broken no-argument legacy example were not widened into this task. Logs: `/tmp/stock-bot-engine-cleanup-20261026/cl17-{root-tests,root-types,postgres}.log`. diff --git a/test/integration/dataset-preparation.test.ts b/test/integration/dataset-preparation.test.ts index 63938eb0..2bac9cbe 100644 --- a/test/integration/dataset-preparation.test.ts +++ b/test/integration/dataset-preparation.test.ts @@ -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); diff --git a/test/integration/ingestion-backtest.test.ts b/test/integration/ingestion-backtest.test.ts index 1fdf8358..82261955 100644 --- a/test/integration/ingestion-backtest.test.ts +++ b/test/integration/ingestion-backtest.test.ts @@ -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, }); diff --git a/test/integration/intraday-storage.test.ts b/test/integration/intraday-storage.test.ts index 7988b02d..598b1e48 100644 --- a/test/integration/intraday-storage.test.ts +++ b/test/integration/intraday-storage.test.ts @@ -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'); diff --git a/test/integration/mode-lifecycle.test.ts b/test/integration/mode-lifecycle.test.ts index c1e0b093..b92c90f0 100644 --- a/test/integration/mode-lifecycle.test.ts +++ b/test/integration/mode-lifecycle.test.ts @@ -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'); diff --git a/test/integration/order-execution.test.ts b/test/integration/order-execution.test.ts index 9ba3d9bc..11bbd1bf 100644 --- a/test/integration/order-execution.test.ts +++ b/test/integration/order-execution.test.ts @@ -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({ diff --git a/test/integration/stored-dataset-preparation.test.ts b/test/integration/stored-dataset-preparation.test.ts index 58e81c76..0b3bf520 100644 --- a/test/integration/stored-dataset-preparation.test.ts +++ b/test/integration/stored-dataset-preparation.test.ts @@ -120,7 +120,7 @@ function fixture( read, query, questdb, - storage: new StorageService(container, mongodb, null, questdb), + storage: new StorageService(container.logger, mongodb, questdb), container, }; } diff --git a/test/integration/strategy-contracts.test.ts b/test/integration/strategy-contracts.test.ts index e6515f4e..ae14b7be 100644 --- a/test/integration/strategy-contracts.test.ts +++ b/test/integration/strategy-contracts.test.ts @@ -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, diff --git a/test/integration/typescript-backtest.test.ts b/test/integration/typescript-backtest.test.ts index aff5b193..29f03cc5 100644 --- a/test/integration/typescript-backtest.test.ts +++ b/test/integration/typescript-backtest.test.ts @@ -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({ diff --git a/test/postgres/strategy-recovery.test.ts b/test/postgres/strategy-recovery.test.ts index 22da88e7..aeead35e 100644 --- a/test/postgres/strategy-recovery.test.ts +++ b/test/postgres/strategy-recovery.test.ts @@ -104,7 +104,7 @@ describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => { await prior.shutdown(); await original.execution.enqueueMarketData(quote('two', 100, 100, start + 1)); const services: OrchestratorServices = { logger, postgres: f.postgres }; - const storage = new StorageService(services, null, f.postgres, null); + const storage = new StorageService(services.logger, null, null); const execution = new ExecutionService(services, storage, { clock: f.getTime }); let feedStarted = false; class OfflineMarket extends MarketDataService { @@ -130,7 +130,6 @@ describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => { logger, marketData: market, execution, - storage, strategies: manager, }); cleanup.push(() => mode.shutdown());