Skip to content

perf(returns): share one realization across all --by-group scopes - #1844

Merged
robcohen merged 2 commits into
mainfrom
perf/returns-shared-realization
Jul 22, 2026
Merged

robcohen merged 2 commits into
mainfrom
perf/returns-shared-realization

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

report returns --by-group computes one summary for the whole scope plus one per group. After #1843 each is a single-pass compute_returns, but that still re-runs the booking pass once per scope — even though booking (applying transactions, realizing inventories) is entirely scope-independent; only the valuation filters by scope.

This shares one realization across all scopes. Adds compute_returns_multi, which books the ledger once — over the union of every scope's flow dates — and reuses that single forward pass for every scope's valuation. Per-group booking goes from O(scopes × directives) → O(directives).

How

  • investment_values_multi — one BookingEngine forward pass; at each union date it values every scope that needs that date (per-scope cursors into each scope's ascending date list, handling a duplicated end_date). The engine state at any date is exactly transactions ≤ date — identical to what per-scope investment_values_at builds — so each scope's values are unchanged. Falls back to per-scope investment_values_at on an unsorted stream.
  • compute_returns_multi — preps each scope (extract_flows, which may fail independently), runs the one shared realization, then assembles each Returns. A scope whose flow can't be priced sits out the shared pass and reports its own error without affecting the others.
  • CLI — --by-group now calls compute_returns_multi once for [TOTAL, ...groups].

Correctness

Each scope's result is identical to compute_returns(that scope) — the booking is shared, the per-scope flow extraction and valuation are not. Drift guards (the per-scope path is the oracle):

  • compute_returns_multi_matches_per_scope — asserts compute_returns_multi[i] == compute_returns(scope_i) across a happy single-holding scope, a scope whose EUR flow can't be priced (independent error → skipped from the shared pass, exercising the alignment), and an income-only scope (zero-capital TWR guard).
  • investment_values_multi_matches_per_scope — the lower-level pass vs per-scope investment_values_at.
  • All 19 report_returns integration tests pass unchanged.

Scope

Part of #1832 — this is the shared-realization increment (the last big perf lever). Remaining minor item: the self-containment warning scan (first_shared_inscope_account) still walks transactions per group; folding it into the same pass is small and warning-only.

Part of #1832. Part of #1814.

🤖 Generated with Claude Code

report returns --by-group computed the whole-scope TOTAL and each group with a
separate compute_returns call — each re-running the booking pass even though the
booking is scope-independent. Add compute_returns_multi, which realizes the
portfolio ONCE (over the union of all scopes' dates) and reuses it for every
scope's valuation, turning the per-group booking from O(scopes x directives) into
O(directives). Flow extraction and valuation stay per scope, so each scope's
result is identical to compute_returns(that scope).

- investment_values_multi: one booking forward pass, per-scope value vectors at
  each scope's dates (union snapshotting with per-scope cursors); falls back to
  per-scope investment_values_at on an unsorted stream.
- compute_returns_multi: prep each scope (extract_flows, may fail independently),
  one shared realization, then assemble each Returns; a failed scope sits out the
  shared pass and its error is reported without affecting the others.
- CLI --by-group now calls compute_returns_multi once for [TOTAL, ...groups].

Drift guards: compute_returns_multi_matches_per_scope (happy / unpriceable-flow /
income-only, so error-skip alignment and zero-capital are covered) and
investment_values_multi_matches_per_scope; the 19 report_returns integration
tests pass unchanged.

Part of #1832.
Copilot AI review requested due to automatic review settings July 21, 2026 20:26
@robcohen
robcohen requested a review from a team as a code owner July 21, 2026 20:26
@github-actions

github-actions Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 36.2ms ± 2.9ms 24.1 MB
beancount 761.5ms ± 8.3ms 50.7 MB
Comparison 21x faster 2.1x less

vs main branch (2026-07-21)

Metric main this PR Change
Time 33.5ms 36.2ms +8.1% 🟡
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

Optimizes rledger report returns --by-group by sharing a single whole-ledger booking/realization pass across the TOTAL scope and all per-group scopes, eliminating the previous “re-book once per group” cost while keeping per-scope flow extraction and valuation semantics unchanged.

Changes:

  • Added investment_values_multi + compute_returns_multi to compute multiple scopes’ returns using one shared booking forward pass over the union of required valuation dates.
  • Re-exported compute_returns_multi from rustledger-returns’ public API.
  • Updated the CLI report returns --by-group path to call compute_returns_multi once for [TOTAL, ...groups] and render the results.

Reviewed changes

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

File Description
crates/rustledger/src/cmd/report_cmd/returns.rs Switches grouped returns reporting to a single shared-realization call (compute_returns_multi) while preserving output rendering behavior.
crates/rustledger-returns/src/lib.rs Exposes compute_returns_multi as part of the returns crate’s public surface.
crates/rustledger-returns/src/extract.rs Implements the shared-realization machinery (investment_values_multi, compute_returns_multi) and adds drift-guard tests to pin parity with per-scope computation.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@codecov

codecov Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.34884% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/report_cmd/returns.rs 95.34% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@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

…nd_date; consistent error label

Deep-review follow-ups (review found no correctness regression; the multi==per-scope
equivalence holds):

- Add # Errors / # Panics / #[must_use] to the public compute_returns_multi (its
  panics are internal alignment invariants, mirroring compute_returns).
- Guard the riskiest path with compute_returns_multi_matches_per_scope_edge_cases:
  a scope with a flow ON end_date (so its dates carry end_date twice and the union
  collapse must still emit both values) and an empty-flows scope, each asserted
  equal to per-scope compute_returns.
- Make the CLI error context consistent: compute_group now wraps failures with the
  row label ("...for TOTAL" / "...for Tech"), matching the --by-group shared loop,
  so the whole-portfolio error text no longer differs by path.

The stderr warning-ordering shift on the abort path (group warnings now print
before a whole-portfolio pricing error) is inherent to sharing the realization
across TOTAL + groups (the total is computed after build_groups); it is benign
(more diagnostics, not wrong ones), left as-is.

Part of #1832.
Copilot AI review requested due to automatic review settings July 21, 2026 20:45
@robcohen

Copy link
Copy Markdown
Member Author

Deep review → fixes (82cb565)

The review confirmed the core: no correctness regression — the multi==per-scope equivalence holds (union/cursor logic, ready/failed alignment, all branches). Findings were diagnosability, coverage, and docs:

# Finding Resolution
3 No test for the riskiest path (duplicate end_date == last flow date → union collapse must still emit both values), nor empty-flows Added compute_returns_multi_matches_per_scope_edge_cases: a scope with a sale ON end_date + an empty-flows scope, each asserted == per-scope compute_returns
4 compute_returns_multi missing # Panics/# Errors/#[must_use] Added all three (its .expects are internal alignment invariants, mirroring compute_returns)
1 Whole-portfolio TOTAL error context read "for TOTAL" in the by-group path but "for the scope" elsewhere compute_group now wraps with the row label too — consistent across paths ("...for TOTAL" / "...for Tech")
2 Group warnings now print to stderr before a whole-portfolio pricing error aborts (old path computed TOTAL first) Accepted: inherent to sharing the realization across TOTAL + groups (the total is computed after build_groups); benign — more diagnostics, not wrong ones

Gauntlet green (58 returns + 19 CLI tests, 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.

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