feat(engine): add deterministic historical replay

This commit is contained in:
Boki 2026-10-22 23:34:35 -04:00
parent ccf333cc0a
commit 417a7bd21e
10 changed files with 2055 additions and 28 deletions

View file

@ -16,6 +16,16 @@ Implement the replay cursor once: sorted immutable events with stable availabili
Consume F05's explicit event contract without reconstructing a second matcher: quote observation time is not delivery time, and eligibility requires an order to be ready by physical quote time. Open time must equal its execution key; skip/reject missed opens, never relabel them as newly occurring. Decision admission uses the coordinator's shared portfolio/order revision, distinct from the nested economic ledger revision. Terminal F05 failures retain diagnostic prefixes but must fail/discard the replay attempt, never produce successful performance results.
## Execution handoff clarifications
- Add an internal prepared-input cursor over MatchingAccount, not a second public session API or a legacy-runtime cutover. D01 currently has bar datasets only: reject quote-mode replay input until a quote dataset contract exists. Existing F05 quote tests remain relevant matcher evidence, not a claim of quote replay support.
- Accept typed prepared bars with canonical decimals and retained session boundaries. Document that F07 must verify/adapt the frozen D01 snapshot; do not duplicate the TS normalizer/hash algorithm. Validate executable-series/config agreement, raw execution prices, bounds and eligibility; retain exploratory limitations. Bind checkpoints to the exact prepared input/config, not only a caller-supplied dataset label.
- Initialize using true venue open times, including the preceding open for a mid-session warmup/start. Never restamp missed opens. Publish late observations without regressing authoritative mark time; capacity uses the physically latest completed available execution-series volume, not latest arrival or future volume.
- Resolve feature-series sequence ties with stable series identity. Only declared cadence triggers decisions; due owners share one immutable context/revision. Warmup cannot trade; observations at tradeEnd may mark only; later observations are unavailable.
- Internal barrier/cursor/checkpoint and fixed decision-trace replay belong here. Public NAPI session protocol, frozen dataset transport, TS strategy state/RNG and strategy recomputation belong to F07/S01. Prefer offset-based observation prefixes to copying all history on every advance.
- Sorting may be O(n log n); traversal is linear plus matching/risk work. Measure 1k/10k/100k release workloads with economics equality and explicit load/replay timing. This is a canonical Rust component measurement, not TS callback or end-to-end research throughput.
- Existing F04/F05 policy evaluates risk after each mark. Equal-time cross-asset marks are applied in deterministic instrument order, not atomically: an intermediate portfolio value can latch a loss/drawdown halt even when the final same-time valuation recovers. Pin this behavior with a permutation regression and disclose it as a modeling limitation. Do not implement an F06-local risk bypass or silently introduce atomic marking; changing that economic policy requires coordinated approval and fixtures.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
@ -47,6 +57,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks;
- adjacent_open_zero_latency, positive_latency_skips_open, future_ohlcv_does_not_change_open_fill, daily_close_target_survives_to_open.
- feature_timeframe_does_not_duplicate_liquidity, equal_timestamp_symbol_permutation, warmup_cannot_trade, stale_mark_timestamp_preserved.
- Replay/restore trace equality. Extend P01 with1k/10k/100k release-build load/replay scaling; preserve economics before accepting faster runs.
- Delayed older observations do not regress marks/capacity; mid-session starts retain true session boundaries; terminal observations are mark-only; equal-time feature-series sequence ties are stable; altered input/config checkpoint restore rejects.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.

View file

@ -12,7 +12,11 @@ Scheduling source of truth: [manifest entry F07](../manifest.json). No task is a
## Intended behavior and implementation scope
Expose a small pull session (load/create/advance/submit/finalize/dispose) in the existing worker, backed by the same financial kernel. advance returns a tagged union: progress, decision batch, or complete. For a decision batch, all due strategies receive immutable views from the same ledger revision; collect all decisions before ordered admission. Use one native test strategy/intent trace for conformance, not a port of every Rust built-in. Per-session dataset load once; cross-trial residency is P03.
Expose a small pull session (load/create/advance/submit/finalize/dispose) in the existing worker, backed by the same financial kernel. advance returns a tagged union: progress, decision batch, or complete. For a decision batch, all due strategies receive the same immutable financial view; collect all decisions before ordered admission. The submission token is F05/F06's coordinator admission revision, not the nested ledger snapshot revision (reservations and order state can change without an economic posting). Use one native test strategy/intent trace for conformance, not a port of every Rust built-in. Per-session dataset load once; cross-trial residency is P03.
F06 consumes internal typed prepared bars/session tables, not an independently authenticated D01 snapshot. This adapter must verify the frozen v2 dataset with the existing normalizer/hash verifier, preserve its hash/eligibility/limitations, convert numeric fields through canonical decimal ingress, and map exact calendars/execution series/bounds into F06. Do not trust a supplied hash label alone or reconstruct a competing normalizer. Quote replay stays unsupported until its dataset contract is explicitly added. Retain prefix-only strategy contexts; do not expose native full-dataset/checkpoint host handles to strategy callbacks.
Expose recorded model limitations, including F06's explicitly unsupported abutting venue sessions and F04/F05's sequential equal-time portfolio marks (intermediate valuations can latch risk halts). An event budget bounds event count, not wall time or the cost of an individual matching transition. These are not promises of atomic multi-asset valuation, arbitrary-calendar support or constant-latency cancellation.
## Exclusions

View file

@ -48,6 +48,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks;
- Sharpe uses periodic excess-return mean/std; Sortino uses downside deviation relative to the declared target; zero-variance/undefined cases are null with reasons.
- Exposure uses the union of occupied intervals; open positions count; attribution distinguishes fills and round trips.
- Reviewed calculation functions are reused where their conventions match. Any deliberate difference has a versioned policy and independent arithmetic fixture, not an unexplained second formula.
- Preserve the sequential equal-time marking policy and its material risk limitation in result provenance: intermediate valuations may latch halts despite a recovered synchronized value. Do not report such traces as atomically marked portfolio risk. Before canonical multi-asset default cutover, apply R05's explicit owner policy-review gate; component F06 acceptance does not satisfy it.
## Mandatory tests

View file

@ -42,11 +42,13 @@ Parallel eligibility: only with disjoint actual files and reserved write locks;
- Changing template, strategy source or provider history after dataset freezing cannot alter an admitted run. A source query alone is not labelled a frozen dataset.
- No strategy decision executes before artifact verification and atomic dataset binding; failed preparation remains diagnosed and retry-safe.
- New results declare financialEngine=rust and strategyExecution separately; correctness-gate evidence requires approved engine/data gates, not a UI flag.
- Before making canonical multi-asset research the default, obtain explicit owner disposition of sequential equal-time mark risk: either accept the disclosed versioned approximation or approve a coordinated atomic-mark policy/implementation with independent fixtures. F04/F05 currently evaluate each ordered mark; F06 demonstrates offsetting simultaneous moves can latch intermediate loss/drawdown halts. A passing deterministic replay suite alone does not resolve this material modeling issue. Single-asset component work and additive native integration need not wait for this decision.
## Mandatory tests
- mutate_template_after_submit, freeze_before_first_decision, frozen_seed_replay, provider_change_after_dataset_bind.
- Full durable runner restart/lease/cancel suite and result contract compatibility.
- Multi-asset default activation rejects while the mark-policy disposition is absent; accepted policy/version/limitations are frozen in provenance, with offsetting-mark regression evidence.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.