# Reading the implementation [Guide home](README.md) · [System map](system-map.md) · [Backtest walkthrough](backtest-walkthrough.md) · [Strategy authoring](strategy-development.md) This guide follows **functions and state**, rather than application boxes. The linked TypeScript files now have explanatory TSDoc comments, and the Rust financial modules have module and method documentation. Read these beside the implementation; you can hover documented symbols in your editor. ## 1. Begin with the decision contract Open [canonical-strategy.ts](../../apps/stock/orchestrator/src/contracts/canonical-strategy.ts). `StrategyProgram` describes the object a strategy factory returns. Its `decide(context)` callback returns two things: - `nextState`: what the strategy wants to remember for its next decision. - `intent`: what exposure or orders it wants the financial engine to consider. Neither is a database write or a completed trade. `StrategyContext` is a read-only view. `positions` contains this owner's holdings; `portfolio.portfolio.positions` contains holdings across the account. `observations` contains the published input accumulated since this owner last ran. Keep any longer feature history in explicit state. Then read [canonical-sma.ts](../../apps/stock/orchestrator/src/strategies/canonical-sma.ts). Follow `createSmaStrategy()` into `decide()`: validate/restore state → consume fresh observations → calculate crossover → return a target. The resulting quantity is a total desired holding. Rust decides the difference between that target, current holdings and working orders. **A useful distinction:** a rejected order can still be a successfully processed strategy decision. The callback's state and random cursor advance when the native admission response is confirmed, even if risk rejected the requested order. Waiting for a fill before committing all strategy state would have different semantics. ## 2. Follow one callback into Rust Read these symbols in order: | Symbol | What to trace in its body | | --- | --- | | [`prepareReplayLoad()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Revalidates dataset bytes, matches execution series, and converts prices and names into the native wire format. It does not calculate strategy features. | | [`runStrategyReplay()`](../../apps/stock/orchestrator/src/backtest/strategy-runtime.ts) | Creates the controller and native session for a fresh attempt. Success includes diagnostics; failure retains the last confirmed diagnostics. | | [`NativeReplaySession.advance()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Calls the NAPI addon and validates the returned identity and schema. `eventBudget` limits work per call, not the number of bars in the experiment. | | [`replaySteps()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Accumulates observations until Rust requests a decision. Its generator alternates between staging decisions and confirming admission; both synchronous and isolated async drivers use it. | | [`StrategyController.stage()`](../../apps/stock/orchestrator/src/strategies/strategy-controller.ts) | Buffers inputs per owner and calls only owners due at the barrier, all against the same financial view. The next callback states are still proposals. | | [`stageStrategyDecision()`](../../apps/stock/orchestrator/src/strategies/strategy-decision.ts) | Constructs the owner-specific context, provides the seeded RNG, rejects async/lossy state, and stamps the decision identity. | | [`NativeReplaySession.submit()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Sends the complete batch to Rust and reads admission feedback. Later eligible market events determine actual fills. | | [`StrategyController.committed()`](../../apps/stock/orchestrator/src/strategies/strategy-controller.ts) | Checks revision and feedback for every staged owner before replacing confirmed state. Clears consumed input for owners that ran. | A **barrier** is a point where Rust pauses historical advancement so all due strategies can decide from one account view. A faster callback must not get a newer view just because another callback already returned. A **revision** identifies which account/admission state a message belongs to; it helps reject stale or mismatched responses. The research diagnostic snapshot is deliberately not a resume token. It lacks the complete financial state. An interrupted durable research attempt starts from the retained original inputs with a fresh native session. Paper recovery has its own durable account/checkpoint protocol. ## 3. Read the financial modules as a chain of responsibilities Start at [financial/mod.rs](../../apps/stock/engine/src/financial/mod.rs), then: | Module and symbols | What they own | | --- | --- | | [`Replay::events`, `advance`, `submit`](../../apps/stock/engine/src/financial/replay.rs) | Schedule available observations and physical execution events, stop for decisions, and require exactly the pending owners. Look at event phases and tie-breaking before changing timing. | | [`MatchingAccount::apply`, `submit`, `execute`](../../apps/stock/engine/src/financial/matching.rs) | Reconcile targets/orders, preserve correctly sized pending orders, apply execution eligibility and distribute finite fill capacity. | | [`RiskAccount::apply`, `reservation`](../../apps/stock/engine/src/financial/risk.rs) | Reserve cash or owner inventory and enforce financial constraints. An affordable order at submission can become unaffordable at a later gap price. | | [`Ledger::apply`, `apply_fill`, `valuation`](../../apps/stock/engine/src/financial/ledger.rs) | Post actual fills/fees, maintain owner cost basis and shared cash, and value remaining inventory. Checked decimal arithmetic lives in [scalar.rs](../../apps/stock/engine/src/financial/scalar.rs). | Two details explain otherwise surprising results: - At a bar's open, that bar's completed volume is still future information. Replay uses the latest published completed bar's volume for capacity. No known volume means no fill capacity. - Ending a replay cancels working orders and values existing holdings. It does not invent a liquidation trade or a closing fee. Inspect positions as well as closed trades. The financial interfaces have command identities and receipts for retry handling. An exact retry may return old effects marked as replayed; callers must not publish them twice. A receipt is not the same thing as a strategy decision, a durable run or a worker attempt. ## 4. Understand how execution survives outside one process The native session above is disposable. The durable workflow around it uses SQL state: 1. [`BacktestServiceV2.createRun()`](../../apps/stock/web-api/src/services/backtest-v2.service.ts) locks the saved template, admits its inputs and inserts both the frozen run request and `backtest_dispatch` row. A submission key recovers the same run after an uncertain HTTP response. 2. [`admitCanonicalRequest()`](../../apps/stock/web-api/src/services/canonical-research.service.ts) resolves the retained version/dataset/build and constructs policies and a research account identity. It returns a request; it does not enqueue or simulate it. `canonicalCapability()` uses admission as a preview; new submissions check again, while receipt retries recover their already admitted run. 3. [`BacktestDispatcher.dispatch()`](../../apps/stock/web-api/src/services/BacktestDispatcher.ts) first recovers expired leases, then reserves due outbox rows in SQL, then publishes run IDs to Redis outside the transaction. A failed publish delays delivery without deleting the saved intent. 4. [`BacktestRunner.runQueued()` and `execute()`](../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts) load the saved request and claim an attempt. `execute()` coordinates heartbeats, progress, cancellation, worker execution and completion. It never edits a paper account. 5. [`PostgresBacktestRunRepository.startCanonical()`](../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts) gives the worker a fresh attempt ID and lease. `loadCanonicalDataset()` checks the bound bytes under that ownership. `completeCanonical()` commits the validated result and completed status together. The worker's **attempt ID is a fencing token**: SQL compares it with the current owner before allowing a write. A stopped worker that wakes up late cannot overwrite a replacement's result. The lease also has to be unexpired according to database time. A local Boolean such as `busy` only protects one runner instance; it cannot replace those database checks. `BacktestRunner.execute()` has three phases: preparing, executing and persisting. Read its `try/catch/finally` as carefully as its success path. Lease uncertainty stops the attempt; it does not authorize the old worker to mark the run failed. Progress writes are drained before completion, and cleanup waits for heartbeat work before reusing the runner. The adapter/process boundary is [RustBacktestAdapter.runCanonical()](../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts) → [NativeBacktestWorker.execute()](../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts) → [native-worker.ts](../../apps/stock/orchestrator/src/backtest/native-worker.ts). The parent can terminate a child that is stuck in native computation. The child still uses the same Rust engine; spawning a process does not introduce another simulator. ## 5. Trace the browser state separately Open [useBacktestV2.ts](../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts), then its caller [BacktestDetailPageV2.tsx](../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx). - `loadBacktest()` loads the editable definition and run list. Generation counters discard late replies after navigation. - `selectRun()` and `refreshSelection()` own one status → result request chain. Polls and WebSocket refresh notifications converge on that chain. - `stopMonitoring()` aborts browser reads. `cancelRun()` requests server cancellation. Leaving the page is not cancelling the experiment. - `createRun()` keeps an in-memory submission key/body after an uncertain response. A repeated click can recover the same accepted run; this is not a persistent browser journal. - `runResults` comes from the saved result API. Charts render those facts; they do not reconstruct cash or fills from a second model. The state names reflect different lifetimes: **template**, **selected run**, **submission**, and **result**. Combining them into one loading/error flag would make navigation and retry behavior harder to represent correctly. ## 6. Where a change belongs | You want to change… | Start here | | --- | --- | | A signal, regime filter or entry/exit decision | Canonical strategy and its parameter/state contracts; see the [strategy guide](strategy-development.md). | | An indicator used in several places | [libs/calculations](../../libs/calculations/README.md), with its warmup/alignment semantics and fixtures. | | Which retained inputs can run | `validateCanonicalSetup()` / `admitCanonicalRequest()` and shared [canonical-research contracts](../../apps/stock/config/src/contracts/canonical-research.ts). | | Fill timing, fees, funding or position accounting | The corresponding Rust financial module and its existing regression tests. | | Worker retry, cancellation or result persistence | Dispatcher, runner and repository; keep attempt ownership checks intact. | | A run display, selection or loading/error state | Backtest feature components, hook and typed API client. | Read tests as concrete examples of the contracts: - [strategy-runtime.test.ts](../../test/integration/strategy-runtime.test.ts): owner isolation, buffered cadence, rejected intents, unconfirmed state and future-data boundaries. - [canonical-sma.test.ts](../../test/integration/canonical-sma.test.ts): hand-checkable signals, next-open fills and money. - [canonical-durable-runner.test.ts](../../test/integration/canonical-durable-runner.test.ts): cancellation, lease loss and retired execution paths. - Rust [replay](../../apps/stock/engine/src/financial/replay_tests.rs), [matching](../../apps/stock/engine/src/financial/matching_tests.rs), [risk](../../apps/stock/engine/src/financial/risk_tests.rs) and [ledger](../../apps/stock/engine/src/financial/ledger_tests.rs) tests: the economic invariants behind each layer. For a first reading exercise, follow a request for ten shares through `stage()` → `submit()` → a later `execute()` → `apply_fill()`. At each step ask: **is this proposed state, accepted state, or persisted state?** Those boundaries explain most of the checks in this execution path.