Skip to content

perf(booking): Optimize inventory cloning and capacity hints - #756

Merged
robcohen merged 2 commits into
mainfrom
perf-booking-optimizations
Apr 11, 2026
Merged

robcohen merged 2 commits into
mainfrom
perf-booking-optimizations

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Optimizes inventory cloning in booking engine and adds capacity hints to reduce heap allocations.

Changes

File Change Impact
book.rs:203-211 Clone only needed inventories O(txn accounts) vs O(all accounts)
interpolate.rs:120 Vec::with_capacity(2) Saves 1 alloc per interpolation
pad.rs:102-106 4 capacity hints Saves allocs in pad processing
lib.rs:69 #[must_use] attribute API clarity

Impact

  • Memory reduction: Clones only inventories for accounts in transaction (typically 2-4) instead of all accounts (could be 100+)
  • Performance: Reduces heap allocations for large ledgers with many accounts
  • All 83 tests pass ✅ (75 unit + 8 prop)

rust-skills Rules Addressed

  • mem-vec-with-capacity ✅ Fixed
  • own-clone-excessive ✅ Fixed (inventory cloning)
  • api-must-use ✅ Fixed

rust-skills: mem-vec-with-capacity, own-clone-excessive

Applied rust-skills review recommendations:

1. book.rs:203-211 - Clone only needed inventories
   - Previously cloned ALL inventories for every transaction
   - Now clones only inventories for accounts in the transaction
   - Reduces cloning from O(all accounts) to O(txn accounts)

2. interpolate.rs:120 - Add Vec::with_capacity(2)
   - unassigned_missing typically has 1-2 postings

3. pad.rs:102-106 - Add capacity hints
   - inventories: directives.len().min(16)
   - pending_pads: 4 (typical max concurrent pads)
   - padding_transactions: directives.len().min(16)
   - errors: 4 (rare to have many pad errors)

4. lib.rs:69 - Add #[must_use] attribute
   - infer_cost_currency_from_postings returns important value

Impact: Reduces memory allocations for large ledgers with many
accounts. Typical transaction touches 2-4 accounts, but previous
code cloned all accounts (could be 100+).

Tests: All 83 tests pass (75 unit + 8 prop).
Copilot AI review requested due to automatic review settings April 11, 2026 15:30
@robcohen
robcohen requested a review from a team as a code owner April 11, 2026 15:30
@codecov

codecov Bot commented Apr 11, 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 Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 37.5ms ± 0.5ms 23.1 MB
beancount 869ms ± 4.2ms 50.1 MB
Comparison 23.2x faster 2.2x less

vs main branch (2026-04-11)

Metric main this PR Change
Time 41.9ms 37.5ms -10.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 improves booking-engine performance by reducing unnecessary cloning of inventories during transaction booking and by adding small with_capacity hints to common collections to reduce heap allocations.

Changes:

  • Optimize BookingEngine::book to clone only inventories relevant to the current transaction’s accounts.
  • Add small with_capacity hints in interpolation and pad processing to avoid predictable reallocations.
  • Add #[must_use] to an internal helper returning Option for clearer API usage.

Reviewed changes

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

File Description
crates/rustledger-booking/src/book.rs Limits working inventory cloning to accounts touched by the transaction (but currently re-clones per posting).
crates/rustledger-booking/src/interpolate.rs Pre-allocates unassigned_missing with a small expected capacity.
crates/rustledger-booking/src/pad.rs Adds initial capacity hints for inventories, pending pads, padding transactions, and errors.
crates/rustledger-booking/src/lib.rs Marks infer_cost_currency_from_postings as #[must_use] to discourage ignoring the result.

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

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

github-actions Bot commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

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

The working_inventories population loop cloned the same inventory on
every iteration when `txn.postings` contained multiple postings for the
same account (e.g., main sale + fee posting on `Assets:Stock`). Each
iteration called `.insert(...)` with a fresh clone, silently overwriting
the previous entry and erasing the very optimization this PR is about.

Switch to `entry().or_insert_with(|| inv.clone())` so each unique
account is cloned exactly once regardless of how many postings
reference it. Added a comment so the next person to touch this loop
understands why the entry API is load-bearing here.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@robcohen
robcohen enabled auto-merge April 11, 2026 16:20
@robcohen
robcohen added this pull request to the merge queue Apr 11, 2026
Merged via the queue into main with commit 58cfa94 Apr 11, 2026
33 of 36 checks passed
@robcohen
robcohen deleted the perf-booking-optimizations branch April 11, 2026 16:33
@rustledger-bot rustledger-bot Bot mentioned this pull request Apr 11, 2026
robcohen added a commit that referenced this pull request Apr 11, 2026
Bumps the whole workspace from 0.11.0 to 0.12.0 (minor version bump
under pre-1.0 semver because the cycle since 0.11.0 includes
user-visible breaking changes that release-plz's auto-detection
missed).

release-plz auto-generated a v0.11.1 patch bump from the `fix:` /
`feat:` commits since 0.11.0. That's too conservative. The cycle
since 0.11.0 shipped the following breaking changes, all merged as
`refactor:` / `fix:` without the `!` conventional-commit marker:

- **`rustledger_booking::BookingError`** collapsed three variants
  (`InsufficientUnits`, `NoMatchingLot`, `AmbiguousMatch`) into a
  single `Inventory(AccountedBookingError)` variant (#751). Out-of-tree
  consumers pattern-matching on the old variants break.

- **`rustledger_core::AccountedBookingError`** added as a new
  canonical user-facing type with `BookingError::with_account()` as
  the constructor (#751). Not a break on its own, but part of the
  unification.

- **`rustledger_lsp::handlers::diagnostics::all_diagnostics`**
  signature changed to take an additional `other_buffer_overlays:
  &[(u16, &[Spanned<Directive>])]` parameter for multi-buffer LSP
  overlays (#760 / #764).

- **`rustledger_lsp::handlers::diagnostics::validation_errors_to_diagnostics`**
  signature changed to take an owned `Vec<Spanned<Directive>>`
  instead of borrowed slices (#758). Optimizes a hot path but breaks
  the function's public signature.

- **`rustledger_loader::LoadError::IncludeCycle`** Display format
  rewritten to match Python beancount's `"Duplicate filename
  parsed: ..."` wording (#767). Substring-matching consumers break.

Under pre-1.0 semver, any breaking change should bump the minor
version (0.x → 0.(x+1)). So 0.11.0 → 0.12.0 is correct.

Highlights since 0.11.0:

### Breaking

- Unified `BookingError` under a single `Inventory` variant with one
  canonical `Display` impl, preventing the wording drift that
  produced #748 (#751).
- `LoadError::IncludeCycle` Display now begins with `"Duplicate
  filename parsed: "` to match beancount's wording for conformance
  (#767).
- LSP `all_diagnostics` and `validation_errors_to_diagnostics`
  signatures changed to support the multi-buffer overlay and avoid
  double-cloning directive lists (#758 / #764).

### Features

- LSP live overlay so in-memory buffer edits reflect in diagnostics
  before save, for both the current file (#685 / #758) and any other
  open buffer in a multi-file ledger (#760 / #764).
- Parser `Vec::with_capacity` hints with DoS caps on `source.len()`
  heuristics (#754).
- `working_inventories` cloning in the booking engine now only
  touches accounts actually referenced in the transaction, and
  dedupes repeated account references (#756).

### Fixes

- `InsufficientUnits` booking error wording restored to `"Not enough
  units in ..."` so pta-standards `reduction-exceeds-inventory`
  conformance assertion passes (#748 / #749).
- `noduplicates` plugin now hashes flag, tags, links, cost, and
  price in addition to date and narration — complete beancount
  `hash_entry` parity (#746 / #747).
- Parser test suite: 14 fake-coverage tests replaced with real tests
  that exercise the functions they claim to cover (#766).
- All Copilot inline review comments on #754-#763, #766, #767
  addressed in fix commits.
- Closed PRs #768 (dead incremental parser) and #769 (hallucinated
  simdutf8 API) — no code shipped from these.

### Internal

- Forbid-unsafe-code invariant now has a dedicated CI check and
  pre-push hook (#770).
- New pre-push `cargo check` hook to catch compile errors before PRs
  are opened (#770).

This commit supersedes release-plz's auto-generated v0.11.1 proposal
to produce the minor bump the breaking changes require.

Co-Authored-By: Claude Opus 4.6 (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