Skip to content

Correct balances and balsheet reports for reductions in holdings - #1726

Merged
robcohen merged 1 commit into
rustledger:mainfrom
weslem:push-qtunqmlrxlpt
Jul 9, 2026
Merged

robcohen merged 1 commit into
rustledger:mainfrom
weslem:push-qtunqmlrxlpt

Conversation

@weslem

@weslem weslem commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Summary

The balances and balsheet output for rledger report would include both positive and negative positions for held commodities. Instead, they should produce the total sum of the currency amounts in a single non-zero value per account, per commodity.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • Feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation (changes to docs only)
  • Refactor (code change that neither fixes a bug nor adds a feature)

Changes

  • Add only the amount from each included position, rather than the cost. This way Inventory.add() will keep a correct sum of the commodity balance.

Testing

  • cargo test passes
  • cargo clippy passes
  • Tested manually with a beancount file
  • Added new tests for the changes

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have added tests that prove my fix/feature works
  • New and existing tests pass locally
  • I have updated documentation if needed
  • My changes don't introduce new warnings

Review Focus

  • Please review the algorithm/logic
  • Please review for beancount compatibility
  • Please review for performance
  • Please review test coverage
  • General review is fine

Related Issues


For Reviewers

Review checklist (see CONTRIBUTING.md):

  1. Correctness - Does the code do what it claims?
  2. Tests - Are there sufficient tests?
  3. Beancount compatibility - Does it match Python beancount?
  4. Performance - Any obvious issues?
  5. Security - Any vulnerabilities?
  6. Documentation - Are public APIs documented?

These reports should not accumulate different positions for holdings
with different costs. They should keep a simple balance of the currency.
Drop the cost from the positions when adding to the inventory so
Inventory.add() sums them together.
@weslem
weslem requested a review from a team as a code owner July 8, 2026 20:26
@CLAassistant

CLAassistant commented Jul 8, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Jul 9, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@robcohen robcohen left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified against bean-check 3.2.3 ground truth — the fix is correct, and I'm going to merge it. Thanks for the clean catch, @weslem.

Confirmed

  • Bug reproduces on main: report balances on a buy(10 AAPL {150})/sell(-5 AAPL {150} @ 180) fixture prints two rows, 10 AAPL and -5 AAPL — the reduction never nets. With your patch it prints 5 AAPL, matching beancount's sum(position) = 5 AAPL {150.00 USD}.
  • Root cause is exactly what your patch implies: the reduction posting resolved to a different lot-key than the augmentation (the @ price/resolve path yields a position that doesn't share the buy's cost key), so Inventory.add couldn't cancel them. Dropping cost lets them net by commodity.
  • This reduces drift rather than adding it: income.rs — the third report consumer with the same pattern — already uses Position::simple. Your change makes balances.rs/balsheet.rs consistent with it.
  • No valuation regression: balsheet's sum_by_currency/net-worth only read units.number+currency; the cost was only ever a lot-key and was never rendered, so nothing downstream loses information.

I'll take it from here

Your fix is good and I don't want to make you chase the extra bits — I'll merge this and add the two follow-ups myself in a small commit on top:

  1. Regression tests — one per report asserting the buy/sell fixture yields a single 5 AAPL row, so this can't silently rot in a future refactor.
  2. A one-line comment noting these are deliberately simplified, cost-less views: two lots at different costs now merge (buy 10 AAPL {150} + buy 10 AAPL {200} → 20 AAPL), where beancount keeps them as separate lots. That's arguably better than the old output (two indistinguishable 10 AAPL rows), but the next reader should know these reports sum by commodity and don't track lots.

For the record, the long-term direction (not this PR): these three report consumers each re-derive an inventory from raw postings; the cost-accurate fix is to have them read the already-booked inventory instead. Larger change, tracked separately.

Nice, tight fix. Merging shortly with your authorship intact. 👍

Thank you for taking the time to submit this fix.

@robcohen
robcohen enabled auto-merge (squash) July 9, 2026 03:43
@robcohen
robcohen merged commit e3d7d24 into rustledger:main Jul 9, 2026
37 of 38 checks passed
robcohen added a commit that referenced this pull request Jul 9, 2026
Follow-up to #1726 (@weslem's fix): add the regression coverage and a
comment the fix was missing.

- New report_reduction_netting_test.rs: a buy(10 AAPL {150})/sell(-5 AAPL
  {150} @ 180) fixture must render a single netted 5 AAPL in both
  `report balances` and `report balsheet` (balsheet across account row,
  assets total, and net worth). Verified these tests FAIL on the pre-fix
  code and pass after — matches beancount 3.2.3 sum(position)=5 AAPL.
- Comment on both report sites documenting the deliberate cost-less,
  sum-by-commodity behavior and its trade-off (two different-cost lots
  merge, e.g. 10 AAPL {150} + 10 AAPL {200} -> 20 AAPL, vs beancount
  keeping separate lots) — acceptable because these reports never render
  cost.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
robcohen added a commit that referenced this pull request Jul 9, 2026
#1726 fixed the symptom — `report balances`/`balsheet` weren't netting a
held-commodity reduction against its augmentation — but the root cause
was structural: three reports (`balances`, `balsheet`, `income`) each
re-derived per-account balances from raw postings with their own copy of
the accumulation logic, and the copies had already drifted (`income` was
cost-less; `balances`/`balsheet` used a cost lot-key that failed to net
reductions). Same question, three implementations, two answers.

This makes "what does each account hold" a single function,
`report_cmd::account_balances`, that every balance-computing report is a
*view* over. The three reports now just partition/filter its output by
account prefix; none re-derives balances. The behavior is identical
(verified) but the drift class is closed: the reports can no longer
disagree, because there is one implementation.

- New `account_balances(directives) -> BTreeMap<Account, Inventory>` in
  report_cmd/mod.rs, documenting the deliberate cost-less sum-by-commodity
  behavior + its trade-off (different-cost lots merge; cost is never
  rendered) in the one place it now lives.
- `balances`/`balsheet`/`income` rewritten to consume it (−61 lines of
  duplicated accumulation).
- Regression tests (report_reduction_netting_test.rs): buy(10 AAPL {150})
  /sell(-5 AAPL {150} @ 180) must render a single netted 5 AAPL in both
  `balances` and `balsheet`. Verified they fail on pre-#1726 code and
  pass now; 5 AAPL matches beancount 3.2.3 sum(position).

Follow-up to #1726 (@weslem). Cost-accurate lot tracking, if ever wanted,
now has exactly one place to live.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
robcohen added a commit that referenced this pull request Jul 9, 2026
#1726 fixed the symptom — `report balances`/`balsheet` weren't netting a
held-commodity reduction against its augmentation — but the root cause
was structural: three reports (`balances`, `balsheet`, `income`) each
re-derived per-account balances from raw postings with their own copy of
the accumulation logic, and the copies had already drifted (`income` was
cost-less; `balances`/`balsheet` used a cost lot-key that failed to net
reductions). Same question, three implementations, two answers.

This makes "what does each account hold" a single function,
`report_cmd::account_balances`, that every balance-computing report is a
*view* over. The three reports now just partition/filter its output by
account prefix; none re-derives balances. The behavior is identical
(verified) but the drift class is closed: the reports can no longer
disagree, because there is one implementation.

- New `account_balances(directives) -> BTreeMap<Account, Inventory>` in
  report_cmd/mod.rs, documenting the deliberate cost-less sum-by-commodity
  behavior + its trade-off (different-cost lots merge; cost is never
  rendered) in the one place it now lives.
- `balances`/`balsheet`/`income` rewritten to consume it (−61 lines of
  duplicated accumulation).
