Skip to content

feat(report): balances/balsheet show lots at cost, like beancount - #1728

Merged
robcohen merged 1 commit into
mainfrom
feat/report-beancount-cost
Jul 9, 2026
Merged

robcohen merged 1 commit into
mainfrom
feat/report-beancount-cost

Conversation

@robcohen

@robcohen robcohen commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

#1727 made account_balances the single source of truth but realized cost-less (a held commodity showed 5 AAPL). This realizes through the booking engine so reports match beancount: 5 AAPL {150.00 USD}.

What changed

  • account_balances 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 lots by the account's booking method (FIFO/LIFO/…).
  • Supersedes refactor(report): single source of truth for account balances (#1726) #1727's trade-off: different-cost lots no longer merge — 10 AAPL {150} + 10 AAPL {200} show separately, like beancount.
  • rustledger-booking: new BookingEngine::into_inventories() exposes the realized map.
  • balances/balsheet render lot cost in text/CSV/JSON (new cost column/field; empty for plain currency → cash/income rows unchanged).

Verified vs beancount 3.2.3

  • reduction (buy 10 / sell 5) → 5 AAPL { 150.00 USD, 2024-01-05}, matching sum(position) (rledger also shows the lot date like beancount's Position str)
  • two lots → shown separately
  • report + CLI suites pass, clippy 0, fmt clean
  • the one failing integration test (test_account_lifecycle_consistency) is pre-existing on main, unrelated (bean-check validation)

holdings (own cost-basis path) and income (no cost) are unaffected.

🤖 Generated with Claude Code

@robcohen
robcohen requested a review from a team as a code owner July 9, 2026 05:32
Copilot AI review requested due to automatic review settings July 9, 2026 05:32

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

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_balances to drive rustledger_booking::BookingEngine and return realized per-account inventories (lot-aware).
  • Updates balances and balsheet renderers to include lot cost in Text/CSV/JSON outputs (new cost column/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 a cost column. This produces malformed CSV with inconsistent column counts; add an empty cost field 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]>
@robcohen
robcohen force-pushed the feat/report-beancount-cost branch from a80ab9a to a07bb9d Compare July 9, 2026 05:54
@codecov

codecov Bot commented Jul 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.00000% with 12 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/report_cmd/balances.rs 72.00% 7 Missing ⚠️
crates/rustledger/src/cmd/report_cmd/balsheet.rs 70.58% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 31.3ms ± 0.7ms 23.8 MB
beancount 860ms ± 4.3ms 50.8 MB
Comparison 27.5x faster 2.1x less

vs main branch (2026-07-08)

Metric main this PR Change
Time 35ms 31.3ms -10.6% 🟢
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

@robcohen

robcohen commented Jul 9, 2026

Copy link
Copy Markdown
Member Author

Deep self-review

Ran 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

Case rledger beancount ✓
Reduction (buy 10 / sell 5) 5 AAPL {150.00 USD} 5 AAPL {150.00 USD} ✓
Two different-cost lots shown separately separately ✓
Same-cost lots (buy 10 + buy 5 @ same price) two lots by date two lots ✓
Price-only (@, no cost) 100 EUR cost-less 100 EUR ✓
Full liquidation account omitted shown empty see note 2

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

  • apply requires booked input — verified balance_input derives from ledger.directives, which is booked (costs resolved). booking is a default feature (full), and the CLI takes the loader with defaults, so directives are always booked in any normal build. The unbooked-over-sell path needs --no-default-features, which the CLI never does. Not reachable (note 4).
  • Determinism: FxHashMap → BTreeMap collect sorts by account; output is stable.
  • CSV injection: the cost string contains a comma ({ 150.00 USD, 2024-01-05}); csv_escape correctly quotes it. JSON escapes cleanly. Verified both.
  • Tests: report_pad_expansion (8), reduction_netting (3), cli_commands (57) pass; clippy 0; fmt clean. The one failing integration test is pre-existing on main (bean-check validation).

Notes (non-blocking)

  1. Lot date is shown ({ 150.00 USD, 2024-01-05}) where bean-query's sum(position) omits it. Deliberate — matches beancount's canonical Position str and fava. More informative; flagging as a conscious choice.
  2. Full liquidation: rledger omits zero-balance accounts (pre-existing balances behavior of skipping empties), beancount shows them empty. Not a regression from this PR.
  3. Perf: reports now run a second inventory-accumulation pass (engine.apply over already-booked directives) on top of the loader's book phase. Fine for one-shot report commands; the way to avoid it later is the deferred consolidation (loader exposes its realized inventories, reports/BQL/FFI read them).
  4. Theoretical unbooked build: account_balances unconditionally realizes via BookingEngine; a --no-default-features loader build (no booking) would feed it unbooked directives. Unreachable via the CLI, but a defensive doc note on the fn wouldn't hurt.
  5. Schema change: CSV/JSON gain a trailing cost column/field. Additive, but positional CSV consumers should know.

Verdict: correct, beancount-faithful, contained. Notes 1 and 5 are the only user-facing decisions (lot-date display, added column) — both intentional.

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 810
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

@robcohen
robcohen enabled auto-merge (squash) July 9, 2026 06:02
@robcohen
robcohen merged commit ecedbfd into main Jul 9, 2026
52 of 53 checks passed
@robcohen
robcohen deleted the feat/report-beancount-cost branch July 9, 2026 06:17
robcohen added a commit that referenced this pull request Jul 10, 2026
…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]>
robcohen added a commit that referenced this pull request Jul 10, 2026
…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]>
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