Skip to content

fix(core): report an ambiguous STRICT match instead of guessing FIFO (closes #2097) - #2099

Merged
robcohen merged 3 commits into
mainfrom
fix/strict-ambiguous-match
Aug 19, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/strict-ambiguous-match

Conversation

@robcohen

Copy link
Copy Markdown
Member

Closes #2097.

What was wrong

plan_strict compared matched lots by cost number and currency only, and drained them oldest-first when those agreed. The comment justifying it said the user "could not have observed a different outcome" and that "beancount falls back to FIFO in that case". Neither is true.

A silent, tax-visible lot choice, under the one booking method whose purpose is to make the user state it.

The fix is a narrowing, not a deletion

Comparison is now the full cost — number, currency, date and label. Lots identical in all four remain interchangeable.

That is not a hedge. Beancount's Inventory is keyed by (currency, cost), so two buys of the same commodity at the same price on the same day are one position there and can never be ambiguous. Ours keeps two lots. Deleting the arm outright rejected that ledger — I tried it first, and a same-day same-price pair started failing:

2024-01-01 * "buy 1"   Assets:B  10 AAPL {150.00 USD}
2024-01-01 * "buy 2"   Assets:B   5 AAPL {150.00 USD}
2024-03-01 * "sell"    Assets:B  -3 AAPL {150.00 USD}

Comparing the whole cost reproduces beancount's observable behaviour without changing how positions are stored. Merging at add would be the more faithful model and a much larger change — Inventory::len counts lots and currency_accounts branches on it — so it is noted in the code rather than attempted here.

Agreement, measured

case beancount main this PR
partial sale, two lots same cost, different dates Ambiguous accepts Ambiguous ✓
partial sale, two lots same cost, same date accepts accepts accepts ✓
sale consuming every matched lot accepts accepts accepts ✓
beancount#889 shape No position matches accepts accepts (deliberate, unchanged)

Corpus

Of 735 files, exactly one changes — parser-lima/test-cases_TotalsAndSigns.TotalCost.beancount — and it changes to agree with beancount, which reports Ambiguous matches on the same line.

Worth flagging how nearly I missed that: comparing exit status showed zero differences, because that file already failed on an unopened account. Only comparing error text surfaced it. A status-only sweep answers "does it still pass", not "does it behave the same".

Fallout fixed here

gen-profile-workload.py's investment shape generates sales of exactly this form, which is why it loaded under rledger and failed under bean-check — the observation that started #2097. Its sells now name the lot by cost and date. Not cosmetic: costs are drawn from a few tens of thousands of strings across thousands of buys per ticker, so collisions are a birthday-problem certainty — 46 of them at n=10000.

check-profile-workloads.sh gains the cross-check that would have caught this years earlier: every shape must load under bean-check too, where it is available. It also gains fifo, which had never been checked at all — the shape added because ordered selection was unprofiled was itself unverified.

Both new tests were confirmed to fail on main.

…loses #2097)

When a reduction's cost spec matched several lots, `plan_strict` compared
their cost NUMBER and CURRENCY only; if those agreed it drained them
oldest-first. The comment justifying it claimed the user "could not have
observed a different outcome" and that "beancount falls back to FIFO in
that case". Neither holds.

Beancount's `booking_method_STRICT` has no fallback at all: more than one
match is the total-match exception or an `AmbiguousMatchError`. And the
outcome is observable, because the lots differ in ACQUISITION DATE.
Selling 16 against `4 GLOB {74.09, 2022-05-10}` + `16 GLOB {74.09,
2024-02-09}` leaves 4 GLOB dated 2024 under FIFO and dated 2022 under any
other choice — same cost basis, which is what kept it quiet, but a
different holding period. This codebase acts on holding periods, in
`report capgains`'s short/long split and in per-lot IRR eligibility. So
the fallback made a tax-visible choice silently, under the one booking
method whose purpose is to make the user state it.

The comparison is now the FULL cost — number, currency, date and label.
Lots identical in all four stay interchangeable, which is not a
concession: beancount's inventory is keyed by (currency, cost), so two
buys of the same commodity at the same price on the same day are ONE
position there and can never be ambiguous. Ours keeps two lots, so
deleting the arm outright would have rejected that very ordinary ledger.
Comparing the whole cost reproduces beancount's observable behavior
without changing how positions are stored.

Found while sizing #2096: the `investment` profiling shape generates
sales of this form, so it loaded cleanly under rledger and failed under
bean-check. Its sells now name the lot by cost AND date. That is not
cosmetic — costs are drawn from tens of thousands of strings across
thousands of buys per ticker, so collisions are a birthday-problem
certainty, and at n=10000 there were 46 of them.

`check-profile-workloads.sh` gains the cross-check that would have caught
this: every shape must load under bean-check too, where it is available.
It also gains `fifo`, which had never been checked at all despite being
the shape added because ordered selection was unprofiled.

Corpus: of 735 files, exactly one changes — and it changes to AGREE with
beancount, which reports `Ambiguous matches` on the same line. Comparing
exit status alone showed no differences at all; that file already failed
on an unopened account, so only comparing error TEXT surfaced it.
@robcohen
robcohen requested a review from a team as a code owner August 19, 2026 17:37
Copilot AI lite review requested due to automatic review settings August 19, 2026 17:37
@codecov

codecov Bot commented Aug 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 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 a Beancount-compatibility bug in STRICT booking where rustledger previously resolved ambiguous lot matches by silently draining FIFO, and updates profiling workloads + tests to prevent regression.

Changes:

  • plan_strict now treats multiple matching lots as ambiguous unless their full cost is identical (number, currency, date, label), preserving the “total-match” exception behavior.
  • Updates generator + workload checks so the investment profiling shape disambiguates sells by cost and acquisition date, and adds fifo to the verified shapes plus an optional bean-check cross-check.
  • Updates/extends core + validator tests and documents the behavior change in the changelog.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
scripts/gen-profile-workload.py Makes investment sells include acquisition date in the cost spec to avoid STRICT ambiguity.
scripts/check-profile-workloads.sh Verifies fifo shape, asserts the dated-lot syntax for investment, and optionally cross-checks shapes with bean-check.
crates/rustledger-validate/src/lib.rs Updates validator regression test to assert AmbiguousLotMatch for partial sale matching two dated lots under STRICT.
crates/rustledger-core/src/inventory/mod.rs Updates inventory-level tests to require ambiguity for same-cost/different-date partial matches, and keeps total-match exception covered.
crates/rustledger-core/src/inventory/booking.rs Changes STRICT matching from “same number+currency” to “full cost equality” for indistinguishable lots; otherwise reports ambiguity (except total-match).
CHANGELOG.md Adds breaking-change entry describing STRICT ambiguity reporting change and rationale.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread scripts/gen-profile-workload.py Resolved
@github-actions

github-actions Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 76.7ms ± 5.3ms 734.8ms ± 12.4ms 9.6x 36.1 MB / 49.9 MB
investment 102.9ms ± 1.6ms 2743.8ms ± 35.9ms 26.7x 39.1 MB / 58.2 MB
fifo 93.9ms ± 1.0ms 15644.4ms ± 88.1ms 166.6x 37.1 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 72.7ms ± 0.6ms 76.7ms ± 5.3ms +5.4% 🟡 slower 35.5 MB → 36.1 MB (+1.7%)
investment 101.4ms ± 1.1ms 102.9ms ± 1.6ms +1.5% ✅ within noise 39.1 MB → 39.1 MB (-0.1%)
fifo 94.7ms ± 4.1ms 93.9ms ± 1.0ms -0.9% ✅ within noise 37.1 MB → 37.1 MB (-0.0%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 2.4ms, investment 0.9ms, fifo 1.9ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 170 masked)
Full AST Match 100%
Total Files 811
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

Found reviewing the STRICT fix in this PR — the same defect, one method
over, and it produces a wrong number rather than a wrong error.

Beancount's `booking_method_STRICT_WITH_SIZE` sorts the size matches by
`cost.date` and takes the first. Ours took the first in SLOT order, which
is insertion order. That is usually date order, so the two usually agreed
by accident — but a lot carrying an explicit cost date is inserted when
its transaction books and dated whenever the user wrote:

    2024-01-01 * "buy A"
      Assets:B   10 X {100.00 USD, 2030-01-01}
    2024-01-02 * "buy B"
      Assets:B   10 X {200.00 USD, 2020-01-01}
    2024-02-01 * "sell by size"
      Assets:B  -10 X {} @ 300.00 USD

Both lots are size 10, so size does not disambiguate. beancount sells the
2020 lot and leaves 1000.00 USD of basis; slot order sold the 2030 lot
and left 2000.00. Neither tool reports anything. Verified against 3.2.3;
rledger now also answers 1000.00.

Ties break on slot index so the choice stays deterministic when two size
matches share a date, and `None` dates sort last: a booked lot always
carries one.

The new test builds its lots in the opposite order to their dates, which
is what makes it fail on the old code — a fixture in date order would
have passed either way.
@robcohen

Copy link
Copy Markdown
Member Author

Deep review pass. It found the same bug one method over, and that one returns a wrong number rather than a wrong error.

STRICT_WITH_SIZE picked the wrong lot

Beancount's booking_method_STRICT_WITH_SIZE sorts the size matches by cost.date and takes the first. Ours took the first in slot order, which is insertion order — usually date order, so the two agreed by accident. A lot carrying an explicit cost date breaks the coincidence, because it is inserted when its transaction books and dated whenever the user wrote:

2024-01-01 * "buy A"
  Assets:B   10 X {100.00 USD, 2030-01-01}
2024-01-02 * "buy B"
  Assets:B   10 X {200.00 USD, 2020-01-01}
2024-02-01 * "sell by size"
  Assets:B  -10 X {} @ 300.00 USD

Both lots are size 10, so size does not disambiguate. beancount leaves 1000.00 USD of basis; main left 2000.00. Neither reports anything. Fixed in 2772118, verified against 3.2.3, and the test builds its lots in the opposite order to their dates — a fixture in date order passes either way.

Also checked, and clear

  • plan_ordered respects the cost spec. Both fallback paths hand it spec, and its keeps predicate includes matches_cost_spec, so it cannot drain a lot the spec excludes.
  • Scale-insensitive cost equality is correct here. Decimal's PartialEq aligns scales, so {2000 USD} and {2000.00 USD} count as one identity — which is what beancount does, since Python Decimal compares numerically and the two would be a single merged position there.

A measurement correction

I reported "1 of 735 corpus files changes". That was measured on error text, which cannot see the STRICT_WITH_SIZE bug at all — it changes which lot is sold on files that report nothing.

Re-measured on per-account cost basis across every corpus file that loads cleanly: 0 changed. The harness was checked against both fixtures above first, and reports them as differing, so the zero means unaffected rather than unmeasured.

So the full picture is: one file changes its errors (into agreement with beancount), and no file changes its numbers.

Review feedback. The change to a 3-tuple added a comment rather than
updating the one already there, leaving two adjacent lines describing the
same variable differently — the older one still saying (units, cost).
@robcohen
robcohen merged commit 2d28b7d into main Aug 19, 2026
57 of 59 checks passed
@robcohen
robcohen deleted the fix/strict-ambiguous-match branch August 19, 2026 18:26
robcohen added a commit that referenced this pull request Aug 23, 2026
* test(compat): add a differential booking fuzzer

Booking decides WHICH lot a reduction consumes. Get it wrong and the
postings still balance, the count is still right and the error list is
still empty — the ledger is simply wrong about what you own and what you
gained. Example-based tests are worst at exactly that, and the fix log
shows it: five booking fixes in twenty commits (#2058, #2069, #2081,
#2093, #2099), each an ordering or lot-selection case nobody had written
a test for.

So this generates ledgers and compares BOOKED LOTS against Python
beancount — an independent implementation, not a restatement of our own
logic. For every account it compares full lot identity, (currency,
per-unit cost, cost currency, lot date) -> units, so consuming the wrong
lot at the same total value is still a failure. It also compares
ACCEPTANCE: a ledger one engine books and the other rejects is a
divergence even when no numbers differ, which is the shape of #2099.

It found a real divergence on its first campaign — 58/60 agreed, both
failures LIFO with same-date lots. Filed separately with a 12-line
reproduction.

Two things learned building it, both encoded in the script:

`cost(position)` is the wrong column to read. For a costless posting it
returns the units themselves, so a cash leg looks like it holds a cost
of 1. `cost_number` is per-unit and null when there is no cost, which is
what makes it the right discriminator. The first draft compared cash
legs against nothing and reported four false divergences per run.

AVERAGE and NONE booking are deliberately not generated: beancount
rejects both outright, so every such run would be a known-unsupported
skip rather than a test.

`--self-test` plants six known outcomes (wrong lot, wrong units, either
side rejecting, and two agreements) and requires each be classified
correctly, then requires the real engines to agree on a hand-checked
ledger. A harness that has only ever printed "no divergences" cannot be
distinguished from one that is incapable of printing anything else; this
one is checked in both directions before it is believed.

* test(compat): address review of the booking fuzzer

Two of the four were real defects, not style.

The `--python` default was `/home/dev/.compat-venv/bin/python` — my own
machine's path, committed. It now defaults to `sys.executable`, which
matches how the sibling compat scripts are invoked (`python3
scripts/compat-values.py`, under an interpreter that already has
beancount) and still takes an override for a dedicated venv.

`json.loads` was unguarded on the rledger side while the beancount side
already caught decode failures. A banner or stray log line on stdout
would have aborted the whole campaign rather than counting as one
booking failure — and the asymmetry between the two paths is what made
it wrong, since the comparison treats them as equivalent. Verified: a
non-JSON stdout now returns ERROR instead of raising.

Also extracted the query out of adjacent string literals so the intent
is explicit, and stopped materializing the seed sequence a second time
after iterating it.

Self-test still passes and seed 35 still reproduces the LIFO divergence
(#2115).
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.

[Compat]: STRICT accepts an ambiguous lot match that beancount rejects, and the comment justifying it is wrong about both beancount and observability

2 participants