stock-bot/docs/development/backlog/tasks/F06.md

7.7 KiB

F06 — Implement deterministic replay once, with linear historical traversal

Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Rust deterministic replay.

Scheduling source of truth: manifest entry F06. No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.

Evidence and root cause

Intended behavior and implementation scope

Implement the replay cursor once: sorted immutable events with stable availability/phase/instrument/sequence ordering; add a small pending-event queue only where required. Absorb P02's nonquadratic load and disabled-by-default hot-loop trade logging. Generate open-only execution events from one designated execution series; feature-only frames do not add liquidity or undeclared decision triggers. Publish completed observations, evaluate declared decision barriers, then next-interval opens under recorded zero/nonzero latency policy.

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.

Likely files and ownership

  • apps/stock/engine/src/backtest/engine.rs
  • apps/stock/engine/src/backtest/mod.rs
  • apps/stock/engine/src/financial/replay.rs (new)

Write locks: rust-replay. One agent owns this change. Lock names do not override actual overlapping files.

Dependencies and blockers

Implementation requires F05, D01, P01 integrated.

Architecture decisions: ADR-003. Agents may not independently amend their policies.

Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.

Acceptance criteria

  • Permuting file arrival order does not change economic results after canonical event ordering.
  • Daily observations remain unavailable before session close; different symbols retain their actual quote timestamps.
  • Multi-timeframe context includes only completed available bars and marks missing/stale inputs explicitly.

Mandatory tests

  • 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. Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.

Regression risks and rollback

Financial or compatibility regression; preserve existing fixtures and version changed semantics. Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.

Handoff

Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.