Skip to content

perf(loader): Fix rust-skills CRITICAL and HIGH issues - #763

Merged
robcohen merged 2 commits into
mainfrom
fix-loader-issues
Apr 11, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix-loader-issues

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Fixes rust-skills violations in the loader crate related to API safety, memory allocation, and cloning.

Changes

File Change Impact
lib.rs:332 #[must_use] on load() API safety - ensures Result handled
lib.rs:384-389 Vec::with_capacity() Saves 1 alloc per cycle detection
lib.rs:481-483 Remove clone() Avoids intermediate PathBuf clone

Impact

  • API Safety: #[must_use] prevents accidentally ignoring load errors
  • Memory: Reduces allocations during cycle detection
  • Performance: Eliminates unnecessary PathBuf clone
  • Loader crate compiles successfully ✅

rust-skills Rules Addressed

  • api-must-use ✅ Fixed
  • mem-vec-with-capacity ✅ Fixed
  • own-clone-explicit ✅ Fixed

rust-skills: api-must-use, mem-vec-with-capacity, own-clone-explicit

Applied rust-skills review recommendations:

1. lib.rs:332 - Add #[must_use] to load()
   - Ensures callers handle the Result
   - Prevents accidentally ignoring load errors

2. lib.rs:384-389 - Vec::with_capacity for cycle detection
   - Pre-allocate Vec with known size (include_stack.len() + 1)
   - Saves 1 alloc per cycle detection

3. lib.rs:481-483 - Remove unnecessary clone()
   - Use .to_string() and .to_path_buf() directly
   - Avoids intermediate PathBuf clone

Tests: Loader crate compiles successfully.
Copilot AI review requested due to automatic review settings April 11, 2026 15:59
@robcohen
robcohen requested a review from a team as a code owner April 11, 2026 15:59

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 addresses rust-skills findings in the rustledger-loader crate by tightening API usage guarantees and making small allocation/cloning adjustments in the loader’s recursive include processing.

Changes:

  • Added #[must_use] to Loader::load() to encourage callers to handle the returned Result.
  • Adjusted include-cycle error construction to pre-size the Vec<String> used for the cycle path.
  • Replaced some explicit .clone() calls with .to_string() / .to_path_buf() when constructing LoadError::PathTraversal.

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

Comment thread crates/rustledger-loader/src/lib.rs Resolved
@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 36.9ms ± 0.6ms 23 MB
beancount 848.4ms ± 3.1ms 50.1 MB
Comparison 23x faster 2.2x less

vs main branch (2026-04-11)

Metric main this PR Change
Time 41.9ms 36.9ms -11.9% 🟢
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 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

Copilot flagged that `Vec::with_capacity(self.include_stack.len() + 1)`
followed by `extend` + `push` is unnecessarily verbose when
`collect::<Vec<_>>()` on a chain of two `ExactSizeIterator`s already
preallocates the exact capacity via `size_hint`. This is the
cycle-error cold path, so the concern is readability not micro-perf.

Rewrote to `.map(...).chain(std::iter::once(...)).collect()`. Added a
comment explaining why the verbose pre-allocation form isn't
necessary here, so nobody re-introduces it thinking it's faster.

Also fixes three pre-existing clippy errors on the branch that were
blocking `-D warnings`, none of which were from this PR's original
diff but which broke the CI once the Copilot review commit landed:

- `double_must_use` on `Loader::load` — the `#[must_use]` attribute
  was redundant because the return type (`Result<LoadResult, _>`)
  is already `#[must_use]`. Removed the redundant attribute.
- `implicit_clone` on `include_path.to_string()` and
  `root.to_path_buf()` — both were already references to the owned
  type (`&String`, `&PathBuf`), so `.to_string()` / `.to_path_buf()`
  were doing an implicit clone that clippy wants spelled explicitly.
  Replaced with `.clone()`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@robcohen
robcohen enabled auto-merge April 11, 2026 16:40
@robcohen
robcohen disabled auto-merge April 11, 2026 16:46
@robcohen
robcohen enabled auto-merge April 11, 2026 16:46
@robcohen
robcohen added this pull request to the merge queue Apr 11, 2026
Merged via the queue into main with commit 8f4e4d1 Apr 11, 2026
30 of 33 checks passed
@robcohen
robcohen deleted the fix-loader-issues branch April 11, 2026 16:59
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