Repository navigation
fix(plugin): hash links/tags/flag/cost/price in noduplicates - #747
Merged
Merged
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs main branch (2026-04-10)
What do these numbers mean?
|
Contributor
There was a problem hiding this comment.
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.
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
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
force-pushed
the
fix/issue-746-noduplicates-links
branch
from
April 10, 2026 14:16
464b449 to
31bd1aa
Compare
robcohen
enabled auto-merge
April 10, 2026 14:17
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
added this pull request to the merge queue
Apr 10, 2026
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The
noduplicatesnative plugin was hashing only(date, narration, payee, postings.account, postings.units)for duplicate detection. Python beancount's reference implementation usesbeancount.core.compare.hash_entry, which hashes every field that contributes to a transaction's structural identity:flag,payee,narration,tags,links, and every posting'saccount,units,cost,price, andflag.The practical effect: the idiomatic beancount pattern for disambiguating legitimate same-day identical postings — attaching a unique
^linkto each — was broken. Real-world bank-statement importers hit this immediately when a day legitimately contains two$100ATM withdrawals or identical wire-transfer fees. On the reporter's ledger,bean-checkpasses butrledger checkreported 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_transactionnow folds inflag,tags, andlinks. 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.hash_postinghelper hashescost,price, and postingflagalongside account/units. Sentinel bytes (0u8/1u8) discriminateNonefromSomeso adjacent optional fields can't collide across cases.hash_costandhash_pricehelpers walk the inner structures field-by-field.hash_entry, which passesexclude_meta=Truefromhash_entries(the function the plugin calls).Before / After
Exact reproducer from the issue:
Before:
Error: Duplicate transaction: 2024-06-11 "ATM Withdrawal", exit 1.After:
✓ No errors found, exit 0 — matchesbean-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.test_noduplicates_transactionandtest_noduplicates_ok_different_amountsstill pass.rledger checkon the exact issue reproducer returns exit 0.cargo test --all-features— all tests pass.cargo clippy --all-features --all-targets -- -D warningsclean.cargo fmt --all -- --checkclean.Reference
Python beancount's
beancount.core.compare.hash_entrycomputes a stable hash fromflag,payee,narration,tags(asfrozenset),links(asfrozenset), and every posting's(account, units, cost, price, flag)— and excludesmetaby default for the noduplicates plugin path.Closes #746
🤖 Generated with Claude Code