Repository navigation
perf(booking): SmallVec for BookingResult::matched - #1077
Conversation
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]>
There was a problem hiding this comment.
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 switchBookingResult::matchedto use it. - Update all
BookingResultconstruction sites ininventory/booking.rsto buildMatchedLots(viaSmallVec::new(),smallvec![...], and.collect()). - Add
smallvecas a workspace dependency and wire it intorustledger-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.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-05-11)
What do these numbers mean?
|
|
| 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]>
Update: tried
|
| 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:
Inventoryalso has twoFxHashMapfields (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 oneVecallocation gets eclipsed by the ~100 ns spent cloning the hashmaps.- 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'smemcpy. 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.
* 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]>
Summary
Refs #1069. Partial fix —
BookingResult::matchedhalf. See "Deferred" below for theInventory::positionspart.BookingResult::matchedchanges fromVec<Position>to a newMatchedLotsalias (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: smallvecmatched: SmallVec::new()(empty case)let mut matched: MatchedLots = SmallVec::new();(FIFO/LIFO loop accumulators, ×4)Deferred:
Inventory::positionsThe 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 (Amount32 +Option<Cost>~72)SmallVec<[Position; 4]>≈ 448 bytes inline (4 × 104 + ~32 header)Vec<Position>≈ 24 bytes emptyBQL aggregations construct many empty
Inventoryinstances (9 sites inexecutor/mod.rsalone). 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 thanVec<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
Inventoryalloc count as a hot spot.BookingResult::matchedis the unambiguous win and ships first.Test plan
cargo test -p rustledger-core --all-features— 338 tests passcargo test -p rustledger-booking— 93 tests passcargo check --workspace --all-features --all-targets— entire workspace compiles unchangedcargo fmt --all -- --check— cleancargo clippy -p rustledger-core -p rustledger-booking --all-features -- -D warnings— clean🤖 Generated with Claude Code