Repository navigation
feat(returns): cash-flow extraction from a booked ledger - #1816
Conversation
Adds the layer that turns a booked ledger into the CashFlow series xirr consumes (#1814 phase 1, building on the engine from #1815). The correctness core is a boundary-crossing model. Every account is classified by a `Scope` into one of three roles: - Investment: holdings + settlement cash (value tracked inside the portfolio, not itself a flow) - Income: dividends / gains / fees generated by the investment (internal to the return) - External: everything else (bank, outside cash) -- the money that actually crosses the boundary For a transaction touching an investment or income account, the flow is the sum of its external postings, converted to one reporting currency at the transaction's date. By double-entry this equals the negation of the investment+income side, and summing the external side directly lands the sign investor-centric with no manual negation. Three correctness properties fall out of the model rather than special cases: - a purchase (external cash debited negative) is an outflow - a sale or dividend-to-bank (external cash credited positive) is an inflow - an internal transfer -- shares or cash moved between two in-scope accounts -- has no external posting, so its flow is zero and it does NOT register. Double-counting internal transfers is the single most error-prone mistake in returns math; here it is excluded structurally. A synthetic terminal flow values the position still held on the end date at market, realized through the booking engine (the same realization as report_cmd::account_balances, so lots keep cost and reductions match the account's booking method) and priced via the oracle. Prices arrive through a new `PriceOracle` trait rather than a concrete price database, so the crate stays a leaf (no dependency on the query engine that owns the price index) and the extraction logic is unit-tested against a hand-specified rate table -- no price-DB fixtures leaking the index's own behavior into extraction tests. The trait method mirrors the price database's `convert`, so the CLI consumer wires it as a pass-through. Extraction fails loud (ExtractError::MissingPrice) rather than dropping a flow it cannot state in the reporting currency: a silently omitted flow does not error, it just yields the wrong rate. 15 extraction tests cover the sign conventions, the internal-transfer and reinvested-dividend traps, multi-currency conversion, the horizon cutoff, terminal valuation (including broker cash and the fully-sold case), missing-price errors, and an end-to-end extract -> xirr sanity check. Deferred to follow-ups (per #1814): dividend/ex-dividend breakout, TWR, and the `rledger report returns` CLI surface + the real `impl PriceOracle for PriceDatabase`.
📊 Benchmark Results
vs main branch (2026-07-20)
What do these numbers mean?
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…ernal) The income/--income role is semantically profit-and-loss: it must capture investment expenses (broker fees, commissions) as well as dividends and gains. A fee left in the External role is treated as money the investor received on a sale -- gross instead of net proceeds -- overstating the return. Spell this out on AccountRole::Income and Scope, and lock it with a test: a sale for 1100 gross minus a 10 fee scoped as P&L yields a +1090 flow, not +1100.
There was a problem hiding this comment.
Pull request overview
Adds the cash-flow extraction layer to rustledger-returns, turning a booked ledger into a single-currency CashFlow series suitable for the existing xirr engine, while keeping price conversion abstract via a PriceOracle trait (so the crate remains a leaf).
Changes:
- Introduces
extract_cash_flows/extract_flowsandterminal_valueto compute boundary-crossing flows plus a terminal market valuation atend_date. - Adds
Scope/AccountRoleclassification andPriceOraclefor caller-supplied currency/price conversion, with explicitMissingPricefailure. - Updates crate docs/README and adds dependencies needed for extraction (booking + thiserror).
Reviewed changes
Copilot reviewed 4 out of 5 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger-returns/src/lib.rs | Wires the new extraction module and re-exports the public extraction API alongside xirr. |
| crates/rustledger-returns/src/extract.rs | Implements boundary-based flow extraction, terminal valuation via the booking engine, and unit tests for key correctness traps. |
| crates/rustledger-returns/README.md | Updates crate description/status to include extraction + terminal valuation and the PriceOracle design. |
| crates/rustledger-returns/Cargo.toml | Adds rustledger-booking and thiserror dependencies required by extraction. |
| Cargo.lock | Locks new dependency edges introduced by the crate changes. |
💡 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 |
…rence Deep review found the extraction's input contract was unspecified, and the pad interaction was the sharpest question. Nail both down: - Input contract (on extract_cash_flows + module docs): the stream must be BOOKED and PAD-EXPANDED (the loader's balance_view -- what report_cmd::account_balances already consumes). A leaf crate cannot book or pad-expand a raw stream: un-booked input lets the booking engine silently realize the wrong inventory, un-expanded input drops pad-seeded positions. This is the same precondition apply/account_balances carry. - From-inception semantics: an opening balance (a pad, or an Equity:Opening-Balances posting) is a GENUINE flow -- the capital already in the position at the start. Its Equity leg is External, so a -500 opening outflow pairs with the +500 that account contributes to terminal value: a 0% return on an untouched opening balance. Dropping that flow is the actual bug (a +500 terminal with no offsetting outlay). Two new tests pin this coherence (0% untouched; +10% with internal dividend growth). - External postings are valued by UNITS (the money that moved through the outside account). Corrected the module's double-entry claim, which holds over balance weights / plain postings, not raw units in general. An external leg carrying its own @price or {cost} is valued by units through the oracle, not its stated weight -- documented as a deliberate common-case limitation (external legs are plain cash). - Documented terminal_value uses market (position.units) not cost, handles net-short (negative units) coherently, and needs no price when a holding is already in the reporting currency. The None-external-amount skip is defensive under the booked-stream contract (unreachable, not a silent drop of a real flow); comment clarified. 34 tests.
Deep review — round 1Ran the workflow-backed review (4 finder angles, adversarial verify pass, high effort) against the branch diff. It surfaced 7 verified findings (3 more were correctly refuted). Dispositions below. The headline finding — and why its framing inverts the correctnessThe finders flagged that With the booked, pad-expanded stream ( So the opening flow is not spurious — it is required. The real defect the finders correctly exposed is that my input contract was unspecified (I never stated "pass Fixed ( Units vs. balance-weight (CONFIRMED — doc corrected)External postings are summed by units (the money that actually moved through the outside account). The module's double-entry identity was stated over units; it holds over balance weights / plain postings, not raw units in general. Corrected the claim, and documented the deliberate limitation: an external leg carrying its own None-amount external posting (PLAUSIBLE — clarified)The defensive Declined / deferred, with reasons
Refuted (agreed)Three findings claimed the 34 tests; clippy/doc/fmt clean. |
…2 review) Round-2 deep review found a real classification bug plus determinism, panic-doc, and test-coverage gaps. Correctness: - classify() now picks the LONGEST matching prefix across both role lists (most-specific wins) instead of "investment always wins". An income account nested under an investment prefix (income Assets:Broker:Dividends under investment Assets:Broker) was classified Investment, so a reinvested dividend's income leg was summed into the terminal value and cancelled the asset it created -- understating the return to ~0%. Regression test added. - terminal_value now reports a held position even when its market value nets to exactly zero (returns None only when NOTHING is held), so the series distinguishes "still holding, net-flat" from "fully liquidated". Determinism / canonical discipline: - terminal_value collects inventories into a BTreeMap (like the canonical account_balances) before valuing, so which currency a MissingPrice names is stable -- an FxHashMap made it hash-order dependent and differ across 32/64- bit targets. Added cross-reference comments at both this loop and account_balances documenting the deliberate re-derivation + the future drift-guard test (the returns CLI PR). Docs: - # Panics on terminal_value / extract_cash_flows: an un-booked stream (a contract violation the leaf crate cannot detect) can make the booking engine debug_assert rather than return Err. - PriceOracle now requires conversion be linear in the amount (convert(-x) == -convert(x)), which is what makes a short position value negatively; the trait previously only mandated same-currency-unchanged. Cleanup: - extract_flows classifies each posting once (collect externals in one pass) instead of twice per transaction. Tests (40 total, +6): longest-prefix classification, nested-income terminal regression, net-short terminal, multi-position terminal sum, net-flat-held terminal, and a same-end-date flow+terminal fed through xirr (~50%).
Deep review — round 2Second workflow-backed pass (4 finder angles + adversarial verify), pointed at the post-round-1 state with deeper angles (real BookingEngine lot semantics, mixed-currency positions, classify precedence under nested trees, short terminals, same-date flows vs xirr, determinism, vacuous-test check). 9 verified findings, 3 refuted. All addressed in Real correctness bug — overlapping-prefix classification (CONFIRMED)
Fixed: Net-flat held portfolio reported as None (CONFIRMED)
Determinism + canonical drift (CONFIRMED / PLAUSIBLE)
Docs (CONFIRMED)
Test gaps (CONFIRMED) + cleanupAdded the three missing coverage cases the finders flagged as vacuously-passable: net-short terminal (−1500), multi-position terminal sum (AAPL+GOOG → 2500), and a same-end-date flow+terminal fed through Refuted (agreed)Two duplicate FxHashMap-nondeterminism entries (kept one), and the PriceOracle sign-linearity concern — which I nonetheless closed by tightening the trait doc. 40 tests (+6); clippy/doc/fmt clean; CLI crate builds with the cross-reference comment. |
…ion)
Round-3 review audited the round-2 changes and caught a regression they
introduced.
Round 2 made terminal_value emit Some(CashFlow{amount:0}) for a held-but-
worthless portfolio, to distinguish "still holding, net-flat" from "fully
liquidated". That is wrong: a zero-valued flow on a date LATER than the real
flows is not neutral to xirr -- it defeats xirr's all-same-date degenerate
guard. A same-date deposit/withdrawal wash plus a worthless residual holding
then produced [-1000, +1000] (same date) + [0 @ end_date]; the later zero
flow bypassed the guard, NPV was identically zero, and Newton returned its
0.10 seed -- a fabricated +10% return for a genuinely-undefined series.
Revert to: a terminal flow is emitted only when the held market value is
nonzero (None otherwise, covering both empty and net-flat/worthless
portfolios). Added a regression test asserting xirr returns None for the
wash scenario, and corrected the round-2 net-flat test to expect None.
Also reverted round-2's single-pass extract_flows rewrite. It allocated a
Vec per transaction -- including the common irrelevant ones -- to save a
re-classify on the few relevant transactions. The original allocation-free
two-pass (relevance gate short-circuits, so an irrelevant transaction costs
only the scan) is better for the common path; the double-classify it
re-introduces touches only the minority of portfolio transactions.
Note: the underlying xirr behavior -- returning its seed when NPV is
identically zero across >=2 distinct dates (reachable only by pathological
multi-date wash series) -- is a pre-existing engine edge, tracked separately
for a small xirr hardening follow-up. This PR removes the extraction-side
trigger.
41 tests.
Deep review — round 3Third pass, split between auditing the round-2 changes for regressions and new angles. It found one live bug — a regression round 2 introduced — plus the already-documented deferred drift-guard. Two findings refuted (both of which I'd reasoned through). The round-2 changes it audited (longest-prefix classify, BTreeMap determinism, currency comparison, date arithmetic, docs) all held up. Regression: zero-valued terminal flow fabricates a return (CONFIRMED)Round-2 finding-2 asked terminal_value to emit a flow even when the held value is zero (to distinguish "net-flat holding" from "liquidated"). I took it — and it was wrong. A zero-valued terminal on a date later than the real flows is not neutral to xirr: it defeats xirr's all-same-date degenerate guard. Concrete failure the finder gave: a same-date deposit/withdrawal wash ( Fixed ( I also reverted round-2's single-pass Deferred (PLAUSIBLE): canonical drift-guard test
Follow-up noted (out of scope): xirr degenerate edgeThe underlying xirr behavior — returning its Newton seed when NPV is identically zero across ≥2 distinct dates (reachable only by a pathological multi-date wash series) — is a pre-existing edge in the merged engine, not introduced here. This PR removes the extraction-side trigger; I'll file a small xirr-hardening follow-up (evaluate NPV at a second rate to detect a flat-zero function) rather than expand this PR into the merged solver. Refuted (agreed)The single-pass None-skip (unreachable under the booked contract) and the 41 tests (+1 net regression test); clippy/doc/fmt clean. |
Re: Copilot inline reviewThanks — all three checked against the current head (
Resolving these threads. |
* feat(returns): rledger report returns (money-weighted / XIRR) Wires the rustledger-returns engine (#1815 xirr, #1816 extraction) into a first-class CLI report, the consumer phase-1 piece of #1814. rledger report returns --investments <prefix> [--income <prefix>] [--currency USD] [--end YYYY-MM-DD] - Report::Returns clap variant + report_cmd/returns.rs. --investments (repeatable, required) and --income (repeatable) define the portfolio boundary; --currency defaults to the ledger's first operating_currency; --end defaults to today. Added Report::Returns to the needs_balance_view gate so extraction receives the booked, pad-expanded stream its contract requires. - impl PriceOracle for PriceDatabase via a PriceDbOracle newtype in the CLI (the composition root). The convert signatures are identical, so it is a pass-through; this keeps rustledger-returns a leaf and rustledger-query free of a returns dependency, rather than putting the impl in query. - Reports the money-weighted return plus supporting figures (capital invested, distributions received, current market value, flow count) in text / json / csv. An undefined series (no sign change) reports n/a, not a fabricated rate. - Drift-guard unit test (owed from #1816 round 2, CLAUDE.md Canonical- Function Discipline): terminal_value's realization must equal the market valuation of report_cmd::account_balances' inventories for the same scope and date. Plus 5 integration tests: the boundary model (a dividend-to-bank is a flow only when --income scopes it: 32.36% vs 30.00%), currency default, json fields, and the missing-currency error. Scope: XIRR (money-weighted) only, whole-scope. Time-weighted return and per-commodity grouping remain follow-ups per #1814. * fix(returns): pin series to extract_cash_flows; unify rate; fix -0.00% (review) Deep review of the returns CLI found two defects plus surfaced an output bug and a coverage gap. - Canonical-Function Discipline: report_returns hand-combines extract_flows + terminal_value into the xirr series (it needs the parts for the summary breakdown), duplicating the engine's canonical extract_cash_flows. Pinned the two as equivalent with a drift-guard test (series_matches_extract_cash_flows) and a cross-reference comment, so an engine change to how the series is assembled can't silently drift the CLI's rate. - Per-format precision: the money-weighted return was 2 decimals for text/csv but 4 for JSON, so the same ledger reported different rates across formats. Unified to 2 decimals everywhere. - Negative-zero display: a 0% return (capital returned unchanged) converges to a tiny signed epsilon that rendered as "-0.00%". Normalized so a rate rounding to zero shows "0.00%" in every format. - Coverage: added an integration test valuing a pad+balance-seeded holding, proving the needs_balance_view wiring (Report::Returns must be in that gate or the pad-expanded stream never reaches extraction and the position vanishes). The prior fixtures used only explicit buys. 8 returns tests (2 unit drift-guards + 6 integration). * test(returns): assert the reporting-currency line, not a bare contains Copilot review: the currency-default test used out.contains("USD"), which passes on the fixtures other USD literals even if the default were wrong. Assert the Reporting currency lines value is USD instead. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
#1840) Closes #1817. A cash-flow series whose flows net to zero on EVERY date has NPV(r) = Σ Sₜ/(1+r)ᵗ with every date-net Sₜ = 0 — i.e. NPV is identically zero at every rate, so the IRR is undefined. With ≥2 distinct dates (two same-day washes on different days) this slips past both the sign-change guard (the canceling flows are +/-) and the all-same-date guard, and Newton's iteration-0 `|NPV| < tol` check then succeeds at the 0.10 seed — so xirr fabricated a +10% return for an undefined series. Detect it exactly: group flows by date and, if every date's net is zero (checked in Decimal — the (1+r)⁻ᵗ for distinct t are linearly independent, so identically-zero NPV ⟺ every Sₜ = 0), return None. This complements the existing all-same-date guard (which catches the nonzero-constant NPV case). Tests: the two-date wash now returns None (was 0.10); and a guard against over-firing — a series whose UNDISCOUNTED total is zero but whose dates differ (-1000 then +1000 a year later) is a genuine 0% return and is still solved. Found in the #1816 round-3 review; the extraction side already avoids emitting the trigger, this closes the underlying engine edge.
What
Phase 1, part 2 of investment returns reporting (#1814), building directly on the XIRR engine merged in #1815. This adds cash-flow extraction: the layer that turns a booked ledger into the
CashFlowseriesxirrconsumes.The model — boundary crossing
Every account is classified by a
Scopeinto one of three roles:For a transaction touching an investment or income account, the flow is the sum of its external postings, converted to one reporting currency at the transaction's date:
Summing the external side directly makes the sign land investor-centric with no manual negation.
Three correctness properties fall out of the model, not special cases
Assets:Bank -1000 USD) → −1000 (outflow) ✓Assets:Bank +500 USD) → +500 (inflow) ✓A synthetic terminal flow values the position still held on the end date at market — realized through the booking engine (the same realization as
report_cmd::account_balances, so lots keep cost and reductions match each account's booking method) and priced via the oracle.PriceOracle— keeping the crate a leafPrices arrive through a new
PriceOracletrait, not a concrete price database. This:rustledger-returnsa leaf (no dependency onrustledger-query, which owns the price index);PriceDatabase::convert, so the CLI consumer implements it in one line.The full core-relocation of
PriceDatabasethat #1814 sketches can still happen on its own merits; the trait means extraction doesn't have to wait on it.Fails loud
extractreturnsExtractError::MissingPricerather than dropping a flow it can't state in the reporting currency — a silently omitted flow doesn't error, it just yields the wrong rate.Tests (15 extraction + 16 existing xirr = 31)
Sign conventions; the internal-transfer and reinvested-dividend traps; multi-currency conversion; the horizon cutoff; terminal valuation (held position, broker cash, fully-sold →
None); missing-price errors on both flow and terminal paths; segment-aware classification; and an end-to-endextract_cash_flows→xirrsanity check (~10%).Deferred to follow-ups (per #1814)
terminal_value)rledger report returns --investments <pattern>CLI surface + the realimpl PriceOracle for PriceDatabase(integration-tested there, where both crates are in scope)Part of #1814.
🤖 Generated with Claude Code