Skip to content

fix(core): AVERAGE pools only the side a reduction takes from - #2395

Merged
robcohen merged 4 commits into
mainfrom
fix/average-pool-by-side-2393
Sep 22, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/average-pool-by-side-2393

Conversation

@robcohen

@robcohen robcohen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

What

An AVERAGE reduction now pools only the side it takes from: the lots whose sign is opposite the reduction's. Every other booking method, and {*} (plan_merge), already matched that way. Only that side is removed and replaced by its remainder; the other side is left as it was.

Why

reduce_average pooled every lot of the commodity, long and short together:

2020-01-01 open Assets:Stock X "AVERAGE"
2020-01-01 * "a short at 101 and a long at 102"
  Assets:Stock  -2 X {101 USD}
  Assets:Stock   5 X {102 USD}
  Assets:Cash  -308 USD
2020-01-05 * "sell 2 from the long pool"
  Assets:Stock  -2 X {} @ 110 USD
  ...
sale booked at holdings
correct 102 -2 X {101}, 3 X {102}
main, report balances 102.67 1 X {102.67} (short gone)
main, BALANCES 1 X {103}
this PR (both surfaces) 102 -2 X {101}, 3 X {102}

Selling 4 of the long 5 was refused as "available 3", and covering 1 of the short at 95 reported a loss of 8 with an unknown holding period instead of a short-term gain of 6. A silent wrong number on any AVERAGE account holding both a long and a short. Beancount rejects AVERAGE, so this is a correctness fix with no oracle.

Not changed: merge_average

merge_average realizes a sum of postings for sum(position) GROUP BY an AVERAGE account. There a sale is a negative lot at the pool's cost and must be netted in, so sign cannot separate sales from shorts. I tried a "leave mixed-sign lots unmerged" rule and reverted it, because it broke the ordinary single-sided case (two core tests caught it). On a mixed account that view is still wrong, on main and here: filed as #2394, with replaying the group through the engine as the direction.

A test that pinned the bug

zero_cost_basis_2351::a_mixed_sign_pool_is_correctly_rounded_through_the_escalation guards #2353's exact-escalation precision on a difference of products, and it got there through the long-plus-short AVERAGE reduction this PR removes. It now reaches the same escalation through merge_average, where a mixed-sign average is legitimate; the premise assertion still holds. It also pins that the reduction prices from the long side.

Evidence

  • Core: reduce_average_pools_only_the_side_it_reduces covers a sale, a sale larger than the net position, a cover, and a refusal against the side's own size.
  • Drift guard: query_report_realization_parity_test gains the mixed AVERAGE ledger.
  • Gains: average_mixed_sides_test pins the cover's realized gain (short sale, cost basis 95, proceeds 101).
  • ADR-0007 amended: one pool per side.
  • Dirty check: with the sign filter removed, both fail, and the drift guard shows the two surfaces disagreeing (1 {103} vs 1 {102.67}).
  • Workspace suite green (167 binaries); clippy clean. Agreement properties clean over 100 fresh runs.
  • Output identity: check and BALANCES byte-identical to main on seven benchmark ledgers.
  • Callgrind on check: −0.004% to +0.12%.

Closes #2393
Refs #2394

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`reduce_average` pooled every non-empty lot of the currency, long and short
together, and then removed every lot of the currency. On an account holding
a long of 5 at 102 and a short of 2 at 101, selling 2 booked at 102.67 (the
short pulled the basis toward its own cost), the holdings became
`1 X {102.67}` with the short gone, and selling 4 was refused as "available
3" from a long of 5. `report balances` and `BALANCES` disagreed with each
other too (102.67 vs 103).

The pool is now the side opposite the reduction's sign, the rule every other
method and `plan_merge` (`{*}`) already apply, and only that side is removed
and replaced by its remainder. A cover takes from the short side the same
way.

`merge_average`, which realizes a SUM of an AVERAGE account's postings, is
unchanged: there a sale is a negative lot at the pool's cost and must be
netted in, so sign cannot separate sales from shorts. A "leave mixed lots
unmerged" rule was tried and broke the single-sided case; #2394 tracks the
sum view of a mixed account.

`zero_cost_basis_2351`'s mixed-sign precision test reached the #2353
escalation through the pooling this removes. It now reaches it through
`merge_average`, where a mixed-sign average is legitimate, and also pins that
the reduction prices from the long side.

Tests: core `reduce_average_pools_only_the_side_it_reduces` (sale, larger
sale, cover, refusal against the side's size) and a drift-guard case in
`query_report_realization_parity_test`; both fail with the sign filter
removed. Agreement properties clean over 100 fresh runs; `check` and
`BALANCES` byte-identical to main on seven benchmark ledgers; callgrind on
`check` -0.004% to +0.12%.

Closes #2393
Refs #2394

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 September 22, 2026 18:30
@codecov

codecov Bot commented Sep 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 44.0ms ± 1.9ms 722.7ms ± 4.8ms 16.4x 51.2 MB / 50.1 MB
investment 67.8ms ± 0.4ms 2799.5ms ± 32.2ms 41.3x 56.9 MB / 58.2 MB
fifo 65.2ms ± 0.4ms 15812.4ms ± 39.7ms 242.7x 57.2 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 43.0ms ± 0.4ms 44.0ms ± 1.9ms +2.5% ✅ within noise 50.9 MB → 51.2 MB (+0.7%)
investment 68.5ms ± 1.5ms 67.8ms ± 0.4ms -1.0% ✅ within noise 57.3 MB → 56.9 MB (-0.7%)
fifo 65.8ms ± 3.3ms 65.2ms ± 0.4ms -0.9% ✅ within noise 57.3 MB → 57.2 MB (-0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.9ms, investment 0.7ms, fifo 1.5ms), 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

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 178 masked)
Full AST Match 100%
Total Files 813
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

Review of #2395. The one mutant `cargo mutants --in-diff` left alive was
`==` -> `!=` in the retain that also drops emptied positions of the reduced
currency: nothing checked that the tidying stays within that currency. The
core test now holds a zero STK position and a zero USD one and asserts the
first goes and the second stays. All 9 viable mutants on the PR's lines are
now caught.

Refs #2393

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

robcohen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member Author

Deep review (head eedb407, three passes)

Verdict: ready once CI is green. No code defects. Two test gaps closed, and ADR-0007 amended.

One implementation, every consumer

reduce_average is AVERAGE's only pooling path. try_reduce (booking's preview) runs AVERAGE as clone().reduce(...), and reduce dispatches to reduce_average; {*} on cost-less lots falls back to it; apply, the validator and the query replay all reach it through reduce. So the fix applies to every surface that realizes an AVERAGE account. The one exception is sum(position)'s merge_average, left alone deliberately and tracked as #2394.

The rule matches the other methods

The pool is the non-empty lots whose sign is opposite the reduction's: the same test plan_merge makes for {*} ("prevents accidentally netting long and short positions") and that ordered selection's keeps makes. The remainder is pushed back at the side's average, and the matched lot carries the side's sign, so a cover still yields a negative matched lot, as reduce_average_short_cover_matched_lot_carries_inventory_sign expects.

Mutation testing (cargo mutants --in-diff)

10 mutants: 9 caught, 1 unviable, 0 missed. The first run missed == → != in the retain that also drops emptied positions of the reduced currency; the core test now pins that the tidy-up stays within that currency.

The test that was changed

zero_cost_basis_2351's mixed-sign precision test guarded #2353's exact escalation on a difference of products, and reached it through the long-plus-short pooling this PR removes. It now reaches the same escalation through merge_average (a SUM of postings, where a sale is a negative lot and a mixed-sign average is legitimate). Its premise assertion, that the product is inexact so the escalation runs, still holds. It also now pins the corrected reduction.

