Skip to content

fix(booking): solve an elided units number from the cost or price - #1913

Closed
robcohen wants to merge 2 commits into
mainfrom
fix/interpolate-units-from-cost
Closed

robcohen wants to merge 2 commits into
mainfrom
fix/interpolate-units-from-cost

Conversation

@robcohen

@robcohen robcohen commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

What

A posting whose units number is elided beside a per-unit cost is now solved as residual / cost_per_unit and written in the posting's own commodity. The same inversion covers a per-unit price, which had the identical gap.

2010-05-28 *
  Assets:Account1            HOOL {300.00 USD}
  Assets:Account2    -600.00 USD
Assets:Account1
before nothing booked; E3001 residual -600.00 USD (the whole other leg)
after 2 HOOL {300.00 USD}

Why it was broken

One wrong premise, not a missing feature. A units-missing posting was registered under its units currency, but a posting carrying a cost weighs in the cost currency. It therefore absorbed a residual that was none of its business. That fabricated lots rather than merely failing to fill them, which makes this worse than the issue reported:

input before after
A HOOL {300.00 USD} / B -600.00 USD / D 5.00 HOOL A = -5.00 HOOL — wrong sign and magnitude, taken from D's residual A = +2.00 HOOL
A {300.00 USD} / B -600.00 USD A = 600.00 USD {300.00 USD}, an invented lot whose imbalance was then reported as an invented 179400.0000 USD refused, with a reason

Registering the unknown under the weight currency also fixes the count rule: a cost posting now collides with a plain elided posting in that same currency, exactly as beancount's InterpolationError does.

What is deliberately refused

Only a per-unit factor is inverted. A total cost {{600 USD}}, a total price @@, a zero factor, an empty {} and a compound {a # b} are refused with a reason naming the shape. The first four contribute a weight that does not vary with the units at all, so the input is genuinely ambiguous rather than merely hard; the compound form admits two roots and I would rather refuse than pick one.

These must error rather than be left unfilled. validate_transaction_balance deliberately skips a transaction containing an unfilled posting, on the documented assumption that interpolation already reported the real failure. An early draft of this PR left them unfilled and silently turned four erroring cases green.

Not copied from beancount

beancount crashes on much of this space rather than diagnosing it:

  • TypeError: bad operand type for abs(): 'type' on a total cost, a zero cost
  • AssertionError: Internal error; residual currency different than missing currency on a zero price

So the rule here is derived from the weight algebra in cost_number_weight_generic rather than from beancount's output. Where beancount does produce an answer, this agrees with it.

Verification

  • Value oracle, 560-file comparable corpus: 4 divergences to 3, the one removed being test-cases_IncompleteInputs.UnitsMissingNumberWithCost (beancount=2 rledger=None). No new divergence, identical eligibility (560 compared / 198 skipped on both sides).
  • All 7 new tests confirmed to fail against the pre-fix logic (neutered units_weight to its old behavior, watched them go red, restored). The 120 pre-existing tests stayed green under the neuter, so they pin new behavior without over-constraining the old.
  • solved_units_reproduce_the_canonical_cost_weight is the drift guard: it feeds the solved number back through the canonical cost_number_weight and asserts it cancels the cash leg, so the inverse cannot drift from the forward function.
  • Workspace: 4411 passed, 0 failed. Clippy clean under the CI pin (1.97.0) with -D warnings. cargo fmt clean.
  • Three of the four official IncompleteInputs.*WithCost lima vectors improve; the fourth is unchanged.

Two separate defects found, filed not fixed here

  1. E3002 rejects two elided postings in different currency groups #1914 — E3002 rejects two elided postings in different currency groups. The validator builds a per-currency map and then sums it, discarding the grouping. interpolate itself is correctly per-currency, so the validator shadows it.
  2. A bare price sigil is treated as 'no price' instead of an unknown #1915 — a bare price sigil (100.00 USD @) is treated as "no price" instead of an unresolved unknown. This PR makes it newly visible: IncompleteInputs.UnitsMissingNumberWithPrice went from rejected-for-the-wrong-reason to accepted, because beancount counts that bare @ as a second unknown in the group and we do not. The parse is unchanged by this PR (main reads it the same way); only the solve improved.

Closes #1911

A posting whose units number is elided beside a per-unit cost is solved
as `residual / cost_per_unit` and written in the posting's own commodity.
`HOOL {300.00 USD}` against `-600.00 USD` now books `2 HOOL {300.00 USD}`
where it previously booked nothing and reported the whole other leg as an
imbalance. The same inversion covers a per-unit price, which had the
identical gap.

The root cause was one wrong premise, not a missing feature. A
units-missing posting was registered under its UNITS currency, but a
posting carrying a cost weighs in the COST currency. It therefore
absorbed a residual that was none of its business, which fabricated lots
rather than merely failing to fill them:

  A  HOOL {300.00 USD} / B -600.00 USD / D 5.00 HOOL
    was  A = -5.00 HOOL   (wrong sign AND magnitude, from D's residual)
    now  A = +2.00 HOOL

  A  {300.00 USD} / B -600.00 USD
    was  A = 600.00 USD {300.00 USD}, an invented lot whose imbalance was
         then reported as an invented `179400.0000 USD`
    now  refused: a cost spec names the cost currency, not the commodity

Registering the unknown under the weight currency also fixes the count
rule, which now collides with a plain elided posting in that same
currency exactly as beancount's InterpolationError does.

Only a PER-UNIT factor is inverted. A total cost `{{600 USD}}`, a total
price `@@`, a zero factor, an empty `{}` and a compound `{a # b}` are
refused with a reason naming the shape: the first four contribute a
weight that does not vary with the units at all, and the compound form
admits two roots. These MUST error rather than be left unfilled --
validate_transaction_balance deliberately skips a transaction containing
an unfilled posting, on the documented assumption that interpolation
already reported the failure, so a silent skip accepts an unbalanced
transaction. An early draft did exactly that and turned four erroring
cases green.

Not copied from beancount, which crashes on much of this space rather
than diagnosing it: `TypeError: bad operand type for abs(): 'type'` on a
total or zero cost, and `AssertionError: Internal error; residual
currency different than missing currency` on a zero price. The rule here
is derived from the weight algebra in `cost_number_weight_generic`, and
`solved_units_reproduce_the_canonical_cost_weight` guards the inverse
against that canonical so the two cannot drift.

Value oracle over the 560-file comparable corpus: 4 divergences -> 3,
the one removed being test-cases_IncompleteInputs.UnitsMissingNumberWithCost
(`beancount=2 rledger=None`). No new divergence, same eligibility.
All 7 new tests were confirmed to fail against the pre-fix logic.

Closes #1911
@github-actions

github-actions Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.4ms ± 0.5ms 24 MB
beancount 921.5ms ± 5.5ms 50.7 MB
Comparison 26.8x faster 2.1x less

vs main branch (2026-08-01)

Metric main this PR Change
Time 37.2ms 34.4ms -7.5% 🟢
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 1, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.65734% with 21 lines in your changes missing coverage. Please review.

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

📢 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

Fixes interpolation in rustledger-booking so postings with an elided units number next to a per-unit cost or per-unit price are solved by inverting the posting’s weight (units = -residual / per_unit_factor) and written in the posting’s own commodity, preventing fabricated lots and aligning with beancount’s weight algebra.

Changes:

  • Add InterpolationError::UnsolvableUnits and a UnitsWeight classifier to refuse shapes where the units number cannot be uniquely determined (total cost/price, zero factors, empty {}, compound {a # b}, etc.).
  • Register units-missing postings under their weight currency (cost/price currency) and invert residuals during fill, including correct quantization in the units currency.
  • Add both unit-level tests in rustledger-booking and an end-to-end loader pipeline test for #1911.

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 Implements weight-currency registration + inversion for units-missing postings with per-unit cost/price; adds explicit refusal errors and extensive targeted tests.
crates/rustledger-loader/tests/loader_test.rs Adds an end-to-end regression test covering parse → interpolate → book → validate behavior for the #1911 scenario.

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

Assets:Account1 HOOL {300.00 USD}\n \
Assets:Account2 -600.00 USD\n",
)
.unwrap();
Comment on lines +70 to +74
#[error("cannot interpolate the units number for the {account} posting: {reason}")]
UnsolvableUnits {
/// The account of the posting whose units could not be solved.
account: rustledger_core::Account,
/// Why the balance does not determine the number.
@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 1, 2026
fix(compat): compare balances as money, not as raw Decimals

Re-lands the correction from #1910, which was pushed after that PR had
already auto-merged and so never reached main.

The comparison used raw Decimal equality, which reported two divergences
that were representation differences rather than value disagreements. The
two tools quantize at different layers: beancount rounds when it books,
rledger books what the arithmetic implies and rounds when it displays.

`0.035 SPY @ 137.142857143 USD` against an explicit `4.80` leaves 5e-12.
beancount books 0.00 and loses it; rledger books 0.000000000005, keeps
the postings summing to exactly zero, and renders 0.03 on every surface
that knows the currency. Only `sum(number)` - a deliberately
currency-less projection, which is what this harness asks for - shows the
residue, and there the exact sum is the correct answer. #1909 was closed
as working-as-intended on that basis: rledger preserving the value is the
better behavior, since beancount silently discards a tenth of a cent
someone deliberately typed.

Each side is now quantized to beancount's own exponent before comparing:
beancount has already rounded to the currency's precision at booking, so
its exponent IS the precision at which these figures are money. Stated
cost: a genuine divergence smaller than one display unit is invisible,
which is by definition a difference no user could observe in a balance.

Verified against seven cases that this silences only what it should -
both #1909 representation cases go quiet, while a one-cent error, a sign
flip, a missing posting and a magnitude blowup all still report.

Corpus, with #1913 also applied: 4 divergences -> 1, the survivor being
issue-520.beancount, a tracked regression fixture.
The rustdoc build denies warnings, and  is not
something `cargo test` catches. Describe the private UnitsWeight cases
inline instead of linking to them.
Copilot AI review requested due to automatic review settings August 1, 2026 03:05

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 (2)

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

  • InterpolationError is part of the public API of rustledger-booking (interpolate() returns it). Adding the new UnsolvableUnits variant is a breaking change for downstream crates that exhaustively match on this enum; consider bumping the crate’s minor version accordingly (or planning a future #[non_exhaustive] transition) so the semver signal matches the API change.
    /// A posting's units number is missing and cannot be recovered from the
    /// balance, because the posting's weight does not vary with that number
    /// (#1911). The cases are enumerated on the private `UnitsWeight` classifier
    /// in this module: a total cost or price, a zero factor, an empty `{}` spec,
    /// a compound cost, and a cost with no units currency to write into.
    ///
    /// Reported rather than left unfilled: `validate_transaction_balance` skips
    /// a transaction that still has an unfilled posting, so staying silent here
    /// would accept an unbalanced transaction.
    #[error("cannot interpolate the units number for the {account} posting: {reason}")]
    UnsolvableUnits {
        /// The account of the posting whose units could not be solved.
        account: rustledger_core::Account,
        /// Why the balance does not determine the number.
        reason: &'static str,
    },

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

  • The rustdoc for UnitsWeight mentions an "_ => arm" that fails closed, but the match statements in units_weight() are exhaustive over CostNumber/PriceKind (so new variants will cause a compile error, not a runtime refusal). This comment is misleading and should be updated to reflect the compile-time exhaustiveness guarantee.
/// This mirrors the weight ladder in [`crate::cost_weight`] /
/// [`crate::cost_number_weight_generic`] — inverted. A new `CostNumber` variant
/// must be classified here as well as given a weight there; the `_ =>` arm
/// below fails closed (refuse to solve) rather than guessing a multiplier.

@robcohen

robcohen commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

Superseded, not abandoned: this branch's two commits are already on main.

#1918 was stacked on this branch, so its squash (45cc9b961) carried both changes in together, and this PR is now DIRTY against a main that already has its content. Verified on main:

$ rledger query i1911.beancount "SELECT account, units, cost_number"
Assets:Account1  2 HOOL   300.00
Assets:Account2  -600.00 USD

UnsolvableUnits, scaled_missing and elided_unknown_groups are all present in crates/rustledger-booking/src/interpolate.rs on main.

My mistake in the stacking: I armed auto-merge on both, and the child cleared its checks first while this one was still in mutation testing. Next time the parent should merge before the child is armed.

@robcohen robcohen closed this Aug 1, 2026
auto-merge was automatically disabled August 1, 2026 14:26

Pull request was closed

robcohen added a commit that referenced this pull request Aug 2, 2026
fix(booking): answer a bare price sigil instead of ignoring it

`100.00 USD @` asks for the price to be COMPUTED. rledger read the bare
sigil as "no price" and weighed the posting at its units, so the request
went unanswered and the posting silently stopped competing for the
residual it was supposed to cancel.

  Assets:A    100.00 USD @        was  E3001 does not balance
  Assets:B    -50.00 EUR          now  @ 0.50 EUR, balanced

`@` weighs `units x price` and `@@` weighs `total x signum(units)`, so
each is inverted accordingly. A `@@` is answered with a TOTAL and stays a
`@@`; beancount normalizes it to a per-unit rate, but the weight is
identical and keeping the author's form is the ADR-0008 position.

NOT what beancount computes. It solves the MAGNITUDE, |residual|/|units|,
which balances only when the other side happens to be opposite-signed. On
the `IncompleteInputs.PriceMissing` vector - `100.00 USD @` against a
POSITIVE `120.00 CAD` - it fills `@1.2 CAD`, giving two +120.00 CAD
weights, and then reports the 240 CAD imbalance it just created. The
value that balances is -1.2, and a negative price is not a price, so the
honest answer is to refuse and say which number the balance was asking
for. That mirrors the existing NegativeInferredCost rule for `{}` specs.

The sigil is also an unknown for the one-per-currency-group rule, which
is what #1915 was filed for. Its group is resolved from the residual it
has to cancel, falling back to the other postings' WEIGHT currencies when
nothing is known yet - not their units currencies, since a price
redenominates the weight. An earlier draft used units currencies and put
`? CAD @ 1.2 USD` in CAD, which split the two unknowns into separate
groups and hid a real ambiguity.

Alongside a cost the sigil is inert and stays untouched: cost beats
price, so it feeds implicit price directives and never the balance.

`cost_unknowns_by_currency` is renamed `weight_unknowns_by_currency`,
which is what it has always counted and now visibly holds two shapes.

Sweep of 995 corpus files under auto_accounts (without it, E1001 masks
the whole IncompleteInputs family): exactly two change status, both
ok -> ERR, and beancount rejects both -
UnitsMissingCurrencyWithPrice (CategorizationError) and
UnitsMissingNumberWithPrice (InterpolationError). The latter is the
regression #1913 introduced and #1915 recorded, so this closes it.

All eleven hand-built shapes now match beancount's accept/reject. Six of
the seven new tests were confirmed to fail against the pre-fix logic; the
seventh guards against over-reach on the cost path, which the neuters do
not exercise.

Closes #1915
@robcohen
robcohen deleted the fix/interpolate-units-from-cost branch August 10, 2026 00:42
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.

cannot interpolate a missing units number when a cost is present

2 participants