Skip to content

fix(loader)!: read account-name options as leaves under a root, as beancount does - #2415

Merged
robcohen merged 2 commits into
mainfrom
fix/account-option-leaf-semantics-2408
Sep 24, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/account-option-leaf-semantics-2408

Conversation

@robcohen

Copy link
Copy Markdown
Member

The decision (#2408)

Beancount's semantics end to end, plus a migration warning. Chosen after the analysis in this session.

  • What beancount specifies: v2 and v3 both define the five previous/current account options as "Leaf name of the equity account …", validated by options_validate_leaf_account (is_valid_leaf) and joined onto name_equity by get_previous_accounts / get_current_accounts. Defaults are Opening-Balances, Earnings:Previous, Conversions:Previous, Earnings:Current, Conversions:Current. account_unrealized_gains is a leaf too, under the income root (doctor.py).
  • How rustledger diverged:
    • rledger check rejected beancount's form with E7002 (option "account_previous_balances" "Anfang"; bean-check exits 0);
    • docs/reference/options.md documented the full-name form, which beancount reads as Equity:Equity:…;
    • the component exported full names, and rustfava's balance sheet shows Equity:Equity:Earnings:Current and Equity:Equity:Conversions:Current in its committed snapshots, because its tree.py joins the root on, as fava does.
  • Why not "accept both forms": the same ledger would name different accounts in rledger and in beancount, and in rledger and rustfava, which always joins. That is the kind of silent disagreement correctness-first rules out.

What changes

option value before after
"Anfang" (beancount's form) error[E7002] Equity:Anfang
"Equity:Anfang" (rustledger's old documented form) Equity:Anfang Equity:Equity:Anfang, as in beancount, plus warning[E7010]: ... resolves to "Equity:Equity:Anfang"; write "Anfang" for Equity:Anfang
unset, name_equity "Eigenkapital" Eigenkapital:Opening-Balances (since #2410) same
"bad leaf" E7002 E7002
  • Loader:
    • fields hold the leaf (beancount's defaults), and previous_*_account / current_*_account return the full name;
    • the join lives in one place, rustledger_loader::resolve_leaf_account;
    • is_valid_leaf runs the canonical account lexer on Assets:<leaf>.
  • E7010: a warning, raised once all options are set, since name_* can follow the account options. It is raised in the loader's post-parse pass, the LSP's single-file path and wasm's validate_option_tuples. Loads with option warnings are never cached, so a cached load cannot hide it.
  • Component contract 3.12.0 (API_VERSION 3.12): ledger-options carries the leaves, as beancount's options map does, documented in world.wit. account-current-conversions is always present (Conversions:Current when unset), because a host falling back to its own full-name default would double it. In-process consumers (BQL summaries, session.clamp) resolve through resolve_leaf_account.
  • Caches: loader v37 and wasm v28. A v36 entry archives the old full-name defaults, which the new code would read as leaves and resolve to Equity:Equity:Opening-Balances. The MetaValue / CostNumber layout tripwires advance their FIXTURE_VERSION only; their fixture bytes and hash are unchanged, confirming no directive layout moved.
  • Docs: options.md gets an account-name options section with a table; the configuration table and a new E7010 entry in errors.md are updated.

Tests

Downstream

Moving to a release with this change, rustfava's tree.py needs no change: it already joins the root, and now gets Equity:Earnings:Current. Its committed Equity:Equity:* snapshots will update, and its options.py fallback defaults (full names) become dead, since every key is now always exported. I'll file that as a rustfava issue linking this PR.

Closes #2408

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…ancount does

beancount v2 and v3 define `account_previous_balances`, `_earnings`,
`_conversions` and `account_current_earnings`, `_conversions` as LEAF names
("Leaf name of the equity account ..."), validated with `is_valid_leaf` and
joined onto `name_equity` by `get_previous_accounts` /
`get_current_accounts`; fava joins them the same way. rustledger took them
as full account names:

- `rledger check` rejected beancount's form (`option
  "account_previous_balances" "Anfang"`) with E7002, which bean-check
  accepts;
- the docs told users to write `"Equity:Retained-Earnings"`, which beancount
  reads as `Equity:Equity:Retained-Earnings`;
- the component exported full names, and rustfava, joining the root as fava
  does, showed `Equity:Equity:Earnings:Current` in its balance sheet.

The loader now stores and validates leaves (beancount's defaults), and
resolves full names in one place, `resolve_leaf_account`. A value that starts
with one of the ledger's root names, the old documented form, resolves as
beancount resolves it and raises the new warning E7010 naming the leaf to
write, after all options are set (in the loader, the LSP and wasm).

The component contract moves to 3.12.0: `ledger-options` carries the leaves,
as beancount's options map does, with `account-current-conversions` always
present, and in-process consumers (BQL summaries, session clamp) resolve
them. Loader cache v37 and wasm cache v28: cached options hold the old
full-name defaults.

Closes #2408

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 September 24, 2026 14:48
@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.55072% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-loader/src/options.rs 98.50% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 43.9ms ± 1.1ms 568.4ms ± 3.1ms 13.0x 51.2 MB / 50.0 MB
investment 64.5ms ± 1.0ms 2216.4ms ± 7.8ms 34.3x 55.1 MB / 58.0 MB
fifo 62.3ms ± 1.0ms 12446.0ms ± 230.3ms 199.8x 53.1 MB / 57.7 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 43.3ms ± 0.9ms 43.9ms ± 1.1ms +1.3% ✅ within noise 51.0 MB → 51.2 MB (+0.4%)
investment 65.1ms ± 1.2ms 64.5ms ± 1.0ms -0.9% ✅ within noise 55.2 MB → 55.1 MB (-0.0%)
fifo 62.1ms ± 1.0ms 62.3ms ± 1.0ms +0.3% ✅ within noise 57.1 MB → 53.1 MB (-7.1%)

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

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 178 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

…account

A value that is the equity root itself ("Equity") was told to write
"Equity", and one under another root ("Income:Oops") was told to write
"Oops", naming an unrelated equity account. Only a value under the equity
root has a leaf form; the others now say why none exists.

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

Copy link
Copy Markdown
Member Author

Deep review

Fixed in fa87193: E7010's advice was wrong for two input shapes.

  • A value that is exactly the equity root ("Equity") was told to write "Equity".
  • A value under another root ("Income:Oops") was told to write "Oops", which names an unrelated equity account.

Now only a value under the equity root gets a "write X" suggestion. The other two cases say why no leaf form exists. There is a test for each shape, and errors.md covers them.

Checked, no change needed

  • Consumer sweep. Only three places read the raw option values: the FFI export, summary_accounts_from, and clamp_accounts. All three resolve through resolve_leaf_account. The remaining hardcoded Equity:Opening-Balances strings are pad examples and tests.

  • E7010 edge cases. It fires when name_equity is set after the option, a custom root is caught, Equity:Equity:X suggests Equity:X, and defaults stay silent. Loads that raise option warnings are never cached.

  • Mutation testing (cargo mutants --in-diff): 8 mutants, 6 caught, 2 unviable, 0 missed.

  • Local checks: the workspace suite ran 171 test binaries with 0 failures. Clippy and rustdoc pass with -D warnings.

  • rustfava check (advisory, red): the 5 failing tests are the intended changes.

    rustfava needs a snapshot refresh to match (Balance sheet shows Equity:Equity:Earnings:Current; refresh for rustledger component 3.12 (leaf account options) rustfava#327).

@robcohen
robcohen merged commit 6a41dd3 into main Sep 24, 2026
67 of 68 checks passed
@robcohen
robcohen deleted the fix/account-option-leaf-semantics-2408 branch September 24, 2026 16:40
robcohen added a commit that referenced this pull request Oct 7, 2026
- 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 added a commit that referenced this pull request Oct 8, 2026
…inks (#2495)

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

`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

* chore: regenerate cargo-vet exemptions

* fix(extract): harden import dedup found in adversarial review

- 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

* fix(extract): make import dedup order-independent and reimport-safe

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

* fix(extract): flag money-only dedup matches and harden the matcher

- 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

* fix(extract): bound the skip report and warn on a partly broken --existing

- 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

* fix(importer): check the transaction id column up front and warn on repeats

- 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

* fix(importer): refuse misconfigured transaction id columns up front

- 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

* docs(extract): make the Monzo and CSV Options examples work as written

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

* docs(dedup): bring the roadmap, CHANGELOG numbers and doc examples up 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

* docs(dedup): drop comments describing the pre-#2421 matcher

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
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.

account_previous_* / account_current_* options: beancount takes them relative to name_equity; rledger rejects that form (E7002)

1 participant