Skip to content

feat(extract): importer profiles from open directive metadata - #2262

Merged
robcohen merged 4 commits into
mainfrom
feat/importer-profiles-from-open-metadata
Sep 6, 2026
Merged

robcohen merged 4 commits into
mainfrom
feat/importer-profiles-from-open-metadata

Conversation

@robcohen

@robcohen robcohen commented Sep 5, 2026

Copy link
Copy Markdown
Member

Addresses #2257, proposed by @petemounce in #2126.

An account's open directive already declares the account and its currency — two of the three things an importer needs. --ledger lets it declare the third:

2024-01-01 open Liabilities:CreditCard USD
  importer: "ofx"
  importer-pattern: "*.qfx"
$ rledger extract card.qfx --ledger main.beancount
2024-01-15 * "COFFEE SHOP"
  Liabilities:CreditCard  -50.00 USD
  Expenses:Unknown

Account and currency both come from the directive. No importers.toml is needed at all for a self-describing format like OFX.

Scope: a selector, not a second config format

importer names a built-in parser (csv, ofx) or an importers.toml entry whose column mappings to use. The ledger never carries column mappings itself.

Two reasons. A ledger is a record of what happened, not a configuration file — putting date-column in it means your ledger changes when your bank changes its CSV export. And a full second schema would need keeping in sync with the TOML one forever, which is the two-sources-of-truth problem #2257 flagged as the actual work.

Rules, each with a test

  • Opt-in. Without --ledger nothing here runs, so no existing invocation changes behavior. Accounts without an importer key are ignored, so pointing it at an ordinary ledger is harmless.
  • Currency only when the account opens with exactly one. open Assets:X USD,EUR cannot be narrowed, and guessing which a statement uses would be a silent wrong answer.
  • importer without importer-pattern is an error, not a skip. Such a profile can never match a file, so it is a typo, and staying quiet is how someone ends up believing their profile works.
  • Two accounts claiming one file is an error, matching how importers.toml resolves an ambiguous match. Picking one would make the result depend on directive order in the ledger.
  • --importer outranks a profile — the flag is this invocation, the ledger is standing configuration.
  • A profile outranks importers.toml for account and currency: the open directive is the account's declaration, so a config file disagreeing with it is the bug.

Why --ledger and not --existing

--existing is documented as "existing ledger file for duplicate detection". Reusing it would give one flag two unrelated jobs, and would mean you could not read profiles without also enabling dedup. They may name the same file.

Verification

471 tests pass; 6 new unit tests plus end-to-end checks against the built binary:

--ledger with a matching profile   -> Liabilities:CreditCard, USD
no --ledger                        -> unchanged (Assets:Bank:Checking default)
importer: without importer-pattern -> error naming the account
two accounts matching one file     -> error naming both
open with USD,EUR                  -> currency falls back, account still applies
nonexistent ledger                 -> error

It also composes with #2259: with a correct profile, the statement-vs-account warning stays silent, because the account now matches what the statement says it is.

Note

--ledger also had to be threaded through ag-rledger's arg builder, which constructs Args as a struct literal. That is the third time this session a new Args field has needed it and cargo build --bin rledger has not caught it.

An account's `open` directive already declares the account and its
currency, two of the three things an importer needs. `--ledger` lets it
declare the third, so they need not be repeated in importers.toml.
Addresses #2257, proposed by @petemounce in #2126.

    2024-01-01 open Liabilities:CreditCard USD
      importer: "ofx"
      importer-pattern: "*.qfx"

    $ rledger extract card.qfx --ledger main.beancount

posts to Liabilities:CreditCard in USD with no importers.toml at all.

A selector, not a second config format. `importer` names a built-in
parser (csv/ofx) or an importers.toml entry whose column mappings to
use; the ledger never carries column mappings itself. A ledger is a
record of what happened rather than a configuration file, and a second
full schema would need keeping in sync with the TOML one forever.

Deliberate rules, each with a test:

- Opt-in. Without `--ledger` nothing runs, so no existing invocation
  changes behavior. Accounts without an `importer` key are ignored.
- The currency is taken only when the account opens with exactly one.
  `open Assets:X USD,EUR` cannot be narrowed, and guessing which a
  statement uses would be a silent wrong answer.
- `importer` without `importer-pattern` is an error, not a skip: such a
  profile can never match a file, so it is a typo.
- Two accounts claiming one file is an error, matching how importers.toml
  resolves an ambiguous match. Picking one would make the result depend
  on directive order.
- `--importer` outranks a profile; a profile outranks importers.toml for
  account and currency, since the `open` directive is the account's own
  declaration.

`--ledger` is separate from `--existing` deliberately. Reusing the latter
would give one flag two unrelated jobs.

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 5, 2026 14:40
Copilot AI lite review requested due to automatic review settings September 5, 2026 14:40
@codecov

