Skip to content

perf(returns): single-pass compute_returns entry point (one extract + one realize per group) - #1843

Merged
robcohen merged 3 commits into
mainfrom
perf/returns-combined-entry
Jul 21, 2026
Merged

robcohen merged 3 commits into
mainfrom
perf/returns-combined-entry

Conversation

@robcohen

Copy link
Copy Markdown
Member

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 returns CLI computed each scope by calling extract_flows, terminal_value, and twr separately — and twr internally re-ran extract_flows and its own realization pass. So every group did ~2 flow extractions and ~2 realizations; with --by-group that cost is paid N+1 times (per group + TOTAL).

How

compute_returns folds extract_flows + terminal_value + xirr + twr into one walk:

twr's unit-value chaining is factored into twr_from_values so twr and compute_returns share it; twr's own behavior is unchanged. The CLI's compute_group now just calls compute_returns and 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 → None guard and the lazy price-error short-circuit: an intermediate MissingPrice degrades TWR to None, an end_date MissingPrice errors, matching terminal_value).

Guards:

  • New engine drift guard compute_returns_matches_manual_composition pins compute_returns against composing the four primitives by hand on a buy + dividend-inclusive holding (every field non-trivial).
  • The CLI's existing drift guards (terminal_value_matches_account_balances_realization, series_matches_extract_cash_flows) and all 19 report_returns integration 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-group groups (O(groups × …) → one pass) — is the next increment.

Part of #1832. Part of #1814.

🤖 Generated with Claude Code

… 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).
@robcohen
robcohen requested a review from a team as a code owner July 21, 2026 19:29
Copilot AI review requested due to automatic review settings July 21, 2026 19:29
@codecov

codecov Bot commented Jul 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 32.5ms ± 0.7ms 24 MB
beancount 723.3ms ± 4.6ms 50.7 MB
Comparison 22.3x faster 2.1x less

vs main branch (2026-07-21)

Metric main this PR Change
Time 33.5ms 32.5ms -3.0% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_returns and a Returns summary struct to the rustledger-returns engine, factoring TWR chaining into a shared helper.
  • Updated the CLI returns report to delegate per-scope computation to compute_returns (instead of composing extract_flows/terminal_value/twr).
  • Added a drift-guard test ensuring compute_returns remains 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.

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 812
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

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.
Copilot AI review requested due to automatic review settings July 21, 2026 19:42
@robcohen

Copy link
Copy Markdown
Member Author

Deep review → fixes (0c59810)

The review confirmed the core: no wrong-result bugs — the equivalence holds. Findings were coverage/diagnosability/cleanup:

# Finding Resolution
1 Drift guard only hit the all-nonzero happy path (zero-suppression / zero-capital / missing-price branches unguarded) Factored a comparison helper, run across 3 shapes (happy, income-only zero-capital, worthless terminal) + a missing-end-price errors test
4 compute_returns open-codes extract_cash_flows's series with no drift guard The helper now also asserts r.money_weighted == xirr(extract_cash_flows(..)) (canonical-function discipline)
5 Three passes over flows Single pass for invested + distributions + net_by_date
3 Stale series_matches_extract_cash_flows docstring Rewritten — the CLI no longer builds the series by hand; the test now reads as an independent check that extract_cash_flows == flows+terminal+sort
2 Two phase-specific error contexts collapsed to one Accepted: the underlying ExtractError still names the currency + date (the actionable info); compute_returns is one call, so a per-phase attribution would need an error-variant change disproportionate to the diagnostic gain
— (refuted) values.pop().expect(..) panic path Provably safe — end_date is always pushed, so dates/values is non-empty

Gauntlet green (55 returns + 19 CLI + 3 unit, clippy -D warnings, doc, fmt).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_returns docs claim a date-sorted input requirement/panic, but both compute_returns and twr route valuations through investment_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
Copilot AI review requested due to automatic review settings July 21, 2026 19:49

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants