Skip to content

fix(query): realize sum(position) of an AVERAGE account through booking (#2394) - #2529

Merged
robcohen merged 3 commits into
mainfrom
fix/bql-sum-average-mixed-pool
Oct 9, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/bql-sum-average-mixed-pool

Conversation

@robcohen

@robcohen robcohen commented Oct 8, 2026

Copy link
Copy Markdown
Member

What changed

  • sum(position) over a group drawn from one AVERAGE account no longer sums the postings and then pools them. It replays the group's postings through BookingEngine::replay_transaction, the canonical walk that BALANCES and account_balance use, with one subset transaction per source transaction. It then presents the result as one weighted-average pool per side.
  • Inventory::merge_average pools the long lots and the short lots of a commodity separately. Its input is now a realized inventory, where a negative lot is a short. (This changes the behavior of a public function, so the CHANGELOG entry is under Breaking.)
  • The AVERAGE check reads the ledger's default method too, using the same rule as register_account_methods/method_for: the open's method if it parses, otherwise the ledger's. An account that books AVERAGE through option "booking_method" is now realized as well. Previously it listed the sale's lot beside the lots it sold from (10 {100}, 10 {110}, -14 {105}).
  • When a WHERE keeps a subset that booking cannot realize, for example a sale of more units than the selected postings hold, the plain sum of the postings stands, unmerged. The old pooling would have netted the sale into a buy instead.

Why

The issue shows that a sum of postings cannot tell a sale (a negative lot at the pool's cost) from a short, so no rule inside merge_average can fix this. #2393 tried "leave mixed lots unmerged" and reverted it. Booking can tell them apart. Once the group has been realized, a negative lot can only be a short, and pooling each side separately is correct. That is the direction the triage suggested. The stopgap (leave the pool unmerged) is used only as the fallback when the subset cannot be realized.

Grouping postings by transaction keeps replay_transaction's booking order inside each transaction (#2380). Each subset transaction holds only the group's postings, which gives #1985's filtered-subset semantics. On a WHERE year = 2021 subset the result matches BALANCES FROM year = 2021.

Verification

Issue ledger (Assets:Stock, AVERAGE, a short at 101 and a long at 102, then a sale of 2):

surface main branch
sum(position) GROUP BY account 1 X {104 USD} 3 X {102 USD} -2 X {101 USD}
BALANCES 3 X {102 USD} -2 X {101 USD} same

Other shapes, main vs branch:

shape main branch reference
two buys, sale of 14, buy of 2 (per-account AVERAGE) 8 X {111} 8 X {111} unchanged
same, AVERAGE from option "booking_method" 10 {110} 10 {100} 2 {130} -14 {105} 8 X {111} pool
WHERE year = 2021 subset -12 X {101} -12 X {105} BALANCES FROM year = 2021: -12 X {105}
FIFO / LIFO / STRICT variants 10 X {110} 2 X {130} same bean-query: same

Oracle: beancount 3 refuses this ledger (bean-check: "AVERAGE method is not supported"), so for AVERAGE the reference is rledger's own BALANCES and booking. The new tests assert agreement with BALANCES. For the non-AVERAGE shapes, bean-query gives the same output as main and the branch.

  • New crates/rustledger-query/tests/sum_position_average_realized.rs, 4 tests. On main, 3 fail: the long/short case ([(1, 104)]), the ledger-default case (dangling lots), and the unrealizable subset (-12 {103.48…}). The single-sided regression guard passes on main.
  • merge_average_pools_each_side_apart (core) and a_mixed_sign_pool_keeps_each_side_at_its_own_cost (booking) fail when merge_average's side key is reverted to currency-only.
  • I rewrote the two core tests and the booking test that pinned the old both-sides pooling (merge_average_collapses_… with a sale lot, merge_average_net_zero_removes_lots, a_mixed_sign_pool_is_correctly_rounded_through_the_escalation). After AVERAGE pools long and short lots together: wrong basis and a vanished short on a mixed account #2393 and this change, no path averages a long and a short together, so the mixed-sign escalation regime is unreachable. Same-sign escalation stays covered by average_cost_properties.
  • cargo test -p rustledger-core -p rustledger-booking -p rustledger-query --all-features: 1707 passed, 0 failed. Workspace clippy, fmt, and cargo doc -D warnings are clean.
  • BQL compat harness run locally over the 38 in-tree files both tools accept: 690/722 matched on both main and the branch, identical per pair.

No CACHE_VERSION bump: this is query-time only, and booking output is unchanged.

Known remaining divergence (pre-existing, unchanged): for an AVERAGE account with several buys and no sale yet, sum(position) shows the pool (20 X {160}, pinned by test_average_account_sum_position_merges_to_single_pool). BALANCES lists the lots, because booking merges only when it sells.

Closes #2394

Refs #2388 (designed together, shipped separately).

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…ng (#2394)

`SELECT account, sum(position) ... GROUP BY account` summed an AVERAGE
account's postings and pooled every cost-bearing lot of the commodity.
A sale is a negative lot in that sum and so is a short, so an account
holding both netted one into the other: `-2 X {101}` beside `3 X {102}`
came out as `1 X {104}`, a lot nobody held, while BALANCES was right.

The group is now replayed through `BookingEngine::replay_transaction`,
the walk BALANCES uses, one subset transaction per source transaction,
and presented as one weighted-average pool per side.
`Inventory::merge_average` now pools the long lots and the short lots
apart, since its input is realized and a negative lot is a short. The
AVERAGE check also reads the ledger's default method, so an account
that books AVERAGE through `option "booking_method"` is realized the
same way. A subset booking cannot realize keeps the plain sum.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner October 8, 2026 18:21
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 44.6ms ± 0.8ms 737.3ms ± 6.7ms 16.5x 51.0 MB / 50.1 MB
investment 70.4ms ± 1.2ms 2779.5ms ± 27.3ms 39.5x 55.1 MB / 58.0 MB
fifo 67.0ms ± 1.1ms 15896.3ms ± 561.3ms 237.2x 55.2 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 43.5ms ± 0.6ms 44.6ms ± 0.8ms +2.4% ✅ within noise 51.0 MB → 51.0 MB (+0.2%)
investment 70.1ms ± 0.9ms 70.4ms ± 1.2ms +0.4% ✅ within noise 55.0 MB → 55.1 MB (+0.1%)
fifo 67.1ms ± 0.9ms 67.0ms ± 1.1ms -0.1% ✅ within noise 55.0 MB → 55.2 MB (+0.3%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.4ms, investment 0.7ms, fifo 0.6ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 819
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@codecov

codecov Bot commented Oct 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.48485% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/booking.rs 96.42% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

A property test generates ledgers with AVERAGE accounts (on the open and
through the ledger default), FIFO and STRICT accounts, two commodities,
two cost currencies, and buys, sales, shorts and a short beside a long,
keeping only what booking accepts. For every FROM filter, and the same
filter as a WHERE, an AVERAGE account's sum must equal its BALANCES
inventory pooled per side, and any other account's must equal BALANCES
exactly. A companion test asserts the generator reaches realized and
mixed AVERAGE accounts, so the property cannot pass by skipping.

Documents the AVERAGE `sum(position)` semantics in bql.md, including
the plain-sum fallback for a subset booking cannot realize, and amends
ADR-0007, whose last amendment still said `merge_average` pooled both
sides and that the mixed case was open.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

robcohen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member Author

Adversarial review (author self-review)

1. Property: sum(position) vs BALANCES. New test crates/rustledger-query/tests/sum_position_balances_agreement.rs.

  • Ledgers generated: up to 3 accounts, booking AVERAGE (on the open, or through the ledger default), FIFO or STRICT, with AVERAGE, STRICT or FIFO as the ledger default. Two commodities, two cost currencies. Buys, {} sales, explicit-cost shorts, and the issue's short-beside-a-long transaction. A transaction booking rejects is dropped, so every ledger is one that booking accepts.
  • Filters checked: 5 FROM filters (none, two date ranges, two narration filters), plus the same filter written as a WHERE, which keeps the same postings.
  • What it asserts:
    • An AVERAGE account's sum equals merge_average(BALANCES).
    • Any other account's sum equals BALANCES exactly.
    • A companion test checks that the generator actually reaches realized AVERAGE accounts (>200) and mixed long/short ones (>10), so the property cannot pass by skipping everything.
  • Results:
    • 256 cases by default. One run counted 1,952 realized AVERAGE accounts (688 holding both a long and a short) and 42 skipped subsets.
    • A 20,000-case search (PROPTEST_CASES=20000, FROM and WHERE) found no disagreement.
    • On main's code the property fails immediately (the old two-sided pooling, and the dangling lots under a default AVERAGE).
  • Excluded cases, both documented:
    • (a) Booking keeps unsold AVERAGE buys as separate lots while sum(position) shows the pool. This is absorbed by comparing against merge_average(BALANCES).
    • (b) Subsets booking cannot realize: there BALANCES errors, so the property skips them.
  • FIFO/LIFO/STRICT vs bean-query (scratch harness, not committed): random ledgers that both bean-check and rledger check accept, three filters each. 276/276 matched; a further 57/57 matched on both main and the branch.

2. Should the fallback stay silent? Decision: keep the plain sum, and document it.

  • The executor has no warnings channel; QueryResult has no field for one.
  • Erroring would break queries that answer today, e.g. WHERE year = 2021 over a sale whose purchases came in 2020.
  • The plain sum is exactly what the selected postings add up to. That is bean-query's sum meaning for every other method, and what sum(position) already returns for a group spanning several accounts.
  • What should not happen is a pool that nets a sale into a buy, and that is gone.
  • Documented in docs/reference/bql.md, and in a new amendment to ADR-0007. ADR-0007's AVERAGE pools long and short lots together: wrong basis and a vanished short on a mixed account #2393 amendment still said merge_average pooled both sides and that the mixed case was open; that was stale and is corrected.

3. The no-sale divergence. sum(position) shows 20 X {160}; BALANCES lists 10 {150} and 10 {170}.

  • ADR-0007's Decision is that an AVERAGE account's realized balance is one pool. That matches every system it surveys: a WAC position is a single running pool, recomputed on each purchase.
  • The separate lots are an artifact of booking merging lazily, only at a sale. Because of that, BALANCES changes shape depending on whether a sale has happened yet. So sum(position) is the correct view, and it is BALANCES / report balances that lag.
  • Recommendation: a separate PR. It would present AVERAGE accounts one pool per side on BALANCES and report balances, as a presentation step in the shared realization, not by changing booking. Booking keeps lot dates and exact totals, and changing booking would hit the caches and the rustfava snapshots.
  • It is not in this PR because it changes two more surfaces, the realization parity test and rustfava snapshots. It needs its own issue; nothing filed.

4. The three inventory walks.

  • This PR adds no walk: the group goes through BookingEngine::replay_transaction, the canonical walk that BALANCES and account_balance use.
  • merge_average has no other caller. Apply (realize_posting) and validate (update_inventories) do not use it, and their reduce-or-augment decision is still the single is_booking_reduction.
  • Each subset transaction holds only the group's postings, so walk_step's any_cost is computed over the subset. That cannot change the result: a transaction in which this account has no cost-bearing posting has no reduction for this account to order against. The property covers this, since every transaction carries a cost-less cash leg.

Pushed in ddeb5d4: the property test, the bql.md section, the ADR amendment, and a corrected AccountInfo::booking doc. No production code changed in this round.


Second pass: other docs on AVERAGE pooling and merge_average (ee5564a)

I read every doc and comment on AVERAGE pooling, merge_average, mixed-sign pools and sum(position) semantics against the final code. This pass covered ADR-0007, docs/reference/bql.md, docs/migration/*, compatibility.md, report.md, options.md, the rustdoc on Inventory, merge_average, weighted_average_cost and the replay paths, and the CHANGELOG.

Fixed:

  • CHANGELOG, AVERAGE pools long and short lots together: wrong basis and a vanished short on a mixed account #2393 entry. It still said sum(position) "still nets the two sides". Both entries sit in the same unreleased section, so that line was stale. It now points to the sum(position) GROUP BY an AVERAGE account nets a short into the long pool on a mixed account #2394 entry.
  • ADR-0007 Decision. It described merge_average pooling all lots of a currency, and sum(position) calling it directly, with nothing pointing to the amendments. Both bullets now carry an inline pointer to the amendments.
  • CHANGELOG, Breaking entry for merge_average. It now tells a library caller exactly what changed:
    • The signature is unchanged.
    • Pooling is now per side, where it was per commodity.
    • A raw sum of postings now gets its sales back as a separate short pool.
    • There is no switch back to the netting, which is the bug. To get a correct result, realize the postings first with BookingEngine::replay_transaction, then call merge_average, as the executor does.
  • bql.md. It now says the account may book AVERAGE through the ledger's booking_method option, not only its open.

Checked and still accurate: report.md (AVERAGE lots have no acquisition date), the rustdoc on merge_average, weighted_average_cost and the aggregation path, docs/migration/* and compatibility.md (neither describes AVERAGE pooling).

The PR was MERGEABLE, so no merge from main was needed.

The #2393 CHANGELOG entry still said `sum(position)` nets the two sides,
and ADR-0007's Decision still described `merge_average` pooling every lot
of a commodity, with nothing pointing at the amendments. The Breaking
entry now tells a library caller what `merge_average` does differently
and how to get a realized input. bql.md names the ledger default method.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit efc3547 into main Oct 9, 2026
70 of 71 checks passed
@robcohen
robcohen deleted the fix/bql-sum-average-mixed-pool branch October 9, 2026 01:54
robcohen added a commit that referenced this pull request Oct 9, 2026
#2529 changed `group_is_single_average_account` in aggregation.rs to
resolve an account's method the way booking does: the `open`'s method,
else the ledger's. This branch had moved that check into
`account_is_average`, which the row-filtered BALANCES path also calls.
The helper now carries #2529's resolution, so the partial-BALANCES path
also sees AVERAGE under a global `option "booking_method"`.

Tests added on top of #2529's:

- sum_position_balances_agreement now also runs the posting-level
  filters `FROM number > 0` and `FROM number < 0`, which select part of
  an account. That is the case where BALANCES sums the selected postings
  instead of reading booking's inventory. 3,000 cases pass.
- a targeted test pins BALANCES and sum(position) to the same lots on a
  partly selected AVERAGE account holding two longs, a short and a sale.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
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.

sum(position) GROUP BY an AVERAGE account nets a short into the long pool on a mixed account

1 participant