Skip to content

fix(plugin)!: noduplicates compares every directive type, as beancount's does - #2616

Merged
robcohen merged 6 commits into
mainfrom
fix/noduplicates-all-directives
Oct 12, 2026
Merged

robcohen merged 6 commits into
mainfrom
fix/noduplicates-all-directives

Conversation

@robcohen

@robcohen robcohen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

What

noduplicates compares every directive type, as beancount's does. The native plugin compared only transactions, so a repeated open, close, commodity, pad, balance, note, document, event, query or custom passed where bean-check reports Duplicate entry. It now compares every type but price (beancount allows repeated prices too).

The semantics follow beancount's compare.hash_entries(entries, exclude_meta=True), read from beancount 3's source (stable_hash_namedtuple):

Directive Fields compared (metadata never)
transaction flag, payee, narration, tags, links, postings (account, units, cost, price, flag)
open account, currencies, booking
close / commodity account / currency
pad account, source account
balance account, amount, tolerance (diff_amount ignored, as in beancount)
note / document account, comment / path, tags, links
event / query type, description / name, query string
custom type, values

plus the date. As in beancount, lists are compared without regard to order (beancount sorts the element hashes): tags and links (sets), an open's currencies, a custom's values, and a transaction's postings. Numbers keep their scale (10 USD is not 10.00 USD).

Two consequences on transactions that beancount already has:

  • the same postings in another order are a duplicate (a test asserted the opposite; bean-check contradicts it, so it is flipped);
  • 2 HOOL @@ 10 USD is 2 HOOL @ 5 USD (beancount's parser rewrites @@ per unit before plugins run), and a booked {{10 USD}} on 2 units is {5 USD}. The per-unit number uses Python's division scale (10.00 / 2 is 5.00).

The key is now an exact byte stream (fingerprint::structural_key), not a 64-bit digest, so two different directives can never collide.

Each duplicate is reported at the later copy, naming it: Duplicate entry: 2024-01-04 note Assets:Bank "hello" (transactions keep Duplicate entry: 2024-01-02 "Lunch").

Deliberate divergences (documented in docs/reference/plugins.md and the structural_key doc):

  • the directive's type is part of its identity: beancount does not hash it, so an event "a" "b" and a query "a" "b" on one date are duplicates there;
  • a total price or total cost whose per-unit number does not multiply back to it exactly is compared as written: beancount's 28-digit quotient makes 3 HOOL @@ 10 USD a duplicate of 3 HOOL @ 3.333333333333333333333333333 USD, two transactions whose totals differ;
  • an absent value never equals a written one (beancount's str(None) equals a payee written "None").

Python compat layer: prices, events and queries

Comparing against beancount's real noduplicates.py under the compat layer (#2592) found that the layer read three wire fields under the wrong names, so no Python plugin could run on a ledger with a single @ price, event or query:

  • a posting's price annotation was read as a bare amount: every price reached the plugin as Amount(None, None);
  • an event's description was read from description (the host sends value), a query's string from query_string (the host sends query);
  • writing any of those entries back failed the whole plugin: serialization error: failed to parse entries.

A plugin now sees a price as beancount presents it, a per-unit Amount (@@ divided by the units, zero units giving zero, as beancount's parser does), and a price it leaves alone goes back exactly as written, @@ total included. A price the plugin replaces goes back as the per-unit price it holds.

Cache

WASM CACHE_VERSION 38 -> 39: Ledger runs the regular plugins and archives their errors, so a v38 blob of a ledger with a repeated note would serve no error. The loader cache archives parsed directives only, unchanged.

API

rustledger_ops::dedup::StructuralDuplicate::narration is replaced by summary; fingerprint::structural_key is new. Under ### Breaking in the CHANGELOG, since rledger check now fails on ledgers it passed.

How tested

  • Oracle, per directive type: 60 two-directive ledgers (one duplicate per type, plus near-copies differing in one hashed field, in metadata only, in tag/currency/value/posting order, scale, @@ vs @, total vs per-unit cost, payee "" vs none, account vs string custom values, event vs query). bean-check vs native: identical on all but the three documented divergences (event vs query; the two inexact @@/{{}} cases) and one interpolation-scale case (2.5 HOOL @@ 10 USD vs 2.5 HOOL @ 4 USD: rledger interpolates the first cash leg as -10 and the second as -10.0, beancount both as -10.0; a pre-existing interpolation difference, not this plugin's).
  • Oracle sweep: every repo ledger and the 742-file compat corpus (1,071 files), each wrapped with plugin "beancount.plugins.noduplicates": bean-check finds 302 duplicates in 56 files, and native agrees on all but 3 files, each explained by a pre-existing difference elsewhere: two lima lexer-error fixtures (beancount drops a transaction with a bad posting line, rledger keeps its good postings), tests_lots (rledger books {{9.00 GBP}} on 10.00 units at 0.90, beancount at 0.9, so one more pair matches), and the oklink export (rledger does not parse its *-masked account names, 16k parse errors).
  • Python compat, real plugin: beancount's own noduplicates.py (copied from the beancount 3 wheel, not committed) run by rledger on the same 60 ledgers agrees with bean-check except for the compat layer's CostSpec shape (see follow-ups); before the compat fix every ledger with an event, query or price failed with a serialization error.
  • New tests (each fails without the fix: the source changes reverted with git apply -R, tests kept):
    • plugin_conformance::noduplicates_compares_every_directive_type: a ledger with a copy of every type and near-copies; native reports exactly bean-check's 12 lines, and beancount's plugin logic in the compat layer reports the same lines. Failed: the reported lines did not match.
    • plugin_conformance::python_compat_reads_events_queries_and_prices: a plugin sees event location=Paris; query cash=SELECT account; price 5.00 USD; price 4 USD; price 3.333333333333333333333333333 USD, and the postings come back identical to the ledger without the plugin (JSON, to the digit). Failed (serialization error).
    • native_plugins_test: test_noduplicates_reordered_postings_are_duplicates, test_noduplicates_total_price_is_its_per_unit_price, test_noduplicates_compares_non_transaction_directives (three tests that asserted the old behavior, flipped to bean-check's answers). All three failed.
    • rustledger-ops unit tests for every type, metadata, dates, sets vs multisets, custom value types, open/balance fields, @@, booked total cost. These use the new API, so without the fix they do not compile.
  • cargo test for rustledger-ops (132 lib), rustledger-plugin (all suites), rustledger-wasm (153), and plugin_conformance + python_plugin_wasi with RLEDGER_REQUIRE_PYTHON_WASI=1; workspace clippy --all-features --all-targets -D warnings; release-config clippy (--no-default-features --features mimalloc,ag-rledger); cargo doc -D warnings for the changed crates.

Follow-ups (not in this PR)

  • The Python compat layer presents a booked posting's cost as CostSpec(number_per, number_total, ...) where beancount presents Cost(number, ...), so beancount's plugin under rledger does not take 2 X {{10 USD}} and 2 X {5 USD} for duplicates as bean-check does.
  • rledger books a total cost's per-unit number at rust_decimal's scale (9.00 / 10.00 is 0.90), beancount at Python's (0.9).

Closes #2599

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…t's does

The native `noduplicates` compared only transactions, so a repeated open,
close, commodity, pad, balance, note, document, event, query or custom
passed where bean-check reports it. It now compares every type but price
on the fields beancount hashes, metadata excluded, by an exact byte key
(`fingerprint::structural_key`) rather than a 64-bit digest. Like
beancount, a transaction's postings are a multiset, and a total price or
booked total cost is compared as the per-unit number it stands for when
that number multiplies back to it exactly.

Comparing against beancount's own plugin under the Python compat layer
found that the layer read prices, events and queries under the wrong wire
fields: every price was Amount(None, None), and returning any such entry
failed the whole plugin. Fixed, with `@@` presented per unit and an
untouched price returned as written.

WASM CACHE_VERSION 38 -> 39: `Ledger` archives plugin errors.

Closes #2599

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner October 11, 2026 17:38
@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 35.3ms ± 0.5ms 579.1ms ± 5.7ms 16.4x 51.6 MB / 50.0 MB
investment 55.4ms ± 0.5ms 2181.5ms ± 17.2ms 39.4x 57.5 MB / 58.2 MB
fifo 55.1ms ± 0.4ms 12215.4ms ± 56.5ms 221.8x 59.6 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 35.8ms ± 2.4ms 35.3ms ± 0.5ms -1.3% ✅ within noise 51.5 MB → 51.6 MB (+0.1%)
investment 55.6ms ± 0.5ms 55.4ms ± 0.5ms -0.3% ✅ within noise 57.4 MB → 57.5 MB (+0.2%)
fifo 55.7ms ± 1.1ms 55.1ms ± 0.4ms -1.1% ✅ within noise 57.6 MB → 59.6 MB (+3.4%)

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

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 819
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

@codecov

codecov Bot commented Oct 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...tledger-plugin/src/native/plugins/no_duplicates.rs 0.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

…plicates

Beancount's parser writes `0 X @@ 10 USD` as `0 X @ 0 USD`, so its
noduplicates takes the two postings for one (bean-check reports the
duplicate), and the Python compat layer already presents the price that
way. The native key left a zero-unit total price as written, so the pair
passed. Review round 1.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

Copy link
Copy Markdown
Member Author

Review rounds (#2599)

Round Head reviewed Checks Findings Fix
1 03046eb Re-read structural_key, the posting and price normalization, and the compat layer's price parsing against beancount 3.2.3's compare.stable_hash_namedtuple and grammar.py. Lists are hashed as sorted multisets of element hashes, meta and diff_amount are ignored, and prices are exempt: the PR matches all of this. A zero-unit total price kept its @@ form (LOW). beancount's parser writes 0 X @@ 10 USD as 0 X @ 0 USD (ZERO if units.number == ZERO else ...), so bean-check reports two such transactions as duplicates, and the compat layer already presents the price that way. The native key left the price as written, so the pair passed. It is now the per-unit 0 (ZERO's scale; @ 0.00 still differs, as in beancount). The unit test that asserted the old behavior is flipped, and it fails without the fix. 947389f
2 947389f Read the round-1 change; reviewed dedup.rs, whose only caller is the plugin; checked that the persisted import Fingerprint is untouched (structural_hash is in-process only). Probes: zero-unit pairs @ 0 and @ 0.00, compared against bean-check (1/1 and 0/0). The 61 per-type oracle cases give the same verdicts as before. Re-ran the native side of the 1,071-file corpus sweep with the new binary: the only change is the oklink export, which the first sweep had timed out at 60 s (the old binary also reports 37 there, in 10 s). Those 37 are real repeated transactions, differing only in txHash metadata, that bean-check's lexer drops along with the transactions' *-masked account names. So it remains the documented parse difference, and the four disagreeing files are the ones the PR body lists. Suites: ops+plugin 551, plugin_conformance 46, python_plugin_wasi 7, 0 failed; workspace clippy is clean. none —
3 947389f Re-read the CHANGELOG entries and docs/reference/plugins.md (no {{; the divergences are stated). Required checks are green on 947389f. rustfava is at the expected 8 failed, 671 passed. Slim Build (sccache infra) and SemVer (plugin-types), a crate this PR does not touch, also fail on main. none —

Merge note: #2611 also bumps the WASM CACHE_VERSION from 38 to 39. Whichever of the two merges second must bump to 40.

…directives

# Conflicts:
#	CHANGELOG.md
#	crates/rustledger-wasm/src/cache.rs
…directives

# Conflicts:
#	CHANGELOG.md
#	crates/rustledger-wasm/src/cache.rs
@robcohen robcohen closed this Oct 12, 2026
@robcohen robcohen reopened this Oct 12, 2026
…directives

# Conflicts:
#	CHANGELOG.md
#	crates/rustledger-wasm/src/cache.rs
@robcohen
robcohen merged commit 67d9dd1 into main Oct 12, 2026
57 of 59 checks passed
@robcohen
robcohen deleted the fix/noduplicates-all-directives branch October 12, 2026 20:33
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.

noduplicates: native plugin compares only transactions; beancount compares every directive

1 participant