Skip to content

perf(geom): make NURBS derivative allocation-free up to degree 10 - #2434

Merged
FredApps merged 1 commit into
storytold:mainfrom
vangel76:perf-nurbs-derivative-stack
Nov 8, 2026
Merged

FredApps merged 1 commit into
storytold:mainfrom
vangel76:perf-nurbs-derivative-stack

Conversation

@vangel76

@vangel76 vangel76 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

What

Spline::derivative_unchecked (crates/geom/src/nurbs.rs) no longer allocates for splines up to degree 10. It used to allocate six Vecs per call (two bases, three Vecs each) and computed the degree p-1 basis separately, although the degree p recurrence passes through it. Both bases now come from one sweep into stack buffers (basis_pair_into). Degrees 11 and above keep the old heap path.

The same operations run in the same order, so results are bit-identical. The change is local to this function and its new private helper; nothing else in nurbs.rs or spline.rs is touched, to stay clear of #2129, #2122 and #2143. git merge-tree against current upstream/main is clean.

Measurements

Release build, pinned with taskset to one core, perf stat -e instructions:u, same bench program for both binaries (output hashes are identical for old and new):

Scenario Before After Ratio
Spline::length + 20 param_at_length, 40 control points 128.9M 74.8M 1.72x
Spline fillet x30 162.9M 124.0M 1.31x

Tests

  • derivative_is_bit_identical_to_the_heap_implementation: the old implementation is kept as a test-only oracle. It is compared with to_bits over random splines of degree 1 to 12 (clamped and unclamped knots, repeated knots, non-rational, rational, zero and negative weights), at the domain ends, at every knot and its neighbours, out-of-range, NaN and infinite parameters. It asserts that every degree ran more than 1000 comparisons. Degrees 11 and 12 use the unchanged old path, so for them it only checks the dispatch.
  • derivative_dispatch_around_the_stack_limit_does_not_change_results: degrees 10 and 11 against the oracle.
  • cargo test -p cadcraft-geom passes (106 tests), cargo fmt --check and cargo clippy -p cadcraft-geom --all-targets -- -D warnings are clean. I did not run the full cargo xtask ci; only crates/geom changed.

Closes #2431

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements
    • Improved derivative calculations for splines within supported degree ranges, with results remaining consistent with previous behavior.
    • Other degree ranges retain their existing calculation behavior.

derivative_unchecked allocated six Vecs per call and computed the degree
p-1 basis separately although the degree p recurrence passes through it.
Up to degree 10 both bases now come from one sweep into stack buffers;
higher degrees keep the previous heap path. The operations and their order
are unchanged, so results are bit-identical.

The old implementation stays as a test-only oracle, compared bit for bit
over random splines of degree 1 to 12.

Closes storytold#2431

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 336243e and c217537.

Files selected for processing: 1
  • crates/geom/src/nurbs.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Walkthrough

derivative_unchecked now uses a shared stack-based basis sweep for degrees 1 through MAX_STACK_DEGREE. Other degrees retain the heap-based calculation. Tests compare results with the previous implementation across randomized splines and degree boundaries.

Changes: NURBS derivative basis calculation

Layer / File(s) Summary
Paired basis sweep
crates/geom/src/nurbs.rs
A private helper computes degree p and p - 1 basis values in one Cox–de Boor sweep.
Derivative dispatch and equivalence tests
crates/geom/src/nurbs.rs
derivative_unchecked uses stack buffers through MAX_STACK_DEGREE and retains the heap path for other degrees. Tests compare derivative results bit-for-bit with the previous implementation.

Priority: Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Possibly related PRs

  • storytold/cadcraft#1834: Adds stack-based basis evaluation and MAX_STACK_DEGREE infrastructure used by this derivative change.

Suggested reviewers: dylanmtaylor

Merge Risk: Minimal · up to c2175

The derivative uses a shared stack-based sweep for lower degrees and retains the heap path for higher degrees. No merge-blocking issue is evident.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: improving NURBS derivative performance by removing allocations for degrees up to 10.
Linked Issues check Passed Issue #2431 has these coding requirements: (1) use stack buffers instead of heap Vecs in Spline::derivative_unchecked; (2) compute degree p and p-1 bases in one shared sweep, so the degree p-1 basis i…
Out of Scope Changes check Passed The whole-PR diff against the merge base changes only crates/geom/src/nurbs.rs. The changes are: a new import of MAX_STACK_DEGREE; the private helper basis_pair_into; the stack/heap dispatch in deriva…
Full details: Linked Issues check

Explanation

Issue #2431 has these coding requirements: (1) use stack buffers instead of heap Vecs in Spline::derivative_unchecked; (2) compute degree p and p-1 bases in one shared sweep, so the degree p-1 basis is not recomputed separately; (3) keep the heap path for degrees above the stack limit; (4) keep results bit-identical; (5) add an old-versus-new oracle test over random splines; (6) keep the change local to this function. The diff in crates/geom/src/nurbs.rs meets each one. derivative_unchecked now calls the new private helper basis_pair_into when 1 <= p <= MAX_STACK_DEGREE (10, defined in spline.rs at the merge base and unchanged). Otherwise it uses the existing heap basis calls. basis_pair_into performs the same Cox-de Boor operations in the same order as spline.rs basis_into. It saves the degree p-1 state at j == p, before the last step. This matches the separate degree p-1 computation. The test derivative_is_bit_identical_to_the_heap_implementation compares to_bits against derivative_unchecked_old (the previous implementation) for degrees 1 to 12 over random splines and boundary parameters. The test derivative_dispatch_around_the_stack_limit_does_not_change_results covers degrees 10 and 11. The issue reports benchmark numbers as context, not as acceptance criteria. The PR did not run tests in this review, so the bit-identity result rests on code reading and the author's reported test run. No unmet coding requirement was found.

Full details: Out of Scope Changes check

Explanation

The whole-PR diff against the merge base changes only crates/geom/src/nurbs.rs. The changes are: a new import of MAX_STACK_DEGREE; the private helper basis_pair_into; the stack/heap dispatch in derivative_unchecked and its doc comment; and test-module additions (derivative_unchecked_old oracle, XorShift and random_spline generators, bits helper, and two tests). Each change supports objective #2431. The oracle, generators, and tests verify the bit-identical requirement. The helper and dispatch implement the stack-buffer and shared-sweep requirement. spline.rs shows no diff against the merge base, so the change does not touch the areas that the issue cites as shared with #2129, #2122, and #2143. No change lacks a connection to the linked issue.

Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 6 functions across 1 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@vangel76

Copy link
Copy Markdown
Contributor Author

