Repository navigation
fix(booking): infer a currency-less units number from the account balance - #2490
Conversation
…ance
A posting written as a number with no currency (`Assets:Foo 42.50`)
beside an auto-posting was refused with "cannot infer currency" even
when the account held only USD. Python beancount accepts it.
The currency now follows beancount's categorize_by_currency rule:
the one currency group of the other postings when this is the only
undetermined posting and it has no cost or price; else the single
currency the account held before the transaction; else refused. The
booking engine resolves it before booking, so a cost-bearing reduction
like `-5 {300 USD}` finds its lots too.
The residual is no longer a source. Reading the currency off the one
currency left out of balance accepted shapes beancount refuses.
Closes #2465
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
📊 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?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Review of #2490. Tolerances were inferred from the resolved copy, so a posting written `42.5` loosened its resolved currency's tolerance to 0.05 and an auto-posting beside it was quantized to `-32.400 USD` where beancount books `-32.377 USD`. Beancount infers tolerances from the postings as written, where that currency is still MISSING. Both engine entry points now compute them from the original transaction. Also bump the wasm CACHE_VERSION to 33: `ParsedLedger` and `Ledger` blobs archive booked directives and their errors, which this PR changes. The loader cache archives parsed directives only and is unchanged. Document the LSP inlay-hint divergence (no running balances) at both sites. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Adversarial review passHead is now 1. "Before" column now measuredI built
Row 22 makes a second acceptance-to-refusal change, next to row 13. In both, the old residual rule picked a currency that happened to close the residual exactly, so the old answer was plausible. Beancount refuses both, and so does this PR. Maintainer decision: whether to keep the residual rule as a last-resort step after beancount's. That would be a documented lenient divergence (rledger accepting ledgers beancount rejects). The PR currently does not keep it. 2. Cases outside the first matrix (rows 25–37), each checked against beancount 3.2.3Covered: the same account twice, several currency-less postings, an account holding different currencies, a held currency that differs from the cost currency, An automated diff of booked number and currency per posting across all 24 accepted files shows rledger and beancount identical. The diff was shown to report differences first, through a broken invocation. Bug found and fixed (row 26): tolerances were inferred from the resolved copy. So
Known gap, not fixed: under 3. Other callers of booking and interpolation
4. CACHE_VERSIONMy first claim of "no bump needed" was wrong.
Verification at the new head
Second review pass (head
|
| Shape | base Ir | head Ir | Change |
|---|---|---|---|
| simple | 354.66M | 355.62M | +0.27% |
| investment | 533.89M | 534.88M | +0.19% |
| fifo | 548.19M | 549.05M | +0.16% |
That is roughly 100 instructions per transaction, well under the 1–2% bar, so I left it as is. The bot's "+9% on simple" (PR side ±6.3 ms) was noise.
Docs. Nothing in docs/ described the old residual rule or the "cannot infer currency" error, so there was nothing false to correct. Added a BOOK: Cannot Infer Currency entry to docs/reference/errors.md with the rule, what does not count (open currencies, pads, the residual), and an example. I checked the example against beancount, which also refuses it. Added a short pointer in docs/reference/syntax.md under Transaction. No {{ in either file.
Code quality. The two engine entry points each computed tolerances and resolved currencies separately. That is now one prepare helper, so the order (tolerances from the transaction as written, then resolution) cannot drift between them. No behavior change: all booking and loader tests pass (538). Nothing is left over from the A units number with no currency is silently dropped or rewritten, and the transaction is accepted #1920 residual rule; the free-function path calls the new resolver. The error message is unchanged ("cannot infer currency for posting to account X", which names the account) so that anything matching on it keeps working.
CHANGELOG brought up to date: two shapes now refused (rows 13 and 22, with the corpus note), both tolerance fixes, and the wasm cache bump 32 → 33 (older blobs are refused, and the host re-parses).
Fourth review pass (head bcc1cedd02, main merged in)
- Merged origin/main (fix(query): order BALANCES rows by account_sortkey #2492 BALANCES ordering, docs(query): resolve the private intra-doc links in rustledger-query #2494 query docs). The only conflict was the CHANGELOG, where both entries are kept. Booking 281, loader 257, lsp 346 and wasm 154 tests pass on the merged tree.
- Interactions with what merged since.
- BQL (
BALANCES, replay, summarize) only realizes already-booked postings throughreplay_transaction, which never interpolates, so this PR doesn't touch it. - No booking path runs plugins, so the feat(plugin): let the host set the WASM plugin and importer time budget #2485 time budget is unrelated.
- BQL (
- wasm
CACHE_VERSIONcollision check. I read the diffs of all ten other open PRs. None touchesrustledger-wasm/src/cache.rsor the booking crate. fix(wasm): inventory query cells carry each position's cost #2491 changes query-cell types, which the cache payloads do not store. v33 stays this PR's alone. - Second engine consumer (finding). LSP diagnostics build their own running balances, so the balance step now matters there too. They book in
booking_sort_keyorder, the same ascheck, and get the same answer. This is now pinned bycurrency_less_posting_books_from_the_balance_as_check_does, which uses the issue's ledger with the funding transaction placed after the spend in file order. The test fails without the fix. - Error-message wording. The reference entry now quotes the exact message. The LSP labels this failure
E3001where the CLI saysBOOK. That mapping already existed and is not introduced here; proposed as a separate follow-up. - Decision A is recorded: the PR body says "Decided: no residual fallback (option A, robcohen)", and nothing in it still reads as pending.
Fifth review pass (head 8e907e09fc, main merged in again)
Nothing new found. No code changes in this pass, only the merge.
-
Merged origin/main (fix(importer): resolve equal-length mappings deterministically in file order #2497, chore(baselines): add the four corpus files upstream added (#2473) #2487, fix(lsp): skip WASM and Python plugins in every build, as E8006 says #2496, docs(migration): same-day lot pooling agrees with beancount since #2118 #2488). The only conflict was the CHANGELOG, where both entries are kept;
diagnostics.rsmerged cleanly with fix(lsp): skip WASM and Python plugins in every build, as E8006 says #2496. On the merged tree all tests pass (booking 281, loader 258, lsp 347, wasm 154) and workspace clippy with-D warningsis clean. -
Every place that books or interpolates. I searched the workspace, including benches, fuzz targets and the wasm/ffi crates, for
book_interpolate_apply,book_and_interpolate*,interpolate*(,BookingEngine::*,replay_transactionandbegin_replay. These are the only production consumers:Consumer Path New rule? Pinned loader run_booking(CLI, wasmload_and_book, ffi)book_interpolate_applyyes, full rule loader e2e tests LSP diagnostics book_and_interpolate+apply, sorted bybooking_sort_keyyes, full rule pass-4 LSP test LSP inlay hints free interpolatestep 1 only; can show no hint, never a different one documented at both sites BQL default FROM / summarize / reportreplay_transaction/applyon booked postingsn/a (never interpolates) — booking fuzzer book_and_interpolateyes, but it never generates currency-less units follow-up already proposed pipeline_benchfree interpolatestep 1 only; bench, no assertions — wasm and ffi themselves only call
merge_with_padding/process_pads, after booking. Every consumer whose behavior changed is already pinned. -
LSP
E3001vs CLIBOOKlabel.booking_error_codemaps every interpolation failure except overflow toE3001by design; this PR adds no variant and does not touch the mapping. The PR makes the mismatch less visible, not more: number-only postings that used to fail now resolve, and only the two refused shapes (rows 13 and 22) produce this message where they used to book. This is left as a separate follow-up rather than done here.
…m_cost Second review of #2490. Beancount's infer_tolerances reads `units.number` whatever the currency, so under `infer_tolerance_from_cost` a posting written `-5.5 {10 USD}` widens USD's tolerance by 0.05 x 10, exactly as `-5.5 HOOL {10 USD}` does. transaction_tolerances only read complete amounts, so the auto-posting beside it stayed `44.75` where beancount, and rledger with the commodity written, book `45`. Its units tolerance still lands under the unknown currency and is still skipped. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…ed currency Third review of #2490. Both engine entry points computed tolerances and resolved currency-less units numbers separately. That is now one `prepare` helper, so the order (tolerances from the transaction as written, then resolution) cannot drift between them. No behavior change. Document the rule in the error reference (a new "BOOK: Cannot Infer Currency" entry) and the syntax reference. Bring the CHANGELOG entry up to date with the review passes: two shapes now refused, the tolerance fixes, and the wasm cache bump. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…ency-from-balance # Conflicts: # CHANGELOG.md
Fourth review of #2490. The LSP builds its own running balances to book diagnostics, so the balance-based currency inference has a second consumer. Pin it with the issue's ledger, written with the funding transaction after the spend in file order, so the test also needs the booking-order sort. Quote the reported message in the error reference. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…ency-from-balance # Conflicts: # CHANGELOG.md
…ency-from-balance # Conflicts: # CHANGELOG.md
) The booking fuzzer never generated a posting written as a number with no currency, so the categorize_by_currency rule #2490 ported had no differential coverage. Every seed now also books a second ledger, drawn from its own RNG so the lot-selection ledgers are unchanged, with number-only postings in seven shapes against accounts holding one currency, several, none, or one since emptied. The report tallies agreement per shape and per holding, with both-booked and both-refused counts, and the self-test fails if a shape or holding stops appearing. Seeds 0-1999 agree against main. Three deliberately broken builds of the rule each produce divergences. Closes #2513 Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
…unts 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
* 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]>
What changed
A posting written as a number with no currency (
Assets:Foo 42.50) now gets its currency the way Python beancount 3.2.3 gives it, ported frombeancount.parser.booking_full.categorize_by_currency:cannot infer currency for posting to account …).rustledger-booking/src/interpolate.rs: newresolve_elided_units_currencies(txn, held), the one implementation of the rule. The freeinterpolatefunction calls it with no balances, so only step 1 applies there. That replaces the A units number with no currency is silently dropped or rewritten, and the transaction is accepted #1920 rule, which read the currency off the single non-zero residual.rustledger-booking/src/book.rs:book_interpolate_applyandbook_and_interpolate_with_gainsresolve against the engine's running inventories before booking, because a cost-bearing reduction (-5 {300 USD}) needs the commodity to find its lot. This runs on a copy, and the caller's transaction is changed only if everything succeeds. It costs nothing when the transaction has no such posting. The loader, LSP diagnostics and wasm all go through these entry points.Why
The ledger in #2465 is refused today and Python beancount accepts it. Step 2 also resolves
-5 {300 USD}/-10 @ 1.2 USDout of a single-commodity account. Before this change #1920 refused those, and beancount accepts them.Two shapes that used to be accepted are now refused, the same as in beancount, because the old rule read the currency off the one currency left out of balance: row 13 (other postings in USD and EUR,
5.00booked as EUR) and row 22 (1500.00booked as USD beside an unresolved{}). In both the number happened to close the residual exactly, so the old answer was plausible; it is still a guess beancount refuses to make, and keeping it would accept ledgers beancount rejects. Keeping the residual as a fallback was considered and declined; see "Decided" below. The #1920 guarantees hold: the author's number is kept, and an imbalance is still reported (E3001).Beancount behavior matrix (bean-check + bean-query, beancount 3.2.3)
The "before" column was MEASURED with a build of the base commit (
184e9d1f1d), not inferred. All 37 rows give beancount's result in rledger after this change.-42.50 USD, no historyopen Assets:Qux USD, empty balance-5 {300 USD}, account holds only HOOL-10 @ 1.2 USD, account holds only EURpad(pads expand after booking)10 {300 USD}, empty account-5 {300 USD}, account holds HOOL and AAPL-2into an account holding HOOL at cost{} @ 310 USDwith two auto-postings-5 HOOL {}) disables step 1, empty account42.5resolves to USD beside-42.46 USD(validation tolerance)42.5+-10.123 USD+ auto (interpolation tolerance)5 EURthen42.50, account holds USD5 {300 EUR}into an account holding HOOL {USD}-5 {}out of an account holding HOOL-10 @ 1.2(price currency elided too), account holds EUR3in the same account (group USD)42.50/-42.50, same account-10 EUR @ 4.25 USD), account holds CADNo deliberate divergence. One scope note: when beancount resolves the units currency but cannot resolve a
{}cost currency on the same posting, it refuses. Here the cost currency is still left to rledger's existing cost-currency inference, which this PR does not touch.Decided: no residual fallback (option A, robcohen)
The rule this PR replaces (#1920) read a currency-less posting's currency off the one currency left out of balance. Beancount never does that, and it is not kept. Measured against the base build, exactly two matrix shapes depended on it, and both are now refused, as in beancount:
100 USD/-100 USD/-5 EUR/5.00, empty account5.00 EUR-5 HOOL {}/1500.00/-10 USD/10 USD, empty account1500.00 USDA ledger rledger accepts therefore also loads in beancount and fava. The corpus sweep (1067 files: every
.beancountin the repo plus the 740-file compat corpus) found no file that goes from accepted to refused. Keeping the residual as a last resort was considered and declined: it would be a lenient divergence resting on circumstantial evidence, since nothing the author wrote names the currency.Second review pass
infer_tolerance_from_costgap closed (third commit). Beancount'sinfer_tolerancesreadsunits.numberwhatever the currency. So under the option,-5.5 {10 USD}widens USD's tolerance by0.05 x 10, exactly as-5.5 HOOL {10 USD}does. Before this commit,transaction_tolerancesonly read complete amounts, so the auto-posting stayed44.75. Beancount, and rledger withHOOLwritten, book45. The posting's own units tolerance still lands under the MISSING currency and is still skipped. Testinfer_tolerance_from_cost_counts_the_currency_less_postingfails without the commit.Corpus sweep, base vs head, 1067 files. Two diffs compared
rledger check -f jsoncodes and messages, and bookedunits/costper posting (90,264 rows). Each harness was first shown to report differences on the matrix (19 and 18 files changed). Booked postings: 0 changes. Check outcomes: 3 files changed, and no file changed between accepted and refused:tests/fixtures/python-plugins/with_plugins.beancount: the E8002 backtrace text varies run to run on the base build alone, so this is noise.parser-lima/examples_data_error-includes.beancount: a parse-recovered-25.00 oops NZDposting now resolves to NZD from the balance, so one BOOK error disappears. The file is still refused for its parse errors (P0012) and its missing include.double-entry-generator/example_oklink_example-oklink-output.beancount: 16 parse-recovered postings (beancount:Invalid token) now resolve from balances, so 16 BOOK errors become 16 E3001 imbalances. The error count is the same (9875), and the file is refused by both tools.Tolerance refactor is a no-op for every other transaction.
transaction_tolerancesis now computed once from the transaction as passed in. When there is no currency-less posting,resolve_elided_units_currenciesreturnsNoneand does not touch the transaction, so it is the same input both versions read. Theinfer_tolerance_from_costchange only readsNumberOnly, whichPosting::amount()(Complete only) never returned. Empirically, the 0-row booked diff above covers every corpus file.Booking methods. I ran the 12 cost/price matrix rows (9, 10, 16, 17, 19, 22, 23, 29, 30, 31, 33, 34) under FIFO, LIFO, HIFO, AVERAGE, STRICT and NONE, each set both via
option "booking_method"and per account onopen: 144 files, compared on accept/refuse and booked postings against beancount. 134 identical. The 10 that differ are all AVERAGE, which beancount 3 rejects outright ("AVERAGE method is not supported"). rledger accepts them, and accepts them the same way with the commodity written (checked on the base build too). That is rledger's existing AVERAGE support, which beancount 3 lacks, not this PR.Performance (third pass): cachegrind instruction counts, release builds of base and head: +0.27%
simple, +0.19%investment, +0.16%fifo(about 100 instructions per transaction). Wall time was not readable at load average 16–22.Docs: new
BOOK: Cannot Infer Currencyentry indocs/reference/errors.md, and a pointer to it indocs/reference/syntax.md.Merged with main (fix(query): order BALANCES rows by account_sortkey #2492, docs(query): resolve the private intra-doc links in rustledger-query #2494 at
d56f740085; fix(importer): resolve equal-length mappings deterministically in file order #2497, chore(baselines): add the four corpus files upstream added (#2473) #2487, fix(lsp): skip WASM and Python plugins in every build, as E8006 says #2496, docs(migration): same-day lot pooling agrees with beancount since #2118 #2488 at8e907e09fc). Booking 281, loader 258, lsp 347 (including a new diagnostics test pinning the editor tocheckon the issue ledger), wasm 154: all pass on the merged tree.How tested
crates/rustledger-booking/tests/elided_units_currency_2465.rs: 18 tests covering the matrix rows, all through both public engine entry points (which must agree). With the first commit's fix reverted, 7 fail; with only the second commit's tolerance fix reverted, the tolerance test fails: every acceptance beancount makes that rledger refused, plus the residual row. The other 8 are refusals and group-rule cases that pin the beancount behavior.interpolate::tests::number_only_does_not_read_the_residual_currency: fails without the fix (the old rule booked EUR).crates/rustledger-loader/tests/elided_units_currency_test.rs: 4 end-to-end tests throughload: the issue ledger verbatim,openconstraint not a source, pad not a balance, and imbalance still reported. 2 fail without the fix.cargo test --all-featureson booking / loader / lsp / wasm at the new head: 280 + 257 + 345 + 154 passed, 0 failed (validate: 154 passed at the first head). Workspace clippy-D warningsandcargo doc -D warningspass.scripts/compat-booking-fuzz.py --self-testpasses.--runs 200 --start-seed 2465: 200/200 agree, 0 unexplained divergences.CACHE_VERSION32 -> 33:ParsedLedger/Ledgerblobs archive BOOKED directives and their errors, which this changes (the first push wrongly said no bump was needed). The loader cache archives parsed directives only, so its version and the pin stay at 37.the_resolved_posting_does_not_set_the_tolerance, fails without the second commit).Closes #2465
🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr