Repository navigation
fix(booking): refuse a sale priced or paid in another currency than its cost - #2589
Conversation
…ts cost
A reduction priced in another currency than its lot's cost booked a
"gain" in two currencies with no rate between them, and a cost spec
written without a currency (`{}`) matched lots in any cost currency, so
`-1 HOOL {}` beside USD cash sold a EUR lot. Both are refused now, as
beancount 3.2.3 refuses them:
- a reduction whose cost and price currencies differ: "Cost and price
currencies must match";
- a `{}` takes the cost currency of beancount's categorize_by_currency
(its price's, else the other postings' one group, else the account's
one cost currency), resolved with the units currencies in one pass
over the transaction as written, before any lot is matched.
AVERAGE and `{*}` pools are held to the spec's currency too. Three
cases where beancount refuses a well-defined ledger keep main's answer
and are documented as Known Differences 17. WASM cache version 37.
Closes #2571
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
An independent review of the first head found four gaps:
- a `{}` sale no step of the rule resolves (other postings in USD and
EUR, lots in both) still sold by the account's method and booked a
gain in two currencies; it is refused now, as beancount refuses it,
unless every other posting is an auto-posting;
- a sale priced in another currency that is not a reduction (under
NONE, or opening a short) passed the mismatch check;
- the own-commodity rule also applied to purchases, booking
`5 HOOL {}` beside HOOL postings at a cost of 0 USD where main and
beancount book `{1 HOOL}`; it now applies to sales only;
- the inferred-currency message blamed the currency when a lot in that
currency existed and the cost number was wrong.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Review round 2: the check that decides whether a missing lot is the currency's fault read the inventory from before the transaction, so when an earlier posting had already taken the only lot at that cost, the message wrongly suggested writing another currency. It now reads the working inventory, as the reduction-override probe does. Also documents, under Known Differences 17, the older case of an unresolved cost currency on a posting that reduces no lot. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
A sale priced in its cost currency but paid in another still books, as in beancount; the headline said "or paid" (review round 3). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Review rounds (#2571)Rounds 1–3 were run by an independent adversarial reviewer. It read each round's diff plus one part of the PR not yet re-read, and checked probe ledgers against
Fuzzer (beancount 3.2.3), current code: seeds 0–3999 agree 4000/4000 on both ledger kinds, with 0 divergences. The |
|
Decision (robcohen): keep the three documented divergences (compatibility.md Known Differences 17): (1) a purchase priced in another currency books; (2) a 🤖 Generated with Claude Code |
…e-currency-mismatch # Conflicts: # CHANGELOG.md
…unding Resolves the overlap with #2589 in book.rs (prepare keeps both the elided cost currencies and the interpolation tolerances) and takes main's CHANGELOG plus this PR's entries. Wasm cache 37 -> 38 for the booked-output change of #2582. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* perf: linear error rendering and {} sales from many-lot accounts
#2604's 9.8G instructions (1,000 lots, 333 `{}` sales) were 96% error
rendering: the ledger opens its accounts after its transactions, so all
2,666 transactions draw E1001, and miette's text source counts lines from
byte 0 for every snippet, which makes `check` O(errors x file size). The
renderer now indexes line starts once and hands miette a window starting
a few lines before the span, rebased onto the whole file, so output is
byte-identical (pinned field by field against miette's whole-file read).
Two booking terms remained, and LIFO/HIFO had the same ones:
- a `{}` sale taking the account's cost currency (#2589) walked every lot
to find it; CostIndex now counts its slots per cost currency and
`Inventory::sole_cost_currency` answers from the counts, falling back to
the walk for several currencies.
- draining a lot removed it from the ordered index with `Vec::remove`,
shifting every later entry, at the front where every ordered method
consumes; the index is a VecDeque and the entry is found by binary
search.
Callgrind (release, mimalloc, cache off): #2604's ledger 9,754M -> 369M;
FIFO n lots + n/3 sales at 1k/2k/4k 109M/234M/554M -> 98M/191M/379M
(1.9x, 2.0x per doubling); fifo shape 20k -10.3%; investment +0.36%.
Booked output byte-identical across the repo and compat corpus; booking
fuzzer agrees with beancount on seeds 0-1999.
Closes #2604
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* perf(core): answer Inventory::currencies from the per-currency lot counts
Review round 1 of #2604: a `{}` sale whose units name no currency
(`-1 {}`, #2490) resolves it through `Inventory::currencies()`, which
walked every lot, so such sales from a many-lot account were O(lots)
each (1,000 / 2,000 / 4,000 lots: 143M / 378M / 1,146M instructions,
2.65x then 3.03x per doubling; bean-check accepts the ledger).
The units cache already counts each currency's non-empty lots by sign,
and leaves a zero lot out exactly as `currencies()` leaves out an empty
position, so the answer comes from those counts (98M / 191M / 379M).
The walk stays as the fallback for an unbuilt cache and as the
definition a debug assertion checks against.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* test(report): cover multi-line spans and uneven context in the windowed read
Review round 2 of #2604: the equivalence test only used spans of 0-3
bytes and equal context before and after, while a ledger error's span
covers a whole multi-line transaction. It now also uses lengths 9 and
40 and sets the context before and after independently.
It also showed the window's extra line is load-bearing, not the harmless
margin the comment called it: miette computes a span's end as
`(offset + len).saturating_sub(1)`, which clamps for an empty span at
local offset 0, so a window starting at the span's own line read
"\n\n\n"'s empty span at byte 1 differently. The comment now says so,
and the test fails if the extra line is dropped.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* docs(changelog): report the error-rendering timing as CPU time
Review round 3 of #2604: the 112 s figure for the 9,875-error corpus
ledger was wall-clock time measured at a load average of about 43. Its
user time is 19.7 s against 0.17 s, which is the figure that does not
depend on the machine's load.
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]>
#2611) * fix(booking): check a cost written on an AVERAGE sale against the pool An AVERAGE sale books at the pool's average cost, and the cost number in its spec was dropped: with the pool at 11.00 EUR, `-1 X {99.00 EUR}` booked at 11.00 without a word. Under every other method a written cost is a filter, and #2589 already checked the spec's currency. The number is now a claim about the average. It holds within the transaction's tolerance for the cost currency of the pool's exact average (the balance check's tolerance, rounded down, so never looser); a transaction with no tolerance in that currency holds it to the places written, as a `{*}` claim is. A total states the total over the units sold, compared against the pool's exact total, and a compound cost `a + b / units`. A claim the pool is not is the new BookingError::AverageSpecMismatch (E4001), naming the pool's cost. Beancount has no AVERAGE booking, so this is rledger's definition, documented under E4001 and in ADR 0007. WASM cache version 39. Closes #2603 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * fix(booking): hold an AVERAGE sale's stated cost to its written precision robcohen's decision on #2603: a cost written on an AVERAGE sale holds when it is a correct rounding of the pool's exact average at the precision written, half a unit in its last written digit, inclusive, the rule a `{*}` claim follows (#2398). This replaces the transaction-tolerance rule, whose verdict depended on the cash leg (`{106.67 USD}` for 106.666... failed beside cash written `106.667`), which `infer_tolerance_from_cost` widened by the claim's own value, and which gave AVERAGE and `{*}` different rules. A total cost is compared as a total, |T - average x units| <= w(T), not divided by the units first; a compound `{a # b}` states the total `a x units + b` and holds within units x w(a) + w(b), each part being rounded to its own places. Booking no longer needs the transaction's tolerances, so their threading into `book_with` is reverted. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * docs(core): describe AverageSpecMismatch by the decided rule The variant doc still described the transaction-tolerance rule that #2603's decision replaced. Review round 2. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * docs: state the compound-cost allowance in words A code span with a trailing space (`units × `) read badly in E4001 and the CHANGELOG. Review round 3. 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]>
What
A sale whose price or cash is in another currency than its lot's cost no longer books a "gain" in two currencies. Both shapes from the issue are refused, as beancount 3.2.3 refuses them:
A. A sale priced in another currency than its cost.
-2 HOOL {11.00 EUR} @ 14.50 USDis refused with beancount's wording,Cost and price currencies must match: EUR != USD(newBookingError::CostPriceCurrencyMismatch, E4001 in the LSP). This covers a reduction, a short being opened, and a sale under NONE.B. A cost spec written without a currency (
{},{11.00},{2020-01-02}) matched lots in any cost currency. It now takes the currency that beancount'scategorize_by_currencygives it, before any lot is matched:-1 HOOL {}besideAssets:Cash 13.00 USDfrom an account holding only EUR lots now reportsNo matching lot for HOOL in Assets:Stock held at a cost in USD: the cost spec names no currency, so it takes USD from its price, the other postings or the account's lots; ...(newBookingError::NoLotInInferredCostCurrency, E4001). That message is used only when a lot would have matched with any currency; a wrong cost number gets the ordinary "no matching lot". A FIFO sale beside USD cash, from an older EUR lot and a newer USD lot, sells the USD lot, as beancount does. A{}sale that no step resolves (other postings in USD and EUR, lots in both) is refused, as beancount refuses it:cannot infer the cost currency for the {} cost spec: candidates EUR, USD.How
interpolate::resolve_elided_currencies(generalizing fix(booking): infer a currency-less units number from the account balance #2490'sresolve_elided_units_currencies) resolves units and cost currencies in one categorization of the transaction as written, as beancount does. They count each other: a currency-less cash number is an unknown that keeps a{}from taking the cash's group. Resolving the units first would have refused a ledger beancount books (a_currency_less_cash_number_leaves_the_cost_currency_to_the_account).BookingEngine::preparecomputes the cost currencies and hands them tobook.bookfills the spec's currency before the reduction-or-augmentation question, the lot match and the augmentation's fill-in, so all three see the same currency. The publicbookresolves them itself.{*}pool the whole account and ignore the spec's filter, sobookchecks the pool's cost currency against the spec's afterwards. That covers a filled currency, and a written one on AVERAGE (-1 HOOL {USD} @ 13 USDsold a EUR pool). A currency written on a{*}was already checked bycheck_merge_spec. No oracle here: beancount supports neither.The other inventory walks
update_inventories(validate) andreplay_posting(BQL) see only booked postings. Every reduction there names its lot's currency explicitly, and a refused transaction is set aside before either runs.rledger checkreports one BOOK error for each probe ledger.rledger queryrefuses to run on a ledger with an unbooked transaction, as before.Where beancount refuses a well-defined ledger: kept, documented, open for decision
Three cases keep what main booked, because beancount's refusal hits a ledger whose answer is well defined. They are listed as Known Differences 17 in
docs/reference/compatibility.md, cross-referenced at the code sites, and pinned by tests:2 HOOL {11.00 EUR} @ 14.50 USDCost and price currencies must match(a parser error on every posting){}sale whose only other postings are auto-postings, from an account holding lots in two cost currenciesFailed to categorize posting{}sale of X whose only other group is X itself (10 Xmoved in beside-4 X {})No position matchesA purchase in that third shape keeps beancount's answer, a cost in X.
The third came up through two existing tests (
same_transaction_short_test,query_report_realization_parity_test). Step 2 now skips a group that is the posting's own commodity, because no lot of X is held at a cost in X.One beancount quirk is matched rather than corrected. Two
{}sales beside USD cash are two unknowns, so step 2 does not apply and each takes its account's cost currency (EUR). Beancount books that, with a gains posting in both currencies, and so does rledger (two_empty_costs_each_take_their_accounts_cost_currency).Also
report capgainsno longer receives cross-currency disposals from booking, sodocs/commands/report.mdand theCapitalGaindocs now say so. Two booking unit tests pinned the old cross-currency recording. They now pin the refusal, and the fact that a priced{}sale takes only lots in the price currency.decimal_overflow_test::oversized_cost_basis_on_reduction_is_reportedused a B-shaped sale (USD lot, CASHU cash). Its cash is now in USD, so the sale still reaches the reduce path it tests.CACHE_VERSION36 → 37: booking errors change for these ledgers. Loader v38 is unchanged because parsed directives did not move.scripts/compat-booking-fuzz.pyno longer avoids these shapes (see below).How tested
Oracle (beancount 3.2.3,
bean-check+bean-query) on 18 probe ledgers covering A (@and@@), B ({},{} @,{11.00},{date}), the controls, step 1 choosing between lots in two currencies, the currency-less cash number, two{}sales, and the three divergences above. Every case matches beancount except those three.New tests in
crates/rustledger-booking/tests/cost_currency_2571.rs(17), each cross-checked against the oracle where beancount supports the method. Fail without the fix: with the fill and the mismatch check disabled, 6 of the first 11 fail (A, B under every method,{*}, price,{11.00}, lot selection). Disabling only the AVERAGE/{*}pool check fails the AVERAGE and{*}cases. Computing cost currencies after the units are resolved failsa_currency_less_cash_number_.... Limiting the pool check to filled currencies failsan_average_pool_in_another_cost_currency_than_written_.... Without the own-commodity rule,the_commoditys_own_postings_...fails. The four review-round tests (an_unresolved_empty_cost_beside_written_postings_is_refused,a_non_reducing_sale_priced_in_another_currency_is_refused,an_augmentation_beside_its_own_commodity_keeps_beancounts_cost_currency,a_wrong_cost_number_is_an_ordinary_no_match) all fail on the first head. The remaining pins (augmentation, unresolved{}, two{}, control) pass on main by design: they pin behavior that did not change.Booking fuzzer.
--self-testpasses, and now also fails if anyCURRENCY_CASESentry goes ungenerated. The generator varies a reduction's price currency, its cash currency, and accounts holding lots in two cost currencies, and tallies each case. All runs used copied, named binaries against beancount 3.2.3.Current head, seeds 0–3999: 4000/4000 lot-selection and 4000/4000 number-only ledgers agree, with 0 divergences.
Self-check: a broken build is reported. With the cost-currency fill and the mismatch check disabled, seeds 0–499 give 8 number-only divergences, all
cost-reduceand all in the new currency cases (5 price-other, 4 cash-other, 2 mixed; a ledger can count in more than one). Lot-selection ledgers stay 500/500.Suites:
cargo testfor rustledger-booking, -core, -validate, -loader, -lsp, -wasm, -query and rustledger (3701 passed on the first head, and 3069 across booking, validate, loader, lsp, wasm, query and rustledger on the second. Under this machine's load (30+) the only failures were the Python plugin time-budget tests, which are timing-sensitive and passed on the other runs). Workspaceclippy --all-features --all-targets -D warningsandcargo doc -D warningsfor booking, lsp and wasm pass. Release-config clippy (--no-default-features --features mimalloc,ag-rledger) reports only an unusedwasm_plugins_dirintests/cli_commands_test.rs. This PR does not touch that file, and the warning comes from the feature set, not from this change.Closes #2571
🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr