Repository navigation
perf(returns): single-pass compute_returns entry point (one extract + one realize per group) - #1843
Conversation
… one realize per group) The CLI computed each scope's summary by calling extract_flows, terminal_value, and twr separately — and twr internally re-ran extract_flows and its own realization — so every group did ~2 flow extractions and ~2 portfolio realizations. With --by-group that is paid N+1 times. Add `rustledger_returns::compute_returns`, which folds extract_flows + terminal_value + xirr + twr into ONE flow extraction and ONE forward realization: the portfolio is valued at every flow date and end_date in a single pass, then reused for the terminal value, the money-weighted series, and the time-weighted chaining. The CLI's compute_group now just calls it and attaches the row label. - Factor `twr_from_values` (the unit-value chaining) out of `twr` so it runs over values realized once; `twr` and `compute_returns` share it. `twr`'s own behavior is unchanged. - Result is byte-identical to the old hand-composition (including the zero-capital TWR guard and lazy-price-error semantics), pinned by the new `compute_returns_matches_manual_composition` drift guard; the CLI's existing drift guards and 19 report_returns integration tests still pass. Part of #1832 (the remaining item: share ONE whole-ledger realization across all --by-group groups).
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-07-21)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Introduces a new rustledger_returns::compute_returns API that computes a scope’s full returns summary (invested, distributions, current value, MWR/XIRR, TWR) from a single flow extraction plus a single batched valuation pass, and updates the rledger report returns CLI to use it to avoid redundant work per group.
Changes:
- Added
compute_returnsand aReturnssummary struct to therustledger-returnsengine, factoring TWR chaining into a shared helper. - Updated the CLI returns report to delegate per-scope computation to
compute_returns(instead of composingextract_flows/terminal_value/twr). - Added a drift-guard test ensuring
compute_returnsremains byte-identical to the prior manual composition.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| crates/rustledger/src/cmd/report_cmd/returns.rs | Switches group computation to the new engine entry point to avoid duplicate extraction/realization per group. |
| crates/rustledger-returns/src/lib.rs | Re-exports the new Returns/compute_returns API from the crate root. |
| crates/rustledger-returns/src/extract.rs | Implements compute_returns, factors out twr_from_values, and adds a drift-guard test. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
…accumulation Deep-review follow-ups (no wrong-result bugs found; all coverage/cleanup): - The compute_returns drift guard only exercised the all-nonzero happy path, so a future break in the zero-terminal suppression, the zero-capital TWR guard, or the eager end-price error could ship undetected. Factor a comparison helper and run it across three shapes — happy (buy + dividend), income-only (zero capital), worthless terminal (holding priced to zero) — and add a test that a missing end-date price errors (matching terminal_value). - Pin the money-weighted series compute_returns open-codes against the canonical extract_cash_flows (CLAUDE.md canonical-function discipline): the helper now also asserts r.money_weighted == xirr(extract_cash_flows(..)). - compute_returns now accumulates invested, distributions, and net_by_date in a single pass over the flows instead of three. - Refresh the stale series_matches_extract_cash_flows docstring: the CLI no longer builds the series by hand (it delegates to compute_returns); the test now reads as an independent check that extract_cash_flows == flows+terminal+sort. Part of #1832.
Deep review → fixes (0c59810)The review confirmed the core: no wrong-result bugs — the equivalence holds. Findings were coverage/diagnosability/cleanup:
Gauntlet green (55 returns + 19 CLI + 3 unit, clippy -D warnings, doc, fmt). |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (1)
crates/rustledger-returns/src/extract.rs:814
compute_returnsdocs claim a date-sorted input requirement/panic, but bothcompute_returnsandtwrroute valuations throughinvestment_values_at, which explicitly falls back to an order-independent per-date path when transactions are not date-sorted. This should be documented consistently (sorting affects performance, not correctness/panics).
/// # Panics
///
/// Same booked, pad-expanded, date-sorted input requirement as [`twr`].
…roup wording Copilot doc-accuracy: compute_returns realizes in ONE pass only on the date-sorted fast path (an unsorted stream falls back to per-date), so its summary and # Panics no longer claim date-sortedness as a hard requirement; align the # Panics with twr. Also clarify that the prior CLI inefficiency was twr internally re-running extract_flows + a second realization. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
What
Adds
rustledger_returns::compute_returns— a single-pass entry point that computes a scope's entire return summary (invested, distributions, current value, MWR, TWR) from one flow extraction and one portfolio realization.Before, the
report returnsCLI computed each scope by callingextract_flows,terminal_value, andtwrseparately — andtwrinternally re-ranextract_flowsand its own realization pass. So every group did ~2 flow extractions and ~2 realizations; with--by-groupthat cost is paid N+1 times (per group + TOTAL).How
compute_returnsfoldsextract_flows+terminal_value+xirr+twrinto one walk:end_datein one forward realization pass (investment_values_at, from perf(returns): single-pass realization for twr (was O(flows × directives)) #1842);xirr), and the time-weighted chaining.twr's unit-value chaining is factored intotwr_from_valuessotwrandcompute_returnsshare it;twr's own behavior is unchanged. The CLI'scompute_groupnow just callscompute_returnsand attaches the row label.Correctness
The result is byte-identical to the old hand-composition — same invested/distributions/current_value, same MWR (xirr over flows + terminal), same TWR (including the zero-capital →
Noneguard and the lazy price-error short-circuit: an intermediateMissingPricedegrades TWR toNone, anend_dateMissingPriceerrors, matchingterminal_value).Guards:
compute_returns_matches_manual_compositionpinscompute_returnsagainst composing the four primitives by hand on a buy + dividend-inclusive holding (every field non-trivial).terminal_value_matches_account_balances_realization,series_matches_extract_cash_flows) and all 19report_returnsintegration tests pass unchanged.Scope
Part of #1832. This is the "combined entry point" increment (halves per-group work). The remaining item — sharing one whole-ledger realization across all
--by-groupgroups (O(groups × …)→ one pass) — is the next increment.Part of #1832. Part of #1814.
🤖 Generated with Claude Code