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

48 lines
6.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# F09 — Return compact canonical replay projections
Parent epic: E2. Priority/severity: P1 / High. Complexity: M. Specialist: Rust/TypeScript financial integration.
Story: As a researcher, I can obtain authoritative terminal holdings, P&L and actual fills without serializing the complete nested execution journal, while retaining full diagnostics when needed.
Scheduling and ownership: [manifest F09](../manifest.json). This is the independently deliverable projection portion of F08, not a replacement for its historical metrics.
## Evidence and root cause
- **PER-01 / KEEP-02 — Verified:** [full native finalization](../../../../apps/stock/engine/src/api/replay.rs#L165) exports every nested matching receipt through a JSON value tree. The recorded F07 release workload emits 66.7MB/103.6MB at 10k total bars; finalization averages 0.963s/1.377s, approximately 35–39% of trial time. This is conformance output, not useful minimal research output.
- **FIN-05 — Verified:** [Ledger::valuation](../../../../apps/stock/engine/src/financial/ledger.rs#L674), [FinancialEffect](../../../../apps/stock/engine/src/financial/contract.rs#L327) and existing ledger receipts already contain authoritative terminal values, realized basis/P&L, actual fees and ownership. Recomputing these in TypeScript would create competing financial authority.
## Scope and pinned contract
- Add a small Rust projection module. Emit the existing terminal snapshot/view, checked Ledger valuation and owner contributions, plus flattened actual fills copied from committed commands/effects in authoritative order. Retain IDs, event time, owner/decision/order/fill, side/quantity/price, fee, cash/quantity deltas, released basis and realized gross P&L. Fills are not completed round trips.
- `cashDelta` preserves the ledger effect's gross notional movement; the fee is a separate posting, not an additional fee already included in that delta. Valuation owner contributions include reserve capital and can be negative. Schema coherence checks compare the returned cash/equity strings with the existing view without reproducing accounting arithmetic.
- Iterate borrowed ledger receipts once, skipping replay-labelled aliases. A read-only ledger receipt accessor and serialization derives for existing valuation types are allowed. No checkpoint cloning, ledger reconstruction, replay or financial arithmetic duplication to produce output. Preserve internal receipts, idempotency indexes and restore behavior.
- Add native `project(identityJson)` beside the unchanged full diagnostic `finalize(identityJson)`. Compact output has `format: "projection"`, `projectionVersion: 1`, `financialVersion: 1`, the same identity/status/manifest/policy/view/limitations, and `projection: { valuation, fills }`; it has no nested `receipts`. Use typed serialization with borrowed metadata where practical.
- TS adds a strict projection parser and typed `NativeReplaySession.project()`. The existing conformance loop may select `resultFormat: "projection" | "trace"`; old omitted-format calls and the existing diagnostic parser retain their trace behavior. No second loop. New compact consumers explicitly select projection; active legacy/durable defaults do not change.
- The existing fixed-trace worker request may carry the optional format; the parent captures expected format with identity/policy and rejects mismatched responses. Both formats share completion, failure, disposal and cancellation guards.
- Extend observational metrics with finalization native-call time (including Rust work/serialization), JSON decode time, schema-validation time and disposal time. Keep these outside economic outputs and deterministic hashes; do not call them pure crossing measurements. Expose unavailable internal Rust/GC splits honestly.
## Exclusions
No session-close equity curve, return ratios, Sharpe/Sortino, exposure percentage, round-trip win rate, invented defaults or legacy DTO coercion: these remain F08. No journal deletion/compaction, new accounting, risk/timing changes, new persistence/service, pagination, DSL, cache or default engine/paper/live cutover.
## Files and ownership
- `apps/stock/engine/src/financial/result.rs` and tests; `ledger.rs` read-only accessor/valuation serialization; module registration.
- `apps/stock/engine/src/api/replay.rs` and generated binding verification.
- `apps/stock/orchestrator/src/contracts/native-replay.ts`, `backtest/native-replay.ts`, existing worker supervisor/dispatch as needed.
- Focused native/projection/worker fixtures and tests. Benchmark files belong to P07; root coordinates final paired comparisons.
Write locks: financial-projection, native-public-api, worker-protocol, result-contract. One owner. Dependencies: F07; approved ADR-002/003/004. P07 baseline work is independent; benchmark integration uses the frozen projection contract, not concurrent reinterpretation.
## Acceptance and mandatory tests
1. `compact_full_financial_parity`: terminal snapshot/valuation/flattened fills agree with the retained full trace and independent hand-calculated fixtures; all amounts remain canonical decimal strings.
2. `projection_aliases_once`, `partial_fill_projection`, `two_owner_projection`: duplicate command/fill aliases do not duplicate output, partial fills remain distinct, owner attribution and fees reconcile, including final residual basis. No-trade output has zero fills and honest terminal values.
3. `projection_is_read_only`: repeated project/finalize calls preserve state/checkpoints and original diagnostic output; restored sessions produce the same projection. Full-trace fixture hashes remain unchanged.
4. `projection_terminal_guard`, `projection_identity_policy_format`: incomplete/failed/disposed sessions cannot return successful compact output; malformed identities, policies and requested formats reject, including worker races/cancellation and post-result abort.
5. Strict TS/schema/architecture/native gates pass. No receipt/future-data leakage into strategy contexts; no broadening of worker-only native reachability.
6. Paired release measurements on the same frozen dataset/config/decisions show identical financial projection hashes and reduced output bytes/finalization cost. Preserve full trace as an explicit diagnostic oracle. Record actual before/after; no timing threshold in CI and no promised speedup. P07 supplies representative workload variants.
Regression risk: alias double counting, effect-to-fee mispairing, silently changed output semantics or a successful result from failed state. Review G1/G2 independently; retain existing F07 regressions and disposable worker/runner durability gates. Rollback is additive API deployment, not weaker financial policies.
Definition of done: reviewed source, exact integrated test/benchmark evidence and canonical manifest handoff. No commit/push/PR without separate authorization.