Skip to content

fix(booking): AVERAGE realizes a single weighted-average pool - #1444

Merged
robcohen merged 3 commits into
mainfrom
fix/average-booking
Jun 20, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/average-booking

Conversation

@robcohen

Copy link
Copy Markdown
Member

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. 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_average returns a single synthetic matched lot of the reduced quantity at the average cost (it was returning every lot, which book.rs expanded into one reduction posting per lot → emptied the position). The remainder keeps the average cost.
  • New Inventory::merge_average collapses a currency's cost lots into one weighted-average lot.
  • The query realizes an AVERAGE account as one pool: AccountInfo carries the account's 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's model). FIFO/LIFO/STRICT/HIFO/NONE are unaffected.

Verification

Validated against a weighted-average-cost reference oracle:

Scenario Pool Gain
partial sell (10@150, 10@170, sell 5) 15 {160} −200
sell-all 0 −800
interleaved buy/sell/buy/sell 10 {163.33} −258.33

All exact. FIFO accounts still show separate lots.

Two usual AVERAGE pitfalls were investigated and don't apply here (see ADR): balance assertions are quantity-only (no rolling-state issue), and gains compute exactly under rust_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). Full rustledger-core (406+, incl. prop_average_* property tests) and rustledger-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

robcohen and others added 2 commits June 20, 2026 00:13
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]>
@robcohen
robcohen requested a review from a team as a code owner June 20, 2026 00:19
Copilot AI review requested due to automatic review settings June 20, 2026 00:19
@codecov

codecov Bot commented Jun 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.90210% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/booking.rs 98.31% 2 Missing ⚠️
crates/rustledger-query/src/executor/mod.rs 83.33% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 37.6ms ± 0.9ms 24.8 MB
beancount 798.2ms ± 2.3ms 50.7 MB
Comparison 21.2x faster 2.0x less

vs main branch (2026-06-19)

Metric main this PR Change
Time 34.2ms 37.6ms +9.9% 🟡
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

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 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_average to return a single synthetic matched lot at the weighted-average cost and keep the remainder at the same average cost.
  • Add Inventory::merge_average and apply it in BQL SUM(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.

@github-actions

github-actions Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

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

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]>
@robcohen
robcohen merged commit f906dfb into main Jun 20, 2026
51 checks passed
@robcohen
robcohen deleted the fix/average-booking branch June 20, 2026 02:19
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]>
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