Skip to content

fix(booking): keep the number when only the currency is elided - #1921

Merged
robcohen merged 1 commit into
mainfrom
fix/numberonly-units-currency
Aug 2, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/numberonly-units-currency

Conversation

@robcohen

@robcohen robcohen commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

Stacked on #1919 (this branch contains its commits). Auto-merge deliberately not armed until that one lands, so the parent cannot be orphaned the way #1913 was.

What

A posting written as a number with no currency was silently rewritten or silently dropped, and the transaction was accepted however unbalanced it was.

2010-05-28 * "currency omitted by typo"
  Assets:A    120.00
  Assets:B   -999.00 USD
before ✓ No errors found, and Assets:A booked as 999.00 USD
after E3001 does not balance: residual -879.00 USD, Assets:A booked as 120.00 USD

The number the author typed was discarded and replaced by whatever balanced the books. A dropped currency is a one-character typo, so this turned a typo into a fabricated amount that check then blessed.

Why

The number is data, not something to solve for. Only the currency needs reading off the balance.

Such postings were routed through unassigned_missing, which exists for postings that have no number either and are legitimately solved from the residual. Conflating the two is what overwrote the number.

With a cost or price present the units currency is unknowable: a cost or price names its own currency, never the commodity being counted, so 10 {300.00 USD} is ten of something and nothing says what. Those are now refused. Previously they left the posting unfilled and unreported, so validate_transaction_balance took its documented early return, which is only sound when interpolation has already reported the failure. That is the same invariant established in #1911, violated from a different direction.

Matches beancount on every case tested

input beancount rledger after
120.00 + -120.00 USD accepts, fills 120.00 USD same
120.00 + -999.00 USD fills 120.00 USD, reports imbalance same
120.00 @ 1.2 USD CategorizationError refused
10 {300.00 USD} CategorizationError refused

A pre-existing test asserted the old behavior

interpolate_number_only_infers_currency_and_balances pinned a NumberOnly leg with @ 1 USD contributing its raw number to the price currency's residual. Beancount rejects that input outright (Could not resolve units currency). The unit multiplier of 1 is what made it look harmless; at any other price the residual was wrong too, since the arm added the number without applying the multiplier at all.

Rewritten to assert the refusal, with the reasoning recorded in the test.

Verification

  • 995-file corpus sweep under auto_accounts (without it, E1001 masks this whole family and the sweep is vacuous): exactly two files change, both IncompleteInputs.UnitsMissingCurrencyWithCost in its two copies, both ok → ERR, and beancount rejects both with the same diagnosis.
  • Four of the five new or rewritten tests confirmed to fail against the pre-fix logic. The fifth covers the accepted case, where old and new coincidentally agree; saying so rather than claiming all five.
  • Workspace 4433 passed, 0 failed. Clippy clean at the CI pin (1.97.0) with -D warnings; rustdoc -D warnings clean.

Incidental

number_only_currency, extracted in #1919, loses its only caller here and is removed.

Closes #1920


Follow-ups folded in from review

Three findings from Copilot review, all verified and fixed on this stack:

  1. @ 1.20 had its number overwritten. A price with a number but no currency was treated as a bare sigil, so 1.20 was replaced with whatever balanced the books. It now keeps the number and infers only the currency, matching both beancount and rledger's own calculate_residual. (fed3423e1, on fix(booking): answer a bare price sigil instead of ignoring it #1919)
  2. @ USD was invisible to the fallback ladder. price_currency_of reads only complete price amounts, so such a posting offered its units currency. Added declared_price_currency, deliberately wider and documented as such. (fed3423e1, on fix(booking): answer a bare price sigil instead of ignoring it #1919)
  3. Unguarded overflow in the number-only fill. It ran after the blanket unrepresentable gate, so an overflow left a partial residual in a public field while units had already been written. Now checked at the point of use.

Downstream

rustledger/rustfava#270 updates the one snapshot this changes. rustfava's errors.beancount contains the 4.14 fixture, and its snapshot pinned rledger's old rejection of it. Regenerated from the fixed binary and verified against beancount, which produces the same 4.14 USD / 9.86 USD. That PR should land with or after this one.

@robcohen
robcohen requested a review from a team as a code owner August 1, 2026 22:53
Copilot AI review requested due to automatic review settings August 1, 2026 22:53
@codecov

codecov Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.87179% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/interpolate.rs 94.87% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 36.7ms ± 5.5ms 23.9 MB
beancount 880.2ms ± 7.4ms 50.6 MB
Comparison 24x faster 2.1x less

vs main branch (2026-08-01)

Metric main this PR Change
Time 37.2ms 36.7ms -1.3% ✅
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 tightens the booking/interpolation pipeline so that (1) a units number written without a currency is treated as authoritative data (only the currency may be inferred from the balance), and (2) a bare price sigil (@ / @@ with no amount) is treated as an explicit request to compute a price rather than being silently ignored. This directly addresses previously silent acceptance/fabrication cases in rustledger-booking::interpolate, and adds loader-level end-to-end regression tests.

Changes:

  • Treat IncompleteAmount::NumberOnly as “number is known, currency must be inferred from the residual” (and refuse NumberOnly-with-cost/price shapes where the units currency is genuinely unknowable).
  • Track bare @ / @@ annotations as weight-unknowns and solve them from the residual when the price currency can be determined; introduce dedicated interpolation errors for ambiguous/unsolvable/negative inferred prices.
  • Add end-to-end loader tests covering bare-price solving (#1915) and “currency omitted by typo” imbalance reporting (#1920).

Reviewed changes

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

File Description
crates/rustledger-booking/src/interpolate.rs Core interpolation logic updates for bare price sigils and number-only units; adds new error variants and extensive unit tests.
crates/rustledger-loader/tests/loader_test.rs Adds end-to-end regression tests for bare @ solving and for preserving number-only units while reporting imbalance.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 93%
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
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen added a commit that referenced this pull request Aug 2, 2026
Copilot review catch on #1921.

The number-only fill calls accumulate_residual AFTER the blanket
unrepresentable gate has already run, so an overflow there recorded the
currency and carried on: a partial residual would reach the public
InterpolationResult while units had already been written into the
posting. That contradicts the gates own rationale, which exists so a
solved amount is never derived from a total we could not compute.

Checked at the point of use, matching the guard the price paths already
carry.
Copilot AI review requested due to automatic review settings August 2, 2026 01:12
@robcohen
robcohen force-pushed the fix/numberonly-units-currency branch 2 times, most recently from 276645e to bc5143c Compare August 2, 2026 01:12
robcohen added a commit to rustledger/rustfava that referenced this pull request Aug 2, 2026
rledger used to reject this transaction in tests/data/errors.beancount:

  2018-07-07 * "a" "b"
    Assets:Cash     -14.00 USD
    Expenses:Stuff    4.14
    Expenses:Stuff

reporting "multiple postings missing amounts or with unresolved cost
specs for currency USD (2 unknowns)".

`4.14` is a number with the currency elided. rledger was treating it as a
posting to be SOLVED rather than one that merely needs denominating, so
it counted two unknowns where there is one. It now infers the currency,
keeps the number, and books 4.14 USD and 9.86 USD, which is exactly what
Python beancount does with the same input.

Fixed in rustledger by rustledger/rustledger#1921 (issue beancount#1920). The
other two entries in the snapshot are unchanged.

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

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (4)

crates/rustledger-booking/src/interpolate.rs:1029

  • Similarly, for @ 1.20 (price number written, currency elided), once the price currency is inferred the author-written price_number precision still isn’t reflected in max_scale_by_currency. That can cause later interpolations in that currency group to round too aggressively compared to cases where the price amount was complete and its scale was recorded during the initial scan.
        let Some(currency) = bare_price_currency(transaction, idx, &residuals) else {
            return Err(InterpolationError::AmbiguousBarePriceCurrency {
                account: transaction.postings[idx].account.clone(),
            });
        };

crates/rustledger-booking/src/interpolate.rs:85

  • AmbiguousBarePriceCurrency is now also returned for @ 1.20 (price number written, currency elided) via the price_number_known path, but the doc/error text repeatedly says “bare price” (no amount). That makes the user-facing message misleading for the non-bare case; consider generalizing the wording to cover both shapes (bare sigil and number-only price).
    /// A bare price sigil (`@` / `@@` with no amount) asks for the price to be
    /// computed, but no single currency stands out to compute it in (#1915).
    #[error(
        "cannot tell which currency the bare price on the {account} posting should be \
         computed in; write the price currency (e.g. `@ 1.20 USD`)"
    )]

