Skip to content

fix(importer): resolve equal-length mappings deterministically in file order - #2497

Merged
robcohen merged 3 commits into
mainfrom
fix/importer-mappings-deterministic
Oct 8, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/importer-mappings-deterministic

Conversation

@robcohen

@robcohen robcohen commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

What changed

[importers.mappings] was read into a HashMap<String, String>, and the rules were sorted only by Reverse(len). When two patterns of the same length both matched ("foo" and "bar" against foobar), the account depended on hash order, which is randomized per map. The same input produced different accounts from one run to the next. The issue shows 14 runs out of 20 picking one account and 6 the other.

The tie-break is now file order:

  • ImporterEntry::mappings is a new Mappings type, a list of (pattern, account) pairs in the order the file wrote them.
  • The toml crate (without preserve_order) yields table keys sorted, not in document order, so the deserializer reads each key as toml::Spanned<String> and orders the pairs by key span. I did not turn on preserve_order: feature unification would apply it to every crate in the workspace that uses toml, which would reorder every other table the workspace serializes (for example entry_toml_from_inferred's output).
  • build_config_from_entry keeps its stable sort_by_key(Reverse(len)). Longer patterns still win, and among patterns of equal length the first one written wins.

This tie-break is documented in docs/guides/importing.md, in the doc comments, and in the CHANGELOG (Fixed).

I did not add a warning for input that matches several equally ranked patterns, which the issue suggested as optional. With a deterministic, documented tie-break, a warning on every such row would be noise for configs that rely on the order on purpose.

How tested

  • equal_length_mappings_resolve_deterministically_in_file_order: TOML text → load_importers_config → build_config_from_entry → CsvImporter, 200 runs per file order. Both orders are tested (foo, bar gives Expenses:Foo, and bar, foo gives Expenses:Bar), which shows that file order is what decides.
  • mappings_keep_file_order: a reverse-alphabetical table comes back in file order through the CLI loader.
  • mappings_keep_file_order_through_build, in rustledger-importer: the bare-table form the component's importer.extract parses keeps file order, and the built config orders by length and then file order.
  • Fail without the fix:
    • With the parsed pairs collected through a HashMap (the old behavior), both CLI tests fail. The determinism test got Expenses:Bar where Expenses:Foo was expected.
    • Before the span ordering was added (plain next_entry::<String, String>), both tests failed with keys in sorted order, which is how the toml key-order behavior was found.
  • cargo test -p rustledger-importer -p rustledger-ffi-component -p rustledger --all-features: 1178 tests pass across 37 test binaries.
  • cargo clippy --workspace --all-features --all-targets -D warnings and cargo doc -D warnings -p rustledger-importer are clean.

API note

ImporterEntry::mappings changes type from HashMap<String, String> to Mappings, which offers get, len, is_empty, iter and FromIterator<(String, String)>. Deserializing the field requires the toml deserializer, because it reads key spans. Every existing path (toml::from_str in the CLI and the component) does.

Merging alongside #2495, #2497 and #2498

These three PRs touch the same importer and extract code. I merged them onto origin/main (184e9d1) in five orders: A-B-C, A-C-B, B-A-C, C-B-A and C-A-B, where A is #2495, B is #2497 and C is #2498. Every order gives a byte-identical tree. The only conflicts are in CHANGELOG.md, where two PRs add a bullet at the top of the same section (### Fixed / ### Breaking). Keep both bullets.

toml_entry.rs, extract_cmd/mod.rs and docs/guides/importing.md all merge automatically. On the combined tree, 1300+ tests pass across the ops, importer, ffi-component and rustledger suites. A CSV entry with no currency then takes EUR from the open directive, and dedup compares in EUR. The #2498 test the_resolved_currency_is_what_dedup_compares checks this, and it fails on the combined tree when the old USD fallback is restored.

Closes #2423

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…e order

`[importers.mappings]` was read into a HashMap and the rules were
ordered only by pattern length, so two equally long patterns that both
matched picked an account by hash order, differently from run to run.

Mappings are now a list kept in file order (the `toml` deserializer
yields keys sorted, so each key's span restores the written order), and
the stable length sort makes the first-written pattern win a tie.

Closes #2423

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:47
@codecov

codecov Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.96970% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-importer/src/toml_entry.rs 96.62% 3 Missing ⚠️
crates/rustledger/src/cmd/extract_cmd/mod.rs 97.67% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@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

Subtables, inline tables, dotted keys, literal and unicode keys, empty
tables and several [[importers]] entries all keep file order through
the span-based Mappings deserializer.

Refs #2423

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

Adversarial review pass

I checked whether file order survives every way an importers.toml can be loaded:

  • Load paths. Every path parses with toml::from_str into ImporterEntry: the CLI's load_importers_config (one function for --config, ./importers.toml, $RLEDGER_CONFIG_DIR and the user config dir, which differ only in the file path), --ledger profile entries, and the component's ImporterEntry::from_toml_str. Nothing deserializes an entry through toml::Value, which carries no spans.

  • Spellings. The new test mappings_keep_file_order_in_every_toml_spelling puts these in one [[importers]] array with several entries:

    • a [importers.mappings] subtable with basic, literal ('mm literal') and bare keys
    • an inline table mappings = { … }
    • dotted keys mappings."zz", mappings.mm, mappings."a a"
    • unicode keys
    • an empty mappings = {}
    • an entry with no table

    Every one keeps file order. A non-string account is still a parse error, not a silent skip.

  • Fail without fix. With the parsed pairs collected through a HashMap again, both importer-level order tests and both CLI tests fail.

Nothing needed fixing in this pass; the new test pins the behavior. 1179 tests pass across 37 binaries, and clippy and rustdoc are clean. All of it ran on a target dir used only by this worktree, since shared target dirs can reuse another worktree's build.

PR Benchmark is red for an unrelated reason. bench-pr.yml installs hyperfine "latest", and hyperfine v2.0.0 (published 2026-10-07T21:13Z) changed the --export-json schema: per its release notes, "results[i].mean is now results[i].summary.time_wall_clock.mean". The comment script then fails with KeyError: 'mean' in ms(). Runs of this check before that release passed.

Second pass: cross-PR integration and docs

I merged this PR together with #2495 and #2498 in five orders onto origin/main. Every order gives an identical tree, and the only conflicts are adjacent CHANGELOG.md bullets (keep both). toml_entry.rs takes this PR's Mappings field, #2495's transaction_id_column and #2498's currency doc together without conflicts. On the combined tree, 1312 tests pass across 40 binaries, including the 200-run determinism test and every TOML spelling.

I re-read the docs (importing.md, the tie-break paragraph): longer patterns first, file order among equal lengths, first match wins. That matches the code. Head ec7a672 is unchanged since the first pass.

Third pass: code quality and docs

I found nothing to change in this pass.

  • Mappings exposes only get, len, is_empty, iter, FromIterator and a span-ordered Deserialize.
  • len and is_empty are const, and the accessors are #[must_use].
  • The CHANGELOG entry and the guide's tie-break paragraph match the code: longer patterns first, file order among equal lengths, first match wins.

Head ec7a672 is unchanged.

@robcohen
robcohen merged commit 5679be1 into main Oct 8, 2026
48 of 50 checks passed
@robcohen
robcohen deleted the fix/importer-mappings-deterministic branch October 8, 2026 05:03
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.

importers.mappings: equal-length overlapping keys produce nondeterministic accounts

1 participant