Skip to content

fix(plugin): hash links/tags/flag/cost/price in noduplicates - #747

Merged
robcohen merged 6 commits into
mainfrom
fix/issue-746-noduplicates-links
Apr 10, 2026
Merged

robcohen merged 6 commits into
mainfrom
fix/issue-746-noduplicates-links

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

The noduplicates native plugin was hashing only (date, narration, payee, postings.account, postings.units) for duplicate detection. Python beancount's reference implementation uses beancount.core.compare.hash_entry, which hashes every field that contributes to a transaction's structural identity: flag, payee, narration, tags, links, and every posting's account, units, cost, price, and flag.

The practical effect: the idiomatic beancount pattern for disambiguating legitimate same-day identical postings — attaching a unique ^link to each — was broken. Real-world bank-statement importers hit this immediately when a day legitimately contains two $100 ATM withdrawals or identical wire-transfer fees. On the reporter's ledger, bean-check passes but rledger check reported 16 false-positive "Duplicate transaction" errors, all of which were genuine distinct postings disambiguated by links.

Closes #746.

Fix

crates/rustledger-plugin/src/native/plugins/no_duplicates.rs:

  • hash_transaction now folds in flag, tags, and links. Tags and links are sorted before hashing because beancount models them as unordered sets (frozenset), so the hash must be stable regardless of the order the parser emitted them.
  • New hash_posting helper hashes cost, price, and posting flag alongside account/units. Sentinel bytes (0u8 / 1u8) discriminate None from Some so adjacent optional fields can't collide across cases.
  • New hash_cost and hash_price helpers walk the inner structures field-by-field.
  • Metadata is intentionally still NOT hashed — this matches beancount's hash_entry, which passes exclude_meta=True from hash_entries (the function the plugin calls).

Before / After

Exact reproducer from the issue:

option "operating_currency" "USD"

plugin "beancount.plugins.noduplicates"

2024-01-01 open Assets:Checking:Test USD
2024-01-01 open Expenses:ATM          USD

2024-06-11 * "ATM Withdrawal" ^stmt-2024-06-seq1
  Assets:Checking:Test  -100.00 USD
  Expenses:ATM

2024-06-11 * "ATM Withdrawal" ^stmt-2024-06-seq2
  Assets:Checking:Test  -100.00 USD
  Expenses:ATM

Before: Error: Duplicate transaction: 2024-06-11 "ATM Withdrawal", exit 1.
After: ✓ No errors found, exit 0 — matches bean-check.

Test plan

  • test_noduplicates_distinct_links_are_not_duplicates — exact issue reproducer at the plugin level.
  • test_noduplicates_distinct_tags_are_not_duplicates — tags also disambiguate.
  • test_noduplicates_tag_order_independent — reordered tag sets hash equal (verifies the canonical sort).
  • test_noduplicates_distinct_flags_are_not_duplicates — * vs ! disambiguate.
  • Existing test_noduplicates_transaction and test_noduplicates_ok_different_amounts still pass.
  • End-to-end: rledger check on the exact issue reproducer returns exit 0.
  • Full cargo test --all-features — all tests pass.
  • cargo clippy --all-features --all-targets -- -D warnings clean.
  • cargo fmt --all -- --check clean.

Reference

Python beancount's beancount.core.compare.hash_entry computes a stable hash from flag, payee, narration, tags (as frozenset), links (as frozenset), and every posting's (account, units, cost, price, flag) — and excludes meta by default for the noduplicates plugin path.

Closes #746

🤖 Generated with Claude Code

@robcohen
robcohen requested a review from a team as a code owner April 10, 2026 13:50
Copilot AI review requested due to automatic review settings April 10, 2026 13:50
@codecov

codecov Bot commented Apr 10, 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

github-actions Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 40.7ms ± 3.1ms 23.3 MB
beancount 888.8ms ± 5.9ms 50.5 MB
Comparison 21.8x faster 2.2x less

vs main branch (2026-04-10)

Metric main this PR Change
Time 45.8ms 40.7ms -11.1% 🟢
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

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

Updates the native noduplicates plugin’s transaction hashing to better match beancount’s hash_entry, preventing false-positive duplicates for transactions disambiguated by links/tags/flags and richer posting identity fields.

Changes:

  • Expand duplicate-hash inputs to include transaction flag, tags, links, and posting cost/price/flag (plus helpers for hashing nested structures).
  • Canonicalize tag/link order before hashing to make results order-independent.
  • Add regression tests covering links, tags (including order-independence), and flag-based disambiguation.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

File Description
crates/rustledger-plugin/src/native/plugins/no_duplicates.rs Extends and refactors hashing logic for duplicate detection to include additional identity fields.
crates/rustledger-plugin/tests/native_plugins_test.rs Adds regression tests validating link/tag/flag behavior for duplicate detection.

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

@github-actions

github-actions Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 99%
BQL Compatibility 100%
Full AST Match 98%
Total Files 784
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 and others added 4 commits April 10, 2026 09:15
Mirrors Python beancount's beancount.plugins.noduplicates, which hashes
a transaction's full structural identity via beancount.core.compare.
hash_entry: flag, payee, narration, tags, links, and every posting
(account, units, cost, price, flag). The Rust implementation was only
hashing date, narration, payee, and posting account/units, so any two
transactions that differed only on flag / tags / links / cost / price
were flagged as duplicates — diverging from bean-check.

The practical effect was that the idiomatic beancount pattern for
disambiguating legitimate same-day identical postings — attaching a
unique ^link to each — was broken. Real-world bank statement importers
hit this immediately when a single day has multiple $100 ATM
withdrawals or identical wire-transfer fees.

Changes:

- hash_transaction now folds in flag, tags, and links (tags and links
  sorted for stability since they are unordered sets in beancount).
- hash_posting helper hashes cost, price, and posting flag alongside
  account and units, with sentinel bytes discriminating None from Some
  so adjacent optional fields don't collide across cases.
- Metadata is intentionally still NOT hashed: hash_entry defaults to
  exclude_meta=True for the noduplicates plugin.

Tests (crates/rustledger-plugin/tests/native_plugins_test.rs):

- test_noduplicates_distinct_links_are_not_duplicates: exact issue
  reproducer at the plugin level (two identical ATM withdrawals, only
  the ^link differs).
- test_noduplicates_distinct_tags_are_not_duplicates: tags also
  disambiguate.
- test_noduplicates_tag_order_independent: reordered tag sets hash
  equal (verifies the canonical sort).
- test_noduplicates_distinct_flags_are_not_duplicates: * vs ! hashes
  differently.
- Existing test_noduplicates_transaction and
  test_noduplicates_ok_different_amounts still pass.

Closes #746

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Deep-review follow-ups on the noduplicates fix:

1. hash_posting now uses a sentinel byte (0u8 vs 1u8) for posting.units
   for consistency with the existing cost/price handling. The previous
   approach silently appended nothing for None units, which in theory
   could collide with adjacent Some-case byte sequences (negligible in
   practice, but inconsistent with Python beancount where None always
   contributes a fixed value to the tuple hash).

2. New test_noduplicates_distinct_costs_are_not_duplicates — pins that
   posting cost is part of structural identity.

3. New test_noduplicates_distinct_prices_are_not_duplicates — pins that
   posting price is part of structural identity.

4. New test_noduplicates_metadata_differences_are_still_duplicates —
   pins that metadata is intentionally NOT hashed, matching
   beancount's hash_entry(exclude_meta=True) default. This guards
   against a future change that adds metadata to the hash and
   surprises users.

All nine noduplicates tests pass, along with the full workspace test
suite, clippy --all-features --all-targets, and cargo fmt --check.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Second deep-review follow-up: the hand-written hash functions for
TransactionData / PostingData / CostData / PriceAnnotationData /
AmountData implicitly depended on the current field list. If a
maintainer adds a new field — say, `external_id` — the hash would
silently ignore it and diverge from beancount's hash_entry without
any warning.