codecov Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.37587% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/extract_cmd/mod.rs 97.15% 6 Missing ⚠️
...s/rustledger/src/cmd/extract_cmd/ledger_profile.rs 99.54% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

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

There are correctness issues in the new ledger-profile dispatch path (and profile error surfacing) that can lead to selecting the wrong importer or silently ignoring broken profiles.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Adds an opt-in rledger extract --ledger <FILE> path that discovers importer “profiles” from open directive metadata, allowing account/currency (and optionally importer selection) to come from the ledger instead of being duplicated in importers.toml.

Changes:

  • Documented the new --ledger flag and the metadata keys (importer, importer-pattern) in the extract command docs.
  • Added ledger_profile parsing/matching to load profiles from ledger open directives and apply them during extract.
  • Threaded the new Args.ledger field through the CLI (including ag-rledger) and adjusted importer/config resolution to accept an explicitly supplied importer entry name.
File summaries
File Description
docs/commands/extract.md Documents --ledger behavior, keys, and precedence rules.
crates/rustledger/src/cmd/extract_cmd/mod.rs Adds --ledger arg, wires profile loading into dispatch/config selection, and refactors config-entry resolution to accept explicit names.
crates/rustledger/src/cmd/extract_cmd/ledger_profile.rs New module to load/match profiles from open directive metadata (with unit tests).
crates/rustledger/src/bin/ag-rledger.rs Threads ledger through arg builder struct literal.
Review details
  • Files reviewed: 4/4 changed files
  • Comments generated: 2
  • Review effort level: Lite

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

@github-actions

github-actions Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: investment

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 53.3ms ± 6.6ms 852.2ms ± 2.9ms 16.0x 54.9 MB / 50.1 MB
investment 76.6ms ± 7.7ms 3148.7ms ± 73.0ms 41.1x 61.1 MB / 58.2 MB
fifo 75.4ms ± 6.0ms 16441.7ms ± 245.3ms 218.2x 61.0 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 55.4ms ± 5.3ms 53.3ms ± 6.6ms -3.8% ✅ within noise 55.1 MB → 54.9 MB (-0.2%)
investment 71.9ms ± 4.1ms 76.6ms ± 7.7ms +6.5% 🟡 slower 61.2 MB → 61.1 MB (-0.1%)
fifo 73.5ms ± 4.9ms 75.4ms ± 6.0ms +2.6% ✅ within noise 59.1 MB → 61.0 MB (+3.3%)

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

@github-actions

github-actions Bot commented Sep 5, 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 812
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 5, 2026 15:24
Self-review of #2262. All three were in the new code, not pre-existing.

1. A profile naming an `importers.toml` entry never reached the
   dispatcher: `resolve_entry_for_dispatch` was passed `None` instead of
   the profile's entry name. An entry declaring `type = "ofx"` was
   therefore parsed as CSV — precisely the #2260 failure, reintroduced
   through the new path. It survived a first manual test only because a
   single-entry config falls back to "the only entry"; a third entry
   removes that accident and the test now pins it.

2. A profile did not outrank `importers.toml` for the account on the CSV
   path, only on the minimal-config one. The docs and the PR both stated
   the rule that the code implemented in one branch of two. The override
   now applies once after the whole config chain, so `--auto` and raw
   CLI arguments are covered as well.

3. The importers.toml fallback warning claimed "using --account/--currency
   instead" even when a profile had already supplied the account, which
   was simply untrue. It is suppressed when a profile applies.

Both behavioral fixes have a regression test, and both tests fail with
the fix reverted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Second review pass on #2262. Both findings are the same failure this
feature has now hit three times: a thing the user wrote on purpose being
read as absent.

- `importer-pattern` without `importer` was skipped in silence, while
  `importer` without a pattern errored. The halves are equally wrong —
  one can never match a file, the other says which files an account
  claims without saying how to read them — so both now error.

- A key present with a non-string value was read as absent, so
  `importer: 42` quietly meant "no profile here". It is now a type error
  naming the account and the key.

Both have a test, and both tests fail with the fix reverted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Sep 5, 2026
Third review pass on #2262.

- The previous pass made a profile outrank `importers.toml`, but applied
  it unconditionally, so it also overrode an explicit `--importer`. The
  docs said the flag wins; the fix for one precedence bug created
  another. An explicit `--importer` now drops the profile, with a warning
  rather than in silence.

- `rustledger_loader::load` reports parse failures through
  `Ledger::errors`, not `Err`. A ledger that does not parse therefore
  arrived looking like a ledger with no `open` directives, so
  `--ledger broken.beancount` silently applied no profile and imported to
  the `--account` default. `rledger check` reports the same file as a
  parse error. `--ledger` is an explicit request to read a file, so it is
  now an error naming the first diagnostic.

Docs also note that patterns match the filename rather than the path,
matching `filename_pattern`.

Four tests, including that a valid ledger with no profiles stays
harmless.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Sep 6, 2026
Third review pass on #2262.

