Skip to content

refactor(core): Account domain newtype (refs #1163) - #1171

Merged
robcohen merged 2 commits into
mainfrom
feat/account-newtype
May 21, 2026
Merged

robcohen merged 2 commits into
mainfrom
feat/account-newtype

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Second slice of #1163. After #1169 plumbed `Currency`, this PR does the same for `Account` — the 8 `account: InternedStr` fields on Open / Close / Balance / Pad / Note / Document / Posting now use the typed newtype.

What changed

AST field types (rustledger-core/src/directive.rs):

  • `Posting.account`
  • `Open.account`, `Close.account`
  • `Balance.account`
  • `Pad.account`, `Pad.source_account`
  • `Note.account`
  • `Document.account`

All now `crate::Account` instead of `InternedStr`. Constructors take `impl Into` so bare-string call sites continue to compile.

Hot maps migrated in tandem to avoid per-lookup conversions:

  • `BookingEngine.inventories: FxHashMap<Account, Inventory>`
  • `BookingEngine.account_methods: FxHashMap<Account, BookingMethod>`
  • `LedgerState.accounts / inventories / pending_pads / late_close_processed`
  • `Executor`'s per-from balance maps (`FxHashMap<Account, Inventory>`)
  • Report-cmd `BTreeMap<Account, Inventory>` totals (balsheet, income, balances, holdings)
  • `pad::process_pads` internal HashMaps

Error types that previously carried bare `InternedStr`:

  • `AccountedBookingError.account` → `Account`
  • `InterpolationError::CannotInferCurrency.account` → `Account`
  • `CapitalGain.account` → `Account`
  • `PadError.account` → `Option`

Parser (one-line change): `parse_account` returns `Account` instead of `InternedStr`. Everything downstream just compiles.

Loader dedup pass uses `account.as_interned_mut()` to feed the workspace-wide interner without unwrapping the newtype. No allocation, same dedup behaviour.

Why

The compiler can now distinguish accounts from currencies, tags, and arbitrary interned strings at the type level — passing a `Currency` where an `Account` is expected (or vice versa) is now a type error, not a runtime bug.

Performance

  • `Account` is `#[repr(transparent)]` over `InternedStr`
  • `Hash` / `Eq` delegate to `InternedStr` (`Arc::ptr_eq` fast path preserved end-to-end)
  • HashMap keys migrated in tandem — zero conversion sites in hot loops
  • `Borrow` impl preserved for ergonomic `map.get("Assets:Bank")` lookups

What's deferred

  • Tag migration (`Transaction.tags`, `Document.tags`, pushtag/poptag)
  • Link migration (`Transaction.links`, `Document.links`)
  • `MetaValue::{Account, Currency, Tag, Link}` — still `String`, design decision deferred

Test plan

  • `cargo check --workspace --all-features --all-targets` — clean
  • `cargo clippy --workspace --all-features --all-targets -- -D warnings` — clean
  • `cargo test -p rustledger-core -p rustledger-parser -p rustledger-booking -p rustledger-validate -p rustledger-query -p rustledger-loader -p rustledger -p rustledger-lsp --all-features` — 1800+ pass
  • CI full workspace test + compat suite

🤖 Generated with Claude Code

Second slice of #1163 — wraps the account: InternedStr field on
Open, Close, Balance, Pad (account + source_account), Note,
Document, and Posting behind the existing Account newtype.

Pattern matches the Currency slice in #1169:
- AST field types switch to Account
- HashMap/BTreeMap keys migrated in tandem to avoid hot-loop
  conversions (BookingEngine.inventories, BookingEngine.account_methods,
  LedgerState.accounts/inventories/pending_pads/late_close_processed,
  query executor balance maps, report builders)
- Loader dedup pass uses account.as_interned_mut() to feed the
  workspace-wide interner without unwrapping the newtype
- Constructors take impl Into<Account> so bare-string call sites
  continue to compile
- BookingError, InterpolationError, CapitalGain, PadError, and
  AccountedBookingError carry Account instead of InternedStr

What is deferred (next slices):
- Tag migration (Transaction.tags, Document.tags, pushtag/poptag)
- Link migration (Transaction.links, Document.links)
- MetaValue::{Account, Currency, Tag, Link} still String — design
  decision deferred

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner May 20, 2026 23:53
Copilot AI review requested due to automatic review settings May 20, 2026 23:53
@codecov

codecov Bot commented May 20, 2026

Copy link
Copy Markdown

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 continues the domain-typed identifier refactor (refs #1163) by plumbing the Account newtype through the AST and hot-path data structures, replacing prior InternedStr-typed account fields/keys to make account-vs-currency mixups a compile-time error.

Changes:

  • Migrates core directive/account-bearing AST fields (Posting/Open/Close/Balance/Pad/Note/Document) from InternedStr to Account, updating constructors accordingly.
  • Updates downstream booking/validation/query/reporting code to use Account in maps, errors, and processing logic (avoiding per-lookup conversions in hot paths).
  • Adjusts parser and loader dedup/reintern logic to produce and canonicalize Account without allocation.

Reviewed changes

Copilot reviewed 19 out of 19 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/rustledger/src/cmd/report_cmd/income.rs Switch income/expense aggregation maps to Account keys.
crates/rustledger/src/cmd/report_cmd/holdings.rs Switch holdings map to Account keys.
crates/rustledger/src/cmd/report_cmd/balsheet.rs Switch balance-sheet section maps to Account keys.
crates/rustledger/src/cmd/report_cmd/balances.rs Switch balances report map to Account keys.
crates/rustledger/src/cmd/extract_cmd/suggest.rs Update ML suggestion rewrite to assign Posting.account as Account.
crates/rustledger/src/cmd/doctor/missing_open.rs Track opened/used accounts with Account in sets/maps.
crates/rustledger/src/cmd/doctor/directories.rs Track discovered accounts with Account in a BTreeSet.
crates/rustledger-validate/src/validators/balance.rs Update subaccount summation helper to use Account-keyed inventories.
crates/rustledger-validate/src/lib.rs Migrate validator ledger state/pending pads/maps/sets to Account keys.
crates/rustledger-query/src/executor/mod.rs Migrate executor balance maps and running per-account balances to Account.
crates/rustledger-parser/src/parser.rs Make parse_account return Account instead of InternedStr.
crates/rustledger-loader/src/lib.rs Update loader reintern test to validate Account sharing via underlying interned ptr equality.
crates/rustledger-loader/src/dedup.rs Reintern directive pass now mutates Account via as_interned_mut() to dedup across files.
crates/rustledger-core/src/inventory/mod.rs Update booking error context to carry Account (and with_account signature).
crates/rustledger-core/src/identifiers.rs Update identifier module docs to reflect Account is now fully plumbed.
crates/rustledger-core/src/directive.rs Convert directive structs’ account fields to Account; constructors now accept Into<Account>.
crates/rustledger-booking/src/pad.rs Use Account-keyed inventories/pending pad maps and PadError.account: Option<Account>.
crates/rustledger-booking/src/interpolate.rs Update interpolation error variant to store Account for better typed context.
crates/rustledger-booking/src/book.rs Migrate booking engine inventories/account-method maps and gain/error context to Account.

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

Comment thread crates/rustledger-booking/src/pad.rs Resolved
Comment thread crates/rustledger-booking/src/book.rs Resolved
@github-actions

github-actions Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33.6ms ± 0.7ms 25.2 MB
beancount 881.8ms ± 4.8ms 50.6 MB
Comparison 26.2x faster 2.0x less

vs main branch (2026-05-20)

Metric main this PR Change
Time 40.2ms 33.6ms -16.4% 🟢
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

@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 786
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

Addresses Copilot review on #1171.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit fb3a7e2 into main May 21, 2026
59 checks passed
@robcohen
robcohen deleted the feat/account-newtype branch May 21, 2026 01:35
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