Switch each helper to an exhaustive destructuring pattern so adding
a field anywhere along the transaction path causes a compile error
in no_duplicates.rs, forcing whoever adds the field to explicitly
decide:
  - Add it to the hash (contributes to structural identity), or
  - Bind it with `_` (and document why it's excluded, matching the
    precedent set by `metadata: _`).

Also factor out:
- Named `ABSENT` / `PRESENT` constants for the None/Some sentinel
  bytes, replacing the unlabeled `0u8` / `1u8` magic numbers.
- `hash_amount` helper so units and price both delegate to the same
  amount-hashing path.

No behavior change — the existing 9 noduplicates tests all still
pass, clippy and fmt clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… hash

Copilot review flagged two correctness issues in the set-hashing path:

1. Set multiplicity: tags and links are beancount `frozenset`s, but
   the previous sort-only approach preserved duplicates. A parser that
   happened to emit `[#a #a]` would hash differently from `[#a]` even
   though beancount treats them as the same set. Now dedup after sort
   so duplicate Vec entries collapse to a single set member.

2. Collision between tag and link streams: the previous code hashed
   sorted tags followed by sorted links with no boundary. That meant
   `tags={a,b}, links={}` hashed identically to `tags={a}, links={b}`
   because both produce the byte stream "a", "b". Prefix each set
   with its length before hashing so the two streams can't be merged
   or swapped without changing the resulting hash. The postings loop
   also gets a length prefix for the same reason.

New regression tests:

- test_noduplicates_duplicate_tags_collapse_to_set — pins that
  `[morning, morning]` hashes equal to `[morning]`.
- test_noduplicates_tag_link_boundary_no_collision — pins that
  `tags={a,b}, links={}` does NOT collide with `tags={a},
  links={b}`.

All 11 noduplicates tests pass, clippy and fmt clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@robcohen
robcohen force-pushed the fix/issue-746-noduplicates-links branch from 464b449 to 31bd1aa Compare April 10, 2026 14:16
@robcohen
robcohen enabled auto-merge April 10, 2026 14:17
robcohen and others added 2 commits April 10, 2026 09:24
Grow the noduplicates test suite from 11 to 33 tests to pin the full
beancount hash_entry contract, every branch of the hash helpers, and
known structural pitfalls. Grouped into:

Transaction-level identity (6 new):
- distinct_dates
- distinct_narration
- distinct_payees
- none_vs_empty_payee (None is not equal to Some(""))
- link_order_independent (matches the existing tag order test)
- empty_vs_absent_tags (frozenset() == frozenset([]))

Posting-level identity (11 new):
- distinct_accounts
- distinct_posting_count
- reordered_postings (postings are ordered in beancount, order matters)
- none_vs_some_units (auto-balancing None differs from explicit units)
- cost_with_date_differs
- cost_with_label_differs
- total_vs_per_unit_cost
- unit_vs_total_price (@ vs @@)
- incomplete_vs_complete_price (currency-only vs full Amount)
- distinct_posting_flags
- posting_metadata_does_not_disambiguate (excludes posting-level meta)

