Skip to content

fix(extract)!: take a CSV entry's missing currency from its open directive - #2498

Merged
robcohen merged 9 commits into
mainfrom
fix/csv-importer-no-silent-usd
Oct 8, 2026
Merged

robcohen merged 9 commits into
mainfrom
fix/csv-importer-no-silent-usd

Conversation

@robcohen

@robcohen robcohen commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

What changed

An importers.toml entry that named no currency, run without --currency, got "USD" from deep inside the CSV importer (csv_importer.rs, default_currency). A euro or pound account's statement was booked in dollars with no warning, and because the currency was wrong, --existing could no longer match the transactions the user had entered by hand (#2464). Correctness comes first here: a guessed currency corrupts the ledger silently.

CLI (rledger extract), for entries without a currency, in a new resolve_entry_currency:

  1. If the --ledger ledger has an open directive for the entry's account that names exactly one currency, that currency is used, and a line on stderr says so. --existing is consulted only when --ledger never opens the account, so an ambiguous open in --ledger is not overruled by another file. Includes are followed, and a later close does not matter.
  2. Otherwise extract stops with an error that names the importer, says why the ledger could not answer (no ledger given, no open for the account, or an open declaring none or several currencies), and points to the fix:
importer 'bank' does not set `currency`, and it cannot be taken from the ledger: `open Assets:Bank:Euro` in ledger.beancount declares EUR, CHF, more than one
  set `currency = "..."` in the 'bank' entry of importers.toml, or pass --currency

An entry with a currency_column still imports, because its rows carry their own currency.

Importer library (CsvImporter): there is no built-in currency any more. A config with neither currency nor currency_column is refused up front. A row with a blank currency cell and no currency is a row error instead of USD.

Unchanged on purpose:

  • The raw-flag path (-a … -c …, --auto) keeps its documented --currency [default: USD].
  • The component's importer.extract keeps the USD default that its WIT doc promises (currency defaults to USD exactly like the CLI's --currency flag). It sets currency before building, so it does not reach the importer's new refusal. Changing that contract is a WIT-level decision, so it is left for a follow-up.
  • The payee rewrite request in [Bug]: Issues with CSV importer #2464 ("Hofer Dankt" → "Hofer") is a separate feature and is not implemented here.

This is a behavior change, so it goes in the CHANGELOG under Breaking. The entry tells users how to keep the old result: add currency = "USD" to the entry, pass --currency USD, or, for library users, set ImporterConfig.currency = Some("USD"). Docs: docs/commands/extract.md and docs/guides/importing.md.

This PR uses Refs #2464 rather than closing it. The issue also asks for payee rewriting and reports a dedup miss that still needs a sample from the reporter. #2495 changes the dedup matching.

Decisions (approved by @robcohen)

  • An entry without currency takes the currency from the account's open. --ledger is the authority. --existing is consulted only when --ledger never opens the account. Anything ambiguous is an error that names the importer and the fix.
  • The component's importer.extract keeps its documented USD default, and the raw-flag --currency default stays as it is.
  • Refs #2464, not Closes. Payee rewriting is a separate feature, and the remaining dedup report is waiting on a sample.

How tested

  • entry_without_currency_uses_the_open_directive: an entry with no currency, plus open Assets:Bank:Euro EUR, produces -5.00 EUR through both --existing and --ledger.
  • entry_without_currency_and_no_single_open_currency_is_an_error: covers no ledger, an open with EUR,CHF, and a ledger with no open for the account. Each gives an error naming the importer and the reason.
  • test_csv_import_without_a_currency_is_refused, at the importer level: no currency and no column gives an error, and a blank currency cell gives a row warning.
  • Fail without the fix: with resolve_entry_currency removed and the importer's USD fallback restored (main's behavior), all three tests fail. Main output was Assets:Bank:Euro -5.00 USD.
  • test_csv_import_default_currency pinned the USD default, so it is removed. Five existing CLI tests whose importers.toml fixtures had no currency (and so silently relied on USD) now set currency = "USD", and test_csv_importer_new sets it on its builder.
  • cargo test -p rustledger-importer -p rustledger-ffi-component -p rustledger --all-features: 1177 tests pass across 37 test binaries.
  • cargo clippy --workspace --all-features --all-targets -D warnings and cargo doc -D warnings (importer and rustledger) are clean.

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.

Refs #2464

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…ctive

An `importers.toml` entry without `currency` got `USD` from inside the
CSV importer, so a euro account's statement was booked in dollars with
no warning.

`rledger extract` now fills a missing entry currency from the account's
`open` directive in `--ledger` (then `--existing`) when it names exactly
one currency, and otherwise refuses with an error naming the importer
and the fix. `CsvImporter` has no built-in currency any more: a config
with neither `currency` nor `currency_column` is refused, and a blank
currency cell with no default is a row error.

The raw-flag `--currency` default and the component's documented USD
default are unchanged.

Refs #2464

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:54
@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 44.9ms ± 2.4ms 796.3ms ± 7.1ms 17.7x 51.1 MB / 49.9 MB
investment 67.0ms ± 0.4ms 2995.8ms ± 21.5ms 44.7x 55.2 MB / 58.1 MB
fifo 65.0ms ± 0.4ms 15181.1ms ± 96.0ms 233.6x 55.2 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 43.7ms ± 0.4ms 44.9ms ± 2.4ms +2.8% ✅ within noise 51.0 MB → 51.1 MB (+0.3%)
investment 67.0ms ± 0.3ms 67.0ms ± 0.4ms -0.1% ✅ within noise 55.2 MB → 55.2 MB (+0.0%)
fifo 64.5ms ± 0.3ms 65.0ms ± 0.4ms +0.8% ✅ within noise 55.2 MB → 55.2 MB (+0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.1ms, investment 0.2ms, fifo 0.2ms), 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 98.87955% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/extract_cmd/mod.rs 98.56% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

When --ledger opens the importer account with no currency or several,
that is the answer (an error), not a reason to consult --existing;
--existing is read only when --ledger never opens the account. Tests pin
included-file opens, a later close, and an unconstrained open, and the
CHANGELOG says how to keep the old result (`currency = "USD"`).

Refs #2464

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 the "single open currency" rule against every shape of open I could find:

Case Result
open lists several currencies (EUR,CHF) error: "open Assets:Bank:Euro in … declares EUR, CHF, more than one"
open with no currency constraint error: "… declares no currency"
Account never opened in the ledger error: "… has no open Assets:Bank:Euro directive"
No ledger given error: "no --ledger or --existing ledger was given …"
open in an included file EUR is used (the loader follows includes)
Account closed later EUR is used; a close does not change the account's currency
--ledger ambiguous, --existing unambiguous error, which is the fix in this pass. Before it, --existing silently overruled --ledger. Now --existing is consulted only when --ledger never opens the account

Every error starts importer '<name>' does not set currency`` and ends set currency = "..."` in the '' entry of importers.toml, or pass --currency`.

The CHANGELOG Breaking entry now tells users how to keep the old result: add currency = "USD" to the entry, pass --currency USD, or, for library users, set ImporterConfig.currency = Some("USD").

This PR still uses Refs #2464 rather than closing it. The issue also asks for payee rewriting, which is not done here, and reports a dedup miss that is waiting on a sample from the reporter.

Fail without fix. With main's behavior restored (no resolution, USD fallback), all 5 new CLI tests and the importer test fail. With the --ledger-authority breaks removed, ledger_open_outranks_existing_open fails. 1180 tests pass across 37 binaries, and clippy and rustdoc are clean. All of it ran on a target dir used only by this worktree.

Second pass: cross-PR integration and docs

I merged this PR together with #2495 and #2497 in five orders onto origin/main. Every order gives an identical tree, and the only conflicts are adjacent CHANGELOG.md bullets (keep both).

On the combined tree, an entry with no currency and an --existing ledger that opens Assets:Bank:Euro EUR imports in EUR, and #2495's commodity-scoped dedup skips the EUR duplicate. An existing USD entry is not treated as a duplicate.

The new test the_resolved_currency_is_what_dedup_compares pins this. It fails on the combined tree when the old USD fallback is restored. On this branch alone it cannot fail, because main's dedup ignores commodity; it is an integration pin.

I re-read the docs against the final behavior and corrected extract.md and importing.md: --ledger decides when it opens the account, --existing is read only when it does not, and included files are followed. 1181 tests pass across 37 binaries, and clippy and rustdoc are clean. All of it ran on per-worktree target dirs.