- The previous pass made a profile outrank `importers.toml`, but applied
  it unconditionally, so it also overrode an explicit `--importer`. The
  docs said the flag wins; the fix for one precedence bug created
  another. An explicit `--importer` now drops the profile, with a warning
  rather than in silence.

- `rustledger_loader::load` reports parse failures through
  `Ledger::errors`, not `Err`. A ledger that does not parse therefore
  arrived looking like a ledger with no `open` directives, so
  `--ledger broken.beancount` silently applied no profile and imported to
  the `--account` default. `rledger check` reports the same file as a
  parse error. `--ledger` is an explicit request to read a file, so it is
  now an error naming the first diagnostic.

Docs also note that patterns match the filename rather than the path,
matching `filename_pattern`.

Four tests, including that a valid ledger with no profiles stays
harmless.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen force-pushed the feat/importer-profiles-from-open-metadata branch from 21ef9b0 to 41eec4e Compare September 6, 2026 02:18
Third review pass on #2262, plus a Copilot finding. All three are the
same shape: something stated on purpose being read as absent.

- The previous pass made a profile outrank `importers.toml` but applied
  it unconditionally, so it also overrode an explicit `--importer`. The
  docs said the flag wins; fixing one precedence rule broke another. An
  explicit `--importer` now drops the profile, with a warning rather than
  in silence.

- `rustledger_loader::load` reports parse failures through
  `Ledger::errors`, not `Err`, so a ledger that does not parse arrived
  looking like one with no `open` directives. `--ledger broken.beancount`
  silently applied no profile and imported to the `--account` default,
  while `rledger check` calls the same file a parse error. It is now an
  error naming the first diagnostic.

- `Pattern::new(..).is_ok_and(..)` at match time turned an invalid glob
  into "did not match", so `importer-pattern: "[unclosed"` silently
  disabled the profile. Patterns are compiled in `load_profiles` and
  carried as `glob::Pattern`, so the silent path no longer exists.

Docs also note that patterns match the filename rather than the path,
matching `filename_pattern`.

Copilot's other finding on this PR - that a profile-named entry's `type`
might not reach the dispatcher - was already fixed by an earlier commit on this branch; verified
against the built binary with a three-entry config so the single-entry
fallback cannot mask it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen force-pushed the feat/importer-profiles-from-open-metadata branch from 41eec4e to 2657892 Compare September 6, 2026 02:20
@robcohen
robcohen enabled auto-merge (squash) September 6, 2026 02:20
@robcohen
robcohen merged commit b98db62 into main Sep 6, 2026
51 checks passed
@robcohen
robcohen deleted the feat/importer-profiles-from-open-metadata branch September 6, 2026 02:43
robcohen added a commit that referenced this pull request Sep 6, 2026
* feat(extract): refuse an unconfigured liability import

Closes #2256.

An OFX statement states which side of the balance sheet it describes.
#2259 used that to warn when the configured account contradicts it. This
covers the case underneath: when nothing configured an account at all.

Importing a credit-card statement with no `--account`, no importers.toml
entry and no `--ledger` profile posted it to the `Assets:Bank:Checking`
default, inverting the sign of every transaction and using an account the
user never named. That is now refused, with the three ways to name one.

The account argument becomes `Option<String>` rather than carrying a clap
default, because "not named" and "named as the default" are genuinely
different and only the first is refused. Comparing against the default
string instead would have refused an explicit `-a Assets:Bank:Checking`
while merely warning about `-a Assets:Foo`, which is arbitrary. A test
pins that clap and the guard share one constant.

Deliberately not the account NAME inference the issue also asked about.
`Liabilities:CreditCard` is a guess about someone's chart of accounts,
not a fact in the file, and the module already refuses to guess a
currency for the same reason. Since the issue was filed, #2261 and #2262
gave two ways to supply the account without repeating it, so the case for
inventing a name is weaker than it was; the reasoning is recorded on the
issue.

Four tests, and the refusal test fails with the guard disabled.

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

* fix(extract): the refusal must consider every account source

Copilot review on #2263, plus the rustdoc failure it exposed.

The guard's comment said "no --account, no importers.toml entry, no
--ledger profile", but the code checked only `args.account`. An entry or
profile naming the same string as the default was therefore treated as
"nobody named an account" and the import refused. The comment described
the intent; the code implemented a third of it.

All three sources now collapse into one `named_account` binding, used
both to build the config and to decide the refusal, so the two cannot
disagree about what was named.

Also:

- The rustdoc build failed: the public `account` field linked to
  `DEFAULT_ACCOUNT` and `Args::account_or_default`, both private. Named
  in prose instead. `cargo clippy` and `cargo test` do not catch this;
  `cargo doc -D warnings` does, and it is now run before pushing.

- The `DEFAULT_ACCOUNT` comment still called it "the clap default" after
  the clap default was removed.

One test, which fails with the guard reverted to the args-only check.

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

---------

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

2 participants