Overview of the three independent speedups in crates/geom from the same audit (#2430, #2431, #2432), so reviewers can see them together. Each PR touches one file, they do not depend on each other and can merge in any order.

PR Where What Measured (release, one pinned core, perf stat -e instructions:u)
#2436 region.rs build (HATCH / BOUNDARY picks) No pair-dedup hash set: each pair is tested once, in the lowest shared grid cell; flat Vec grid 3 picks on 12k segments: 4146M to 912M (4.5x)
#2434 nurbs.rs derivative_unchecked No allocation up to degree 10: both bases from one sweep on the stack Spline length + 20 param_at_length: 128.9M to 74.8M (1.72x); spline fillet x30: 162.9M to 124.0M (1.31x)
#2435 spline.rs solve Elimination limited to the band of the matrix (dense storage kept) 200 fits x 100 points: 210.0M to 91.0M (2.3x); 2 fits x 1000 points: 166.7M to 32.6M (5.1x); tolerance fit, 400 points: 14.1M to 3.7M (3.8x); closed fits: +4% (they keep the full sweep)

All three keep their results bit-identical to the old code: the old implementation stays as a test-only oracle and tests compare the outputs with to_bits over random inputs (the PRs list the guards for signed zeros and non-finite input in #2435). They add no new dependencies.

Known limits: #2435 only does the band-limited loops; band storage with one factorisation for both right-hand sides is a possible follow-up. The pair-budget exit in the long-segment phase of #2436 is not covered by a test. The full cargo xtask ci was not run locally, only the geom checks; CI runs the rest.

@austin62jake austin62jake 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.

Tested on Windows 10 Pro x64 (Rust 1.99.1, cargo-nextest 0.9.150), with this PR merged onto current main (336243e). It merges cleanly, and it works.

  • All 113 cadcraft-geom tests pass, including derivative_is_bit_identical_to_the_heap_implementation and the dispatch test around degree 10/11.
  • cargo xtask ci passes all 7 steps (2622 tests) with this PR merged onto main together with #2435 and #2436, which I tested at the same time, and #2198 so the gate runs on Windows.

Timing on this machine (release build, wall time, three runs each, all within 1.5%; measured with #2435 and #2436 merged too, which don't touch this path): Spline::length plus 20 param_at_length on a 40-point cubic, repeated 200 times, takes 2,635 ms on main and 767 ms with this PR, about 3.4× faster. The sums of the results are identical.

I read basis_pair_into with the never-crash rule in mind. Every index (n[r], left[j - r], right[r + 1], lower[..p]) is at most p, and the length check at the top returns before any of them when a slice is shorter than that. So the indexing can't panic, and degrees above MAX_STACK_DEGREE keep the old heap path.

@FredApps FredApps 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.

ReviewerA — source-read COMMENT (not an approval)

I read the first hunk: the NURBS module imports MAX_STACK_DEGREE from the spline module, and per the title derivative evaluation is allocation-free up to degree 10, using fixed-size stack arrays, as the editing limit says "Highest degree the editing operations work with". Avoiding heap allocations in an evaluation loop is a sound optimisation. The risk is an out-of-bounds index for degrees above the constant, so the code must fall back to heap buffers (not panic) above it. I did not read the implementation. Add tests comparing the stack and heap paths for degrees 1, 3, 10 and 11, derivative orders 0 to 3, knots with multiplicity, and rational splines. Results must be bit-identical to before. Nothing was run.

I ran nothing and have no exact-head CI result for this PR, so this is not an approval. Where a diff was long I read its code hunks rather than every generated or documentation line.

Status: waiting_author.

@FredApps FredApps 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.

Reviewed c2175377fd7ea8207b60d58f1b3a3162ae312ee0. No findings after reviewing the complete implementation and tests. The paired basis sweep preserves the old arithmetic; the slice-size guards bound every access, and degrees above 10 retain the heap path. The existing randomized oracle already covers degrees 1–12, repeated knots, rational and zero/negative weights, endpoint-adjacent parameters, and non-finite parameters. This supersedes my earlier partial review, which asked for tests already present in this head.

Validation: inspected the hosted gate logs, which checked this head merged into 336243e0 as a4b1d2e. All seven gate steps passed (fmt, clippy, tests, i18n, assets, layers, wasm), with 2630 tests passed and 1 skipped. Both derivative oracle/dispatch tests passed. CodeRabbit also passed for this head. No local Rust build or benchmark was run.

@FredApps
FredApps merged commit 0e7e0f5 into storytold:main Nov 8, 2026
6 checks passed
@FredApps

FredApps commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Merged c2175377 into main as 0e7e0f59. The approved head was unchanged, maintainer edits were enabled, and the hosted gate passed. No additional local tests were run for this merge.

2ez4gcx added a commit to 2ez4gcx/cadcraft that referenced this pull request Nov 11, 2026
Brings the branch up to main 6d74488, which has storytold#2954's fix for
mtext::tests::strips_formatting. The one conflict is in
crates/geom/src/nurbs.rs, where main makes the derivative allocation-free
(storytold#2434, basis_pair_into) and this branch adds reversed_loop. The merged
file is main's plus exactly this branch's own lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

[Perf] NURBS derivative allocates six Vecs per call and recomputes the basis

3 participants