Third pass: code quality and docs

  • The importer-profile reader and the new open-currency lookup each built the same plugin-free, validation-free LoadOptions. They now share one load_unvalidated helper.
  • The no-currency row error uses plain context.
  • When an entry has no currency, the ledger is still loaded twice: once for profiles or currency, and once more by --existing dedup. The cost is small, but I'm noting it as a possible follow-up.
  • The CHANGELOG Breaking entry tells users how to keep the old result: currency = "USD", --currency USD, or ImporterConfig.currency = Some("USD").
  • The docs match the --ledger-over---existing rule.

1181 tests pass across 37 binaries, both mutations still fail their tests, and clippy and rustdoc are clean, all on this worktree's own target. Head: 3798d10.

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

I merged origin/main into this branch (935839b); the only conflict was CHANGELOG.md, where I kept both entries. The merged tree passes 1185 tests across 37 binaries, and clippy is clean. Both mutations still fail their tests: restoring main's USD default fails 5 CLI tests and 1 importer test, and letting --existing overrule --ledger fails 1 test.

Findings

  • A ledger whose open line fails to parse makes the account look unopened, so extract stops and asks for currency. That is the safe outcome, and no change is needed.
  • An open inside an included file, and an account closed later, are both already pinned by tests.
  • CHANGELOG wording: "keeps its documented USD default for now" read as provisional. robcohen approved that default, so the wording is now final (d0d1642). The PR body lists the approved decisions.

All local runs used this worktree's own target.

Fifth pass: every user-facing message and degraded input

All messages go to stderr and stdout carries only beancount. Checked against a release build:

Case Result
No ledger exit 1; names the importer and the fix
open with EUR,CHF exit 1; "declares EUR, CHF, more than one"
--ledger with a failing include exit 1 via the profile reader: "ledger … has 1 error(s) and cannot be read"
Include that loads but has a later broken entry EUR is used
Blank currency cell with no default row warning, then exit 1 with "no transactions were extracted"
-o file written only on success
--existing is a directory exit 1

Finding fixed in 6fad6b0. When --existing's open sat in an include that failed to load, the error said the ledger "has no open Assets:Bank directive", which sends the user to look in the wrong place. It now says no open Assets:Bank directive loaded from …, which has 1 load error(s) (first: …); the open may be in the part that failed. Fail without fix: with the load errors not named, the new test fails.

1186 tests pass across 37 binaries, both earlier mutations still fail their tests, and clippy is clean. All runs used this worktree's own target.

Sixth pass: misconfiguration of currency

I checked each case against a release build. Every finding below was fixed in 851d771.

  • A currency that is not a commodity. "usd" and "€" failed with canonical formatter failed to re-parse the synthesized directive text, which names nothing the user configured. "" was worse: it succeeded, emitting Assets:Bank -4.00 with no commodity. All three now fail with an error naming the source: `currency` in the 'm' entry of importers.toml is "usd", which is not a valid commodity (commodities are upper-case, like USD or EUR), or the same with --currency. The check is the new rustledger_parser::is_valid_currency, which runs the lexer the same way is_valid_account_name does, so it cannot drift from the parser. A non-string value (currency = 5) was already a TOML type error.
  • Precedence is now documented and conflicts are reported. The order is: a --ledger profile, then --currency, then the entry's currency, then the account's single open currency. The configured value always wins. Before this fix, a configured currency that the account's open does not allow (EUR into open … CHF) was silent, and rledger check would then reject every posting. It now prints warning: currency in the 'm' entry … books EUR, but open Assets:Bank in … allows only CHF. A --currency that a --ledger profile overrides used to be dropped silently; it now gets warning: --currency EUR is not used: the --ledger profile for … declares USD.
  • Fail without fix. Removing the validation, the conflict warning or the override warning each fails its test. The main-behavior mutation still fails 6 CLI tests and the importer test.

1189 tests pass across 37 binaries, 664 parser tests pass, and clippy and the parser's rustdoc are clean. All runs used this worktree's own target.

One trade-off for review. The conflict check reads the open from --ledger/--existing even when currency is set. With --existing that means the ledger is loaded a second time on every import. I'm keeping this for correctness and listing it alongside the existing double-load follow-up.

Seventh pass: harness integrity and a literal docs walkthrough

Harness integrity. I re-ran every mutation from passes 1–6 through a harness that, for each mutation:

  1. asserts the exact match count for every replacement;
  2. checks the file on disk changed;
  3. requires Compiling <crate> lines as proof of a rebuild;
  4. adds up every test result: line;
  5. restores the files byte for byte and checks them again.