crates/rustledger-booking/src/interpolate.rs:1011

  • When completing a NumberOnly units amount, the explicit decimal precision of the author-written number isn’t recorded in max_scale_by_currency. If there is also an interpolated (CurrencyOnly) posting in the same inferred currency, round_interpolated may round using a too-small scale (taken only from previously-complete amounts), despite this number now being a complete amount in that currency.

This issue also appears on line 1025 of the same file.

        result.postings[idx].units =
            Some(IncompleteAmount::Complete(Amount::new(number, &currency)));
        filled_indices.push(idx);

crates/rustledger-booking/src/interpolate.rs:1109

  • These comment lines still say “cost-unknown currency”, but the map is now weight_unknowns_by_currency (covers {} cost specs and bare price sigils). Updating the terminology here will avoid misleading future readers.
    // Pick the lexicographically-smallest cost-unknown currency for the
    // error so the message is reproducible across runs.

@robcohen
robcohen enabled auto-merge (squash) August 2, 2026 01:27
A posting written as a number with no currency (`120.00`) was either
silently rewritten or silently dropped, and the transaction was accepted
however unbalanced it was. `rledger check` reported success.

  2010-05-28 * "currency omitted by typo"
    Assets:A    120.00
    Assets:B   -999.00 USD

  before  check: no errors;  Assets:A booked as 999.00 USD
  after   E3001 does not balance: residual -879.00 USD
          Assets:A booked as 120.00 USD

The number the author typed was discarded and replaced by whatever
balanced the books. A dropped currency is a one-character typo, so this
turned a typo into a fabricated amount.

The number is DATA, not something to solve for. Only the currency is read
off the balance now, and the posting no longer routes through
`unassigned_missing`, which exists for postings that have no number
either and are solved from the residual. Conflating the two is what
overwrote the number.

With a cost or price present the units currency is unknowable: a cost or
price names ITS OWN currency, never the commodity being counted, so
`10 {300.00 USD}` is ten of something and nothing says what. Those are
now refused. Previously they left the posting unfilled AND unreported, so
`validate_transaction_balance` took its documented early return (which is
only sound when interpolation has already reported the failure, the
invariant from #1911) and an arbitrarily unbalanced transaction passed
silently. Python beancount refuses the same shapes with "Could not
resolve units currency".

Matches beancount on every case tested: it accepts the bare form and
infers the currency while keeping the number, and rejects both the cost
and price forms.

One pre-existing test asserted the old behavior and has been rewritten.
`interpolate_number_only_infers_currency_and_balances` pinned a
NumberOnly leg with `@ 1 USD` contributing its raw number to the PRICE
currency's residual. Beancount rejects that input outright. The unit
multiplier of 1 is what made it look harmless; at any other price the
residual was wrong too, since the arm added the number without applying
the multiplier.

`number_only_currency`, extracted in #1919, loses its only caller here
and is removed.

Corpus: over 995 files under auto_accounts, exactly two change status,
both `IncompleteInputs.UnitsMissingCurrencyWithCost` (the same vector in
two copies), both ok -> ERR, and beancount rejects both.

Four of the five new or rewritten tests were confirmed to fail against
the pre-fix logic. The fifth covers the accepted case, where old and new
happen to agree.

Closes #1920

Also, from Copilot review: the fill calls accumulate_residual AFTER the
blanket unrepresentable gate has already run, so an overflow there would
record the currency and carry on, letting a partial residual reach the
public InterpolationResult while units had already been written into the
posting. That contradicts the gate's own rationale, so it is checked at
the point of use, matching the guard the price paths carry.
@robcohen
robcohen force-pushed the fix/numberonly-units-currency branch from bc5143c to 8ebfa9e Compare August 2, 2026 01:30
@robcohen
robcohen merged commit 81b2869 into main Aug 2, 2026
60 of 61 checks passed
@robcohen
robcohen deleted the fix/numberonly-units-currency branch August 2, 2026 01:57
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.

A units number with no currency is silently dropped or rewritten, and the transaction is accepted

2 participants