Skip to content

fix(core): store interchangeable lots as one position - #2139

Merged
robcohen merged 6 commits into
mainfrom
feat/merge-interchangeable-lots
Aug 24, 2026
Merged

robcohen merged 6 commits into
mainfrom
feat/merge-interchangeable-lots

Conversation

@robcohen

Copy link
Copy Markdown
Member

Supersedes #2138, which should be closed if this is accepted. Same semantics, far less machinery, and at parity rather than 8-14% slower. Implements Rule 1 of rustledger/pta-standards#45.

The realisation

add already merged cost-less positions, through simple_slot. The merge machinery was fully general and only the gate was narrow:

let merge_idx = position.cost.is_none().then(|| ...)

Lots agreeing on commodity, cost per unit, cost currency, acquisition date and label are indistinguishable in exactly the same way: no attribute the model records separates them. Keeping them apart only let the order they were written decide which units a reduction consumed (#2118).

Widening that gate makes the group one position, which is what the RFC says it is and what Python beancount stores. Everything #2138 needed then disappears: no identity-to-ordinal map, no per-slot view, no monotonic counter, no anchor in the sort key. Ordering returns to (order_key, slot) exactly as before this work began. The group holds its position until its units reach zero and a re-acquisition after a full drain lands at the end, both because that is what one position does.

That is also why #2138 needed three separate fixes across add, cost_index_remove and rebuild_index: it was reconstructing at three call sites a property merging gives by construction.

#2138 anchoring this
fuzzer, seeds 0-999 1000/1000, 0 divergences 1000/1000, 0 divergences
ex-FIFO-2000 +8% 363ms vs main's 384ms
ex-FIFO-20000 +14% 21759ms vs main's 21996ms
state to keep in sync 3 maps, 3 call sites none

Faster, for having fewer positions to sort and walk.

This changes what add means, so here are the six tests, one at a time

It is not only an ordering change, and the tests encoding the old contract were examined individually rather than swept:

test disposition
test_add_no_cancel_same_sign Asserted two same-cost same-date buys stay separate: the exact case #2118 is about. Rewritten as test_add_merges_same_identity, plus a new boundary test that labelled lots still stay apart, since that is what labels are for.
test_add_costed_positions_kept_separate A negative of the same identity now nets into the lot. Renamed to say so. Booking a sale is unaffected: that goes through reduce, not add.
test_add_costed_positions_net_units Same case, same disposition.
test_merge_keeps_lots_separate merge adds each position, so the same identity lands in one. Renamed.
iter_slots_yields_indices_that_address_their_own_position Subject preserved. It is about slot addressing, not merging; it needed two positions equal by value as a trap for index bugs. They now differ by label, so they stay two lots while still comparing equal on units and cost.
interchangeable_lots_consume_independently_of_write_order Mine, from #2138. Rewritten: the property is now stronger, since the lots are literally one position.

The add(+10) / add(-10) netting is the part worth a reviewer's attention. It is a real change to a documented contract, and it is why I did not fold this into #2138 as an optimisation.

Verification

  • booking fuzzer seeds 0-999: 1000/1000, zero divergences of any kind
  • capgains fuzzer: 200/200
  • 492 core tests, clippy clean on 1.97
  • corpus_parity fails identically here and on main (28 files, stale prebuilt wasm), unaffected

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

robcohen and others added 5 commits August 24, 2026 15:49
Two lots agreeing on commodity, cost per unit, cost currency, acquisition
date and label are indistinguishable in every attribute the model records.
Booking consumed them in acquisition order anyway, so an unrelated lot
written BETWEEN them changed which units were sold.

Three purchases on one date at two costs, written in the six possible
orders, produced three distinct cost bases where Python beancount produces
two. Sorting a journal or switching importers could therefore move a
reported basis and a realized gain without changing a fact.

No external standard supplies the missing distinction. Treas. Reg.
1.1012-1(j)(3)(i) orders units "in order of time from the earliest DATE" and
says nothing about sequence within one; IAS 2.23 and ASC 330 treat FIFO as a
cost-flow assumption over INTERCHANGEABLE items, reserving specific
identification for items that are not. Lots identical in commodity, basis and
date are interchangeable by definition, so the finer ordering was ours to
invent, and inventing it from an editing accident was the wrong choice.

Ordering now breaks ties on the earliest slot holding an interchangeable lot.
That removes the last divergence class the differential booking fuzzer
reported: 250/250 seeds agree with zero divergences of any kind, where main
reports six, two of them ledgers one engine refuses to load.

Implemented at PARITY. `cost_index` already buckets slots by (units currency,
cost number, cost currency) in slot order, so the earliest interchangeable
slot is the first bucket member agreeing on date and label. Buckets hold one
or two entries and the lookup hashes three cheap values. The obvious
implementations are much worse and are recorded in the RFC: a scan inside the
sort comparator is 9.7x, a dedicated identity map 1.15x to 1.21x.

  ex-FIFO-2000    main 357ms    branch 357ms
  ex-FIFO-20000   main 22021ms  branch 21782ms

LIFO, HIFO and STRICT are at parity too.

The regression test covers BOTH ordering paths deliberately. `try_reduce` on
a fresh inventory sorts a scanned list; a reduction after the index exists
places later acquisitions through `ordered_index_insert`. An earlier version
covered only the scan and passed with the insert path's lookup disabled.

This is a user-visible change: cost basis, realized gains, surviving lot
dates and `meta.hash` move for any account holding a repeated lot identity
within a date, and a reduction naming an explicit cost may begin or cease to
resolve.

Closes #2118.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
The first cut derived a group's ordering position from its earliest
SURVIVING member. That is not the same thing as the group's position, and
the difference is observable: drain the earliest member and the survivors
jump to wherever the next one sits, so a group that sat before another lot
lands behind it part-way through a ledger.

Found by widening the sweep past the 250 seeds CI runs. At 1000 seeds the
previous commit still reported two divergences, both LIFO. Reduced: the same
ledger agrees under FIFO and differs under LIFO, because LIFO reverses the
primary key, so a group whose anchor slides lands on the wrong side of its
neighbor.

The anchor is now a monotonic ordinal assigned when an identity is first
acquired and released only when no lot carries it. That reproduces Python
beancount exactly, where a pooled position holds its slot in the inventory
dict until its units reach zero and a re-acquired identity is re-inserted at
the end.

Three places had to agree for that to hold, and each was a separate bug in
the first cut:

  - `add` assigns the ordinal before the ordered insert reads it
  - `cost_index_remove` releases it only when the cost bucket has no lot left
    sharing the identity, asking the bucket rather than every slot: scanning
    `slot_ordinal` was O(lots) per drained lot, worth +23%
  - `rebuild_index` repopulates the per-slot view after compaction renumbers
    slots, while keeping `ident_ordinal`, which is the entire reason the
    anchor is keyed by identity

Missing the last one turned two LIFO divergences into one UNEXPLAINED HIFO
divergence, a worse failure that the earlier 250-seed sweep would not have
shown either.

Differential booking fuzzer, seeds 0-999: 1000/1000 agreed, zero divergences
of any kind. Seeds 5000-5499, a range never developed against: also zero.
Capgains fuzzer: 200/200. 491 core tests, clippy clean on 1.97.

Costs 8% at 2,000 transactions and 14% at 20,000 on the FIFO shape, from the
ordinal bookkeeping in `add`. That is a real regression and not yet
recovered; the previous approach was at parity but wrong.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Exploratory. Do not merge as-is: six tests encode the contract this changes.

`add` already merged cost-less positions through `simple_slot`; the merge
machinery was general and only the gate was narrow. Widening that gate to
lots agreeing on cost, cost currency, date and label deletes the whole
ordinal apparatus the previous commit needed: no `ident_ordinal`, no
`slot_ordinal`, no `next_ordinal`, no per-slot anchor, and the sort key goes
back to `(order_key, slot)` exactly as on main.

Net 109 lines removed against that approach, and it is faster: +2%/+5% at
2,000/20,000 transactions against +8%/+14%. Correctness is identical,
1000/1000 fuzzer agreement with zero divergences.

The catch is that it changes what `add` MEANS, not just how lots are
ordered. `add(+10 @cost)` then `add(-10 @cost)` now nets to a single
zero-unit position where the codebase deliberately kept two lots:

  test_add_costed_positions_kept_separate
  test_merge_keeps_lots_separate
  test_add_costed_positions_net_units
  test_add_no_cancel_same_sign
  iter_slots_yields_indices_that_address_their_own_position

Those are a documented decision ("costed positions are kept as separate lots
for O(1) add performance; aggregation happens at display time"), not
incidental coverage. The RFC asks for interchangeable lots to consume as one
position; it does not ask for `add` to become a netting operation, and that
is a wider change than the one under review.

Recorded so the comparison is on the record rather than in a scratch branch.
Supersedes the anchoring approach on #2138. Same semantics, far less
machinery, and at parity rather than 8-14% slower.

`add` already merged cost-less positions through `simple_slot`. The merge
machinery was general and only the gate was narrow. Lots agreeing on
commodity, cost per unit, cost currency, acquisition date and label are
indistinguishable in the same way: no attribute the model records separates
them, so keeping them apart only let the order they were WRITTEN decide
which units a reduction consumed (#2118).

Widening that gate makes the group one position, which is what Rule 1 of the
pta-standards RFC says it is, and what Python beancount stores. Everything
the anchoring approach needed then disappears: no identity-to-ordinal map, no
per-slot view, no monotonic counter, no anchor in the sort key. Ordering goes
back to `(order_key, slot)` exactly as before this work started. The group
holds its position until its units reach zero, and a re-acquisition after a
full drain lands at the end, both because that is what one position does.

That is also why anchoring needed three separate fixes across `add`,
`cost_index_remove` and `rebuild_index`: it was reconstructing at three call
sites a property merging gives by construction.

This changes what `add` MEANS, not only how lots are ordered, so the six
tests encoding the old contract were each examined rather than swept:

  test_add_no_cancel_same_sign -> test_add_merges_same_identity. It asserted
    two same-cost same-date buys stay separate, which is the exact case
    #2118 is about. Rewritten, plus a new boundary test that LABELLED lots
    still stay apart, since that is what labels are for.
  test_add_costed_positions_kept_separate -> test_add_nets_a_negative_of_
    the_same_identity, and test_add_costed_positions_net_units likewise: a
    negative of the same identity nets into the lot. Booking a sale is
    unaffected, since that goes through `reduce`.
  test_merge_keeps_lots_separate -> test_merge_nets_the_same_identity.
  iter_slots_yields_indices_that_address_their_own_position keeps its
    subject, which is slot addressing, not merging. It needed two positions
    equal by value; they now differ by label, so they stay two lots while
    still comparing equal on units and cost, which is the trap it guards.

Differential booking fuzzer, seeds 0-999: 1000/1000, zero divergences of any
kind. Capgains fuzzer 200/200. 492 core tests, clippy clean on 1.97.

  ex-FIFO-2000    main 384ms    branch 363ms
  ex-FIFO-20000   main 21996ms  branch 21759ms

Faster, for having fewer positions to sort and walk.

`corpus_parity` fails identically here and on main (28 files, stale prebuilt
wasm), unaffected by this change.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner August 24, 2026 17:44
Copilot AI lite review requested due to automatic review settings August 24, 2026 17:44

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 updates rustledger-core’s Inventory::add semantics so that cost-bearing lots that are interchangeable by the model (same units currency, cost number/currency, acquisition date, and label) are stored as a single pooled position—matching the stated RFC rule and aligning behavior with Python beancount’s inventory pooling for identical lot identities.

Changes:

  • Extend Inventory::add merge behavior from cost-less positions to also merge cost-bearing interchangeable lots via cost_index lookup.
  • Make ordered-slot sorting explicitly deterministic by sorting with (order_key, slot) in both the core index builder and booking scan path.
  • Update/expand unit tests to reflect the new pooling semantics and to pin “write-order independence” for interchangeable lots; add a changelog entry describing the user-visible impact.

Reviewed changes

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

File Description
crates/rustledger-core/src/inventory/mod.rs Implements interchangeable-lot merging in add, adjusts ordered-index sorting, and updates tests/comments around inventory behavior.
crates/rustledger-core/src/inventory/booking.rs Aligns scan-path candidate ordering with (order_key, slot) tie-breaking and adds a regression test for interchangeable-lot write-order independence.
CHANGELOG.md Documents the user-visible semantics change (pooling interchangeable lots) and its impacts.
Suppressed comments (3)

crates/rustledger-core/src/inventory/mod.rs:1929

  • This comment mentions a slot “anchor” recorded by add, but there is no anchor concept used in ordered_index_insert anymore (the insertion key is (order_key, slot)). This should be revised to avoid implying there’s additional state affecting ordering.
        // The slot's anchor is already recorded by `add`, so this reads it.

crates/rustledger-core/src/inventory/mod.rs:2314

  • This comment says an “identity map” is rebuilt during compaction, but the code here is rebuilding the ordered index lists after slot renumbering. The current wording is confusing/outdated (especially now that the identity-map machinery from #2138 is gone).
            // Compaction renumbers slots, so the identity map is rebuilt with
            // them rather than patched.

crates/rustledger-core/src/inventory/mod.rs:1946

  • The rustdoc refers to Self::anchor, but there is no anchor method, and interchangeable lots are now merged into one position so this tie-break description is no longer accurate. This also risks a broken intra-doc link warning.
    /// Ties fall through to [`Self::anchor`], which keeps interchangeable lots
    /// together at the position of the first of them and otherwise preserves
    /// source order. That tiebreak is ascending for EVERY ordering, including

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

@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 49.3ms ± 6.0ms 728.1ms ± 6.4ms 14.8x 55.0 MB / 50.0 MB
investment 68.5ms ± 2.6ms 2817.9ms ± 48.9ms 41.1x 59.1 MB / 58.2 MB
fifo 65.8ms ± 0.7ms 15840.9ms ± 177.5ms 240.9x 61.2 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 49.1ms ± 6.7ms 49.3ms ± 6.0ms +0.3% ✅ within noise 55.1 MB → 55.0 MB (-0.2%)
investment 67.5ms ± 0.9ms 68.5ms ± 2.6ms +1.5% ✅ within noise 59.1 MB → 59.1 MB (+0.0%)
fifo 65.8ms ± 0.8ms 65.8ms ± 0.7ms +0.0% ✅ within noise 61.0 MB → 61.2 MB (+0.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 4.0ms, investment 1.2ms, fifo 0.5ms), 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

@codecov

codecov Bot commented Aug 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@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

Four comments still described an anchor tiebreak that no longer exists: the
ordered index sorts by `(order_key, slot)`, with no secondary key, because
`add` stores interchangeable lots as ONE position rather than keeping several
adjacent.

Reported by Copilot on #2139, which caught all four sites.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

Copy link
Copy Markdown
Member Author

Good catch, and correct on all four sites — fixed in b4d807e.

Those comments were written for the anchoring approach on #2138, which ordered per-acquisition slots around a stable anchor. This PR removed that machinery but I left its documentation behind, so the file described a secondary tiebreak the code no longer has.

Corrected:

  • OrderedIndex.by_currency now says sorted by order then slot ascending, and says WHY no further tiebreak is needed: add stores interchangeable lots as one position, so a group has one slot rather than several needing to be kept adjacent.
  • ordered_index_insert no longer claims add records an anchor.
  • order_key says ties fall through to the slot number.
  • rebuild_index no longer mentions rebuilding an identity map.

I also swept the file for other references to the removed machinery (anchor, ident_ordinal, slot_ordinal, canonical) and found none beyond unrelated uses of "canonical" in error-wording docs.

Worth noting the class of defect: this is documentation describing a design that was replaced, which is exactly the kind of thing that survives review and then misleads the next reader. The four sites you listed were all of them.

@robcohen
robcohen merged commit 7c82121 into main Aug 24, 2026
61 checks passed
@robcohen
robcohen deleted the feat/merge-interchangeable-lots branch August 24, 2026 19:18
robcohen added a commit that referenced this pull request Aug 25, 2026
Self-review findings on the new booked-value gate.

The step was inserted between an existing comment block and the step it
documents, so "Mirrors the BQL step's `--baseline`..." -- written about
`Gate on check regressions` -- read as though it described this gate
instead. Moved up beside the other comparison gates, which is where it
belongs anyway.

`steps.booked_values.outputs.failed != '0'` fired on an EMPTY output. When
an earlier step aborts the job, this one is skipped, its outputs are unset,
and `'' != '0'` is true: the gate ran on an already-red build and annotated
it with a booked-value divergence that never happened. Added
`outcome != 'skipped'`. Kept `!= '0'` rather than the `== '1'` the fuzz
gates use, and said why in a comment: those report a boolean, this forwards
the script's exit code, and a usage error exits 2.

`--limit` truncates the corpus, so it silently produced a partial
divergence set. `--write-baseline --limit 5` would have shrunk the recorded
file from 34 entries to whatever the first five files happened to diverge
on, and `--baseline --limit 5` reports every unvisited entry as RESOLVED and
exits 0. Both read as success. Now refused outright.

Dropped a function-local `import os` for `path.name`; `path` is already a
`Path` and the KNOWN_POSTING_DIVERGENCES lookup keys on `path.name` two
hundred lines up.

Documented what the key does not pin: it records WHERE we diverge, not by
how much, so a known-diverging cell whose numbers get worse still passes.
Pinning values was considered and rejected -- CI installs beancount from
master, so its side can move with no change here, and a baseline that churns
on upstream commits gets regenerated reflexively instead of read. Also noted
that KNOWN_POSTING_DIVERGENCES is the better home for a divergence that has
a reason worth writing down.

Re-ran every path: baseline clean (known 34, found 34), pre-#2139 binary
still exits 1 naming both keys, three malformed-baseline shapes and a
missing file each give one line and a non-zero exit, --limit alone is
unchanged, self-test passes, actionlint holds at main's 3.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Aug 25, 2026
…2148)

* test(compat): fail on NEW booked-value divergences against beancount

`compat-values.py` compares booked values, per-posting cost/price/lot-date,
error kinds and price directives against Python beancount across the corpus.
Its docstring says why it exists: a bug producing the right number of
postings with the wrong numbers in them "passes silently, which for an
accounting tool is the failure that matters most".

Nothing failed when it found one. The step was `continue-on-error`, `main()`
returned 0 unconditionally, and no gate read the output -- it went to
`compat-values.txt` and the step summary. Every other comparison in this
workflow is gated (budget, booking, capgains, returns, check regressions,
synthetic differential); this one was not. A PR introducing a fresh
divergence printed it into a summary and stayed green.

Gating on ANY divergence was never an option, which is presumably how it
ended up this way. There are 34 today, largely rustledger carrying an exact
value where Python's `decimal` context rounds an intermediate at 28
significant digits:

  number:       beancount=-720.0200000000000000000000001  rledger=-720.02
  price_number: beancount=54.13684210526315789473684211
                rledger=54.136842105263157894736842105

rustledger is arguably the better side of those, and a gate that failed on
them would simply be switched off again.

So this takes the shape the BQL step already uses in the same workflow: a
recorded baseline, where only departures fail. `--write-baseline` records the
current set, `--baseline` fails on anything outside it, and a divergence that
GOES AWAY is reported as RESOLVED rather than failing, so the file can be
trimmed instead of silently accumulating entries that pin nothing.

Keys are (basename, field), matching how `KNOWN_POSTING_DIVERGENCES` is
already keyed: the corpus is fetched to different absolute paths in CI and
locally, so a baseline keyed on full paths would match nothing and pass
everything.

Verified in both directions, which is the only way a gate is worth having:

  against its own baseline          exit 0, "known 34, found 34, new 0"
  against a pre-#2139 binary on a
  ledger exercising #2118           exit 1, naming
                                    "value:Income:Gains USD" and
                                    "posting:<row count>"

Closes #2147.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* test(compat): report a malformed baseline instead of a stack trace

The baseline is generated, so two PRs that both record divergences collide
in it, and an unresolved conflict marker is the likeliest way it goes bad.
Only FileNotFoundError was handled, so that surfaced as a JSONDecodeError
traceback in a CI log.

Also validates shape, which is the quieter half. `set(map(tuple, raw))`
turns a bare string entry into a tuple of its characters rather than a key,
so a hand-edit leaving `["value:x"]` instead of `[["f.beancount",
"value:x"]]` would match nothing and report every known divergence as new,
with nothing in the output to say why.

Each rejection path was run: a conflict marker, a list of bare strings, and
a pair with a non-string element all give one line and exit 1. The real
baseline still reports known 34, found 34, new 0.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* test(compat): fix gate placement, skip-safety and the --limit footgun

Self-review findings on the new booked-value gate.

The step was inserted between an existing comment block and the step it
documents, so "Mirrors the BQL step's `--baseline`..." -- written about
`Gate on check regressions` -- read as though it described this gate
instead. Moved up beside the other comparison gates, which is where it
belongs anyway.

`steps.booked_values.outputs.failed != '0'` fired on an EMPTY output. When
an earlier step aborts the job, this one is skipped, its outputs are unset,
and `'' != '0'` is true: the gate ran on an already-red build and annotated
it with a booked-value divergence that never happened. Added
`outcome != 'skipped'`. Kept `!= '0'` rather than the `== '1'` the fuzz
gates use, and said why in a comment: those report a boolean, this forwards
the script's exit code, and a usage error exits 2.

`--limit` truncates the corpus, so it silently produced a partial
divergence set. `--write-baseline --limit 5` would have shrunk the recorded
file from 34 entries to whatever the first five files happened to diverge
on, and `--baseline --limit 5` reports every unvisited entry as RESOLVED and
exits 0. Both read as success. Now refused outright.

Dropped a function-local `import os` for `path.name`; `path` is already a
`Path` and the KNOWN_POSTING_DIVERGENCES lookup keys on `path.name` two
hundred lines up.

Documented what the key does not pin: it records WHERE we diverge, not by
how much, so a known-diverging cell whose numbers get worse still passes.
Pinning values was considered and rejected -- CI installs beancount from
master, so its side can move with no change here, and a baseline that churns
on upstream commits gets regenerated reflexively instead of read. Also noted
that KNOWN_POSTING_DIVERGENCES is the better home for a divergence that has
a reason worth writing down.

Re-ran every path: baseline clean (known 34, found 34), pre-#2139 binary
still exits 1 naming both keys, three malformed-baseline shapes and a
missing file each give one line and a non-zero exit, --limit alone is
unchanged, self-test passes, actionlint holds at main's 3.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

---------

Co-authored-by: Claude Opus 5 <[email protected]>
robcohen added a commit that referenced this pull request Oct 8, 2026
… (#2488)

The migration guide's "Repeated same-day lots" item and the booking
fuzzer's "expected" bucket still described #2118 as an open divergence.
It was fixed in v0.23.0 (#2139): interchangeable lots are stored as one
position, as Python beancount does.

- docs/migration/from-beancount.md: the worked example now books the same
  on both engines (checked: 10 ACME {20.00 USD} + 5 ACME {10.00 USD} left,
  -150.00 USD gain, bean-check clean). The item now says the engines
  agree since v0.23.0 and what older releases did.
- scripts/compat-booking-fuzz.py: the #2118 waiver is now a tripwire. A
  divergence on a ledger with a repeated lot identity within a date is
  labeled as a likely #2118 regression, counted on its own line, and
  fails the run. same_totals (only used by the waiver) is gone; a new
  classify() carries the verdict and has its own self-test cases.
- compat.yml: the step comment no longer says #2118 does not fail CI.

Verified: self-test passes; seeds 0-249 (the PR window) agree 250/250
with the current binary; the v0.22.0 release binary trips the tripwire
on seed 117 (exit 1).

Closes #2392


Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
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.

2 participants