Repository navigation
feat(report): balances/balsheet show lots at cost, like beancount - #1728
Conversation
There was a problem hiding this comment.
Pull request overview
This PR updates the balances/balsheet reporting path to realize per-account inventories via the booking engine so lots are retained at cost (beancount-style) and reductions net against existing lots using the account booking method, with reports rendering the resulting cost annotations.
Changes:
- Reworks
report_cmd::account_balancesto driverustledger_booking::BookingEngineand return realized per-account inventories (lot-aware). - Updates
balancesandbalsheetrenderers to include lot cost in Text/CSV/JSON outputs (newcostcolumn/field). - Adds a regression test ensuring reductions net correctly and that cost annotations are rendered.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger/tests/report_reduction_netting_test.rs | Adds regression coverage for reduction netting + cost annotation rendering in balances/balsheet. |
| crates/rustledger/src/cmd/report_cmd/mod.rs | Makes account_balances realize balances through the booking engine and return deterministic account ordering. |
| crates/rustledger/src/cmd/report_cmd/income.rs | Partitions shared account_balances output instead of re-summing postings locally. |
| crates/rustledger/src/cmd/report_cmd/balsheet.rs | Adds cost to balsheet rows/output formats while keeping totals/net worth sections. |
| crates/rustledger/src/cmd/report_cmd/balances.rs | Adds cost to balances rows/output formats and renders it in text output. |
| crates/rustledger-booking/src/book.rs | Adds BookingEngine::into_inventories() to expose realized inventories to callers. |
Comments suppressed due to low confidence (1)
crates/rustledger/src/cmd/report_cmd/balsheet.rs:109
- In CSV output the net worth rows still emit only 4 columns (
section,account,amount,currency) even though the header now includes acostcolumn. This produces malformed CSV with inconsistent column counts; add an emptycostfield for these rows.
// Add net worth rows
for (currency, total) in &net_worth {
writeln!(writer, "Net Worth,TOTAL,{total},{currency}")?;
}
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Follow-up to #1727. That PR made `account_balances` the single source of truth but realized cost-less (a held commodity showed `5 AAPL`). This realizes through the booking engine instead, so reports match beancount: `5 AAPL {150.00 USD}`, with reductions matched against lots and different-cost lots kept separate. - account_balances now drives a `BookingEngine` over the (already-booked) directive stream and returns its realized per-account inventories — the same lot-matching the loader's book phase uses, not a re-implementation. Reductions net against their lots by the account's booking method (FIFO/LIFO/…); this supersedes #1727's documented "different-cost lots merge to 20 AAPL" trade-off — they now stay separate (`10 AAPL {150}` + `10 AAPL {200}`), like beancount. - rustledger-booking: `BookingEngine::into_inventories()` exposes the realized map (previously only single-account `inventory()` existed). - balances/balsheet render the lot cost in text/CSV/JSON (new `cost` column/field; empty for plain currency, so income and cash rows are unchanged). Verified against beancount 3.2.3: reduction nets to `5 AAPL {150.00 USD}`, two lots show separately. Report + CLI suites pass; the one failing integration test (test_account_lifecycle_consistency) is pre-existing on the parent branch and unrelated (a bean-check validation test). Co-Authored-By: Claude Opus 4.8 <[email protected]>
a80ab9a to
a07bb9d
Compare
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-07-08)
What do these numbers mean?
|
Deep self-reviewRan an adversarial pass on this change — interrogating the booking-engine realization on edge cases and the risky contract assumptions, not just the happy path. No blockers found; a handful of notes worth recording. Verified correct against beancount 3.2.3
The same-cost case is the notable one: beancount keeps lots distinct by date even at identical cost, and the engine realization matches — so this is more faithful than the PR title's "different-cost" framing implied. Contract / safety
Notes (non-blocking)
Verdict: correct, beancount-faithful, contained. Notes 1 and 5 are the only user-facing decisions (lot-date display, added column) — both intentional. |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
…ecks, quarter math) (#1741) * chore: consolidate utility copies (CSV/JSON escaping, account-type checks, quarter math) Utility-census batch from the Phase-1 sweep (U1/U2/U5). All changes behavior-identical; no user-visible output changes. - CSV escaping: report_cmd csv_escape and BQL output escape_csv were byte-identical private copies. Hoist to rustledger_core::format::escape_csv (with unit tests); both CLI sites now delegate (report_cmd via a pub(super) use alias so the 26 call sites are untouched). - JSON escaping: report_cmd json_escape hand-chained replace() over exactly the escape set core's format::escape_string handles (backslash, quote, \n, \r, \t) — aliased to the core fn, hand chain deleted. - Account-type checks: four production sites re-derived the account type from raw string prefixes; they now use the core helpers (ACCOUNT_TYPES / account_type), so a future sixth type or rule change has one home: - LSP on_type_formatting + utils is_account_like: the deliberately colon-less mid-typing heuristics now iterate core ACCOUNT_TYPES. - check_drained plugin: six hand-written clauses (three prefixes + three bare-root equalities) collapse to a three-arm match on core account_type, which classifies by root component. - split_expenses plugin: is_expense via account_type (identical for any parsable account, which always has >= 2 components). - Quarter math: the (month - 1) / 3 formula appeared twice within query functions/date.rs, diverging only in off-by-one framing (DATE_TRUNC zero-based vs QUARTER() one-based). Single const quarter_index0 helper now feeds both. Deliberately NOT in this batch: - report-section routing sites (balsheet/income/networth/holdings) are already rewritten config-aware by open PR #1731 — touching them here would conflict. - networth's period bucketing was NOT ported onto query IntervalUnit: its buckets are label-string equality (ISO %V weeks) and switching machinery risks silent boundary changes for purely cosmetic dedup. Reports adopting DisplayContext (U4) is user-visible and belongs in its own PR, like #1728. Note: test_account_lifecycle_consistency (integration_test.rs) fails on main BEFORE this change — rledger check passes an account-used-before-open ledger that Python rejects. Pre-existing; tracked separately. Co-Authored-By: Claude Fable 5 <[email protected]> * fix: reattach add_days docs; tighten escape_csv wording; hoist import (review) - quarter_index0 had been inserted between add_days's doc block and its fn, so rustdoc attached the wrong docs; moved above the block, plus a debug_assert and a note on the 1-based month contract. - escape_csv doc said "newline"; only \n triggers quoting (\r does not), matching the prior copies byte-for-byte — say so. - escape_csv import moved to the top import group in query output. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: DATE_BIN quarter arm is not a quarter_index0 user (deep review) Its bucketing is origin- and width-relative months arithmetic, not calendar-quarter indexing — the doc claimed a third call site that does not (and could not) exist. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: split escape_csv doc paragraph (clippy 1.97 length lint) Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
…1750) * feat(report): render numbers through the ledger DisplayContext (U4) Balance-style reports (balances, balsheet, income, holdings, networth) printed raw Decimal Display, whose precision is an artifact of booking arithmetic rather than ledger convention: an integer-written posting in a 2dp ledger showed "100 USD" where bean-query (and our own BQL output, context-aware since #961/#985) shows "100.00 USD". LoadedReport now carries the loader's DisplayContext (per-currency inferred precision under the MostCommon policy, display_precision overrides, render_commas) and the five reports format every units number and total through format_amount_number — one rendering shared by text, CSV, and JSON arms. Lot-cost annotations keep their existing Display form (pinned to bean-query's Position string in #1728/#1733). Verified byte-identical against beancount 3.2.3 bean-query BALANCES on a mixed-precision fixture, including both directions of the MostCommon policy: 2dp-dominant ledgers pad integers to 100.00, integer-dominant ledgers render 2400 — matching bean-query in each case. New integration test pins the padded rendering and CSV consistency; full CLI suite (incl. the #1733 query==report parity guard) green. Co-Authored-By: Claude Fable 5 <[email protected]> * fix: csv-escape context-formatted amounts; square balsheet CSV row (review) render_commas puts thousands separators inside formatted numbers, so every CSV arm writing them raw produced rows with extra columns — all five reports now csv_escape the numeric fields (RFC-4180 quoting). Also the balsheet Net Worth CSV row gains its empty trailing cost field to match the five-column header. New test drives option "render_commas" "TRUE" end-to-end and asserts quoted amounts plus quote-aware column counts on every row. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
#1727 made
account_balancesthe single source of truth but realized cost-less (a held commodity showed5 AAPL). This realizes through the booking engine so reports match beancount:5 AAPL {150.00 USD}.What changed
account_balancesdrives aBookingEngineover the already-booked directive stream and returns its realized per-account inventories — the same lot-matching the loader's book phase uses, not a re-implementation. Reductions net against lots by the account's booking method (FIFO/LIFO/…).10 AAPL {150}+10 AAPL {200}show separately, like beancount.rustledger-booking: newBookingEngine::into_inventories()exposes the realized map.costcolumn/field; empty for plain currency → cash/income rows unchanged).Verified vs beancount 3.2.3
5 AAPL { 150.00 USD, 2024-01-05}, matchingsum(position)(rledger also shows the lot date like beancount'sPositionstr)test_account_lifecycle_consistency) is pre-existing on main, unrelated (bean-check validation)holdings(own cost-basis path) andincome(no cost) are unaffected.🤖 Generated with Claude Code