# F04 — Enforce cash reservations and portfolio risk centrally Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: L. Recommended specialization: Rust financial risk. Scheduling source of truth: [manifest entry F04](../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-03 — Verified:** Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash. [apps/stock/engine/src/risk/mod.rs:89](../../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../../apps/stock/orchestrator/src/execution/model.ts#L234). - **FIN-06 — Verified:** Native simulation fills complete requested quantities at the latest price without bar-volume participation; current risk must be enforced at acceptance and fill, including pending exposure. [apps/stock/engine/src/backtest/engine.rs:374](../../../../apps/stock/engine/src/backtest/engine.rs#L374); [apps/stock/engine/src/backtest/engine.rs:414](../../../../apps/stock/engine/src/backtest/engine.rs#L414). ## Intended behavior and implementation scope Implement canonical cash-long-only funding, pending fee-inclusive reservations, fill-time affordability and existing per-order/symbol/gross limits. Accept explicit account RiskSessionBoundary commands from the F01 contract; do not infer a day from UTC or independently roll for every venue. Marked daily-loss and drawdown checks use canonical marks. Session rollover resets only daily baseline; peak equity and drawdown halt persist until authorized reset. ## Exclusions No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. ## Execution policy clarifications The approved ADRs remain unchanged. The initial additive implementation pins these explicit configuration semantics; no default production thresholds or active-account migration are introduced: - Quantity units for order/position limits; base-currency amounts for symbol/gross exposure, daily loss and explicitly named maximum drawdown amount. Commission is an immutable Rust rate in [0, 1], calculated from exact quantity × price × rate and rounded once at eight places. - Pending buys reserve fee-inclusive cash at the canonical mark (market) or max(mark, limit). Pending sells reserve owner inventory, never anticipated buying power; their fill proceeds fund fees. Pending sells do not offset buy exposure. Actual fills recheck other commitments and the remainder, including split-fill rounding. Unaffordable remainder rejects/releases without resizing or borrowing. - Increasing risk requires fresh non-future canonical marks across held and pending assets, using explicit engine event time and a configured maximum mark age. Reductions still enforce inventory/funding/order-size rules. Daily and drawdown halts latch on marked loss; explicit account boundaries reset only daily state, including when retained marks are old. Same-session repetition cannot rebase, and future/backdated boundaries reject. - A private-owned Ledger facade is the only canonical risk entry point. Normalized explicit-order and target-derived admission share one policy; actual target expansion, mode enforcement, matching, venue expiry scheduling and replay remain F05/F06. Resource-release hooks are not a second matcher. - Operator reset is a separate host-held capability with recorded reason/baseline, absent from strategy inputs. This is API authority separation, not authentication or an untrusted-code sandbox. F07 must expose only the risk-governed facade; later host/auth adapters must enforce their own authority. - Checkpoints validate reservations, risk state and recorded outcomes by deterministic reconstruction. They do not authenticate an attacker-modified history and are not full replay/strategy/RNG or SQL recovery snapshots. Normal transitions must not copy/replay the entire retained history. ## Likely files and ownership - apps/stock/engine/src/risk/mod.rs (reference only during additive implementation) - apps/stock/engine/src/financial/risk.rs (new) - apps/stock/engine/src/financial/ledger.rs Write locks: rust-ledger, risk-policy. One agent owns this change. Lock names do not override actual overlapping files. ## Dependencies and blockers Implementation requires [F02](F02.md) integrated. Architecture decisions: ADR-002, 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 - No accepted order/fill creates negative available cash or an unsupported short. - Pending/partial orders reserve resources once and release on cancellation/rejection/expiry. - Stale marks block risk increases; marked losses halt increases even without realized trades; reductions remain possible. ## Mandatory tests - competing_reservations, adverse_gap_reject_remainder, stale_other_symbol, marked_loss_halt, explicit_risk_session_boundary. - drawdown_halt_survives_rollover_restore, unauthorized_reset_denied, alternate_venue_does_not_reset_account_day. - Property test raw order and target paths cannot bypass the same policy. - Partial-fill quantum rounding, zero-cash funded sell, pending sells do not credit buy exposure, stale/future other pending symbol, wrong-owner sell/cancel, accepted/rejected command replay and conflicting reuse, same-session no-rebase, future/backdated boundary rejection, restored reservation tamper and overflow atomicity. 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.