Skip to content

perf(returns): single-pass realization for twr (was O(flows × directives)) - #1842

Merged
robcohen merged 4 commits into
mainfrom
perf/returns-single-pass-twr
Jul 21, 2026
Merged

robcohen merged 4 commits into
mainfrom
perf/returns-single-pass-twr

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

Makes rustledger_returns::twr linear in the ledger. It re-realized the whole portfolio from scratch at every distinct cash-flow date — a fresh BookingEngine pass over the directives ≤ that date — so its cost was O(flow_dates × directives). Now the portfolio is valued at every flow date and at end_date in one forward realization pass that snapshots the market value as it crosses each date: O(directives + flow_dates × positions).

How

  • BookingEngine::inventories(&self) — a borrowing counterpart to into_inventories, so a caller can read the realization mid-walk without consuming the engine.
  • investment_values_at — walks the booked stream once through one engine, applying transactions up to each successive (ascending) target date and snapshotting the value. Replaces the D+1 separate investment_value_at calls in twr.
  • value_investment_scope — factored as the single valuation implementation now shared by investment_value_at (one date) and investment_values_at (batch), so the two cannot drift. Both still collect into a BTreeMap first, keeping MissingPrice currency selection deterministic.

Correctness

Behavior is unchanged. The subtlety: the single pass requires the booked stream to be date-sorted (the report's input is — loader sorts by booking_sort_key). The per-date investment_value_at applies transactions in directive order, so the two agree exactly when directive order is date order; all same-date transactions are applied before that date is snapshotted. This is documented and debug_asserted.

Guards:

  • Existing twr numeric tests (the ~15.5% timing-divergence case, the ~10% closed-out case, the net-short/liquidation None cases) all pass unchanged.
  • New drift guard investment_values_at_matches_per_date: pins the batch against the retained per-date investment_value_at on a multi-buy / partial-sale / same-date portfolio valued before, between, on, and after the flows — a cursor off-by-one or same-date miss would trip it.
  • The CLI's terminal_value_matches_account_balances_realization drift guard still passes (it now routes through the shared value_investment_scope).

Scope

This is the first increment of #1832 (the twr single-pass — the original ask). The larger CLI-side wins it enables — a combined compute_returns entry point and one whole-ledger realization shared across all --by-group groups — are follow-ups tracked in the updated #1832.

Part of #1832. Part of #1814.

🤖 Generated with Claude Code

…ves))

`twr` re-realized the whole portfolio from scratch at every distinct cash-flow
date — a fresh `BookingEngine` pass over the directives ≤ that date — so its cost
was O(flow_dates × directives). Replace the per-date `investment_value_at` calls
with one forward pass (`investment_values_at`) that walks the booked stream once
and snapshots the market value as it crosses each date, making it
O(directives + flow_dates × positions), linear in the ledger.

- Add `BookingEngine::inventories(&self)` — a borrowing counterpart to
  `into_inventories` so value can be read mid-walk without consuming the engine.
- Factor `value_investment_scope` as the single valuation implementation shared by
  `investment_value_at` (one date) and `investment_values_at` (batch), so they
  cannot drift; both still collect into a BTreeMap for deterministic MissingPrice.
- The single pass requires the booked stream to be date-sorted (the report's input
  is): the per-date realization applies transactions in directive order, so the two
  agree exactly when directive order is date order. Documented + debug_asserted.

Behavior is unchanged: existing twr numeric tests pass, and a new drift guard
(`investment_values_at_matches_per_date`) pins the batch against the retained
per-date `investment_value_at` on a multi-buy/partial-sale/same-date portfolio.

Part of #1832 (the CLI-side shared-extraction and per-group amplification remain).
@robcohen
robcohen requested a review from a team as a code owner July 21, 2026 17:33
Copilot AI review requested due to automatic review settings July 21, 2026 17:33
@github-actions

github-actions Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 31.7ms ± 0.2ms 24 MB
beancount 887.9ms ± 20.2ms 50.7 MB
Comparison 28x faster 2.1x less

vs main branch (2026-07-21)

Metric main this PR Change
Time 33.5ms 31.7ms -5.4% 🟢
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 rustledger_returns::twr by replacing the previous “re-realize at each flow date” approach with a single forward realization pass that snapshots portfolio value at each relevant date, reducing runtime from ~O(flow_dates × directives) to ~O(directives + flow_dates × positions).

Changes:

  • Added BookingEngine::inventories(&self) to allow reading realized inventories mid-walk without consuming the engine.
  • Introduced investment_values_at (batch valuation) and factored shared valuation logic into value_investment_scope, then rewired twr to use the batch path.
  • Added a drift-guard test ensuring investment_values_at matches repeated investment_value_at across multiple dates (including same-date transactions).

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
crates/rustledger-returns/src/extract.rs Implements single-pass batch valuation for TWR, factors shared valuation logic, updates twr, and adds a drift-guard test.
crates/rustledger-booking/src/book.rs Adds a borrowing inventory iterator (BookingEngine::inventories) to support mid-realization snapshotting.

💡 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

✅ All modified and coverable lines are covered by tests.

📢 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

…y on prices

Deep-review follow-ups on the single-pass rewrite:

- The single-pass cursor is order-dependent (only equivalent to the per-date
  realization when the stream is date-sorted), but the crate's input contract is
  only "booked" and book() preserves input order — so a booked-but-unsorted stream
  would silently produce a wrong valuation in release (the debug_assert only checked the always-
  ascending dates, not the directives). `investment_values_at` now detects an
  unsorted transaction stream and falls back to the order-independent per-date
  `investment_value_at`, so it matches the old twr for ANY booked input.

- Restore lazy price errors: `investment_values_at` returns one `Result` per date
  instead of a single fallible batch, and twr propagates a `MissingPrice` only for
  a date it actually reaches — so an unpriceable later date no longer turns an
  already-undefined (net-short / non-f64) return from Ok(None) into Err.

- `value_investment_scope` now filters to Investment scope before collecting, so
  per-date cost is proportional to in-scope accounts (not the whole chart); the
  `# Performance` doc is corrected to match.

Tests: existing twr numeric guards unchanged; the drift guard updated for the
per-date Result; new `investment_values_at_matches_per_date_when_unsorted` pins
the fallback (a naive cursor would report 0 at January instead of 1000).
Copilot AI review requested due to automatic review settings July 21, 2026 18:07
@robcohen

Copy link
Copy Markdown
Member Author

Deep review → fixes (1082c0e)

A high-effort review found two real correctness issues in the single-pass rewrite; both fixed.

# Finding Fix
1 🔴 The single-pass cursor is order-dependent, but the crate's input contract is only "booked" and book() preserves input order — so a booked-but-unsorted stream would silently produce a wrong valuation in release (the debug_assert only checked the always-ascending dates). investment_values_at now detects an unsorted transaction stream and falls back to the order-independent per-date investment_value_at — correct for any booked input, matching the old twr exactly.
2 🔴 Valuing all dates up front turned the old lazy Ok(None) short-circuit into an eager Err(MissingPrice) when an early sub-period was already undefined AND a later date was unpriceable. Returns one Result per date; twr propagates a MissingPrice only for a date it actually reaches — restoring the exact lazy semantics.
3 🟠 Drift guard only fed sorted input, so it couldn't catch the order-dependence hazard. Added investment_values_at_matches_per_date_when_unsorted (a June buy before a January buy — a naive cursor reports 0 at January instead of 1000).
4 🟡 Perf doc overstated: value_investment_scope collected all accounts per date. Filters to Investment scope before collecting → genuinely O(flow_dates × in-scope accounts); doc corrected.
5 🟡 twr docs didn't mention the sortedness/fast-path behavior. Documented the fast-path-vs-fallback contract.

Behavior for the CLI is unchanged (its stream is loader-sorted; and the CLI wraps twr with unwrap_or(None) anyway). Gauntlet green: 52 returns + 8 booking + 19 CLI returns tests, workspace 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 2 out of 2 changed files in this pull request and generated 4 comments.

Comment thread crates/rustledger-booking/src/book.rs Resolved
Second-review + Copilot follow-ups on the single-pass twr:

- Add a drift guard for the lazy MissingPrice short-circuit that the Vec<Result>
  rework preserves: twr_missing_price_after_an_undefined_subperiod_is_none_not_err
  pins that a net-short (early-undefined) portfolio with an unpriceable report-end
  date returns Ok(None), not Err — a future eager `?`-propagation would flip it.
- Replace the manual sortedness fold with `Iterator::is_sorted_by_key` (clearer;
  it is a cheap O(transactions) date scan, dominated by the booking pass it guards).
- Correct the cost docs/comment: the per-date pass classifies every realized
  account (whole chart) and prices only the in-scope positions, so the per-date
  factor is accounts, not in-scope positions as previously stated.

Note: the borrowing `inventories(&self)` does NOT get `#[must_use]` — `impl
Iterator` already carries it, and a redundant attribute trips clippy's
double_must_use.

The eager-valuation Decimal-overflow edge (a >7.9e28 valuation in an
already-undefined window) is pre-existing (the `total +=` is unchanged from the
old per-date path) and adversarial-only; left as-is.

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

Copy link
Copy Markdown
Member Author

Second deep review + Copilot threads → e9820a9

The rework held up — no correctness regressions in the fix; findings were guards/docs.

  • Lazy price-error guard (the important one): added twr_missing_price_after_an_undefined_subperiod_is_none_not_err — pins that a net-short (early-undefined) portfolio with an unpriceable report-end date returns Ok(None), not Err. A future eager ?-propagation would flip it and fail the test (the CLAUDE.md 'guard a future divergence can trip' rule).
  • Sortedness check → Iterator::is_sorted_by_key (cleaner; a cheap O(txns) date scan dominated by the booking pass it guards).
  • Cost docs corrected (also folds in Copilot's 3 wording threads): the per-date pass classifies every realized account (whole chart) and prices only the in-scope positions, so the per-date factor is accounts.
  • Copilot's #[must_use] suggestion declined: impl Iterator already carries it — adding the attribute trips clippy's double_must_use.
  • Pre-existing overflow edge accepted: the eager-valuation Decimal-overflow (>7.9e28 in an already-undefined window) is adversarial-only and the total += is unchanged from the old per-date path.

All 5 Copilot inline threads resolved. Gauntlet green (53 returns + 8 booking + 19 CLI, 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 2 out of 2 changed files in this pull request and generated 1 comment.

The brace-expansion shorthand named ..._matches_per_date_unsorted, but the test
is ..._matches_per_date_when_unsorted. Spell both out.

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 18:34

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 2 out of 2 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