Skip to content

fix(booking): read an AVERAGE sale's pool-average cost as a reduction beside a same-cost short - #2970

Merged
robcohen merged 5 commits into
mainfrom
fix/average-booking-apply-2958
Nov 13, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/average-booking-apply-2958

Conversation

@robcohen

@robcohen robcohen commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

What was wrong

The committed CI seed (cc 43c8647...) reproduces on main, but its shrunk failure is not the one the issue describes. apply, the replay and the validator all agree with booking when they read the recorded decision. The assertion that fails is property 2 in booking_record_tests: with the recorded decision forgotten, the consumers ask Inventory::is_booking_reduction again and get a different answer. The issue's three-leg case passes on its own. It only fails as the first of three transactions:

AVERAGE, seeds 4 @100 and 2 @100
T1: -1 {}, -4 {}, +2 {100}
T2: +5 {102}, +5 {100}, -3 {}, -1 {101}   -> a short of 1 @101 beside longs 5 @100, 5 @102 (average 101)
T3: -1 {}

Booking reads T3 as a reduction of the longs and books it as -1 X {101 USD}, their average. When that booked posting is asked again, the #2384 own-side exception reads {101 USD} lot by lot. It matches the short and neither long, so the posting is treated as an augmentation and a second short is opened. Booking was right. The re-derivation was wrong, because booking had replaced the cost spec that the rule reads.

The fix

Under AVERAGE, the cost on a reduction (a sale or a cover) is a claim about the pool's average (#2603), not a filter on individual lots. The own-side exception now also treats the other side as named when that side's pool accepts the cost as a claim. The cost must have no date or label, and the pool must be held in the claim's cost currency.

Canonical-function discipline: the claim rule used to live only in check_average_spec in rustledger-booking. It now lives in rustledger-core as average_claim_mismatch, along with written_allowance, fills_decimal and half_unit_in_last_place, which moved with it. Booking's check_average_spec and Inventory::is_booking_reduction both call it, so the two cannot drift.

Behavior change (AVERAGE only): on an account holding both a long and a short, a sale or a cover written with a cost that the facing pool accepts as its average (e.g. -1 X {101 USD} in the shape above, or +1 X {101 USD} beside shorts at 100 and 102 and a long at 101) now books like {}: it reduces the pool. Before, it opened a new lot on its own side. Two consequences, stated in the ADR: a claim the pool accepts only by rounding now beats a lot at exactly that cost (longs 5@100 and [email protected] beside a short at 101: -1 X {101 USD} sells the longs), and a ledger that loaded can now fail with E4002 (-11 X {101 USD} against 10 longs averaging 101 beside a short at 101 reports "requested 11, available 10" instead of opening a short of 11). Python beancount has no AVERAGE booking (AVERAGE method is not supported), so there is no beancount answer to match. ADR 0007 has a new amendment and compatibility.md section 14 has a short note.

Tests

  • crates/rustledger-validate/proptest-regressions/booking_record_tests.txt: the CI seed, committed.
  • an_average_sale_priced_like_a_short_beside_it_agrees_everywhere_2958: the exact shrunk case under every method, and it checks that the pool ends at 9 long and 1 short.
  • an_average_cover_priced_like_a_long_beside_it_agrees_everywhere_2958: the mirror for a cover, under every method. It checks that +1 X {101 USD} beside shorts at 100 and 102 and a long at 101 leaves 9 short and 1 long (main left 10 short and 2 long).
  • sales_beside_a_short_priced_at_the_pool_average_agree_everywhere_2958: nearby shapes under every method, including several sales then a buy in one transaction, partial, whole and over-reductions, a sale stating the average, a sale stating neither cost, a cover, and a {*} sale. It also checks that a stated average and {} book the same.
  • Core: is_booking_reduction_average_*_2958 covers the pool claim, unchanged FIFO/LIFO/HIFO/STRICT behavior, dated and labeled specs, mixed and foreign cost currencies, and a non-terminating rounded average.
  • The new validate and core tests fail with the fix disabled. The keep-the-exception guard passes either way, as it should.

Gates

  • cargo fmt --all --check
  • cargo clippy --workspace --all-features --all-targets -- -D warnings
  • RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --all-features --no-deps
  • cargo test --all-features for rustledger-core, -booking, -loader, -validate, -wasm
  • every_realization_agrees_with_the_record at PROPTEST_CASES=20000, 3 debug runs and 1 release run, all green

Cache

WASM CACHE_VERSION 105 -> 108, because booked directives change for the shape above. 106 is held by #2931 and 107 by #2969. Loader stays at v73 because parsed directives did not move.

Closes #2958

🤖 Generated with Claude Code

… beside a same-cost short

On an AVERAGE account holding a short at 101 beside longs averaging 101, a
sale `-1 X {}` reduced the longs and booked as `-1 X {101 USD}`. Asked again
of the inventory (any consumer realizing a posting with no recorded booking
decision), the #2384 own-side exception read that cost lot by lot: it matched
the short and neither long, so the booked reduction became a second short.