Tests run: -p rustledger-importer -p rustledger-parser --all-features --lib plus -p rustledger --all-features --lib. The baseline (no mutation) is 1107 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) 1107 in 3 binaries 0
p1 main behavior: no resolution + importer USD fallback yes (2 crates rebuilt) 1107 in 3 binaries 7
p2 --existing may overrule an ambiguous --ledger yes (2 crates rebuilt) 1107 in 3 binaries 1
p5 load errors not named yes (1 crates rebuilt) 1107 in 3 binaries 1
p6 no currency validation yes (1 crates rebuilt) 1107 in 3 binaries 1
p6 no open-conflict warning yes (1 crates rebuilt) 1107 in 3 binaries 1
p6 no profile-override warning yes (1 crates rebuilt) 1107 in 3 binaries 1

The the_resolved_currency_is_what_dedup_compares mutation only bites on a tree with #2495 merged in; it was verified on the combined tree in pass 2.

Docs walkthrough. I followed both docs literally against the PR binary.

  • The importing.md Chase example (rledger extract --importer chase chase-statement.csv) works as written.
  • Dropping currency and passing --ledger with open Assets:Bank:Chase USD prints Using currency USD from the open Assets:Bank:Chase directive in main.beancount and imports in USD.
  • With no ledger, the error names the importer and the fix, as the docs say.

Nothing in this PR's docs needed fixing. The extract.md CSV Options block repeats date_column and amount_column, so it fails to parse as TOML when copied. That predates this PR and is fixed in #2495 (3fb32fb) rather than here, so the two PRs don't conflict. Head 851d771 is unchanged and green on the required checks.

An entry without `currency` resolves EUR from the open directive, and an
EUR duplicate already in --existing is then skipped; on a tree with the
#2421 commodity-scoped dedup this fails if the rows carry a stale USD.
Docs describe the --ledger over --existing authority and includes.

Refs #2464

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen and others added 5 commits October 8, 2026 02:15
… currency

One helper builds the plugin-free, validation-free LoadOptions that both
importer-profile reading and open-currency lookup use, and the CSV
importer uses plain `context` for its no-currency row error.

Refs #2464

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
With the `open` inside an include that failed to load, the missing-
currency error said the ledger had no `open` for the account, sending
the user to look in the wrong place. It now says no `open` loaded, gives
the load error count and the first error, and that the `open` may be in
the part that failed.

Refs #2464

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
- A `currency` (or --currency) that is not a commodity (`usd`, `€`, "")
  surfaced as "canonical formatter failed to re-parse", or for "" as
  amounts with no commodity. It is now an error naming its source,
  checked with the new `rustledger_parser::is_valid_currency` (runs the
  lexer, like `is_valid_account_name`).
- A configured currency the account `open` does not allow now warns
  (`rledger check` would reject every posting); the configured value
  still wins. The precedence is documented.
- A --currency that a --ledger profile overrides is reported instead
  of dropped silently.

Refs #2464

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit 3d075c8 into main Oct 8, 2026
62 of 63 checks passed
@robcohen
robcohen deleted the fix/csv-importer-no-silent-usd branch October 8, 2026 14:12
robcohen added a commit that referenced this pull request Oct 8, 2026
…ency one

"currency_column X is V, which is not a valid commodity (commodities are
upper-case, like `USD` or `EUR`)", matching #2498. Pins that the value is
validated after upper-casing (full-width letters and an inner space stay
refused) and that surrounding whitespace is trimmed first.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Oct 9, 2026
… importer (#2531)

* fix(extract): validate currency_column cells and --currency for every importer

A currency_column cell that is not a commodity is now a row error naming
the row, the column and the value, instead of a posting that fails to
re-parse later; a lower- or mixed-case ISO code in a cell is upper-cased.
--currency is checked once at the start of the run for every importer
type, and an OFX/WASM entry's currency like a CSV entry's, through one
shared check_currency.

Closes #2516
Closes #2517

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

* fix(extract): word the currency_column error like the configured-currency one

"currency_column X is V, which is not a valid commodity (commodities are
upper-case, like `USD` or `EUR`)", matching #2498. Pins that the value is
validated after upper-casing (full-width letters and an inner space stay
refused) and that surrounding whitespace is trimmed first.

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

* docs(changelog): drop the stale MIN/MAX entry the merge kept

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

---------

Co-authored-by: Claude Opus 5.5 (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.

1 participant