Multi-transaction & structural (5 new):
- three_identical_reports_two_duplicates
- ignores_non_transaction_directives (duplicate Opens don't count)
- empty_postings_edge_case (transactions with zero postings)
- detects_duplicates_across_distance (50 unrelated txns between dupes)
- source_location_not_part_of_identity (filename/lineno excluded)

New `make_txn_with` test helper takes a mutation closure so each
"identical to baseline except for X" test fits in one expression.

All 33 noduplicates tests pass, full workspace test suite still
passes, clippy --all-features --all-targets clean, cargo fmt clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Two items_after_statements violations where I put a `use` after `let
plugin = ...` inside test functions, and two doc_markdown violations
where `frozenset()` and `HashSet` were missing backticks in doc
comments.

Verified with RUSTFLAGS="-Dwarnings" cargo clippy --all-features
--all-targets -- -D warnings, matching the CI invocation.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@robcohen
robcohen added this pull request to the merge queue Apr 10, 2026
Merged via the queue into main with commit 2d3264e Apr 10, 2026
28 of 33 checks passed
@robcohen
robcohen deleted the fix/issue-746-noduplicates-links branch April 10, 2026 14:46
robcohen added a commit that referenced this pull request Apr 11, 2026
Bumps the whole workspace from 0.11.0 to 0.12.0 (minor version bump
under pre-1.0 semver because the cycle since 0.11.0 includes
user-visible breaking changes that release-plz's auto-detection
missed).

release-plz auto-generated a v0.11.1 patch bump from the `fix:` /
`feat:` commits since 0.11.0. That's too conservative. The cycle
since 0.11.0 shipped the following breaking changes, all merged as
`refactor:` / `fix:` without the `!` conventional-commit marker:

- **`rustledger_booking::BookingError`** collapsed three variants
  (`InsufficientUnits`, `NoMatchingLot`, `AmbiguousMatch`) into a
  single `Inventory(AccountedBookingError)` variant (#751). Out-of-tree
  consumers pattern-matching on the old variants break.

- **`rustledger_core::AccountedBookingError`** added as a new
  canonical user-facing type with `BookingError::with_account()` as
  the constructor (#751). Not a break on its own, but part of the
  unification.

- **`rustledger_lsp::handlers::diagnostics::all_diagnostics`**
  signature changed to take an additional `other_buffer_overlays:
  &[(u16, &[Spanned<Directive>])]` parameter for multi-buffer LSP
  overlays (#760 / #764).

- **`rustledger_lsp::handlers::diagnostics::validation_errors_to_diagnostics`**
  signature changed to take an owned `Vec<Spanned<Directive>>`
  instead of borrowed slices (#758). Optimizes a hot path but breaks
  the function's public signature.

- **`rustledger_loader::LoadError::IncludeCycle`** Display format
  rewritten to match Python beancount's `"Duplicate filename
  parsed: ..."` wording (#767). Substring-matching consumers break.

Under pre-1.0 semver, any breaking change should bump the minor
version (0.x → 0.(x+1)). So 0.11.0 → 0.12.0 is correct.

Highlights since 0.11.0:

### Breaking

- Unified `BookingError` under a single `Inventory` variant with one
  canonical `Display` impl, preventing the wording drift that
  produced #748 (#751).
- `LoadError::IncludeCycle` Display now begins with `"Duplicate
  filename parsed: "` to match beancount's wording for conformance
  (#767).
- LSP `all_diagnostics` and `validation_errors_to_diagnostics`
  signatures changed to support the multi-buffer overlay and avoid
  double-cloning directive lists (#758 / #764).

### Features

- LSP live overlay so in-memory buffer edits reflect in diagnostics
  before save, for both the current file (#685 / #758) and any other
  open buffer in a multi-file ledger (#760 / #764).
- Parser `Vec::with_capacity` hints with DoS caps on `source.len()`
  heuristics (#754).
- `working_inventories` cloning in the booking engine now only
  touches accounts actually referenced in the transaction, and
  dedupes repeated account references (#756).

### Fixes

- `InsufficientUnits` booking error wording restored to `"Not enough
  units in ..."` so pta-standards `reduction-exceeds-inventory`
  conformance assertion passes (#748 / #749).
- `noduplicates` plugin now hashes flag, tags, links, cost, and
  price in addition to date and narration — complete beancount
  `hash_entry` parity (#746 / #747).
- Parser test suite: 14 fake-coverage tests replaced with real tests
  that exercise the functions they claim to cover (#766).
- All Copilot inline review comments on #754-#763, #766, #767
  addressed in fix commits.
- Closed PRs #768 (dead incremental parser) and #769 (hallucinated
  simdutf8 API) — no code shipped from these.

### Internal

- Forbid-unsafe-code invariant now has a dedicated CI check and
  pre-push hook (#770).
- New pre-push `cargo check` hook to catch compile errors before PRs
  are opened (#770).

This commit supersedes release-plz's auto-generated v0.11.1 proposal
to produce the minor bump the breaking changes require.

Co-Authored-By: Claude Opus 4.6 (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.

noduplicates plugin doesn't hash transaction links, diverging from beancount reference

2 participants