refactor(engine): retire abandoned architecture scaffolding (CL15)

This commit is contained in:
Boki 2026-10-26 19:16:51 -04:00
parent 7481d02c6c
commit bc2b8a89da
31 changed files with 76 additions and 3043 deletions

View file

@ -1,153 +1,37 @@
# Migration Guide: Modular Architecture
This guide explains how to migrate from the current monolithic structure to the new modular architecture.
## Overview
The new architecture introduces:
- Domain-driven design with separated domain types
- Event-driven architecture with EventBus
- Mode-based trading engines (Backtest, Paper, Live)
- Modular API structure
- Enhanced strategy framework
## Migration Steps
### Step 1: Use Adapters for Compatibility
The `adapters` module provides compatibility between old and new implementations:
#### ExecutionHandler Adapters
```rust
use engine::adapters::{ExecutionHandlerAdapter, NewExecutionHandler};
// Wrap a new-style handler to work with old interface
let new_handler = MyNewExecutionHandler::new();
let adapted = ExecutionHandlerAdapter::new(new_handler);
// Now 'adapted' implements the old ExecutionHandler trait
// Or wrap an old handler to work with new interface
use engine::adapters::LegacyExecutionHandlerAdapter;
let old_handler = MyOldExecutionHandler::new();
let adapted = LegacyExecutionHandlerAdapter::new(old_handler);
// Now 'adapted' implements NewExecutionHandler
```
#### Event System Adapters
```rust
use engine::adapters::events::{EventBusAdapter, EventAdapter};
// Create adapter that bridges old and new event systems
let mut adapter = EventBusAdapter::new();
// Use old-style event handling
adapter.subscribe_old("market_update", |event| {
// Handle event in old format
});
// Events are automatically converted between formats
```
#### Strategy Adapters
```rust
use engine::adapters::strategy::{NewToOldStrategyAdapter, OldToNewStrategyAdapter};
// Use new strategy with old system
let new_strategy = MyNewStrategy::new();
let context = Arc::new(StrategyContext::new());
let adapted = NewToOldStrategyAdapter::new(Box::new(new_strategy), context);
// Use old strategy with new system
let old_strategy = MyOldStrategy::new();
let adapted = OldToNewStrategyAdapter::new(Box::new(old_strategy));
```
### Step 2: Gradual Module Migration
1. **Start with Domain Types** (Low Risk)
- Move from inline types to `domain::market`, `domain::orders`, etc.
- These are mostly data structures with minimal behavior
2. **Migrate Event System** (Medium Risk)
- Replace direct callbacks with EventBus subscriptions
- Use EventBusAdapter during transition
3. **Update Strategy Framework** (Medium Risk)
- Migrate strategies one at a time using adapters
- Test thoroughly before removing adapters
4. **Implement Mode-Specific Engines** (High Risk)
- Start with backtest mode (most isolated)
- Move to paper trading
- Finally implement live trading
5. **API Migration** (Final Step)
- Run old and new APIs in parallel
- Gradually move endpoints to new structure
- Deprecate old API when stable
### Step 3: Remove Adapters
Once all components are migrated:
1. Remove adapter usage
2. Delete old implementations
3. Remove adapter modules
## Testing Strategy
1. **Unit Tests**: Test adapters ensure compatibility
2. **Integration Tests**: Verify old and new systems work together
3. **Regression Tests**: Ensure no functionality is lost
4. **Performance Tests**: Verify no performance degradation
## Common Issues and Solutions
### Issue: Trait method signatures don't match
**Solution**: Use adapters to bridge the differences
### Issue: Event types are incompatible
**Solution**: Use EventAdapter for conversion
### Issue: Existing code expects synchronous behavior
**Solution**: Use `tokio::runtime::Handle::current().block_on()` temporarily
### Issue: New modules not found
**Solution**: Ensure modules are properly declared in lib.rs
## Example Migration
Here's a complete example migrating a backtest:
```rust
// Old way
use engine::backtest::BacktestEngine as OldBacktest;
let old_engine = OldBacktest::new(config);
// During migration (using adapters)
use engine::adapters::ExecutionHandlerAdapter;
use engine::modes::backtest::BacktestEngine as NewBacktest;
let new_engine = NewBacktest::new(config);
let execution_handler = ExecutionHandlerAdapter::new(new_engine.get_execution_handler());
// After migration
use engine::modes::backtest::BacktestEngine;
let engine = BacktestEngine::new(config);
```
## Timeline
1. **Week 1-2**: Implement and test adapters
2. **Week 3-4**: Migrate domain types and events
3. **Week 5-6**: Migrate strategies and modes
4. **Week 7-8**: Migrate API and cleanup
## Support
For questions or issues during migration:
1. Check adapter documentation
2. Review test examples
3. Consult team lead for architectural decisions
# Canonical execution and retained compatibility
The earlier EventBus, mode-engine and strategy-framework migration described here was abandoned. Its uncompiled alternative modules and unused placeholder adapters have been removed. Do not use that design as an implementation guide.
Current research and paper execution share the authoritative Rust core in [src/financial](src/financial/mod.rs): replay → matching → risk → ledger. TypeScript owns strategy decisions, worker supervision and durable SQL custody. [api/replay.rs](src/api/replay.rs) exposes `FinancialReplaySession`; [api/paper.rs](src/api/paper.rs) exposes `stageFinancialTransaction`. Start with the [code-reading guide](../../../docs/guide/code-reading.md) to trace a complete decision.
## Supported boundaries
| Purpose | Code | Guidance |
| --- | --- | --- |
| Current financial execution | `src/financial/`, `src/api/replay.rs`, `src/api/paper.rs` | Use for canonical research and paper execution. Preserve deterministic ordering, financial invariants and recovery contracts. |
| Indicators and analytical calculations | `src/indicators/`, `src/analytics/`, native risk/orderbook analytics, `libs/calculations/` | Retained capabilities. Reuse reviewed implementations and their fixtures. |
| Legacy native execution and accounting | `TradingEngine`, native `BacktestEngine`, `src/core/`, `src/backtest/`, `src/positions/`, `src/risk/`, `src/strategies/` | Retained for compatibility, regression tests and existing algorithm examples. They are not an alternative execution path for current admitted research jobs. |
| Uncompiled reporting reference | [reference/legacy-reporting](reference/legacy-reporting/README.md) | Original calculation prototypes retained byte-for-byte for inspection. Incomplete and unreviewed; not a runtime API or an oracle for financial results. |
The compiled `src/backtest/simple_results.rs`, `src/strategies/mean_reversion_fixed.rs`, public native constructors, and historical regression fixtures are unchanged by this cleanup. No saved dataset, strategy package, result or checkpoint is migrated or removed.
## CL15 removal and preservation inventory
Evidence baseline: `700ee09c`. Cargo's library target is `src/lib.rs`; its module declarations, `src/backtest/mod.rs` and `src/strategies/mod.rs` define the compiled graph. Repository searches found no consumers of the removed adapters outside their own implementation and this former migration guide.
| Previous path under `src/` | Disposition and reason |
| --- | --- |
| `adapters/{mod,events,strategy}.rs` | Removed unused compiled migration scaffold. The execution adapter fabricated price-100 fills without invoking the wrapped handler; status queries fabricated `Filled`. Event and strategy adapters targeted placeholder interfaces. None were NAPI exports or used by repository tests/applications. |
| `lib_new.rs`, `lib_simplified.rs`, `test_lib.rs` | Removed undeclared alternative crate roots. Cargo has no target or source inclusion for them. |
| `api_new/{mod,backtest,market_data,orders,positions,strategies,system}.rs` | Removed undeclared API skeleton targeting the abandoned root/domain/mode design; many operations were `todo!`. Current `src/api/` is retained. |
| `domain.bak/{mod,market,orders,positions,events}.rs` | Removed undeclared duplicate domain types and elementary position helpers. Compiled legacy types/accounting remain in `src/lib.rs` and `src/positions/`; canonical equivalents remain in `src/financial/`. |
| `events.bak/mod.rs` | Removed undeclared event-bus scaffold. No current event or recovery journal uses it. |
| `modes.bak/{mod,backtest,paper,live}.rs` | Removed undeclared alternate runtime, mock broker and simplistic fill/accounting implementations. These depended on the abandoned event/domain design, not the canonical matcher or any supported broker. |
| `strategies/framework/mod.rs` | Removed undeclared generic strategy trait/context and no-op base strategy. It contained no concrete signal algorithm; all compiled strategies remain. |
| `backtest/metrics_calculator.rs`, `backtest/results.rs` | Moved unchanged to `reference/legacy-reporting/`. They were not declared in `backtest/mod.rs`. Retained because they contain statistical/reporting prototypes and supporting result types worth inspecting before any later reuse. |
The archived calculator includes return, drawdown, streak and symbol-analysis logic alongside placeholder fields and incomplete methods. Moving it does not make those formulas reviewed or compilable. New calculations should enter the reviewed calculation library with explicit semantics and tests, not reactivate the abandoned financial simulator.
## Verification
Run the Rust library tests and rebuild the addon from the same checkout before native binding, market-data and terminal-equity integration tests. Existing architecture checks must continue to prevent production TypeScript entrypoints from reaching prototype financial execution. This cleanup changes the source/module surface, not economic policies, native wire contracts or existing saved artifacts.