Refactor execution boundaries and add durable strategy recovery
This commit is contained in:
parent
d6b09eb635
commit
694c48bbdb
36 changed files with 3077 additions and 491 deletions
101
README.md
101
README.md
|
|
@ -65,6 +65,38 @@ Handler initializers receive their scanner/registry explicitly through the DI ap
|
|||
initialization context. WebSocket connections and completion timers belong to the socket
|
||||
handler and are released on close/shutdown.
|
||||
|
||||
## Orchestrator boundaries and extension points
|
||||
|
||||
Keep runtime composition in `container.ts`; domain code receives explicit capabilities,
|
||||
not the application service container:
|
||||
|
||||
- `contracts/` holds runtime validation schemas. Contracts and the native worker protocol
|
||||
cannot load storage, native engines, or server adapters.
|
||||
- `execution/model.ts` owns accounting/risk rules; `execution/repository.ts` is the storage
|
||||
port, independent of either implementation.
|
||||
- `SimulationExecution` applies order admission, matching and accounting inside the caller's
|
||||
transaction. It does not open transactions or publish notifications.
|
||||
- `StrategyRecovery` owns decision scopes, checkpoint/cursor commits and outbox replay.
|
||||
Its typed runtime port preserves the gateway's transaction and serialization boundaries.
|
||||
- `ExecutionService` composes those components, owns lifecycle/market admission, selects the
|
||||
repository, and publishes only after commit. HTTP and strategies continue using this gateway.
|
||||
- `StrategyManager` owns lifecycle/delivery; `StrategyRegistry` owns strategy factories and
|
||||
aliases. Add a lazy factory to `createBuiltinStrategyRegistry()`, or provide a custom
|
||||
`strategyRegistry` to `registerOrchestratorServices`. No manager switch needs updating.
|
||||
Keep persisted aliases stable; a custom registry must also be supplied on restart.
|
||||
|
||||
New paper strategies must provide a complete versioned checkpoint contract and recovery
|
||||
tests. Registering a factory does not bypass risk checks or the durable-checkpoint requirement.
|
||||
The experimental ML strategy remains unavailable for paper execution.
|
||||
|
||||
Architecture tests run in `bun run check`, checking runtime dependency cycles and the
|
||||
contract/domain/adapter boundaries. The run-local ledger stages only transaction writes,
|
||||
indexes active work and client IDs, and binary-searches the journal; retained history is not
|
||||
deep-copied for every read. Reads/writes remain detached and failed transactions publish
|
||||
nothing. History is still retained in memory for the run; this is not a streaming/retention
|
||||
solution. Run `bun run scripts/benchmark-execution.ts` for a local journal-read microbenchmark,
|
||||
not an end-to-end backtest performance estimate.
|
||||
|
||||
## Backtest data integrity
|
||||
|
||||
Historical storage no longer invents prices when a database is unavailable. Configure a
|
||||
|
|
@ -130,6 +162,68 @@ and an explicit retention policy before scaling.
|
|||
|
||||
## Simulation order execution
|
||||
|
||||
### Durable strategy recovery
|
||||
|
||||
Apply additive migration `13-strategy-recovery.sql` through the web API before starting
|
||||
the orchestrator. Paper startup restores registered strategy configurations and their
|
||||
checkpoints before connecting the feed. No running database is migrated by the tests.
|
||||
|
||||
The recovery path has four checked transaction boundaries:
|
||||
|
||||
1. Validate and durably admit a uniquely identified market payload into
|
||||
`simulation_market_inputs`; retries cannot append a second input or change its payload.
|
||||
2. Apply the next input's quote/account changes and resting-order fills, journal the
|
||||
execution notifications and market payload, and mark the input applied atomically.
|
||||
3. Restore each strategy's latest checkpoint under the account row lock, evaluate its
|
||||
next journal record, then commit indicator/base state, cursor, and order intents together.
|
||||
4. Dispatch an intent through the ordinary risk/idempotency gateway; order/fill accounting,
|
||||
its execution journal notification, and the intent's dispatched status commit together.
|
||||
|
||||
New inputs can queue during an outage or strategy error. Later inputs and new manual
|
||||
orders cannot advance past unfinished enabled-strategy delivery or pending intents.
|
||||
Idempotent order retries still return their committed report; explicit cancellations remain
|
||||
available. Execution/fill notifications have their own durable cursor delivery, not a
|
||||
volatile callback. Strategy reads use the journal's as-of account view, not future quotes.
|
||||
Competing service instances always restore the locked checkpoint before evaluating a step.
|
||||
The manager retries recovery every second without requiring another feed tick, and
|
||||
`GET /api/recovery` exposes pending work and per-strategy cursor lag behind normal API auth.
|
||||
|
||||
SMA (both implementations) and mean reversion have explicit versioned indicator contracts.
|
||||
Base checkpoints include positions, pending orders, performance and a bounded recent-fill
|
||||
cache; the durable cursor, not the cache size, guarantees delivery deduplication. A changed
|
||||
configuration or checkpoint/implementation version requires an explicit new strategy ID;
|
||||
there is no implicit state reset or best-effort schema coercion. Developers must bump the
|
||||
strategy version when its state or decision semantics change. Custom paper strategies must
|
||||
implement and validate their complete finite-JSON checkpoint. Uncheckpointed/experimental
|
||||
ML paper strategies fail **before** model startup: asynchronous model training and weights
|
||||
do not yet have a replay-safe artifact contract. Run-local backtests can still use explicitly
|
||||
unversioned experimental strategies, without claiming restart recovery for their custom state.
|
||||
|
||||
Strategy evaluation must be bounded and deterministic: no fire-and-forget state mutation,
|
||||
wall-clock/random decisions, broker calls, model training or external I/O in callbacks.
|
||||
Repository I/O/direct submissions from a callback fail closed; use the as-of account view
|
||||
and captured order intents. These callbacks run under an account lock, so an unbounded
|
||||
custom callback stalls that account until its owner exits; isolation/time limits for arbitrary
|
||||
third-party code are not provided here. Noncritical signal/UI observers run after commit;
|
||||
their failure cannot erase a financial intent, but those observations are not a durable bus.
|
||||
|
||||
Graceful shutdown suspends strategies without cancelling durable orders or erasing indicators.
|
||||
`StrategyManager.disableStrategy` pauses **new decisions**, preserving already committed
|
||||
intents and open orders; it is not an emergency order-cancel switch. Disabled-period market
|
||||
records do not become retroactive signals on re-enable. To cancel, use the explicit order
|
||||
API (or an intentional strategy stop). If a recovered paper quote has aged out, its indicator
|
||||
state is recovered but it cannot generate fabricated historical fills: resulting stale-price
|
||||
orders are rejected by the normal gateway.
|
||||
|
||||
Legacy fingerprints without payloads are preserved, not invented into replay history.
|
||||
New registrations begin at the current journal boundary with the existing financial
|
||||
projection; pre-migration indicators/performance cannot be reconstructed automatically.
|
||||
This guarantees recovery of **admitted** inputs, not delivery from an upstream socket before
|
||||
admission. A provider replay/acknowledgement protocol is still required for that boundary.
|
||||
Journal/input/history tables currently retain JSONB payloads and as-of account snapshots;
|
||||
configure an archival/retention design before high-volume production use. Do not delete
|
||||
history still needed by a paused strategy's cursor.
|
||||
|
||||
`ExecutionService` is the runtime order gateway for REST, Socket.IO (when enabled), and
|
||||
TypeScript strategies. `PaperTradingManager` is a compatibility facade, not a separate
|
||||
simulator. Strategies consume only the ordered batch stream; individual-event broadcasts
|
||||
|
|
@ -156,7 +250,8 @@ Paper configuration accepts `accountId` (default `paper-default`), `riskLimits`,
|
|||
`slippage`, and `maxQuoteAgeMs` (default 60000). Restarting the same account restores cash,
|
||||
positions, per-strategy quantities, consumed quote liquidity, and unfilled orders; it never
|
||||
resets capital. A different starting capital requires an explicit new account ID. Strategy
|
||||
indicator state is not checkpointed; strategies still need their normal warm-up. Pending
|
||||
indicator state is checkpointed for supported strategies; a new strategy still needs its
|
||||
normal warm-up. Pending
|
||||
orders retain the commission/slippage policy under which they were accepted.
|
||||
|
||||
Order HTTP/Socket.IO submissions require a nonempty `clientOrderId`. Retrying an identical
|
||||
|
|
@ -164,8 +259,8 @@ request returns the existing order; reuse with different fields is a conflict (H
|
|||
Strategies derive stable IDs from the strategy and source event. Supply a stable, unique
|
||||
`eventId` on market data; identical replay is ignored, conflicting reuse is rejected. Without
|
||||
an ID, a deterministic hash of the canonical event is used (identical same-timestamp payloads
|
||||
are indistinguishable). Source events commit before strategy callbacks; a crash in that gap
|
||||
can omit a signal, so this is not an exactly-once strategy-state recovery guarantee.
|
||||
are indistinguishable). Admitted source events, strategy delivery and financial notifications
|
||||
now have durable recovery as described above; this is not a real-broker exactly-once guarantee.
|
||||
|
||||
The deterministic simulator supports market/limit orders and DAY/GTC/IOC/FOK. Quote depth
|
||||
is consumed across orders, partial fills await fresh events, and limit orders never fill
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue