Skip to content

perf(booking): SmallVec for BookingResult::matched - #1077

Merged
robcohen merged 4 commits into
mainfrom
perf/issue-1069-smallvec-booking
May 11, 2026
Merged

robcohen merged 4 commits into
mainfrom
perf/issue-1069-smallvec-booking

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Refs #1069. Partial fix — BookingResult::matched half. See "Deferred" below for the Inventory::positions part.

BookingResult::matched changes from Vec<Position> to a new MatchedLots alias (SmallVec<[Position; 1]>). STRICT booking — the default booking method — produces exactly one matched lot per reducing posting, so storing the result inline eliminates the per-posting heap allocation on the booking hot path. FIFO / LIFO frequently produce single-lot matches too.

Why this is shape-compatible

SmallVec<[T; N]> derefs to [T], so every read-side consumer works unchanged:

  • for matched_pos in &booking_result.matched (book.rs:239) ✓
  • result.matched.iter() (proptests) ✓
  • result.matched.len() (book.rs:236, mod.rs tests) ✓
  • result.matched.is_empty() (mod.rs tests) ✓

The only write-side touch is at the 5 construction sites in inventory/booking.rs:

  • let matched: MatchedLots = matching.into_iter().cloned().collect(); (×2)
  • matched: smallvec![matched] (×2)
  • matched: SmallVec::new() (empty case)
  • let mut matched: MatchedLots = SmallVec::new(); (FIFO/LIFO loop accumulators, ×4)

Deferred: Inventory::positions

The original issue scope included Inventory::positions: Vec<Position> → SmallVec<[Position; N]>. After sizing out the trade-off I decided against it for this PR:

  • Position ≈ 104 bytes (Amount 32 + Option<Cost> ~72)
  • SmallVec<[Position; 4]> ≈ 448 bytes inline (4 × 104 + ~32 header)
  • Vec<Position> ≈ 24 bytes empty

BQL aggregations construct many empty Inventory instances (9 sites in executor/mod.rs alone). A 4-slot inline capacity adds ~400 bytes per inventory in the empty case, which probably outweighs the alloc-count savings for that path. A 1-slot variant cuts that in half but still 5x bigger than Vec<Position> empty, and only wins for inventories with exactly 1 position.

This needs a benchmark before committing. I'll follow up with a measurement-driven PR if profiling shows Inventory alloc count as a hot spot. BookingResult::matched is the unambiguous win and ships first.

Test plan

  • cargo test -p rustledger-core --all-features — 338 tests pass
  • cargo test -p rustledger-booking — 93 tests pass
  • cargo check --workspace --all-features --all-targets — entire workspace compiles unchanged
  • cargo fmt --all -- --check — clean
  • cargo clippy -p rustledger-core -p rustledger-booking --all-features -- -D warnings — clean
  • CI (compatibility, regression, MSRV)

🤖 Generated with Claude Code

STRICT booking (the default) produces exactly one matched lot per
reducing posting; FIFO / LIFO frequently match a single lot too.
Replace `Vec<Position>` with `SmallVec<[Position; 1]>` so the common
case stores the lot inline instead of allocating a heap Vec.

Public-API impact: `BookingResult::matched` field type changes from
`Vec<Position>` to a new `MatchedLots` alias (`SmallVec<[Position; 1]>`,
re-exported from `rustledger_core`). `SmallVec` derefs to `[Position]`,
so all read-side consumers (iteration, `.len()`, `.is_empty()`,
indexing, `.iter()`) work unchanged — the existing call sites in
`book.rs`, the proptest harness, and the inventory unit tests required
zero code changes.

Deferred from #1069 scope: the `Inventory::positions` switch. After
sizing it out (Position ~104 bytes × inline capacity vs 24-byte empty
Vec), the trade-off isn't obviously positive — BQL aggregations
construct many empty `Inventory` instances, and an inline capacity of
4 would balloon each from 24 to ~448 bytes. Will revisit with a
benchmark-driven follow-up if the alloc count shows up in profiles.

Refs #1069

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

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 optimizes the booking hot path by replacing BookingResult::matched’s heap-allocating Vec<Position> with an inline-capacity collection (SmallVec<[Position; 1]>) to avoid allocations in the common single-lot match case (especially under STRICT booking).

Changes:

  • Introduce MatchedLots = SmallVec<[Position; 1]> and switch BookingResult::matched to use it.
  • Update all BookingResult construction sites in inventory/booking.rs to build MatchedLots (via SmallVec::new(), smallvec![...], and .collect()).
  • Add smallvec as a workspace dependency and wire it into rustledger-core.

Reviewed changes

Copilot reviewed 5 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
crates/rustledger-core/src/lib.rs Re-exports MatchedLots alongside existing inventory types.
crates/rustledger-core/src/inventory/mod.rs Defines MatchedLots and changes BookingResult::matched to use it.
crates/rustledger-core/src/inventory/booking.rs Updates booking implementations to construct MatchedLots instead of Vec.
crates/rustledger-core/Cargo.toml Adds smallvec dependency to rustledger-core.
Cargo.toml Adds smallvec = "1" to workspace dependencies.
Cargo.lock Locks the new smallvec dependency.

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

Comment thread crates/rustledger-core/src/lib.rs Resolved
@codecov

codecov Bot commented May 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 60.00000% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/booking.rs 60.00% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 26.2ms ± 0.7ms 21.9 MB
beancount 587.2ms ± 4.2ms 50.3 MB
Comparison 22.4x faster 2.3x less

vs main branch (2026-05-11)

Metric main this PR Change
Time 34.2ms 26.2ms -23.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 11, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

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

Adds bench cases for the small-N regime that the existing
inventory_bench didn't cover. Motivated by an experiment to
swap Inventory::positions from Vec to SmallVec[Position; 1] — the
benches showed the change was a regression (clone got 30-70%
slower across all sizes because the FxHashMap fields dominate
clone cost and the larger struct hurts cache behavior). The
SmallVec change was reverted; the benches stay so a future
attempt has the baseline to measure against.

Refs #1069

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen

Copy link
Copy Markdown
Member Author

Update: tried Inventory::positions → SmallVec<[Position; 1]>, reverted

Added small-N benches (inventory_add/0..1000 extended to include 0/1/2/3; new inventory_clone/0..10) to capture the regime where storage choice should matter most. Captured a baseline with the current Vec<Position>, then made the SmallVec switch. Result was a clear regression across the board:

Bench Vec<Position> SmallVec<[Position; 1]> Δ
inventory_add/0 9.76 ns 16.88 ns +74%
inventory_add/1 97.15 ns 98.28 ns ~0%
inventory_add/2 162.67 ns 160.47 ns ~0%
inventory_add/3 234.92 ns 303.46 ns +26%
inventory_add/10 1.20 µs 1.08 µs −9%
inventory_clone/0 13.56 ns 23.36 ns +72%
inventory_clone/1 51.58 ns 68.62 ns +32%
inventory_clone/2 86.71 ns 108.88 ns +24%
inventory_clone/3 99.63 ns 141.25 ns +40%
inventory_clone/10 294.65 ns 411.76 ns +38%

Why inventory_clone/1 got slower (the one I expected to win)

I expected the 1-position clone to win because no heap allocation. It didn't. The reasons after analysis:

  1. Inventory also has two FxHashMap fields (simple_index + units_cache). For a 1-position inventory those maps each hold one entry; their clone (including a fresh bucket-allocation) dominates the wall-clock cost. The ~50 ns saved from skipping one Vec allocation gets eclipsed by the ~100 ns spent cloning the hashmaps.
  2. Larger struct = worse cache behavior. SmallVec's union representation forces more careful unwrapping per element, and clone of inline data doesn't vectorize as cleanly as Vec's memcpy. Net cost per element is higher.

Decision

Reverted the Inventory::positions change. Kept the new benches — they make this kind of experiment cheap to redo in the future (e.g., if we eventually lazy-allocate the hashmaps or change Position's layout, the trade-off might flip).

The shipped PR scope is now just BookingResult::matched: SmallVec<[Position; 1]> + the inventory benches. BookingResult::matched is still an unambiguous win (STRICT booking always produces a 1-element result; no FxHashMap competing for clone cycles).

Will update the PR title to reflect the reduced scope.

robcohen and others added 2 commits May 10, 2026 22:41
* Drop MatchedLots re-export from rustledger_core root and make the
  alias pub(crate). External code that reads BookingResult.matched
  via the slice deref (.iter(), .len(), indexing) is unaffected; only
  internal modules that need to name the concrete type by alias use
  it. This avoids committing downstream consumers to smallvec as
  part of our public API surface.

* Document the BookingResult.matched type change as breaking with a
  release-bump note (0.15.0). The pre-1.0 minor-bump convention
  applies, but flagging it in the doc comment makes the constraint
  explicit at the point of use.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit bad3311 into main May 11, 2026
40 checks passed
@robcohen
robcohen deleted the perf/issue-1069-smallvec-booking branch May 11, 2026 03:55
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