- Regression tests (report_reduction_netting_test.rs): buy(10 AAPL {150})
  /sell(-5 AAPL {150} @ 180) must render a single netted 5 AAPL in both
  `balances` and `balsheet`. Verified they fail on pre-#1726 code and
  pass now; 5 AAPL matches beancount 3.2.3 sum(position).
- Drift guard: a test asserts `balances` and `balsheet` report the same
  figure for the same account — the invariant the shared source enforces,
  so a future re-fork is caught. `holdings` (needs cost) and `networth`
  (per-period time series) are deliberately NOT folded in: they are
  different computations, not drift copies, and both are already correct.

Follow-up to #1726 (@weslem). Cost-accurate lot tracking, if ever wanted,
now has exactly one place to live.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
robcohen added a commit that referenced this pull request Jul 9, 2026
…#1727)

* refactor(report): single source of truth for account balances (#1726)

#1726 fixed the symptom — `report balances`/`balsheet` weren't netting a
held-commodity reduction against its augmentation — but the root cause
was structural: three reports (`balances`, `balsheet`, `income`) each
re-derived per-account balances from raw postings with their own copy of
the accumulation logic, and the copies had already drifted (`income` was
cost-less; `balances`/`balsheet` used a cost lot-key that failed to net
reductions). Same question, three implementations, two answers.

This makes "what does each account hold" a single function,
`report_cmd::account_balances`, that every balance-computing report is a
*view* over. The three reports now just partition/filter its output by
account prefix; none re-derives balances. The behavior is identical
(verified) but the drift class is closed: the reports can no longer
disagree, because there is one implementation.

- New `account_balances(directives) -> BTreeMap<Account, Inventory>` in
  report_cmd/mod.rs, documenting the deliberate cost-less sum-by-commodity
  behavior + its trade-off (different-cost lots merge; cost is never
  rendered) in the one place it now lives.
- `balances`/`balsheet`/`income` rewritten to consume it (−61 lines of
  duplicated accumulation).
- Regression tests (report_reduction_netting_test.rs): buy(10 AAPL {150})
  /sell(-5 AAPL {150} @ 180) must render a single netted 5 AAPL in both
  `balances` and `balsheet`. Verified they fail on pre-#1726 code and
  pass now; 5 AAPL matches beancount 3.2.3 sum(position).
- Drift guard: a test asserts `balances` and `balsheet` report the same
  figure for the same account — the invariant the shared source enforces,
  so a future re-fork is caught. `holdings` (needs cost) and `networth`
  (per-period time series) are deliberately NOT folded in: they are
  different computations, not drift copies, and both are already correct.

Follow-up to #1726 (@weslem). Cost-accurate lot tracking, if ever wanted,
now has exactly one place to live.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(report): pin balsheet holding propagates to totals + net worth

Addresses Copilot review on #1727: assert_netted_to_5 verified every AAPL
line reads 5 but not that balsheet actually carries the holding into
Total Assets and Net Worth — a regression dropping the commodity from the
totals could print a lone 5 AAPL account row and still pass. The balsheet
test now asserts the 5 AAPL figure appears in the Total Assets line and
the Net Worth section explicitly.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
robcohen added a commit that referenced this pull request Jul 10, 2026
…#1733)

Drift guard from the Phase-0 duplication sweep (realization family, Z2).
The two surfaces realize balances differently by construction — query
re-aggregates booked postings with naive Inventory::add; reports realize
through the booking engine — and agree today ONLY because both consume
post-booking directives. That invariant holds by pipeline design, not by
any check: feeding the executor unbooked directives would silently
reactivate the #1726 netting class in BQL while reports stayed correct.

Pins agreement on the two #1726 reduction shapes (explicit-cost + price;
FIFO empty-{} across two lots), asserting a single netted AAPL row with
identical units and lot cost on both surfaces, at the beancount-verified
values (5 @ 150.00 / 5 @ 200.00).

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.

3 participants