perf(research): add compact replay projections and representative profiling

This commit is contained in:
Boki 2026-10-23 10:42:31 -04:00
parent 19e9dad68b
commit e3bd722e31
21 changed files with 2830 additions and 130 deletions

View file

@ -13,19 +13,23 @@ Scheduling source of truth: [manifest entry F08](../manifest.json). No task is a
## Intended behavior and implementation scope
F09 now supplies the independently deliverable compact terminal/owned-fill projection. F08 consumes it and adds historical sampling/statistical reporting; do not duplicate its native transport work. F09 is not completion of this story.
Use canonical Rust ledger postings, owned fills, occupied intervals and session-ending marks as the sole financial inputs. Reuse reviewed TypeScript statistical functions in `libs/calculations/src/analytics/` for return ratios and reports; do not port them to Rust merely for language uniformity. Add a small adapter for the engine-declared session calendar rather than blindly regrouping every venue by UTC date.
Version economics and metrics independently. Define sampling, annualization, benchmark and risk-free conventions in the result policy. Missing benchmark/risk-free inputs must not silently become invented measurements. Undefined or unsupported metrics are null with reasons. Adapt existing result DTOs without rewriting old rows.
Measurable benefit: comparable, independently checked rankings without a second ledger or a needless analytics rewrite.
Before implementation, pin reporting-only conventions in the handoff: account boundaries currently execute before equal-time observations and are not automatically close-equity samples; partial final sessions must be explicit; exposure needs a declared elapsed/venue-time denominator; the reviewed statistics currently assume 252 periods and default to 2% risk-free, so the adapter must pass a supported explicit policy and diagnose omitted inputs. These choices must not alter financial event ordering or risk semantics. Fills are not round trips.
## Exclusions
No accounting/fill recomputation in TypeScript, statistical library rewrite, forced native port, new service, or silent reinterpretation of historical results. Native analytics remain an option only if measured as a bottleneck.
## Likely files and ownership
- apps/stock/engine/src/backtest/simple_results.rs (authoritative projections, not new statistical formulas)
- apps/stock/engine/src/financial/result.rs and replay reporting hooks (canonical outputs; legacy simple_results.rs remains separate)
- apps/stock/orchestrator/src/backtest/native-result.ts
- apps/stock/orchestrator/src/backtest/BacktestReport.ts
- libs/calculations/src/analytics/return-statistics.ts
@ -36,7 +40,7 @@ Write locks: result-contract. One agent owns this change. Lock names do not over
## Dependencies and blockers
Implementation requires [F06](F06.md) integrated.
Implementation requires [F06](F06.md) and [F09](F09.md) integrated.
Architecture decisions: ADR-002, ADR-003. Agents may not independently amend their policies.

View file

@ -0,0 +1,48 @@
# 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.

View file

@ -0,0 +1,42 @@
# P07 — Profile representative canonical replay workloads
Parent epic: E7. Priority/severity: P1 / High. Complexity: M. Specialist: performance/test infrastructure.
Story: As a platform developer, I can distinguish replay, financial turnover, result transport and diagnostic overhead before choosing the next optimization.
Scheduling and ownership: [manifest P07](../manifest.json). Extend P01's existing harness; do not create another benchmark framework.
## Evidence and root cause
- **PER-01 — Verified:** the F07 [turnover profile](../../../../scripts/benchmark-replay.ts#L100) alternates positions at every barrier. At 10k total bars it creates 9,999/19,980 fills; 2.65–3.61s is not the cost of merely reading bars.
- In the original F07 measurement, finalization consumed approximately 35–39%; fixture decisions less than 2%; native creation approximately 3%. Before F09, the [adapter](../../../../apps/stock/orchestrator/src/backtest/native-replay.ts#L184) combined native work and JSON validation, without a separate disposal timer. These measurements did not establish a pure NAPI overhead, Rust bottleneck, or need for a DSL.
## Scope
- Extend `scripts/benchmark-replay.ts`, `scripts/benchmark-research.ts` and their tests only. Reuse frozen fixture generation, source/addon/host/runtime hashes and cold-process/fresh-session structure.
- Add `none` (same callbacks/cadence, no targets), `sparse` (one opening and one closing fill per owner/asset), and `turnover` (existing alternating unit targets) profiles. Preserve existing invocation behavior; expose explicit CLI profile/format selection and an opt-in 100k size. No new application input limits.
- Measure verified dataset preparation, native load, actual advance/submit/decision/finalization/disposal phases, emitted bytes, observed fills/decisions/calls, wall time and process RSS. Consume optional finalization subphase metrics only after the contract owner publishes them. Do not infer internal Rust/GC time from an unexplained residual.
- Independent integer-based fixture oracles remain test/benchmark-only. Repeated runs/reversed callback evaluation must preserve economic output. Full trace keeps exact normalized-result hash validation; compact/full comparisons use the same canonical financial projection, not unlike wire-envelope hashes.
- Baseline profiles work against committed F07 independently. Paired compact runs are enabled only after F09's contract is frozen/accepted by root; do not edit adapter/schema/native files to make the benchmark fit. Record the exact source/artifact for each baseline/candidate.
- Run selected 10k and explicitly requested 100k workloads sequentially. Report unavailable measurements/resource failures honestly rather than silently trimming data/traces. Full-history 100k diagnostic output can be large; no throughput claim for cases not run.
## Exclusions
No financial semantic change, arbitrary hot-loop refactor, native dataset cache, shared feature framework, worker pool, DSL, new service, web paging or journal deletion. Select a concrete next optimization from evidence; implementation beyond F09 requires a scoped follow-up.
## Dependencies, locks and parallelism
Code prerequisites: F07 and P01. No new economic policy or ADR-008 approval is needed for measurements alone. P03/P04/P06 remain gated. Write lock: benchmark-harness, with the three explicit files above. Safe parallel work with F09's separate core/adapter files. Compact comparison is a conditional integration gate requiring F09; baseline compilation/tests must not depend on unmerged native APIs.
## Acceptance and mandatory tests
1. `profile_none`, `profile_sparse`, `profile_turnover` pin deterministic call/fill/fee/basis/terminal-equity expectations, including multiple owners/assets and retained session gaps.
2. `benchmark_profile_arguments` rejects unsupported flags/combinations; existing P01/F07 invocation and tiny tests still work.
3. `profile_identity_mismatch` rejects changed dataset/policy/strategy/native result identity; profile/result format is included in provenance. Different profiles are never compared as equivalent economics.
4. `compact_trace_projection_parity` and reversed callback order agree on authoritative projection; diagnostics remain complete and independently testable.
5. No fake zero/unavailable timings, no timing-flaky assertions. Print raw repeated rows and a concise breakdown with timing boundaries/build profile. Distinguish first process/setup from reused prepared JS inputs and fresh native sessions.
6. Integrated evidence documents measured candidate effects, remaining unattributed costs and the smallest justified next action. No unsupported 10x/100x claim.
Regression risk: benchmark oracle mistakes, comparing different policies/profiles, or profiling work inside a purported engine-only timer. Mandatory focused tooling/native fixtures, strict TypeScript and scoped lint; financial/result owner reviews oracle/parity independently. No native rebuild concurrent with another agent's artifact review.
Definition of done: reproducible script/tests, baseline and accepted-candidate measurements, independent review and root manifest handoff. Missing resource-dependent large runs must be explicit; not a pass. No commits/pushes/PRs without authorization.