Second pass

  • Realized gains were the untested consequence (fixed in 9c24b46). On a mixed AVERAGE account, covering 1 of a short opened at 101 by buying at 95 is a short-term gain of 6, on proceeds of 101. Main priced the cover from the net pool: report capgains showed a loss of 8 with an unknown term, and the account became 4 X {102.67}. average_mixed_sides_test pins the disposal (short sale, units, cost basis 95, proceeds 101) and fails with the sign filter removed.
  • ADR-0007 decided "one weighted-average pool" per commodity. Amended to one pool per side, with the reason the surveyed systems (hledger, GnuCash, AVCO) are silent (they model a single position), and a note that merge_average is unchanged and why (sum(position) GROUP BY an AVERAGE account nets a short into the long pool on a mixed account #2394).
  • check_average_cost does not re-derive AVERAGE: it checks only NONE-booked accounts, as beancount's does.
  • Rollback stays sound. In apply the narrowed retain still tombstones through set_dead, which records to the undo log, as does the pushed remainder.

Third pass: measured on AVERAGE itself

No benchmark ledger uses AVERAGE, so earlier "byte-identical, perf flat" results never ran the changed code. The FIFO benchmark opened as AVERAGE (one account, a {} sale per transaction) at 2k and 20k transactions gives byte-identical check, BALANCES, report balances and report capgains output (6685 lines) to main. Callgrind on check is +0.086%. So single-sided AVERAGE, the case every existing AVERAGE ledger is in, is unchanged.

The sale's gain on a mixed account is now pinned too (eedb407): 2 sold at 110 against a basis of 204 realize 16, where main realized 15 against 205.33. Its term is ?? in both, because AVERAGE pools are undated by design.

Observation, not in scope

Cost-less units on the reduced side still join the pool: total_units counts them and the numerator does not, so they dilute the average (#2364 noted this). #2379's a_cost_less_buy_does_not_join_an_average_sale_in_its_own_transaction pins the diluted 37.50 as booking's answer. Whether a cost-less X unit in an AVERAGE account should count as zero-cost is its own question. Worth an issue if you want it decided.

Evidence

  • Drift guard (query_report_realization_parity_test) and core test fail with the sign filter removed; the drift guard shows main's two surfaces disagreeing with each other (1 {103} vs 1 {102.67}).
  • Workspace suite green, clippy clean, agreement properties clean over 100 fresh runs.
  • check and BALANCES byte-identical to main on seven benchmark ledgers; callgrind −0.004% to +0.12%.

robcohen and others added 2 commits September 22, 2026 18:52
…ADR-0007

Second review of #2395. The tax-visible consequence of #2393 was untested: on
an AVERAGE account holding a long at 102 and a short at 101, covering 1 of the
short at 95 is a short-term gain of 6 on proceeds of 101. Main priced the
cover from the net pool and reported a loss of 8 with an unknown holding
period, leaving `4 X {102.67}`. `average_mixed_sides_test` pins the disposal
(short sale, units, cost basis, proceeds) and fails with the sign filter
removed.

ADR-0007 decided "one weighted-average pool" per commodity. This amends it to
one pool per side, explains why the surveyed systems are silent on it, and
records that `merge_average` is unchanged and why (#2394).

Also checked: `check_average_cost` only applies to NONE-booked accounts (as in
beancount), so it does not re-derive AVERAGE pools; rollback stays sound, the
narrowed retain still tombstones through the undo log.

Refs #2393

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Third review of #2395. The cover's gain was pinned, the sale's was not: on
the mixed account, selling 2 from the long side at 110 realizes 16 against
a basis of 204; main realized 15 against 205.33.

Also measured in this pass, since no benchmark ledger is AVERAGE: the FIFO
bench shape opened AVERAGE at 2k and 20k transactions gives byte-identical
`check`, `BALANCES`, `report balances` and `report capgains` (6685 lines) to
main, and callgrind on `check` is +0.086%.

Refs #2393

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit 3b602d4 into main Sep 22, 2026
132 of 136 checks passed
@robcohen
robcohen deleted the fix/average-pool-by-side-2393 branch September 22, 2026 20:28
robcohen added a commit that referenced this pull request Sep 23, 2026
…#2399)

* fix(parser): a `*` that begins any cost component is the merge marker

Beancount's grammar takes a cost as a comma-separated list of components
(number, currency, date, label, `*`), and `*` may be any of them:
`{100.00 USD, *}`, `{2020-01-01, *}` and `{*, 100.00 USD}` all set merge
(checked against beancount 3.2.3's parser, which reaches its "Cost merging is
not supported yet" action for each). `MergeFlag` decided the flag from the
first token after the opener only, so a trailing `*` parsed as a plain
per-unit spec, with no diagnostic: `-5 X {110.00 USD, *}` failed with
`No matching lot`, and `-5 X {100.00 USD, *}` silently sold from the lot at
100 instead of the merged pool.

The rule is now: a `*` is the merge marker when the previous non-whitespace
token is the opener or a comma, i.e. when it begins a component. A `*` after a
number or `)` is still multiplication (`{500 * 2 USD}`). `MergeFlag` is the one
machine both the green and red walkers feed, so both change together; the
test that pinned `{2 USD, *}` as not-merge now pins it as a merge, with rows
for the other positions, and the red-tree accessor test gains the trailing
form. `rledger format` round-trips every form unchanged.

Caches: parser output changes, so loader CACHE_VERSION goes to 36 and the
wasm cache to 24 (with its loader pin). The wasm cache archives BOOKED
directives and errors, and the booking fixes merged since v23 (#2379, #2385,
#2391, #2395, #2397) each changed those without a bump, so a v23 blob could
serve their pre-fix answers; v24 covers them too. The CostNumber and
MetaValue byte-layout tripwires still compare their bytes; only their
FIXTURE_VERSION moves.

Not changed: a number in a merge spec is ignored, for the leading form as it
always was and now for the trailing one (#2398).

Tests: the MergeFlag row test and the ast accessor test; a loader test that
`{*}`, `{110.00 USD, *}` and `{100.00 USD, *}` all book from the merged pool
at 110, which fails on main's parser. Workspace suite green (169 binaries);
`check` byte-identical to main on four benchmarks; callgrind -0.03% to
+0.004%.

Closes #2329
Refs #2398

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

* test(parser): pin that MergeFlag ignores a comma before, or a brace after, the opener

Review of #2399. `cargo mutants --in-diff` (the CI mutation gate covers
rustledger-core only, not the parser) left the two `past_opener` guards
alive: flipping either let a comma before the opener, or a second `{` on
malformed input, arm a component start, so `, * {...` or `{2 USD {*` would
read as a merge. Both are malformed-input paths the doc comment promises to
ignore; two direct-feed assertions now pin them, and all 11 in-diff mutants
are caught.

Also checked in review:
- Only `merge` changes. Parsing 18 shapes with main's and this branch's
  parser gives identical number, currency, date and label for every one
  (compound `#` and total `{{}}` included); a missing comma (`{100 USD *}`)
  is still a parse error, as in beancount.
- No other code re-derives the merge flag; `Amount::is_arithmetic` sees the
  posting's amount node, never a cost spec's tokens.
- A trailing `*` on a buy books the same lot as before, as the leading form
  always has.

Refs #2329

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[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.

AVERAGE pools long and short lots together: wrong basis and a vanished short on a mixed account

1 participant