Skip to content

fix(query): realize BALANCES through the booking engine, not a bare add - #1990

Merged
robcohen merged 2 commits into
mainfrom
fix/average-balances
Aug 8, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/average-balances

Conversation

@robcohen

@robcohen robcohen commented Aug 8, 2026

Copy link
Copy Markdown
Member

Closes #1985.

The bug

BQL accumulated per-account balances with Inventory::add — unconditionally,
with no reduction branch at all
. Reports realize through BookingEngine, which
resolves the account's booking method and then reduces against a lot or adds a
new one
.

The two agreed for FIFO/LIFO/HIFO by coincidence: booking has already
resolved a reduction's cost, so its lot key matches an existing lot and add
nets it. Under AVERAGE it doesn't — the reduction is booked at the merged
average
cost, a key belonging to no augmentation — so it survived as a dangling
negative:

query BALANCES   10 AAPL {200.00}   10 AAPL {150.00}   -5 AAPL {175.00}
report balances  15 AAPL {175.00}

…for an account holding 15. SELECT SUM(number) agreed with the report all
along at 15, so the units were right and only the lot-keyed presentation was
wrong.

BQL now calls BookingEngine::apply_posting, newly public because the query
engine needed exactly this decision and was re-deriving a broken half of it. One
realization rather than two that agree by luck — the duplication registry's
realization family, and this was the drift.

Why no differential test could have found this

Python beancount does not implement AVERAGE.
beancount.parser.booking_method.booking_method_AVERAGE raises
AmbiguousMatchError("AVERAGE method is not supported"), with the real
implementation left commented out ("DISABLED - This is the code for AVERAGE,
which is currently disabled"
). Meanwhile Booking.AVERAGE stays in the enum and
is accepted in an open directive — so a ledger declaring it parses and then
books nothing. Run this PR's fixture through beancount and 20 units remain.

So the compat oracle cannot referee this. Correctness rests on the definition
— 10 @ 150 plus 10 @ 200 is 3500 over 20 units, so 175.00 per unit; less 5 leaves
15 at 175.00 — and on the two surfaces agreeing.

That's the general point rather than a footnote: a divergence in a feature the
reference implementation lacks is invisible to differential testing by
construction.
The internal parity guard was the only thing that could have
caught it, which is a decent argument for #1902's whole approach. Documented at
reduce_average, where someone will next be tempted to "match beancount".

Test churn

average_booking_diverges_today was the characterization test added with the
guard in #1986 — it asserted the wrong behavior on purpose so a fix would trip
it. It did. Replaced by average_booking_nets_to_a_single_merged_lot, and
AVERAGE joins the agreeing-methods loop.

Verification

sabotage result
restore the unconditional add 2 tests fail
build the engine without registering account methods (AVERAGE falls back to the default) 2 tests fail

cargo test --workspace — 134 suites, 0 failures. Clippy and fmt clean. The
beancount oracle reports 0 divergences on every axis, and its self-test passes.

Closes #1985.

BQL accumulated per-account balances with `Inventory::add` —
unconditionally, with no reduction branch at all. Reports realize
through `BookingEngine`, which resolves the account's booking method and
then REDUCES against a lot or ADDS a new one.

The two agreed for FIFO/LIFO/HIFO by COINCIDENCE: booking has already
resolved a reduction's cost, so its lot key matches an existing lot and
`add` nets it. Under AVERAGE it does not — the reduction is booked at
the MERGED average cost, a key belonging to no augmentation — so it
survived as a dangling negative and BALANCES reported

  10 AAPL {200.00}   10 AAPL {150.00}   -5 AAPL {175.00}

for an account holding 15. `SELECT SUM(number)` agreed with the report
all along at 15, so the units were right and only the lot-keyed
presentation was wrong.

BQL now calls `BookingEngine::apply_posting`, newly public because the
query engine needed exactly this decision and was re-deriving a broken
half of it. One realization rather than two that agree by luck — the
duplication registry's realization family, and this was the drift.

WHY NO DIFFERENTIAL TEST COULD FIND THIS. Python beancount does not
implement AVERAGE. `booking_method_AVERAGE` raises
`AmbiguousMatchError("AVERAGE method is not supported")` with the real
implementation commented out ("DISABLED - This is the code for
AVERAGE"), while `Booking.AVERAGE` stays in the enum and is accepted in
an `open` directive — so a ledger declaring it parses and books nothing.
Run the fixture through beancount and 20 units remain.

So the compat oracle cannot referee this. Correctness rests on the
definition — 10 @ 150 plus 10 @ 200 is 3500 over 20 units, 175.00 per
unit, less 5 leaves 15 at 175.00 — and on the two surfaces agreeing.
That is the general point, not a footnote: a divergence in a feature the
reference implementation lacks is invisible to differential testing BY
CONSTRUCTION, and the internal parity guard was the only thing that
could have caught it. Documented at `reduce_average`, which is where
someone will next be tempted to "match beancount".

`average_booking_diverges_today` was the characterization test added
with the guard in #1986; it asserted the wrong behavior on purpose so a
fix would trip it. It did. Replaced by
`average_booking_nets_to_a_single_merged_lot`, and AVERAGE joins the
agreeing-methods loop.

Sabotage-verified: restoring the unconditional `add`, and building the
engine without registering account methods so AVERAGE falls back to the
default, each fail two tests. 134 suites, 0 failures; the beancount
oracle reports 0 divergences on every axis.
@robcohen
robcohen requested a review from a team as a code owner August 8, 2026 03:50
Copilot AI lite review requested due to automatic review settings August 8, 2026 03:50
@github-actions

github-actions Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 36.7ms ± 1.4ms 24.1 MB
beancount 891.7ms ± 4.9ms 50.7 MB
Comparison 24.3x faster 2.1x less

vs main branch (2026-08-08)

Metric main this PR Change
Time 38.2ms 36.7ms -3.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

@codecov

codecov Bot commented Aug 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

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 a correctness bug in the BQL BALANCES realization for AVERAGE-booked accounts by routing balance accumulation through the same booking-engine logic used by reports, eliminating lot-key drift (e.g., dangling negative lots) caused by naive Inventory::add aggregation.

Changes:

  • Update the query executor to realize per-account balances via rustledger_booking::BookingEngine (calling apply_posting) instead of accumulating with Inventory::add.
  • Expose BookingEngine::apply_posting publicly as the canonical “apply one booked posting” operation needed by the query engine.
  • Update the realization parity guard to include AVERAGE in the agreeing-methods matrix and replace the prior AVERAGE characterization test with a net-to-single-lot assertion.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.

File Description
crates/rustledger-query/src/executor/mod.rs Switch BALANCES/account-balance realization from naive inventory addition to booking-engine application to match report semantics.
crates/rustledger-booking/src/book.rs Make BookingEngine::apply_posting public so non-report consumers (query) can use the canonical per-posting realization.
crates/rustledger/tests/query_report_realization_parity_test.rs Extend and refine guard tests to ensure query/report realization parity includes AVERAGE and pins the expected netting shape.
crates/rustledger-core/src/inventory/booking.rs Document the deliberate divergence/guard rationale around AVERAGE booking semantics and why internal parity tests are required.
Suppressed comments (1)

crates/rustledger/tests/query_report_realization_parity_test.rs:446

  • This comment says AVERAGE is kept separate from the loop above rather than folded into it, but AVERAGE is now included in the loop test too. Consider rewording to reflect that this test is an additional shape assertion (netting to a single merged lot) on top of the parity check.
/// Kept SEPARATE from the loop above rather than folded into it, because the
/// netting is what makes AVERAGE different: it is the only method whose
/// holding collapses to a single lot, and asserting that shape is worth more
/// than one more iteration of a set comparison.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread crates/rustledger-booking/src/book.rs Resolved
@github-actions

github-actions Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 95% (raw 89%, 162 masked)
Full AST Match 100%
Total Files 812
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

…e stale

All four Copilot comments.

1. `apply_posting` carried TWO summary blocks and two `# Errors`
sections: my insertion landed between `try_apply_posting`'s existing doc
and its signature, orphaning the old one onto the new. That old doc was
also stale in its own right — it described the reduction failure as
ignored and detectable via a `debug_assert`, which #1988 removed.

Fixed by deleting the wrapper rather than the duplicate text: the public
`apply_posting` was a one-line call through to a private
`try_apply_posting` with no other caller worth the indirection, so it is
now one function with one doc.

2. `scan_postings` walked the directive stream TWICE — once to register
account booking methods, once to build `directive_iter`. Registration
now reads the vec already built. `register_account_methods` only looks
at `Open` directives, so order is irrelevant and this is the same
registration one pass earlier.

3. `resolved` was computed for every posting even when nothing read it.
Before this PR the per-account accumulation used it, so unconditional
was right; `apply_posting` resolves the position itself, leaving
`needs_balance` as the only consumer. Now gated on that.

4. The method list said "Four methods" with AVERAGE added.

And one the comment led to: the FILE docstring described an architecture
this PR removed. It explained that the two surfaces agree "ONLY because
both consume post-booking directives ... so naive re-aggregation lands
on the same keys" — true for FIFO/LIFO/HIFO, false for AVERAGE, and the
whole reason #1985 existed. A comment asserting an invariant nobody
checks, with a live exception, is the stale-invariant class #1902 names.
Rewritten to say what is true now and to record why the old claim held
for as long as it did.
@robcohen
robcohen force-pushed the fix/average-balances branch from 72d5133 to 29e3a27 Compare August 8, 2026 04:24
@robcohen

robcohen commented Aug 8, 2026

Copy link
Copy Markdown
Member Author

All four fixed in 29e3a27 — and one of them led somewhere more interesting.

1. Duplicated rustdoc. My insertion landed between try_apply_posting's existing doc and its signature, orphaning the old one onto the new. That old doc was also stale in its own right: it described the reduction failure as ignored and detectable via a debug_assert, which #1988 removed. Fixed by deleting the wrapper rather than the duplicate text — the public apply_posting was a one-line call through to a private function with no other caller worth the indirection, so it's now one function with one doc.

2. Two passes over the directive stream. Registration now reads the vec directive_iter already builds. register_account_methods only looks at Open directives, so order is irrelevant and it's the same registration one pass earlier.

3. resolved computed unconditionally. Before this PR the per-account accumulation used it, so unconditional was right; apply_posting resolves the position itself, leaving needs_balance as the only consumer. Now gated on that.

4. "Four methods" with AVERAGE added.


The one that mattered: chasing #4 turned up that the file docstring described an architecture this PR removes. It explained that the two surfaces agree

ONLY because both consume post-booking directives … so naive re-aggregation lands on the same keys

— true for FIFO/LIFO/HIFO, false for AVERAGE, and the whole reason #1985 existed. A comment asserting an invariant nobody checks, with a live exception, is precisely the stale-invariant class #1902 names. It now says what's true and records why the old claim held for as long as it did.

The section header had the same problem in the present tense ("AVERAGE diverges today"), rewritten to note the matrix stays so the next method added is pinned from the start rather than five releases later.

134 suites, 0 failures. Clippy and fmt clean.

@robcohen
robcohen merged commit fde94cb into main Aug 8, 2026
65 of 67 checks passed
@robcohen
robcohen deleted the fix/average-balances branch August 8, 2026 05:00
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.

[Bug]: BQL BALANCES shows unmerged lots and a dangling negative for AVERAGE-booked accounts

2 participants