Repository navigation
perf(returns): single-pass realization for twr (was O(flows × directives)) - #1842
Conversation
…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).
📊 Benchmark Results
vs main branch (2026-07-21)
What do these numbers mean?
|
There was a problem hiding this comment.
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 intovalue_investment_scope, then rewiredtwrto use the batch path. - Added a drift-guard test ensuring
investment_values_atmatches repeatedinvestment_value_atacross 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 Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
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).
Deep review → fixes (1082c0e)A high-effort review found two real correctness issues in the single-pass rewrite; both fixed.
Behavior for the CLI is unchanged (its stream is loader-sorted; and the CLI wraps |
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.
Second deep review + Copilot threads → e9820a9The rework held up — no correctness regressions in the fix; findings were guards/docs.
All 5 Copilot inline threads resolved. Gauntlet green (53 returns + 8 booking + 19 CLI, clippy -D warnings, doc, fmt). |
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
What
Makes
rustledger_returns::twrlinear in the ledger. It re-realized the whole portfolio from scratch at every distinct cash-flow date — a freshBookingEnginepass over the directives≤that date — so its cost was O(flow_dates × directives). Now the portfolio is valued at every flow date and atend_datein 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 tointo_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 separateinvestment_value_atcalls intwr.value_investment_scope— factored as the single valuation implementation now shared byinvestment_value_at(one date) andinvestment_values_at(batch), so the two cannot drift. Both still collect into aBTreeMapfirst, keepingMissingPricecurrency 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-dateinvestment_value_atapplies 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 anddebug_asserted.Guards:
twrnumeric tests (the ~15.5% timing-divergence case, the ~10% closed-out case, the net-short/liquidationNonecases) all pass unchanged.investment_values_at_matches_per_date: pins the batch against the retained per-dateinvestment_value_aton 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.terminal_value_matches_account_balances_realizationdrift guard still passes (it now routes through the sharedvalue_investment_scope).Scope
This is the first increment of #1832 (the
twrsingle-pass — the original ask). The larger CLI-side wins it enables — a combinedcompute_returnsentry point and one whole-ledger realization shared across all--by-groupgroups — are follow-ups tracked in the updated #1832.Part of #1832. Part of #1814.
🤖 Generated with Claude Code