# F07 — Expose bounded Rust step sessions through existing NAPI workers Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Rust/TypeScript integration. Scheduling source of truth: [manifest entry F07](../manifest.json). 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 - **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). - **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194). - **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). ## 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 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. ## Execution handoff clarifications - Add a separate NAPI FinancialReplaySession and a fixed-intent-trace request variant in the existing worker. Keep the legacy run request and durable runner default unchanged. The trace path is for conformance/debugging, not a declarative strategy language or S01 strategy runtime. - Verify frozen D01 inputs inside the worker before native creation; native prepared input remains a trusted host boundary, not independent proof of a supplied dataset hash. Convert represented numeric values to plain decimal strings, expanding scientific notation and rejecting precision/range loss rather than silently rounding. - Pin a strict version/session/dataset envelope and validate response identities. Emit prefix observation deltas and one shared financial/order/risk view; never pass full prepared data/checkpoints to a callback or clone retained checkpoints in the hot loop. A small read-only F06 range accessor is permitted; replay and risk semantics are not changed. - Permit a test-only include of the new adapter from the financial test module: the crate excludes its API module from ordinary unit builds. Exercise the production host/direct-Replay parity without enabling unrelated legacy NAPI wrappers or changing production module direction. The thin exported wrapper delegates one-to-one to that host and is separately tested through the built addon. - The conformance loop may evaluate fixture callbacks in varied order, but submits the complete due-owner batch once. Callback failure fails/disposes the attempt; no partial submission or later successful finalization. Production strategy state/RNG, artifact imports and durable canonical cutover remain S01/R05. - Preserve existing process supervision: one process/request, hard cancellation, wait for close after a result, rejection after abort, failed worker reuse and stale attempt protection. Run existing runner cancellation/lease regressions, including the disposable PostgreSQL suite at integration. - Extend the existing P01 harness with actual session preparation/load, advance/submit call timings and counts, context/delta bytes and finalization. Calls include real Rust/serialization work; do not label them empty crossings or end-to-end strategy throughput. ## Exclusions No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. ## Likely files and ownership - apps/stock/engine/src/api/replay.rs (additive session; existing backtest API unchanged) - apps/stock/engine/src/financial/replay.rs (read-only published-observation range accessor only) - apps/stock/orchestrator/src/backtest/native-replay.ts - apps/stock/orchestrator/src/contracts/native-replay.ts (schema-only boundary) - apps/stock/orchestrator/src/backtest/native-worker.ts - apps/stock/orchestrator/src/backtest/native-worker-protocol.ts - apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts - scripts/benchmark-research.ts and focused native/worker fixtures Write locks: native-public-api, worker-protocol. One agent owns this change. Lock names do not override actual overlapping files. ## Dependencies and blockers Implementation requires [F06](F06.md), [C02](C02.md) integrated. Architecture decisions: ADR-004. 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 - TS caller handles every step variant; it never assumes each advance returns a decision. Progress/cancel boundaries remain bounded. - All due decisions reference one barrier revision. Reversing callback evaluation order cannot change output when contexts/states are unchanged; final admission uses declared owner priority. - No partial barrier is committed if a decision throws. Rust returns per-intent accepted/rejected outcomes; business rejection is not a rollback of the observed decision event. - Native conformance intent trace and TS fixture use identical financial transitions. Native built-in production strategy parity is not required. - Worker crash/cancel/lease loss cannot publish successful stale results; snapshot/ID/version mismatches reject. ## Mandatory tests - step_tagged_union, immutable_barrier_revision, reverse_callback_order, decision_exception_aborts_barrier, rejected_intent_is_committed_outcome. - Existing native-worker/runner cancellation and lease tests; extend P01 with step and context-byte timings. 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. ## 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.