Skip to content

fix(extract): command-line flags override the importers.toml entry - #2308

Merged
robcohen merged 5 commits into
mainfrom
fix/extract-importer-flag-precedence
Sep 14, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/extract-importer-flag-precedence

Conversation

@robcohen

@robcohen robcohen commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

With --importer, rledger extract built its configuration from the importers.toml entry alone. Every command-line flag that has a matching key was accepted and then silently discarded.

Reproduced on the reporter's own config:

before after
--account Liabilities:… Expenses:Unknown Liabilities:…
--skip-rows 1 first row imported first row skipped
--invert-sign signs unchanged signs inverted
output vs. the same command without those flags byte-identical differs

Precedence is now built-in default < entry < flag. One entry can describe a bank's CSV layout while each file supplies its own account and sign, which is what the reporter was trying to do.

How

Merged at the entry, not into the built config. overlay_cli_args lays every passed flag over the entry, then the existing build_config_from_entry builds it. A flag therefore goes through exactly the parsing and validation its TOML key does — --date-column 3 and date_column = 3 yield the same config. That equivalence is tested for all 18 flags that have a key.

Seven flags stopped carrying clap defaults. --currency (USD), --skip-rows (0), the column names, the date format and the delimiter could not tell "not passed" from "passed the default", so a naive merge would overwrite a config's skip_rows = 1 with a 0 nobody typed. They are Option now with the default applied by accessor — the pattern #2263 introduced for --account. --help still states each default.

The OFX path follows the same order. #2261 made it match the CSV path; changing one without the other would reintroduce that drift.

Also fixed in review

  • --balance used the raw flags, not the resolved account and currency. With an entry naming Liabilities:Card in GBP, postings went there and the balance assertion went to Assets:Bank:Checking in USD — one that can never hold. Even --account left the currency at USD. It now reads the resolved config. Pre-dates this PR; same bug class, same function (507a478b48).
  • ag-rledger's argument adapter had no test against an entry. Restoring a USD default in build_extract_args left all 14 of its tests green. A binary-level test now covers both directions (507a478b48).

Deliberately not changed

  • A --ledger profile still outranks both flag and entry for account and currency. That is its own design decision (the open directive is the account's declaration), and this PR does not reopen it.
  • An entry with no account, run without --account, still posts to Expenses:Unknown rather than the documented --account default Assets:Bank:Checking. Worth deciding separately whether that should fall back or refuse, as OFX: infer the account type from CREDITCARDMSGSRSV1 / ACCTTYPE instead of requiring it in config #2256 did for OFX liabilities.

Behavior change

A command that passes a flag and names an entry that disagrees with it now uses the flag. Recorded in the CHANGELOG under Fixed.

Rust API: seven rustledger::cmd::extract_cmd::Args fields changed from concrete types to Option, which is source-breaking for code that constructs Args directly. Recorded under Breaking, together with the identical change #2263 made to account in 0.24.0 without an entry. The command line, and callers that parse Args with clap, are unaffected.

Verification

Each of the four new tests was mutation-verified, with the patch confirmed present before trusting the result:

mutation fails
remove the merge (the original bug) the #2304 repro
drop one field from the merge the table test, the repro
merge a default in when no flag was passed the overwrite guard, the table test's no-flag check
put the entry ahead of --account on the OFX path the OFX test
--balance reads args again the balance test
restore the currency, skip_rows or delimiter default in ag-rledger's adapter the adapter test, each time

End to end with the real binaries on the reporter's importers.toml. ag-rledger shares the code path and was rebuilt with --features ag-rledger for this. The first run silently used a six-day-old binary, because cargo build -p rustledger skips feature-gated bins.

Gates: workspace tests (156 suites), ag_rledger_test with its feature on, cargo +1.97.0 clippy --workspace --all-targets --all-features -D warnings, rustdoc -D warnings, fmt --check.

Fixes #2304.

🤖 Generated with Claude Code

With `--importer` (or `--config` matching a file), the import configuration
was built from the entry alone, so `--account`, `--invert-sign`, `--skip-rows`,
`--currency`, and every column flag were accepted and silently discarded. An
entry with no `account` posted the account side of every transaction to
`Expenses:Unknown`, and one entry could not be shared across several accounts
at the same bank. Nothing warned. (#2304)

Precedence is now built-in default, then the entry, then the flag.

The flags are merged into the entry before it is built, not into the built
config, so a flag goes through exactly the parsing and validation its TOML key
does: passing `--date-column 3` and writing `date_column = 3` produce the same
config. A table test pins that equivalence for all 18 flags that have a key.

Seven flags carried clap defaults (`--currency` USD, `--skip-rows` 0, the
column names, the date format, the delimiter), which made an unset flag
indistinguishable from one set to its default. Merged naively, those defaults
would overwrite `skip_rows = 1` or `currency = "GBP"` from the config the user
did write. They are `Option` now, with the default applied by an accessor —
the same change #2263 made to `--account`, for the same reason. `--help` keeps
each default in its description.

The OFX path takes account and currency from an entry as well, and #2261 made
it match the CSV path. It now uses the same order, or the two dispatchers
would disagree again about whose value wins.

Not changed: a `--ledger` profile still outranks both for account and
currency, and a named entry with no account and no `--account` still posts to
`Expenses:Unknown`.

Four tests, each mutation-verified with the patch confirmed applied: removing
the merge fails the #2304 repro; dropping one field fails the table test;
merging a default in when no flag was passed fails the overwrite guard;
reverting the OFX order fails the OFX test.

End to end on the reporter's own importers.toml, with the real `rledger` and a
rebuilt `ag-rledger`: all three flags apply, and the output now differs from
the no-flag run, where before the fix the two were byte-identical.

Fixes #2304.

Co-Authored-By: Claude Opus 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 September 14, 2026 14:23
Copilot AI lite review requested due to automatic review settings September 14, 2026 14:23
@codecov

codecov Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 47.5ms ± 5.4ms 820.5ms ± 20.4ms 17.3x 55.1 MB / 50.1 MB
investment 70.6ms ± 2.2ms 3088.5ms ± 115.1ms 43.7x 61.2 MB / 57.9 MB
fifo 71.6ms ± 4.3ms 15643.7ms ± 207.3ms 218.6x 61.2 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 47.1ms ± 3.3ms 47.5ms ± 5.4ms +0.8% ✅ within noise 55.2 MB → 55.1 MB (-0.2%)
investment 71.3ms ± 3.2ms 70.6ms ± 2.2ms -1.0% ✅ within noise 61.2 MB → 61.2 MB (+0.1%)
fifo 71.4ms ± 3.5ms 71.6ms ± 4.3ms +0.2% ✅ within noise 61.2 MB → 61.2 MB (+0.0%)

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical correctness and public API issues remain, along with missing adapter regression coverage.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

rledger extract now gives explicit command-line flags precedence over matching importers.toml values across CSV and OFX imports.

Changes:

  • Overlays supplied flags while preserving omitted defaults.
  • Aligns ag-rledger handling and adds regression coverage.
  • Documents and records the behavior change.
File summaries
File Summary
docs/commands/extract.md Documents precedence and flag mappings.
crates/rustledger/src/cmd/extract_cmd/mod.rs Implements merging, defaults, OFX handling, and tests. Critical (2 votes): --balance uses unresolved arguments. Critical (2 votes): public Args fields became source-breaking Option<T> values. Nit (1 vote): CLI defaults duplicate canonical defaults.
crates/rustledger/src/bin/ag-rledger.rs Preserves unset flags. Moderate (2 votes): missing binary-level regression coverage.
crates/rustledger-importer/src/toml_entry.rs Enables cloning entries for overlays.
CHANGELOG.md Records the precedence change.
Review details

Suppressed comments (1)

crates/rustledger/src/cmd/extract_cmd/mod.rs:649

  • These CLI defaults duplicate the canonical CsvConfig::default() values in crates/rustledger-importer/src/config.rs:117-140 (and the USD fallback in csv_importer.rs:300). If an importer default changes, the raw-CLI path and the entry path can silently produce different configurations. Reuse or re-expose shared defaults instead of maintaining a second set here.
const DEFAULT_CURRENCY: &str = "USD";
const DEFAULT_DATE_COLUMN: &str = "Date";
const DEFAULT_DATE_FORMAT: &str = "%Y-%m-%d";
const DEFAULT_NARRATION_COLUMN: &str = "Description";
const DEFAULT_AMOUNT_COLUMN: &str = "Amount";
  • Files reviewed: 5/5 changed files
  • Comments generated: 3
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread crates/rustledger/src/bin/ag-rledger.rs Resolved
@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 99% (raw 93%, 169 masked)
Full AST Match 100%
Total Files 813
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

robcohen and others added 2 commits September 14, 2026 14:46
…adapter

Review of #2308 (Copilot, three threads).

`--balance` built its assertion from the raw flags, so an `importers.toml`
entry naming `Liabilities:Card` in GBP produced postings there and a balance on
`Assets:Bank:Checking` in USD — an assertion that can never hold. Even with
`--account` the currency stayed USD. It now reads the resolved config, after
the entry, flags, and any `--ledger` profile. This pre-dates the PR, but it is
the same bug class as #2304 in the same function. Mutation-verified: reading
`args` again fails the new test.

`ag-rledger`'s `build_extract_args` constructs `Args` by hand, and nothing
tested it against an entry: restoring a USD default there left all 14 existing
tests passing. A binary-level test now checks both directions through the real
binary — omitted flags keep the entry's account, currency, delimiter and
skip_rows; passed flags replace them, including an explicit `--skip-rows 0`.
It reads `result.stdout`, because the envelope echoes the command line and
would contain the flag values either way. Restoring the currency, skip_rows or
delimiter default each fails it.

The `Args` field type change is source-breaking for code that constructs
`Args` directly, and the crate is published. Recorded under Breaking in the
CHANGELOG, together with the identical change #2263 made to `account` without
an entry.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Deep review of #2308. This PR added a table saying `--no-header` is
`skip_header = true`, which is what the code does: `has_header(!skip_header)`,
and `entry_toml_from_inferred` writes the key only for a headerless file. A few
lines above it, the CSV Options example said the opposite — `# Skip header row`
— and paired the key with named columns. Checked on the real binary against a
CSV that has a header:

  named columns + skip_header = true   exit 1, 0 transactions
  named columns, key left out          2 transactions

A named column is looked up in the header row, so telling the importer there
is none leaves nothing to find. The comment now says what the key does, keeps
it commented out in the example, and warns about the other direction: on a
file with no header, leaving it out silently takes the first row as the header
and drops that transaction.

Also rewords a comment in the component's `import_extract`, which said the CLI
supplies USD "via the `--currency` flag default". This PR removed that clap
default; the CLI now applies USD when neither the flag nor the entry names a
currency.

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

robcohen commented Sep 14, 2026 •

Copy link
Copy Markdown
Member Author

Deep review

Two fixes, both in a6e9f29d78. The rest of this pass went looking for another --balance: a surface still reading the raw flags after the config is resolved. It didn't find one, and what it checked is listed so it doesn't have to be redone.

The skip_header docs said the opposite of what the key does

This PR's new table says --no-header is skip_header = true. That matches the code: has_header(!skip_header), and entry_toml_from_inferred writes the key only for a file with no header. A few lines above it, the CSV Options example said # Skip header row, next to named columns. On a CSV with a header:

Entry Result
named columns + skip_header = true exit 1, 0 transactions (Row 1: missing date column)
named columns, key left out 2 transactions
index columns, no header, skip_header = true 2 transactions
index columns, no header, key left out 1 transaction: the first row is silently taken as the header

Pre-existing, but this PR put a correct statement right next to an incorrect one. The comment now says the key means "no header row" and warns about both directions. The key stays commented out in that example, because it's what broke the named columns.

I left the chase example alone. skip_header = true with index columns is correct for a CSV without a header and only warns on one with a header, and the example doesn't show which file it means.

A stale comment in the component

import_extract said the CLI supplies USD "via the --currency flag default". This PR removed that clap default, so the comment is reworded.

Checked and clear

  • No other raw-flag consumer. After config resolution, args is read only on the --auto and raw-argument paths, where no entry exists, and as the balance fallback. duplicate.rs, suggest.rs, ledger_profile.rs and config.rs never read args.account or args.currency.
  • The WASI component can't have [Bug]: rledger extract ... --importer "foo" --account "Foo" results in "Expenses:Unknown" instead of the account from the flag #2304. import_extract(filename, content, config) takes only the TOML entry, so there are no overrides to drop.
  • Inferred configs agree with the code. entry_toml_from_inferred writes skip_header = true only when !inferred.has_header, and a round-trip test pins has_header.

Third deep review

The branch now includes main, so this pass checked the merge first, then looked for precedence rules the PR states but no test enforces. Three had nothing behind them. Tests added in 347fda265f.

Checked and clear

  • The merge with main. Main touched nothing in extract, the importer or Args since fix(extract): command-line flags override the importers.toml entry #2308's base, and added no Args, ImporterEntry or CsvConfig fields. No conflict markers, each CHANGELOG entry appears exactly once in the right section, and the diff against main is only this PR's 7 files.
  • Flag coverage. Every ImporterEntry field that has a CLI flag (17 of 27) goes through overlay_cli_args. The other 10 have no flag to merge.
  • CI on the merged head. Clippy, Test, Doctests, Documentation, Format, MSRV, both LSP jobs and Benchmarks Compile each passed individually.

Three stated rules with no test behind them

Each was confirmed with a mutation that applied cleanly and still left all 100 extract tests passing:

Mutation Tests that failed before After this commit
drop the flag merge on the --config path where the entry is picked by filename_pattern none flags_override_a_filename_identified_entry
OFX path: entry currency outranks --currency none currency_flag_outranks_an_ofx_entry
--account outranks a --ledger profile, the opposite of the docs none a_ledger_profile_outranks_the_account_flag
  • The first is the second build_config_from_entry call site. Every existing flag test went through --importer, so it was never exercised.
  • The OFX currency test reads the resolved currency through --balance, so it doesn't depend on what the OFX file itself declares.
  • The last pins the one precedence rule the PR deliberately left unchanged. It was documented, but a regression in either direction would have gone unnoticed.

With the tests in, each mutation fails exactly its own test, and the suite is at 103.

robcohen and others added 2 commits September 14, 2026 13:13
Deep review of #2308. The PR states three precedence rules in its code
comments, docs, CHANGELOG and PR body, and nothing enforced any of them.
Each was confirmed by a mutation that applied and still left all 100 extract
tests passing:

- Dropping the flag merge from the `--config` path where the entry is picked
  by `filename_pattern` — the second `build_config_from_entry` call site.
  Every existing flag test went through `--importer`.
- Reversing the OFX path's currency order so the entry outranks `--currency`.
  The OFX test only covered `--account`.
- Letting `--account` outrank a `--ledger` profile, the opposite of the
  documented rule.

One test per path, each mutation-verified: with the tests in, each mutation
fails exactly its own test. The OFX currency test reads the resolved currency
through `--balance`, so it does not depend on what the OFX file declares.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit ee35aff into main Sep 14, 2026
49 of 52 checks passed
@robcohen
robcohen deleted the fix/extract-importer-flag-precedence branch September 14, 2026 19:34
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.

[Bug]: rledger extract ... --importer "foo" --account "Foo" results in "Expenses:Unknown" instead of the account from the flag

2 participants