Skip to content

fix: honor name_* account-root renames in reports and BQL (beanquery parity) - #1731

Merged
robcohen merged 4 commits into
mainfrom
fix/config-aware-account-types
Jul 10, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/config-aware-account-types

Conversation

@robcohen

@robcohen robcohen commented Jul 9, 2026

Copy link
Copy Markdown
Member

Found by the Phase-0 duplication sweep (L5). beancount ledgers can rename their five root accounts (option "name_income" "Revenue") — both engines accept them at check-time, but every rledger consumer classified accounts against hardcoded prefixes. Two user-visible bugs, verified against beanquery 3.2.3:

  • report income rendered an EMPTY income statement under a renamed Income root; same class in balsheet/holdings/networth routing.
  • BQL POSSIGN diverged from beanquery (-100.00 vs +100.00 on a renamed credit-normal root); ACCOUNT_SORTKEY sorted renamed roots as custom where beanquery classifies them.

Fix: one config-aware classifier, threaded everywhere

  • core: new AccountTypes + AccountTypeKind — kind() / is_balance_sheet() / is_income_statement() / is_credit_normal() / sort_index() against the configured names.
  • loader: Options::to_account_types().
  • reports: LoadedReport carries it; balsheet/income/holdings/networth route by kind() — no hardcoded prefixes remain in report routing.
  • query: Executor holds it (set_account_types); POSSIGN + ACCOUNT_SORTKEY classify through it. Threaded via ShellSettings (CLI batch + interactive) and the ffi-component (query/batch/session). query-entries keeps defaults — its WIT contract carries no options (documented inline).

Verified

  • Renamed fixture vs beanquery 3.2.3: POSSIGN +100.00 and ACCOUNT_SORTKEY 3-Revenue:Sales match exactly; income statement shows Revenue:Sales → Net Income 100.00.
  • New report_account_rename_test.rs pins all four surfaces (4 tests).
  • Default-name behavior unchanged: report/CLI (57+8+3), query (12 suites), core/loader green; clippy 0; fmt clean.

Follow-ups (registry, not this PR): remaining cosmetic raw-prefix sites (~9), wasm executor default (wasm LedgerOptions lacks name_* fields today), possible WIT option-passing for query-entries.

🤖 Generated with Claude Code

…parity)

beancount lets a ledger rename its five root accounts (`option
"name_income" "Revenue"`); both engines accept such ledgers at
check-time, but every rledger consumer that classified accounts by
root did so against hardcoded prefixes. Two user-visible bugs:

- `report income` rendered an EMPTY income statement under a renamed
  Income root (`starts_with("Income:")` misses "Revenue:Sales"); same
  class in balsheet/holdings/networth routing.
- BQL `POSSIGN` diverged from beanquery: -100.00 vs beanquery's
  +100.00 on a renamed credit-normal root (hardcoded
  Liabilities|Equity|Income set). `ACCOUNT_SORTKEY` sorted renamed
  roots as custom/5 where beanquery classifies them (index 3).

Fix: a single config-aware classifier, threaded everywhere:

- core: new `AccountTypes` (+ `AccountTypeKind`) — kind()/
  is_balance_sheet()/is_income_statement()/is_credit_normal()/
  sort_index() against the CONFIGURED names; Default = standard five.
- loader: `Options::to_account_types()`.
- reports: `LoadedReport` carries it; balsheet/income/holdings/
  networth route by kind() — no hardcoded prefixes remain in report
  routing.
- query: `Executor` holds `AccountTypes` (default standard) with
  `set_account_types`; POSSIGN + ACCOUNT_SORTKEY classify through it.
  CLI query threads it via ShellSettings (batch + interactive); the
  ffi-component threads it in `query`, `batch`, and session `query`
  from loaded options. `query-entries` keeps defaults — its WIT
  contract carries no options (documented at the call site).

Verified vs beanquery 3.2.3 on the renamed fixture: POSSIGN +100.00
and ACCOUNT_SORTKEY "3-Revenue:Sales" now match exactly; income
statement shows Revenue:Sales / Total Income -100.00 / Net Income
100.00. New report_account_rename_test.rs pins all four surfaces.
Default-name behavior unchanged (report/CLI/query suites green).

Found by the Phase-0 duplication sweep (account-type classification
family: ~13 raw-prefix sites; this fixes the correctness-bearing ones
— the remaining cosmetic sites are follow-up).

Co-Authored-By: Claude Fable 5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner July 9, 2026 15:42
Copilot AI review requested due to automatic review settings July 9, 2026 15:42
@github-actions

github-actions Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 30.5ms ± 0.3ms 23.6 MB
beancount 854.9ms ± 4.4ms 50.7 MB
Comparison 28x faster 2.1x less

vs main branch (2026-07-10)

Metric main this PR Change
Time 33.7ms 30.5ms -9.5% 🟢
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

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.

Pull request overview

This PR fixes root-account renames (option "name_*" ...) being ignored by report routing and BQL classification by introducing a config-aware AccountTypes classifier and threading it through reports, the query executor, CLI shells, and the FFI component surface to match beancount/beanquery behavior.

Changes:

  • Added rustledger_core::AccountTypes / AccountTypeKind for rename-aware account classification (routing, credit-normal checks, sort index).
  • Updated reports (balsheet/income/holdings/networth) to route by AccountTypes::kind() instead of hardcoded "Assets:"/"Income:" prefixes.
  • Updated BQL executor and hosts (CLI + FFI component) so POSSIGN and ACCOUNT_SORTKEY use configured roots; added regression tests covering the renamed-root surfaces.

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
crates/rustledger/tests/report_account_rename_test.rs Adds regression tests validating report routing and BQL behavior under renamed roots.
crates/rustledger/src/cmd/report_cmd/networth.rs Uses AccountTypes to classify assets/liabilities for net worth instead of prefix checks.
crates/rustledger/src/cmd/report_cmd/mod.rs Threads AccountTypes through report loading and dispatch to all relevant reports.
crates/rustledger/src/cmd/report_cmd/income.rs Routes income/expense sections via AccountTypes::kind().
crates/rustledger/src/cmd/report_cmd/holdings.rs Filters holdings to configured Assets root via AccountTypes.
crates/rustledger/src/cmd/report_cmd/balsheet.rs Routes balance sheet sections via AccountTypes::kind().
crates/rustledger/src/cmd/query/output.rs Configures the query Executor with ledger-specific AccountTypes.
crates/rustledger/src/cmd/query/mod.rs Stores AccountTypes in ShellSettings and passes it into interactive/batch execution.
crates/rustledger/src/cmd/query/interactive.rs Wires AccountTypes into interactive shell settings.
crates/rustledger-query/src/executor/mod.rs Adds account_types to Executor, defaults it, and applies it to POSSIGN/ACCOUNT_SORTKEY.
crates/rustledger-query/src/executor/functions/account.rs Makes account_type_index use AccountTypes::sort_index() (rename-aware).
crates/rustledger-loader/src/options.rs Adds Options::to_account_types() constructor for the classifier.
crates/rustledger-ffi-component/src/convert.rs Threads configured AccountTypes into query execution for FFI batch/query/session paths.
crates/rustledger-core/src/lib.rs Re-exports new account type symbols from identifiers.
crates/rustledger-core/src/identifiers.rs Introduces AccountTypeKind and AccountTypes with kind/sign/sort helpers.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 811
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 2 commits July 10, 2026 02:10
split(':').next() can never return None, so the unwrap_or fallback
was unreachable; split_once makes the root-vs-whole-name cases
explicit.

Co-Authored-By: Claude Fable 5 <[email protected]>
The deep review found the PR's own bug class still alive on the wasm
embedding surface: api::query, api::query_multi_file, and the shared
execute_query behind ParsedLedger::query / Ledger::query / balances()
constructed executors without set_account_types, so POSSIGN and
ACCOUNT_SORTKEY silently misclassified renamed ledgers there.

- helpers::account_types_from_raw derives core AccountTypes from raw
  parsed option tuples (the wasm wire LedgerOptions deliberately
  carries no name_*); single-file paths use it (ParsedLedger has
  parse_result in both new() and from_cache(), which re-parses).
- Multi-file paths use loader Options::to_account_types; the Ledger
  struct carries the value, and the cache payload persists it as five
  root names (CACHE_VERSION 2 -> 3 — version mismatch falls back to
  re-parse, the established mechanism) so fromCache ledgers classify
  identically.

Co-Authored-By: Claude Fable 5 <[email protected]>
@codecov

codecov Bot commented Jul 10, 2026

Copy link
Copy Markdown

@robcohen
robcohen merged commit ae5dd3a into main Jul 10, 2026
53 of 54 checks passed
@robcohen
robcohen deleted the fix/config-aware-account-types branch July 10, 2026 09:13
robcohen added a commit that referenced this pull request Jul 10, 2026
…ecks, quarter math) (#1741)

* chore: consolidate utility copies (CSV/JSON escaping, account-type checks, quarter math)

Utility-census batch from the Phase-1 sweep (U1/U2/U5). All changes
behavior-identical; no user-visible output changes.

- CSV escaping: report_cmd csv_escape and BQL output escape_csv were
  byte-identical private copies. Hoist to
  rustledger_core::format::escape_csv (with unit tests); both CLI
  sites now delegate (report_cmd via a pub(super) use alias so the 26
  call sites are untouched).
- JSON escaping: report_cmd json_escape hand-chained replace() over
  exactly the escape set core's format::escape_string handles
  (backslash, quote, \n, \r, \t) — aliased to the core fn, hand chain
  deleted.
- Account-type checks: four production sites re-derived the account
  type from raw string prefixes; they now use the core helpers
  (ACCOUNT_TYPES / account_type), so a future sixth type or rule
  change has one home:
  - LSP on_type_formatting + utils is_account_like: the deliberately
    colon-less mid-typing heuristics now iterate core ACCOUNT_TYPES.
  - check_drained plugin: six hand-written clauses (three prefixes +
    three bare-root equalities) collapse to a three-arm match on
    core account_type, which classifies by root component.
  - split_expenses plugin: is_expense via account_type (identical for
    any parsable account, which always has >= 2 components).
- Quarter math: the (month - 1) / 3 formula appeared twice within
  query functions/date.rs, diverging only in off-by-one framing
  (DATE_TRUNC zero-based vs QUARTER() one-based). Single
  const quarter_index0 helper now feeds both.

Deliberately NOT in this batch:
- report-section routing sites (balsheet/income/networth/holdings)
  are already rewritten config-aware by open PR #1731 — touching
  them here would conflict.
- networth's period bucketing was NOT ported onto query IntervalUnit:
  its buckets are label-string equality (ISO %V weeks) and switching
  machinery risks silent boundary changes for purely cosmetic dedup.
  Reports adopting DisplayContext (U4) is user-visible and belongs in
  its own PR, like #1728.

Note: test_account_lifecycle_consistency (integration_test.rs) fails
on main BEFORE this change — rledger check passes an
account-used-before-open ledger that Python rejects. Pre-existing;
tracked separately.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: reattach add_days docs; tighten escape_csv wording; hoist import (review)

- quarter_index0 had been inserted between add_days's doc block and
  its fn, so rustdoc attached the wrong docs; moved above the block,
  plus a debug_assert and a note on the 1-based month contract.
- escape_csv doc said "newline"; only \n triggers quoting (\r does
  not), matching the prior copies byte-for-byte — say so.
- escape_csv import moved to the top import group in query output.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs: DATE_BIN quarter arm is not a quarter_index0 user (deep review)

Its bucketing is origin- and width-relative months arithmetic, not
calendar-quarter indexing — the doc claimed a third call site that
does not (and could not) exist.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs: split escape_csv doc paragraph (clippy 1.97 length lint)

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
robcohen added a commit that referenced this pull request Jul 10, 2026
* docs: canonical-function discipline and toolchain-bump runbook

Distills the 2026-07 duplication review (PRs #1731-#1743) into standing
guidance: the one anti-pattern every found bug traced to, the ranked
remedies (call the canonical / document divergence at both sites /
drift-guard test), the current canonical inventory, the two supporting
test-hygiene rules (#1729, #1742), and the lockstep toolchain-bump
procedure learned from #1745/#1751.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs: scope the pin claim to stable-channel sites (review)

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
@robcohen robcohen mentioned this pull request Jul 11, 2026
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