Skip to content

fix(extract): dedup against --existing as a scoped multiset with id links - #2495

Merged
robcohen merged 13 commits into
mainfrom
fix/extract-dedup-multiset
Oct 8, 2026
Merged

robcohen merged 13 commits into
mainfrom
fix/extract-dedup-multiset

Conversation

@robcohen

@robcohen robcohen commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

What changed

rledger extract --existing now uses a new matcher, rustledger_ops::dedup::find_import_duplicates, in place of the per-row is_duplicate check. The CSV importer also gains a transaction_id_column.

Correctness (#2421)

Before After
Existing transactions were a set: one existing croissant suppressed every identical croissant on the statement Existing transactions are a multiset: each absorbs at most one new row
Compared the first posting's number only, so other accounts and currencies matched Compares the posting on the importer's account, its commodity and amount. An existing transaction that never touches the account is not a candidate
Ignored ^ofx-<FITID> links A shared id link (^ofx-…, ^csv-…) with the same account, commodity and amount is a duplicate whatever the date or text say. The amount check stops a sanitizer collision (a b and a:b both become csv-a-b) from dropping a different transaction. Different ids in the same namespace mean two transactions, however alike they look. When only one side has an id (a ledger imported before ids existed), the text decides. Namespaces are separate, so an OFX id and a CSV id never contradict each other
Greedy, order-dependent Three passes, strongest evidence first: id link, then identical text, then similar text. A weak match cannot claim an existing entry that a stronger one needed
Only the first posting was compared A ledger entry that splits the account's leg over several postings is also matched on its net movement per commodity. A transfer already booked from the other account's statement is recognized as a duplicate, because it already records this account's leg; main re-imported it. A new row that never posts to the configured account (a WASM importer may post elsewhere) falls back to the first-posting key instead of escaping dedup
Filtered N duplicate transaction(s) Skips are counted by kind on stderr, and up to 20 of each kind are listed with their reason and the existing entry they matched (... and N more for the rest). A partly broken --existing ledger gets a warning

The #2421 reproduction, on main and on this branch:

main:   pair.csv vs 1 existing -> 0 written ("Filtered 2"); other account/currency -> 0 written
branch: pair.csv vs 1 existing -> 1 written; other account/currency -> 1 written
Filtered 1 duplicate transaction(s) already in the existing ledger (0 by id link, 1 by date, amount and text):
  skipped 2024-01-15 "Bakery" "Croissant" -2.50 EUR (same date, amount and text; existing: 2024-01-15 "Bakery" "Croissant" -2.50 EUR)

Performance (#2422)

Existing keys are computed once and bucketed by (date, account, commodity, normalized amount). Id links go in their own index. Text is compared only within a bucket.

Synthetic input: 50,000 CSV rows against a 50,000-transaction ledger on 336 shared dates (generator in the session scratch dir), release builds. The final numbers below were measured at this PR's final head, on an idle machine:

main this branch
extract, no --existing 0.46 s 0.43 s
--existing, 8 accidental dups 101 s (550–804 s on a loaded machine) 0.76 s
--existing, every row a duplicate — 0.37 s (50,000 skipped)
200k × 200k not run (quadratic) 3.6 s

Both binaries write byte-identical output for the 50k × 50k run.

CSV transaction ids (#2387)

transaction_id_column = "Transaction ID" in an importers.toml entry adds ^csv-<id> to each transaction. It goes through the same sanitizer as OFX's ^ofx-<FITID>, which now lives in rustledger_ops::dedup::id_link next to the prefixes dedup recognizes, so the convention has one source. A blank cell adds no link. Misconfiguration fails once, up front, with a message naming the key: a column the file lacks (with a hint for a case or whitespace near-miss), an index past the last column, or a column the importer already reads as amount_column, date_column and so on. Ids that repeat within one statement get a warning. It is documented in docs/commands/extract.md and docs/guides/importing.md. I added no CLI flag, since the issue asks for the config key.

API / component

  • rustledger_ops::dedup::is_duplicate is removed. A per-transaction "does it match any?" check is the set semantics that caused extract --existing silently drops legitimate repeated transactions (ignores multiplicity, account, currency and ids) #2421. find_fuzzy_duplicates keeps its signature and now runs the same matcher unscoped (first posting's account + commodity + amount, multiset, id links).
  • The component's session.dedup uses find_fuzzy_duplicates, so its verdicts change in the same way. Because that is a contract change, the component moves to 3.13.0 (world.wit package plus API_VERSION). This follows fix(loader)!: read account-name options as leaves under a root, as beancount does #2415, which bumped for a purely semantic change. The WIT doc says what changed, and the CHANGELOG lists it under Breaking. The only consumers are this repo's parity tests: rustfava deduplicates through beangulp's importer.deduplicate, not session.dedup, and the MCP server does not call it.
  • ImporterEntry and CsvConfig gained a transaction_id_column field.
  • The fuzz lockfiles (rustledger-ffi-wasi/fuzz, rustledger-loader/fuzz) are refreshed for the new rustc-hash dependency of rustledger-ops. They also pick up bigdecimal/smallvec entries that were already missing on main.

Decisions (approved by @robcohen)

  • Identical empty text is a match. Such a skip is flagged on stderr; see below.
  • An id link matches only together with the same account, commodity and amount, on any date.
  • A transfer already imported from the other account's statement is a duplicate.
  • The component contract moves to 3.13.0 because session.dedup semantics change.
  • rustledger_ops::dedup::is_duplicate is removed, not deprecated.

Identical empty text is a match

If neither the new row nor the existing entry has a payee or narration, they match on account, commodity, date and amount alone. Without this, a statement with no description column is duplicated in full on every re-import, which is what main does. The cost is that two genuinely different description-less rows on one day for one amount, with one already booked, import as one.

Each such skip is reported as AmountOnly, counted separately in the summary and flagged on its own stderr line. The report lists at most 20 rows of each kind (ordinary skips and flagged skips) and counts the rest. A full 50k re-import prints 22 lines instead of 50,000:

Filtered 1 duplicate transaction(s) already in the existing ledger (0 by id link, 0 by date, amount and text, 1 by date and amount alone):
  skipped 2024-01-15 "" -60.00 EUR (same date and amount, and neither has a payee or narration to compare; existing: 2024-01-15 "" -60.00 EUR) -- check: nothing but the date and amount ties these together

A row with text on only one side is never a match.

Scaling and memory

Release builds, load average about 3–9, synthetic input with 336 distinct dates (measured in review pass 3; pass 8 reproduced these to within ±0.03 s):

--existing time peak RSS without --existing
main, 50k × 50k 130 s 207 MB 0.46 s / 195 MB
branch, 50k × 50k 0.73 s 214 MB 0.43 s / 198 MB
branch, 200k × 200k 3.64 s 782 MB 1.97 s / 757 MB

At 4× the input, the dedup work (the time on top of extract alone) grows from about 0.3 s to 1.7 s, roughly 5.5×. That is near-linear: the sort is n log n, and buckets get bigger because the date count is fixed at 336. Memory on top of extract is +16 MB at 50k and +25 MB at 200k. main at 200k × 200k would take hours, since it is quadratic, so I did not run it.

Text matching vs main

The text rules are unchanged from main, apart from empty text and the order independence above. I ran both binaries on these cases and their verdicts were identical:

  • case differences
  • runs of whitespace
  • trailing punctuation
  • bank reference suffixes (COFFEE SHOP 1234 vs Coffee Shop)
  • non-ASCII payees
  • a fully rewritten payee, which is kept by both

Text is not Unicode-normalized, so an NFD é differs from an NFC é. That gap exists in main as well. Its failure mode is a visible duplicate, not a silent drop. It is documented in the guide, and I'm proposing a follow-up for it because the fix needs a new dependency (unicode-normalization).

How tested

All counts are at the final head, run on a target dir used only by this worktree.

  • cargo test -p rustledger-ops -p rustledger-importer -p rustledger-ffi-component -p rustledger --all-features: 1317 tests pass across 40 test binaries, including the doctests.

  • Property tests in crates/rustledger-ops/tests/import_dedup_properties.rs:

    • re-importing a statement adds zero rows;
    • drops never exceed the existing entries;
    • permuting either side keeps the same rows;
    • a half-then-whole import is idempotent.

    They found two bugs, both now fixed: a statement with no description column re-imported every row, and file order decided which row survived the fuzzy pass.

  • Gated parity suite against a freshly built debug wasip2 component: 27 tests pass. The component's own test asserts each session.dedup claim in the WIT doc.

  • Fail without the fix: I ran 18 mutations covering every rule in this PR through a harness. For each one it asserts the exact replacement count, checks the file changed, requires Compiling lines as proof of a rebuild, totals every test result: line, and restores the files byte for byte. Every mutation applied and failed at least one test. The baseline is 892 tests with 0 failed; per mutation, between 1 and 10 tests fail. The full table is in the review comment.

  • cargo clippy --workspace --all-features --all-targets -D warnings and cargo doc -D warnings for the changed crates are clean.

Merging

#2497 has merged into main, and main is merged into this branch. This PR and #2498 merge in either order. The only conflict is in CHANGELOG.md, where both add a bullet at the top of the same section; keep both. On the combined tree, a CSV entry with no currency takes EUR from the open directive, and dedup compares in EUR. #2498's the_resolved_currency_is_what_dedup_compares checks this: it fails on the combined tree when the old USD fallback is restored.

Closes #2421
Closes #2422
Closes #2387

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…inks

`extract --existing` treated the existing ledger as a set: one existing
transaction suppressed every identical new row, so two identical
purchases on one day lost one silently. It compared only the first
posting's number, so other accounts and currencies matched, and it
ignored the `^ofx-` id links the OFX importer emits.

`rustledger_ops::dedup::find_import_duplicates` replaces the per-row
`is_duplicate`:

- existing transactions are a multiset; each absorbs at most one new row
- matching is scoped to the importer's account posting and its commodity
- a shared `^ofx-`/`^csv-` id link is decisive; different ids in one
  namespace mean two transactions
- passes run id, then exact text, then fuzzy text, so weak evidence
  cannot claim an entry strong evidence needed
- existing keys are computed once and bucketed by date, account,
  commodity and amount: 50k x 50k goes from 550-804 s to 1.6 s

The CLI lists every skipped row on stderr with its reason.

The CSV importer gains `transaction_id_column`, emitting `^csv-<id>`
links through the same sanitizer as OFX FITIDs (now shared in ops).

Closes #2421
Closes #2422
Closes #2387

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 7, 2026 20:39
@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 46.7ms ± 3.5ms 853.0ms ± 3.8ms 18.3x 51.1 MB / 50.1 MB
investment 73.0ms ± 0.9ms 3127.2ms ± 55.2ms 42.8x 55.1 MB / 58.1 MB
fifo 70.8ms ± 2.7ms 15686.4ms ± 160.5ms 221.7x 55.0 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 45.7ms ± 0.5ms 46.7ms ± 3.5ms +2.2% ✅ within noise 51.3 MB → 51.1 MB (-0.4%)
investment 73.1ms ± 1.5ms 73.0ms ± 0.9ms -0.1% ✅ within noise 55.3 MB → 55.1 MB (-0.4%)
fifo 69.9ms ± 1.1ms 70.8ms ± 2.7ms +1.3% ✅ within noise 55.0 MB → 55.0 MB (+0.1%)

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

github-actions Bot commented Oct 7, 2026 •

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 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.07031% with 15 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/extract_cmd/mod.rs 97.36% 7 Missing ⚠️
crates/rustledger-importer/src/config.rs 55.55% 4 Missing ⚠️
crates/rustledger-importer/src/csv_importer.rs 98.05% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

- An id link match now also needs the same account, commodity and
  amount: the sanitizer maps `a b` and `a:b` to one link, and such a
  collision must not drop a different transaction.
- A ledger entry that splits the account leg over several postings is
  matched on its net movement per commodity as well.
- A new transaction that never touches the importer account (a WASM
  importer may post elsewhere) falls back to the unscoped first-posting
  key instead of escaping dedup.
- Pin that a transfer already booked from the other account's statement
  is a duplicate (main compared the first posting and re-imported it).
- `session.dedup` semantics changed, so the component contract moves to
  3.13.0, following the #2415 precedent of bumping for a semantic change.
- Docs, roadmap and README describe the id-plus-amount rule.

Refs #2421

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

robcohen commented Oct 7, 2026 •

Copy link
Copy Markdown
Member Author

Current state (head f5b9e9b). This section is authoritative; the passes below are a chronological log

  • Tests: 1317 pass across 40 test binaries (ops, importer, ffi-component, rustledger, including the doctests). The parity suite passes (27 tests) against a fresh debug component. Clippy and rustdoc are clean.

  • Mutations: all 18 apply, trigger a rebuild, and fail at least one test (table in the seventh pass).

  • Performance, idle machine:

    Run Time
    50k × 50k 0.76 s (main: 101 s)
    full re-import, every row a duplicate 0.37 s
    200k × 200k 3.6 s

    Output is byte-identical to main.

  • Decisions, as approved by robcohen:

    • identical empty text is a match, and each such skip is flagged;
    • an id link matches only together with the same account, commodity and amount;
    • a transfer already imported from the other account's statement is a duplicate;
    • the WIT contract moves to 3.13.0;
    • is_duplicate is removed.

Numbers inside earlier passes (for example 1.6 s, 897 tests, the pass-1 mutation counts) describe the head as it was at that pass.

Ninth pass: PR body, this comment, stale comments, quoted strings

  • PR body. Several claims were stale:

    • "every skipped row is listed" (the report now lists at most 20 per kind);
    • the missing id column described as "a per-row error" (it now fails once, up front);
    • test counts from pass 1 (114/236/897);
    • the partial pass-1 mutation list;
    • the loaded-machine benchmark table.

    It now states the final head's behavior and numbers, and lists the decisions as approved.

  • Stale code comments, fixed in f5b9e9b. git grep over the workspace for is_duplicate, first_posting_amount, "first-posting amount", "fuzzy matcher" and "set semantics" found three:

    • the existing-ledger loader doc named first_posting_amount, a function that no longer exists;
    • the dedup module doc described an id-link match without the same-money condition;
    • the component's SessionState::dedup doc did the same.

    The other hits are unrelated (transfer.rs's own helper, query table docs).

  • Quoted strings. Every stderr string the docs quote (-- check: nothing but …, by date and amount alone, same date and amount, and neither …, same date, amount and text, ... and) exists in the code as quoted. The two full quoted blocks were checked byte for byte in pass 7.

Adversarial review pass

I ran release builds of main (184e9d1) and this branch against each scenario below, then decided which result is correct. All local verification was redone on a target dir used only by this worktree. A shared target dir can reuse another worktree's build, so earlier local runs did not count.

Scenario main branch (7deb25c) Correct
Existing entry splits the bank leg (-6.00 + -4.00) for one -10.00 row kept dropped (net movement) branch. Fixed in this pass
Transfer already booked from the savings statement; the checking row comes next kept, so the checking leg is double-counted dropped branch. main compared the first posting
Existing entry with the bank amount elided (interpolated by the loader) kept dropped branch
Importer account appears twice in one existing entry, and one leg matches dropped dropped same
Amount edited after import (-10.00 → -10.50) kept kept same; cannot know
Payee rewritten ("Hofer Dankt" → "Hofer"), same amount, 1 of 2 words shared dropped dropped same fuzzy rule, unchanged threshold
Date ±1 day kept kept same; main never allowed a window
--existing with open/pad/balance/price directives dropped dropped same; only transactions are candidates
Multi-currency rows (currency_column), USD and EUR rows vs one EUR entry both dropped EUR dropped, USD kept branch
Id collision: a:b (rent, -900) vs an existing ^csv-a-b (coffee, -4) n/a kept branch. Fixed in this pass: an id match also needs the same account, commodity and amount
Same id, re-posted a day later with a rewritten narration n/a dropped by id branch
A WASM importer row that never posts to the configured account deduplicated (first posting) was silently never deduplicated Fixed in this pass: it falls back to the unscoped first-posting key

Component. session.dedup verdicts change, so the contract now moves to 3.13.0 (world.wit package plus API_VERSION), following #2415, which bumped for a purely semantic change. The WIT Version Gate only requires a bump for non-comment changes; the gate passes with the bump. The only consumers are this repo's parity tests: rustfava deduplicates through beangulp's importer.deduplicate, and the MCP server does not call session.dedup.

is_duplicate removal. The crates.io reverse dependencies of rustledger-ops are rustledger, rustledger-ffi-wasi, rustledger-importer and rustledger-plugin, all in this workspace and released in lockstep. The crate is 0.x, and cargo-semver-checks runs only on rustledger-plugin-types. A deprecated per-row helper would keep the set semantics that caused #2421, so the function is removed rather than deprecated.

Lockfiles and bot commit. The fuzz lockfiles add rustc-hash for rustledger-ops, which is required, and also pick up bigdecimal/smallvec entries that were already stale on main, since a consistent lockfile needs them. The bot's f69264e swaps two cargo-vet exemptions (pkg-config, tracing-core) for imported bytecode-alliance/mozilla audits. That is upstream audit drift, not caused by this PR, and it tightens the policy.

Fail without fix. I checked each rule by mutating it on the isolated target; each mutation is restored afterwards:

  • no consumption: 3 ops tests and 2 CLI tests fail
  • first-posting key with no account or commodity: 4 ops tests and 1 CLI test fail
  • ids ignored: 2 ops tests and 1 CLI test fail
  • single fuzzy pass: 3 ops tests and 2 CLI tests fail
  • id match without the money check: 1 test fails
  • no net-leg key: 1 test fails
  • no fallback: 1 test fails
  • with_link removed: the CSV importer test fails

Results. 1297 tests pass across 39 binaries. The gated parity suite passes against a freshly built debug wasip2 component (27 tests, 420 s). 50k × 50k now runs in 0.76 s at load 9, with output byte-identical to main.

Second pass: cross-PR integration, properties, WIT, docs

Integration. I merged this PR together with #2497 and #2498 onto origin/main in five orders (A-B-C, A-C-B, B-A-C, C-B-A, C-A-B). Every order gives an identical tree, and the only conflicts are adjacent CHANGELOG.md bullets; keep both. The merge notes are in the PR body.

On the combined tree:

  • 1312 tests pass across 40 binaries.
  • Every scenario in the table above gives the same verdict.
  • A CSV entry with no currency takes EUR from the open, and dedup compares in EUR: an EUR duplicate already in the ledger is skipped, while a USD entry is not treated as a duplicate.

Property tests (crates/rustledger-ops/tests/import_dedup_properties.rs, 512 cases each, also run once at 20 000) found two real bugs, both fixed in 5dbd698:

  1. Re-importing a statement with no description column added every row again, because empty text never matched. Identical empty text now counts as identical. main has the same bug: it wrote both rows again.
  2. Which rows survived depended on file order. The fuzzy pass was greedy in input order, so with coffee and shop both matching one coffee shop entry, the first one listed was dropped. Rows are now visited, and candidates offered, in a canonical content order, so the kept set depends only on the contents of the statement and the ledger.

The four properties now hold:

  • re-importing the same statement adds zero rows;
  • drops never exceed the existing entries, and each one rests on the same money;
  • permuting either side keeps the same rows;
  • importing the first half of a statement and then the whole of it is idempotent.

Fail without the fix: restoring the empty-text guard fails 2 properties, and removing the canonical order fails the order property and a new unit test.

WIT 3.13.0. The bump is complete:

  • world.wit and API_VERSION move in lockstep; the parity suite asserts this and passes.
  • rustfava's _check_api_version checks the major version only (major != SUPPORTED_API_MAJOR), so it accepts 3.13. rustfava tests against PR component shows the known baseline of 5 failed / 674 passed.
  • Downstream paths cover the embedder passes.
  • The docs that cite a contract version say @3.0.0 (integration.md, architecture.md, ADR 0006). They were already stale through 3.12, and earlier bumps never updated them, so this PR leaves them alone.

Docs were re-read against the final behavior: an id match needs the same account, commodity and amount; split legs are compared by net movement; a transfer from the other statement is recognized; a WASM importer's row falls back to its first posting; empty text matches; order does not matter. I corrected importing.md ("id as identity" → id plus amount) and extract.md.

Everything above ran on per-worktree target dirs. 50k × 50k takes 0.92 s, with output byte-identical to main.

Third pass: text robustness, resources, the empty-text decision, code quality

Text robustness, main vs branch. I ran both binaries on these inputs, and the verdicts were identical in every case:

  • case (COFFEE SHOP / coffee shop)
  • runs of whitespace
  • trailing punctuation
  • bank reference suffixes (COFFEE SHOP 1234 + POS 998877 vs Coffee Shop + Morning latte, which match at the 50% word overlap)
  • non-ASCII upper/lower case (ÜBER CAFÉ)
  • a fully rewritten payee (AMZN MKTP US*2K3 vs Amazon), which both keep

The fuzzy rules are main's, apart from empty text and order independence. NFC vs NFD (é) is not normalized, on main or here, so such a pair re-imports as a visible duplicate rather than being dropped. The guide now documents this. I'm proposing a follow-up for it, because the fix needs a new dependency (unicode-normalization).

Resources (/usr/bin/time -v, release builds):

time peak RSS
main, 50k × 50k 130 s 207 MB
branch, 50k × 50k 0.73 s 214 MB
branch, 200k × 200k 3.64 s 782 MB

Extract alone takes 0.43 s / 198 MB at 50k and 1.97 s / 757 MB at 200k. At 4× the input, the dedup overhead grows from about 0.3 s to 1.7 s, which is near-linear. main is quadratic, so I did not run it at 200k.

Empty text. The risky case is two distinct description-less withdrawals on one day for one amount, with one already booked. It used to print same date, amount and text with empty quotes, which is easy to miss. It is now DuplicateReason::AmountOnly, counted separately ("1 by date and amount alone") and flagged on its own line with -- check: nothing but the date and amount ties these together. The PR body restates the decision.

Code quality

  • A split-leg net could overflow Decimal and panic. It now uses checked_add, with a test; that test fails when += is restored.
  • Sort ranks were rebuilt and allocated in every comparison. They are now borrowed and computed once per transaction.
  • ID_LINK_PREFIXES was made private: nothing outside the module uses it.
  • DuplicateReason is now #[non_exhaustive].
  • The id_link docs had gone stale after the id-plus-money rule; they are rewritten.
  • A new_keys helper was split out, so clippy::pedantic is clean for dedup.rs.
  • The report shows the first posting for a row that was matched unscoped.

Fail without the fix. Every mutation from both earlier passes, plus four new ones (no AmountOnly, unchecked add, empty-text guard, no canonical order), fails at least one test.

Results. 1305 tests pass across 40 binaries; the parity suite passes against a fresh debug component (27 tests); clippy and rustdoc are clean. 50k × 50k is byte-identical to main. All of this ran on per-worktree targets. Head: 190723d.

Fourth pass: merged with main (#2497, #2492, #2494) and reviewed as an outside maintainer

I merged origin/main into this branch (ce7b1f6); the only conflict was CHANGELOG.md, where I kept both entries. #2497's Mappings type and this PR's transaction_id_column compose without changes. The merged tree passes 1312 tests across 40 binaries, including the four property tests, and the parity suite passes against a fresh debug component (27 tests). Clippy is clean. Every mutation from the earlier passes still fails its tests.

Findings fixed in a378a9e

  • The stderr report did not scale. A full re-import printed one skipped line per row: 50,000 lines. The report now lists at most 20 rows of each kind. Flagged money-only skips have their own allowance, so ordinary skips cannot crowd them out. The rest are counted (... and 49980 more skipped transaction(s) not listed), and the summary line still carries the full counts. Fail without fix: with no cap, existing_dedup_report_is_bounded_and_keeps_flagged_rows_visible fails.
  • A partly broken --existing ledger was used silently. The loader's parse and include errors were ignored, so duplicates of entries in the part that failed to load were re-imported without a word. extract now prints a warning naming the error count and the first error, and says those duplicates may be imported again. Fail without fix: with no warning, a_partly_broken_existing_ledger_is_reported fails.
  • Windows line endings: CRLF CSVs and trailing spaces already produce clean ^csv- links. This is now pinned by a test, which passes without any fix, so it is a regression guard only.
  • Docs and CHANGELOG describe the bounded report and the warning. The PR body lists robcohen's approved decisions as final.

50k × 50k takes 0.74 s and is byte-identical to main; 200k × 200k takes 3.57 s with 782 MB peak RSS. All local runs used this worktree's own target.

Fifth pass: every user-facing message and degraded input

extract has no --quiet or --format json. Every message below goes to stderr and stdout carries only beancount. I checked exit codes on each case.

Input Result
Empty CSV, header-only CSV exit 1, "no transactions were extracted" (unchanged from main)
CSV with a BOM header is read and the id link is emitted (exit 0)
Id blank on some rows those rows get no link; the rest do
--existing an empty file nothing is deduplicated; exit 0
--existing a directory, unreadable, or missing exit 1, "Failed to load existing ledger". The OS error is repeated three times, but that comes from the loader and is the same on main, so I'm proposing it as a follow-up
Re-importing a statement with a repeated id both rows dropped by id (multiset)

Findings fixed in 54281c0

  • A transaction_id_column the header lacks used to fail every row with failed to read configured transaction id column, which doesn't name the column, and then report "no transactions were extracted". It now fails once with transaction_id_column "Id" is not a column of this file (its columns: Date, Description, Amount). Fail without fix: with the check removed, 2 tests fail.
  • Ids repeating within one statement were accepted silently. That happens when a category, type or date column is picked by mistake, and id dedup then matches an equal-money row on any date. One warning now says how many ids repeat, with an example and its rows: 1 transaction id(s) appear on more than one row (e.g. ^csv-t1 on rows 1, 2); transaction_id_column should name a column that is unique per transaction, or extract --existing may match the wrong rows. Fail without fix: with the warning removed, 1 test fails.

Results. 1314 tests pass across 40 binaries; the parity suite passes (27 tests); clippy is clean. All earlier mutations still fail their tests. 50k × 50k takes 0.75 s, byte-identical to main. All runs used this worktree's own target.

Sixth pass: misconfiguration of the keys this PR adds

I checked each case against a release build.

transaction_id_column setting Result
0 (integer index) works
1.5, true error: "transaction_id_column must be a column name (string) or 0-based index (integer)"
"" error: not a column of this file
"id", " Id" error: not a column, now with a did you mean "Id"? hint
9 (past the last column) was one context-free warning per row, then "no transactions were extracted". Now one error: transaction_id_column 9 is past the last column of this file (it has 4 columns, numbered from 0)
"Amount", "Date" was accepted, emitting ^csv--4.00 and ^csv-2024-01-15. Because id dedup treats an equal id with equal money as the same transaction on any date, an amount column used as the id would drop every equal-amount row. Now refused: transaction_id_column names the same column as amount_column ("Amount"). The same check covers date_column, debit_column, credit_column, narration_column, payee_column, currency_column and secondary_date_column

Used together with [importers.mappings], accounts and id links both come out right.

Fixed in 9f35d4f. Fail without the fix:

  • with the same-column check removed, 1 test fails;
  • with the index range check removed, 1 test fails;
  • with the whole up-front check removed, 3 tests fail.

All earlier mutations still fail their tests. 1315 tests pass across 40 binaries, the parity suite passes (27 tests), and clippy is clean. 50k × 50k takes 0.76 s, byte-identical to main. All runs used this worktree's own target. #2495 is MERGEABLE on main after 092460b.

Seventh pass: harness integrity and a literal docs walkthrough

Harness integrity. In pass 6 a mutation silently stopped applying, so I re-ran every mutation from passes 1–6 through a new harness. For each mutation it:

  1. applies every replacement and asserts the exact expected match count;
  2. checks the file on disk differs from its backup;
  3. runs cargo test without -q, so the Compiling <crate> lines prove a rebuild;
  4. adds up every test result: line (passed and failed), rather than trusting that no FAILED appeared;
  5. restores the files byte for byte and checks them again.

Tests run: -p rustledger-ops -p rustledger-importer --all-features plus -p rustledger --all-features --lib. The baseline (no mutation) is 892 tests, 0 failed. Every mutation applied, triggered a rebuild, and failed at least one test:

Mutation Applied (file changed, crates rebuilt) Tests run Failed
baseline (no mutation) yes (7 crates rebuilt) 892 in 9 binaries 0
p1 no consumption (set semantics) yes (6 crates rebuilt) 892 in 9 binaries 9
p1 first-posting number only (no account/commodity scope) yes (6 crates rebuilt) 892 in 9 binaries 7
p1 id links ignored yes (6 crates rebuilt) 892 in 9 binaries 4
p1 single fuzzy pass (no id/exact priority) yes (6 crates rebuilt) 892 in 9 binaries 10
p1 CSV id link not emitted yes (6 crates rebuilt) 892 in 9 binaries 4
p2 id match without the money check yes (6 crates rebuilt) 892 in 9 binaries 2
p2 no split-leg net key yes (6 crates rebuilt) 892 in 9 binaries 1
p2 no unscoped fallback yes (6 crates rebuilt) 892 in 9 binaries 3
p3 empty text never matches (main's guard) yes (6 crates rebuilt) 892 in 9 binaries 5
p3 no canonical order yes (6 crates rebuilt) 892 in 9 binaries 2
p4 money-only matches not flagged yes (6 crates rebuilt) 892 in 9 binaries 3
p4 unchecked net add (overflow panic) yes (6 crates rebuilt) 892 in 9 binaries 1
p4 skip report uncapped yes (6 crates rebuilt) 892 in 9 binaries 1
p4 no broken --existing warning yes (1 crates rebuilt) 892 in 9 binaries 1
p5 no up-front id column check yes (2 crates rebuilt) 892 in 9 binaries 3
p5 no repeated-id warning yes (2 crates rebuilt) 892 in 9 binaries 1
p6 no same-column check yes (2 crates rebuilt) 892 in 9 binaries 1
p6 no index range check yes (2 crates rebuilt) 892 in 9 binaries 1

Docs walkthrough. I followed extract.md and importing.md literally against the PR binary.

  • The two quoted stderr blocks match character for character.
  • The Quick Start and Duplicate Detection commands run as shown, and the description-less statement case works with default columns.

Findings, fixed in 3fb32fb (docs only)

  • The Monzo transaction_id_column example didn't work as written. It had no account, currency or column keys, so a real Monzo-style file failed with failed to parse date '15/01/2024' and never produced the output shown. It is now a complete entry, and its output matches the doc's beancount block byte for byte.
  • The extract.md CSV Options block was not valid TOML. It repeated date_column and amount_column, so copying it gave a TOML duplicate-key error (this predates the PR, but the PR edits that block). The name-based alternatives are now commented out, and the block runs.
  • Merging this PR and fix(extract)!: take a CSV entry's missing currency from its open directive #2498 together still conflicts only in CHANGELOG.md; the docs edits merge cleanly.

Eighth pass: every other doc and text this PR changes

I checked each item below against the PR binary, the component, and the doctests.

Findings fixed in 9155173

  • docs/roadmap/importing.md, "Stable source IDs" row. It still opened with "Dedup keys on exact date, exact first-posting amount, and a fuzzy payee/narration match", and it listed consuming ids as remaining work, contradicting its own "shipped" sentence. It now records what shipped: OFX ^ofx-, CSV ^csv-, and dedup treating an equal id with equal money as the same transaction. What remains is an id convention for WASM importers (dedup only recognizes the ofx- and csv- prefixes) and extract --output truncates the target file, destroying existing ledger content #2251.

  • CHANGELOG performance entry. It still quoted 1.6 s and 1.8 s from before the review rounds. Re-measured on an idle machine:

    Run Time
    main, 50k × 50k 101 s
    this PR, 50k × 50k 0.76 s (the import alone is 0.43 s)
    full re-import, every row a duplicate 0.37 s
    200k × 200k 3.6 s

    The PR body table is updated to match.

  • docs/development/import-architecture.md. It described id matching without the same-money condition; that is now stated.

Checked and accurate, no change needed

  • The README sentence.

  • Every CHANGELOG claim other than the performance numbers, each checked against the binary in passes 1–7.

  • The WIT session.dedup doc. Each claim is now asserted in the component's own test (dedup_flags_and_format_loaded_close_the_loop):

    • two identical candidates against one held entry → [true, false];
    • a candidate in another first-posting commodity → [false];
    • a shared ^csv- link with the same money but completely different text → [true].

    The gated parity test passes against a freshly built debug wasip2 component.

Rustdoc. None of the new public items in rustledger-ops had an example. find_import_duplicates (the two-coffees multiset case) and id_link now have runnable examples, and cargo test --doc -p rustledger-ops reports 2 passed (the 1 ignored doctest is the existing ml one).

Clippy and rustdoc are clean. All runs used this worktree's own target.

Property tests (new crates/rustledger-ops/tests/import_dedup_properties.rs)
found two invariant failures:

- Re-importing a statement whose rows have no payee or narration added
  every row again: empty text never matched. Identical empty text now
  counts as identical in the exact pass.
- Which rows survived depended on file order: the greedy fuzzy pass let
  an earlier row claim the entry a later one needed. Rows are visited,
  and candidates offered, in a canonical content order, so the kept set
  is a function of the contents alone.

The properties pin: a re-import adds zero rows; drops never exceed
existing entries and each rests on the same money; permuting either
side keeps the same rows; a half-then-whole import is idempotent.

Refs #2421

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen and others added 9 commits October 8, 2026 02:22
- A match where neither side has a payee or narration is reported as
  `DuplicateReason::AmountOnly`, counted separately and flagged on stderr
  ("-- check: nothing but the date and amount ties these together"):
  two different description-less rows on one day for one amount are
  indistinguishable, so the user should see such skips.
- The split-leg net uses checked_add, so a crafted ledger whose net
  overflows Decimal no longer panics the import.
- Ranks are computed once per transaction and borrowed, instead of
  allocating in every sort comparison; `DuplicateReason` is
  `#[non_exhaustive]`; `ID_LINK_PREFIXES` is private (nothing outside
  needs it); `id_link` docs describe the id-plus-money rule.
- Docs note that text is not Unicode normalized (NFC vs NFD differ).

Refs #2421

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

- A full re-import listed every skipped row: 50,000 lines on stderr.
  The report now lists at most 20 rows of each kind (ordinary, flagged
  money-only, so flagged rows never hide behind ordinary ones) and counts
  the rest; the summary line keeps the full counts.
- An --existing ledger with parse or include errors was used silently,
  so duplicates in the part that failed to load were re-imported without
  a word. extract now warns, naming the first error.
- Pin that CRLF CSVs yield clean ^csv- links.

Refs #2421

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

- A `transaction_id_column` the header lacks failed every row with the
  same context-free warning, then reported "no transactions were
  extracted". It now fails once: `transaction_id_column "Id" is not a
  column of this file (its columns: ...)`.
- Ids repeating within one statement (a category or date column picked
  by mistake) made id dedup match an equal-money row on any date. One
  warning now names how many ids repeat, with an example and its rows.

Refs #2387

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
- An index past the last column failed every row with a context-free
  warning; it is now one error naming the key and the column count.
- A name differing from a header only in case or surrounding spaces
  gets a "did you mean" hint.
- The same column as one the importer already reads (`amount_column`,
  `date_column`, ...) is refused: those values are not unique per
  transaction, and id dedup trusts an equal id with equal money as the
  same transaction on any date.

Refs #2387

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Followed literally, the Monzo `transaction_id_column` example had no
account, currency or columns, so it failed on the date and never
produced the output shown; it is now a complete entry whose output
matches the doc byte for byte. The CSV Options block repeated
`date_column` and `amount_column`, a TOML error when copied; the
name-based alternatives are commented out.

Refs #2387

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

- The roadmap row for stable source ids still described dedup as keyed
  on first-posting amount and fuzzy text, and proposed consuming ids as
  remaining work; it now records what shipped and what remains (an id
  convention for WASM importers, #2251).
- The CHANGELOG performance entry quoted 1.6 s / 1.8 s from before the
  review rounds; re-measured: 0.76 s (import alone 0.43 s), 0.37 s for a
  full re-import, 101 s for main on an idle machine.
- import-architecture.md now says an id match needs the same money.
- Runnable doctests for `find_import_duplicates` and `id_link`, and the
  component test asserts each `session.dedup` claim in the WIT doc
  (multiset, commodity scope, id link with equal money).

Refs #2421

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
The existing-ledger loader doc named `first_posting_amount`, a function
that no longer exists, and the dedup module doc and the component's
`SessionState::dedup` doc described an id-link match without the
same-money condition.

Refs #2421

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant