Repository navigation
fix(booking): AVERAGE realizes a single weighted-average pool - #1444
Merged
Merged
Conversation
Found by dogfooding. A partial sale under the AVERAGE booking method silently emptied the whole position and booked a garbage capital gain, and the balance showed every purchase lot separately instead of one pool. Grounded in prior art (hledger SPEC-lots, beancount PR#591, GnuCash, ERP AVCO), which all model AVERAGE as a single running weighted-average pool: - reduce_average returns a single synthetic matched lot of the reduced quantity at the average cost (it was returning every lot, which the consumer expanded into one posting per lot and emptied the position); the remainder keeps the average cost. - New Inventory::merge_average collapses all cost lots of a currency into one weighted-average lot. - The query realizes an AVERAGE-booked account as a single pool: AccountInfo carries the booking method, and sum(position) over a single AVERAGE account merges the lots. The journal keeps the real per-lot costs; only the balance merges (hledger model). FIFO/LIFO/STRICT are unaffected. Verified against a weighted-average-cost reference oracle (partial-sale, sell-all, interleaved); pool and gains are exact. Gains were already correct to full decimal precision; balance assertions are quantity-only, so there is no rolling-state interaction. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…age pool Records the decision and prior-art survey (hledger SPEC-lots, beancount PR#591, GnuCash, ERP AVCO) behind the AVERAGE booking fix: one running weighted-average pool realized at the balance, journal keeps real per-lot costs. Notes why the two usual AVERAGE pitfalls (rolling-state balance assertions, decimal precision) do not apply to rustledger. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs main branch (2026-06-19)
What do these numbers mean?
|
Contributor
There was a problem hiding this comment.
Pull request overview
This PR fixes AVERAGE booking semantics to behave as a single running weighted-average-cost pool (instead of multiple per-lot reductions that could incorrectly drain the entire position), and updates query aggregation to realize AVERAGE-booked account balances as one merged pool while preserving per-lot journal costs.
Changes:
- Fix
Inventory::reduce_averageto return a single synthetic matched lot at the weighted-average cost and keep the remainder at the same average cost. - Add
Inventory::merge_averageand apply it in BQLSUM(position)when the group corresponds to a single AVERAGE-booked account. - Add ADR-0007 plus regression/unit/integration tests covering the corrected AVERAGE behavior.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| docs/reference/adr/index.md | Adds ADR-0007 to the ADR index. |
| docs/reference/adr/0007-average-booking-realization.md | Documents the chosen AVERAGE (WAC) semantics and rationale. |
| crates/rustledger-core/src/inventory/booking.rs | Fixes AVERAGE reduction behavior and adds merge_average + tests. |
| crates/rustledger-query/src/executor/types.rs | Extends AccountInfo to include booking method for query-time realization decisions. |
| crates/rustledger-query/src/executor/mod.rs | Populates cached booking method from Open directives. |
| crates/rustledger-query/src/executor/aggregation.rs | Merges lots during SUM(position) for single-account AVERAGE groups via merge_average. |
| crates/rustledger-query/tests/bql_integration_test.rs | Adds integration coverage ensuring AVERAGE merges to one pool while FIFO keeps lots separate. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Copilot review on #1444: the synthetic matched lot used `reduction` (always positive); it must carry the inventory sign like the FIFO/ordered path so that covering a short pool yields a negative matched lot. Use `reduction * total_units.signum()`. Adds a short-cover sign test and pins the long-case sign. Co-Authored-By: Claude Opus 4.8 <[email protected]>
This was referenced Jul 1, 2026
robcohen
added a commit
that referenced
this pull request
Jul 1, 2026
…tory; add booking property tests (#1677) Property-based tests for the silent-corruption class (the #1444 AVERAGE pool wipe and #1666 phantom-lot signature): randomized buy/sell sequences assert units conservation, aggregate==sum-of-lots, no minted lot identity, no phantom negatives, and failed-reduce-does-not-mutate, across STRICT/FIFO/LIFO/AVERAGE; plus an engine-level property that a labeled sell nets against its lot. The failed-reduce invariant found a REAL bug on the first run: reduce_ordered (FIFO/LIFO) and reduce_hifo mutate lots during the walk and only check sufficiency afterwards, so an oversell error left the inventory partially drained. The validator reduces against the live LedgerState inventories, so an oversell error corrupted every subsequent balance-assertion check on that account. Fixed by checking sufficiency across the matched lots BEFORE mutating; the error values (requested/available) are unchanged. Co-authored-by: Claude Opus 4.8 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Jul 2, 2026
…s pool VALUE (#1692) AVERAGECorrect.tla computed the average cost with integer division (\div), which made the pool value model-inexact — the behavior replay could only check the units abstraction. The model now tracks the pool value as an exact rational valueNum/valueDen (GCD-normalized, opCount-bounded), with reduction as value' = value * (t - u) / t. Exactness admits an invariant the integer model could not state: ZeroUnitsZeroValue — full liquidation empties the pool EXACTLY. TLC checks all six invariants over 1,354 states. - Corpus regenerated: 3,584 behaviors (was 1,500) covering the exact model's full transition graph. - The replay now asserts pool-value conformance: impl value (28-digit Decimal) vs the model's exact num/den, within a 1e-12 tolerance — ~17 orders above accumulated Decimal rounding and ~7 below the smallest genuine conformance discrepancy at these bounds. Units stay exact. - Generator derive updated for the rational state (add-cost recovered exactly from the numerator delta; denominator invariance asserted). All 3,584 behaviors conform — the #1444 AVERAGE-pool fix is now value- verified exhaustively up to the model bound, not just units-verified. Co-authored-by: Claude Opus 4.8 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Found by dogfooding. A partial sale under the
AVERAGEbooking method silently emptied the whole position and booked a garbage capital gain, and the balance showed every purchase lot separately instead of one pool. Closes #2 (dogfooding tracker).Approach (grounded in prior art)
Beancount doesn't implement AVERAGE, so there's no upstream oracle. I surveyed how weighted-average cost is actually modeled — hledger
SPEC-lots, beancount PR #591, GnuCash, ERPNext/Odoo AVCO, QuickBooks Desktop — and they're unanimous: AVERAGE is a single running weighted-average pool, not separate lots. The design and rationale are recorded in ADR-0007.Changes
Inventory::reduce_averagereturns a single synthetic matched lot of the reduced quantity at the average cost (it was returning every lot, whichbook.rsexpanded into one reduction posting per lot → emptied the position). The remainder keeps the average cost.Inventory::merge_averagecollapses a currency's cost lots into one weighted-average lot.AccountInfocarries the account's booking method, andsum(position)over a single AVERAGE account merges the lots. The journal keeps the real per-lot costs; only the balance merges (hledger's model). FIFO/LIFO/STRICT/HIFO/NONE are unaffected.Verification
Validated against a weighted-average-cost reference oracle:
15 {160}010 {163.33}All exact. FIFO accounts still show separate lots.
Two usual AVERAGE pitfalls were investigated and don't apply here (see ADR):
balanceassertions are quantity-only (no rolling-state issue), and gains compute exactly underrust_decimal.Tests
merge_average(3 unit tests),reduce_average_partial_multi_lot_matches_single_synthetic_lot, and a query integration test (test_average_account_sum_position_merges_to_single_pool— AVERAGE merges, FIFO doesn't). Fullrustledger-core(406+, incl.prop_average_*property tests) andrustledger-query(142 + 380) suites green; clippy clean.This touches the core booking engine, so it warrants the compat-suite + booking scrutiny in CI.
🤖 Generated with Claude Code