Skip to content

fix(validate): apply the E3002 rule per currency group, not to the total - #1918

Merged
robcohen merged 3 commits into
mainfrom
fix/e3002-per-currency-group
Aug 1, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/e3002-per-currency-group

Conversation

@robcohen

@robcohen robcohen commented Aug 1, 2026

Copy link
Copy Markdown
Member

Stacked on #1913 — review that first; this branch contains its commits. The grouping fix depends on #1911's weight-currency rule.

What

Interpolation solves one unknown per currency group, so two elided postings are only ambiguous when they compete for the same residual. The E3002 validator built a per-currency map and then summed across every group.

2010-05-28 * "two elided postings, different currencies"
  Assets:A                 USD
  Assets:B                 EUR
  Assets:C   -600.00 USD
  Assets:D    -50.00 EUR
before E3002 Transaction has 2 postings with missing amounts; at most one is allowed
after A = 600.00 USD, B = 50.00 EUR

That is what beancount does, and what rledger's own interpolate already computed — the validator was rejecting a transaction the solver would have handled correctly.

The grouping was never actually populated

The currency hint came from .and_then(|u| u.as_amount()), which returns None for exactly the partial-units postings this rule is about. So every unknown landed in the None bucket and the map had at most one meaningful key. The grouping was not merely discarded by the sum; it was never there.

Not re-derived any more

elided_unknown_groups is new in rustledger-booking and is the same grouping interpolate solves by — both go through the same units_weight classifier. Per the Canonical-Function Discipline in CLAUDE.md, the pre-booking diagnostic and the solver now cannot disagree.

This matters more than usual since #1911: a per-unit cost redenominates the weight, so HOOL {300.00 USD} is an unknown in USD, not in HOOL. Nothing about the posting's units reveals that, which is precisely why a hand-rolled grouping in the validator drifts.

What stays strict

A fully-elided posting (Assets:Cash, no amount at all) has no currency of its own, so it can absorb any residual — including one another unknown is claiming. beancount refuses that combination outright (CategorizationError) and so do we. One bare posting alone is still fine, including when it splits across several currencies.

Verification

Checked against beancount on nine shapes — both elided kinds, bare postings, cost-carrying postings, same-group and disjoint-group pairs:

beancount before after
two elided, different ccy ok E3002 ok
cost + elided, disjoint ok E3002 ok
two elided, same ccy error E3002 E3002
two bare (1 or 2 ccy) error E3002 E3002
bare + elided error E3002 E3002
one elided / one bare across 2 ccy ok ok ok

All nine agree now; two disagreed before. Booked values also match beancount, including the multi-currency split where one bare posting becomes two.

  • No corpus movement: across 758 files, not one changes accept/reject status, and the value oracle is unchanged at 3. The shape does not occur there — so the corpus is evidence of no regression, not evidence for the fix. The synthetic cases and unit tests carry that.
  • Both halves confirmed to fail when neutered: restoring the total-count rule fails test_e3002_two_missing_in_different_currencies_ok; grouping by the units currency fails the drift guard elided_groups_agree_with_what_interpolate_solves.
  • Workspace 4416 passed, 0 failed. Clippy clean at the CI pin (1.97.0) with -D warnings. rustdoc -D warnings clean.

Closes #1914

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
The rustdoc build denies warnings, and  is not
something `cargo test` catches. Describe the private UnitsWeight cases
inline instead of linking to them.
Interpolation solves one unknown per currency group, so two elided
postings are only ambiguous when they compete for the SAME residual. The
E3002 validator built a per-currency map and then summed across every
group, rejecting postings that were in different currencies entirely:

  2010-05-28 * "two elided postings, different currencies"
    Assets:A                 USD
    Assets:B                 EUR
    Assets:C   -600.00 USD
    Assets:D    -50.00 EUR

  was  E3002 Transaction has 2 postings with missing amounts
  now  A = 600.00 USD, B = 50.00 EUR   (what beancount does, and what
       rledger's own interpolate already computed)

The grouping was also never populated. The currency hint came from
`.and_then(|u| u.as_amount())`, which is None for exactly the partial-units
postings the rule is about, so every unknown landed in one bucket and the
map had at most one meaningful key.

The grouping is no longer re-derived here. `elided_unknown_groups` is new
in rustledger-booking and is what `interpolate` itself solves by, so the
pre-booking diagnostic and the solver cannot disagree. That matters more
than usual since #1911: a per-unit cost redenominates the weight, so
`HOOL {300.00 USD}` is an unknown in USD, not in HOOL, and no amount of
looking at the posting's units reveals that.

A fully-elided posting keeps the old strictness. It has no currency of its
own, so it can absorb any residual including one another unknown is
claiming; beancount refuses that combination outright
("CategorizationError") and so do we. One bare posting alone is still
fine, including when it splits across several currencies.

Checked against beancount on nine shapes covering both elided kinds, bare
postings, cost-carrying postings, same-group and disjoint-group pairs:
all nine now agree, where two disagreed before. Booked VALUES also match,
including the multi-currency split.

No corpus movement: over 758 files not one changes accept/reject status,
and the value oracle is unchanged at 3. The shape simply does not occur
there, so the corpus is evidence of no regression rather than evidence
for the fix; the synthetic cases and unit tests carry that.

Both halves were confirmed to fail when neutered - restoring the
total-count rule fails the validator test, and grouping by the units
currency fails the drift guard.

Closes #1914
Copilot AI review requested due to automatic review settings August 1, 2026 04:26
@robcohen
robcohen requested a review from a team as a code owner August 1, 2026 04:26
@robcohen
robcohen enabled auto-merge (squash) August 1, 2026 04:27
@github-actions

github-actions Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.4ms ± 0.7ms 24 MB
beancount 887.1ms ± 3.3ms 50.7 MB
Comparison 25.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 94.28571% with 28 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/interpolate.rs 93.12% 27 Missing ⚠️
crates/rustledger-validate/src/lib.rs 98.63% 1 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 E3002 (“multiple interpolation unknowns”) to be enforced per interpolation currency group (the same grouping the booking/interpolation solver uses), instead of incorrectly summing unknowns across all groups and rejecting valid multi-currency transactions.

Changes:

  • Update rustledger-validate’s E3002 check to use rustledger_booking::elided_unknown_groups(txn) and enforce “≤1 unknown per group”, while keeping fully-elided (“unassigned”) postings strict when combined with any other unknown.
  • Introduce a canonical, solver-aligned unknown grouping API (UnknownGroup + elided_unknown_groups) in rustledger-booking to prevent validator/solver drift.
  • Add regression tests for the multi-currency E3002 behavior and an end-to-end loader pipeline test for the cost-weight currency solve path.

Reviewed changes

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

Show a summary per file
File Description
crates/rustledger-validate/src/validators/transaction.rs Switch E3002 enforcement to canonical per-group counting (including strict handling of unassigned unknowns) and improve diagnostic messaging.
crates/rustledger-validate/src/lib.rs Add regression tests covering “two elided postings in different currencies OK” and “same currency still rejected”.
crates/rustledger-loader/tests/loader_test.rs Add end-to-end test that the full load→interpolate→book→validate pipeline books units-elided-with-cost correctly.
crates/rustledger-booking/src/lib.rs Re-export canonical unknown grouping surface (UnknownGroup, elided_unknown_groups) for cross-crate use by validators.
crates/rustledger-booking/src/interpolate.rs Implement canonical unknown grouping and ensure interpolation/validation share the same weight-currency classification to avoid drift.

💡 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
robcohen merged commit 45cc9b9 into main Aug 1, 2026
62 checks passed
@robcohen
robcohen deleted the fix/e3002-per-currency-group branch August 1, 2026 04:49
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.

E3002 rejects two elided postings in different currency groups

2 participants