Under AVERAGE a cost is a claim about the pool, so the exception now also
treats the other side as named when its pool accepts the cost as a claim.
The claim rule moves from rustledger-booking's check_average_spec into
rustledger-core (average_claim_mismatch, with written_allowance and its
helpers), and both booking and Inventory::is_booking_reduction call it.
A written `-1 X {101 USD}` in that shape now books like `-1 X {}`.

Commits the proptest seed and adds regression tests at core and validate
level. WASM cache bumped to 107 (106 is held by #2931); loader cache
unchanged.

Closes #2958

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 13, 2026 00:10
v107 is claimed by #2969; v106 is held by #2931.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 52.3ms ± 2.6ms 842.2ms ± 3.3ms 16.1x 45.0 MB / 51.0 MB
investment 79.2ms ± 1.2ms 3068.7ms ± 76.3ms 38.8x 47.1 MB / 59.1 MB
fifo 78.8ms ± 2.1ms 15322.8ms ± 595.1ms 194.6x 49.1 MB / 59.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 51.9ms ± 0.4ms 52.3ms ± 2.6ms +0.6% ✅ within noise 45.1 MB → 45.0 MB (-0.2%)
investment 80.6ms ± 1.4ms 79.2ms ± 1.2ms -1.8% ✅ within noise 47.0 MB → 47.1 MB (+0.1%)
fifo 77.6ms ± 1.9ms 78.8ms ± 2.1ms +1.5% ✅ within noise 49.1 MB → 49.1 MB (+0.0%)

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

@codecov

codecov Bot commented Nov 13, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.50000% with 9 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/mod.rs 94.47% 9 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

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 826
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

robcohen and others added 3 commits November 12, 2026 20:49
…quences

The AVERAGE pool-claim rule applies to a buy that covers shorts as well as
to a sale. Say "a sale or a cover" in compatibility.md section 14 and the
v108 WASM cache note, and pin the cover with a test: holding a long at 101
beside shorts at 100 and 102, +1 X {101 USD} covers the shorts (1 long,
9 short left), where main opened a second long (2 long, 10 short).

The ADR 0007 amendment now states two consequences: a claim the pool
accepts only by rounding beats a lot at exactly that cost, and a ledger
that loaded can now fail with E4002 on an over-reduction of the pool.

Also update the adds_to_its_own_side doc comment to describe the AVERAGE
pool test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit 8a1d063 into main Nov 13, 2026
70 of 71 checks passed
@robcohen
robcohen deleted the fix/average-booking-apply-2958 branch November 13, 2026 07:46
robcohen added a commit that referenced this pull request Nov 13, 2026
WASM cache: main holds v107 (#2969), #2970 holds 108 and #2971 holds
109, so this PR moves from 106 to 110. The v107 note now says v106 was
held here and never released; loader cache stays 73.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 13, 2026
…2971)

* fix(wasm): report multi-file errors as rledger check and the FFI do

The multi-file WASM surfaces (validateMultiFile, validateWithHost,
parseMultiFile, Ledger, queryMultiFile, queryWithHost) diverged from
rledger check, the FFI and the single-source surfaces three ways:

- A parse error's message was prefixed with its file path, which is
  already in the error's file field (#2961). load_errors_to_errors now
  maps parse errors through the loader's parse_errors_to_ledger_errors
  and places them with the new ledger_error_to_wasm.
- A loader error (validation finding, booking error, include LOAD error)
  had a null end and no hint, because From<LedgerError> cannot locate the
  end and dropped the hint (#2964). From now copies the hint, and
  ledger_error_to_wasm locates the end of source_span with
  SourceMap::locate; every surface holding the load's SourceMap converts
  through it.
- queryMultiFile / queryWithHost refused on a parse error before process,
  so no Ledger existed and no option diagnostic was listed (#2960). They
  now take the parse errors out and process the rest, as Ledger.fromFiles
  does, and list Ledger::query_option_errors beside them.

The parse_error_mapping_parity drift guard now compares every field, the
end included, and adds two tests: validateSource, validateMultiFile and
Ledger.fromFiles place every finding at the same start and end on the
same ledgers, and the multi-file surfaces keep E8001's hint. The
queryMultiFile skip and the prefix stripping in the wasm-pack tests are
gone. WASM cache v109 (v108 is held by #2970).

Closes #2960
Closes #2961
Closes #2964

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(wasm)!: mark the parse-message prefix change breaking, and state hints as they are

- CHANGELOG: the dropped file prefix on multi-file parse error messages
  moves under Breaking (rustfava unaffected; mcp-server formatErrors no
  longer names the file twice), with a Fixed bullet pointing to it.
- CHANGELOG: multi-file hints match rledger check, a LOAD error carries
  none, and validateSource still differs on E2001 (#2972); in a
  parse-error refusal, queryMultiFile/queryWithHost now report other load
  errors as LOAD, where they were code-less parse-phase errors.
- validate_with_filesystem stays pub: pub(crate) in the private api
  module trips clippy::redundant_pub_crate; say so in a comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[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 booking: apply disagrees with the booking engine on sell 1, sell 4, buy 2 in one transaction (proptest)

1 participant