Skip to content

semver: parse_version_number calls parse_ascii directly on the already-all-digit slice - #34521

Merged
Jarred-Sumner merged 2 commits into
mainfrom
farm/15ed1e5c/semver-parse-version-number
Jul 18, 2026
Merged

Jarred-Sumner merged 2 commits into
mainfrom
farm/15ed1e5c/semver-parse-version-number

Conversation

@robobun

@robobun robobun commented Jul 18, 2026 •

Copy link
Copy Markdown
Collaborator

What

parse_version_number looped over its input byte by byte, matching on X/x/*, digits, whitespace and ., copying the digits into a 20-byte stack buffer before calling T::parse_ascii on the copy.

All three call sites pass &input[part_start_i..last_char_i], where the bounds come from the parser's own digit scan:

b'0'..=b'9' => {
    part_start_i = i;
    i += 1;
    while i < input.len() && input[i].is_ascii_digit() { i += 1; }
    last_char_i = i;

So the slice is already non-empty and 100% ASCII digits. The match arms for non-digit bytes are unreachable and the buffer copy is redundant work done three times per Version::parse, which runs for every version key in every npm manifest.

Observable bug

The 20-byte buffer guard was length-based, not value-based, so it created an inconsistency at 21 bytes regardless of the numeric value. Two cases:

Overflow. A 20-digit component that overflows u64 went through parse_ascii(...).unwrap_or(T::ZERO) and became Some(0), but a 21+ digit component hit the length guard and returned None, which downstream treats as a wildcard. So adding one more digit flipped a caret/tilde range from matching almost nothing to matching everything:

Bun.semver.satisfies("1.0.0", "^" + "9".repeat(20))  // false
Bun.semver.satisfies("1.0.0", "^" + "9".repeat(21))  // true  (node-semver: false)

Leading zeros. A 21+ byte component whose value fits in u64 (for example thirty leading zeros followed by 5) also hit the length guard and became a wildcard, even though the value is just 5:

Bun.semver.satisfies("6.0.0", "^" + "0".repeat(30) + "5")  // true  (node-semver loose: false)

Fix

Call T::parse_ascii(input) directly and keep the existing unwrap_or(T::ZERO) for overflow. A debug_assert! documents the all-digit invariant. Long components now parse to their numeric value when it fits and clamp to zero when it overflows, with no length cliff at 21 bytes. The caret/tilde cases in the new test agree with node-semver loose mode.

Verification

  • New test long version components are not treated as wildcards fails on current release, passes with the fix.
  • Full test/cli/install/semver.test.ts (27 tests, 1822 expect calls) passes.
  • test/regression/issue/{08040,26657}.test.ts pass.

[review] gate passed · iteration 0 · 2 files touched

fails on main (without fix)
ASAN without fix: 1 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/semver.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (1994a7750)

test/cli/install/semver.test.ts:
(pass) Bun.semver.order() > whitespace bug fix [4.17ms]
(pass) Bun.semver.order() > comparisons [36.17ms]
(pass) Bun.semver.order() > loose compare("0", "0.0") [3.89ms]
(pass) Bun.semver.order() > loose compare("1", "1.0") [1.67ms]
(pass) Bun.semver.order() > loose compare("1.2", "1.2.0") [0.86ms]
(pass) Bun.semver.order() > loose compare("1.x", "1.0.x") [0.75ms]
(pass) Bun.semver.order() > loose compare("1.x.x", "1.0.x") [0.78ms]
(pass) Bun.semver.order() > loose compare("2.x", "1.x") [0.79ms]
(pass) Bun.semver.order() > loose compare("2.x", "2.1") [0.77ms]
(pass) Bun.semver.order() > loose compare("2", "1") [0.77ms]
(pass) Bun.semver.order() > loose compare("3.*", "3.1") [0.76ms]
(pass) B
... (truncated)

release without fix: 2 FAILED
bun test v1.4.0-canary.1 (1498d7b77)

test/cli/install/semver.test.ts:
(pass) Bun.semver.order() > whitespace bug fix [0.08ms]
(pass) Bun.semver.order() > comparisons [0.30ms]
(pass) Bun.semver.order() > loose compare("0", "0.0") [0.04ms]
(pass) Bun.semver.order() > loose compare("1", "1.0")
(pass) Bun.semver.order() > loose compare("1.2", "1.2.0")
(pass) Bun.semver.order() > loose compare("1.x", "1.0.x")
(pass) Bun.semver.order() > loose compare("1.x.x", "1.0.x")
(pass) Bun.semver.order() > loose compare("2.x", "1.x")
(pass) Bun.semver.order() > loose compare("2.x", "2.1")
(pass) Bun.semver.order() > loose compare("2", "1")
(pass) Bun.semver.order() > loose compare("3.*", "3.1")
(pass) Bun.semver.order() > loose compare("3.2.*", "3.2.0")
(pass) Bun.semver.order() > loose compare("4294967295.4294967295.x", "4294967295.4294967295.4294967294")
(pass) Bun.semver.order() > loose compare("*", "4294967295.4294967295.4294967294")
(pass) Bun.semver.order() > equality [0.19ms]
(pass) Bun.semver.satisfies() > expected errors [0.26ms]
(pass) Bun.semver.satisfies() > failures does not cause weird memory issues [86.91ms]
(pass) Bun.semver.satisfies() > exact versions [0.48ms]
30
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/semver.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (1994a7750)

test/cli/install/semver.test.ts:
(pass) Bun.semver.order() > whitespace bug fix [3.89ms]
(pass) Bun.semver.order() > comparisons [35.35ms]
(pass) Bun.semver.order() > loose compare("0", "0.0") [3.08ms]
(pass) Bun.semver.order() > loose compare("1", "1.0") [1.23ms]
(pass) Bun.semver.order() > loose compare("1.2", "1.2.0") [0.78ms]
(pass) Bun.semver.order() > loose compare("1.x", "1.0.x") [0.76ms]
(pass) Bun.semver.order() > loose compare("1.x.x", "1.0.x") [0.78ms]
(pass) Bun.semver.order() > loose compare("2.x", "1.x") [0.78ms]
(pass) Bun.semver.order() > loose compare("2.x", "2.1") [1.14ms]
(pass) Bun.semver.order() > loose compare("2", "1") [0.94ms]
(pass) Bun.semver.order() > loose compare("3.*", "3.1") [0.81ms]
(pass) B
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
[configured] bun-profile → bun (stripped) in 1132ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/76] gen generated_host_exports.rs
generated_host_exports.rs: 91 exports (host=3, lazy=10, generic=78, rust=0); 244 extern-C blocks audited
[1/76] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: component rust-std is up to date

  nightly-2026-05-06-x86_64-unknown-linux-gnu unchanged - rustc 1.97.0-nightly (e95e73209 2026-05-05)

info: checking for self-update (current version: 1.29.0)
�[1m�[92m   Compiling�[0m bun_semver v0.0.0 (/workspace/bun/src/semver)
�[1m�[92m   Compiling�[0m bun_ast v0.0.0 (/workspace/bun/src/ast)
�[1m�[
... (truncated)
diff hotspot
src/semver/Version.rs           | 47 ++++-------------------------------------
 test/cli/install/semver.test.ts | 19 +++++++++++++++++
 2 files changed, 23 insertions(+), 43 deletions(-)

gate history · 1 passed · 0 rejected · iteration 0

evidence per changed file
file                             reads  edits  tests
src/semver/Version.rs                4      1      0
test/cli/install/semver.test.ts      2      3      0

…y-all-digit slice

All three call sites pass a slice bounded by the parser's own digit scan,
so the byte-by-byte match on X/x/*/space/dot and the copy into a 20-byte
stack buffer never do anything. The 20-byte cap also meant a 21+ digit
component returned None (a wildcard) while a 20-digit overflow returned
Some(0), so the two overflow lengths disagreed. Both now return Some(0).
@robobun

robobun commented Jul 18, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 6:17 PM PT - Jul 17th, 2026

⏳ @robobun, your commit 1994a77 is still building in Build #74869, but has 2 failures so far (All Failures):

@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 19 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: fe29e225-2366-4db0-84ab-0f0810f376fe

📥 Commits

Reviewing files that changed from the base of the PR and between 8cac538 and 1994a77.

📒 Files selected for processing (2)
  • src/semver/Version.rs
  • test/cli/install/semver.test.ts

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

@claude claude Bot 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.

LGTM — the inline nit on the test comment is non-blocking.

What was reviewed:

  • Confirmed all three parse_version_number call sites pass &input[part_start_i..last_char_i] from the digit-scan loop, so the all-digit/non-empty invariant holds and the removed match arms were unreachable.
  • Verified bun_core::parse_unsigned returns Err (not panic) on overflow for arbitrarily long digit runs, so unwrap_or(T::ZERO) is reached for both 20- and 21+-digit inputs.
  • Checked the function is module-private (fn, not pub fn) with no other callers; the Option<T> return now never yields None, and the only prior None path (21+ digits → wildcard) is exactly the bug being fixed.
Extended reasoning...

Overview

This PR simplifies VersionType::parse_version_number in src/semver/Version.rs from a ~40-line byte-scanning loop with a 20-byte stack buffer down to a single T::parse_ascii(input).unwrap_or(T::ZERO) call guarded by a debug_assert!. It also adds a regression test in test/cli/install/semver.test.ts covering the observable bug: 21+-digit version components previously fell through to None (wildcard) while 20-digit overflow became Some(0).

Correctness of the invariant

The function is module-private and has exactly three call sites, all inside VersionType::parse at lines 542/547/552, each passing &input[part_start_i..last_char_i]. Those bounds are set inside the b'0'..=b'9' match arm: part_start_i = i (pointing at a digit), then i advances while is_ascii_digit(), then last_char_i = i. So the slice is always ≥1 byte and 100% ASCII digits — the removed X/x/*, whitespace/., and byte_i == 0 branches were provably dead. The new debug_assert! documents this. Wildcard tokens are handled by a separate b'x' | b'*' | b'X' arm in parse, not via this helper.

Security risks

None. This is pure integer parsing of an already-bounded byte slice; no allocation, no I/O, no user-controlled indexing beyond what the caller already validated. bun_core::parse_unsigned accumulates in u128 and returns Err on overflow, so arbitrarily long digit runs degrade to T::ZERO rather than panicking or wrapping.

Level of scrutiny

Low-to-moderate. The change is a net -39 lines to a private helper, replacing dead-code defensive filtering with a documented invariant. The one behavioral change (21+ digits: None → Some(0)) is the intended bug fix, aligns with node-semver, and is covered by the new test which exercises both the 20- and 21-digit boundary across ^, ~, and minor-position placements. The debug-only pretty_errorln! diagnostic is dropped, which is fine — it only fired on overflow and release builds already silently returned 0.

Other factors

The test follows harness conventions (Buffer.alloc(n, fill).toString() instead of .repeat(), added alongside existing tests in the right file). The full 27-test / 1810-assertion suite plus the two related regression tests are reported passing. The single finding is a 4-line comment style nit — purely cosmetic and not worth blocking on.

Comment thread test/cli/install/semver.test.ts Resolved
A component like thirty leading zeros followed by 5 is 31 bytes but has
value 5, so parse_ascii returns Ok(5) rather than hitting the overflow
fallback. The new assertions distinguish Some(5) from both the old
wildcard and from Some(0).

@claude claude Bot 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.

LGTM — the earlier comment nit was addressed and the extra non-overflow >20-byte case is a nice addition.

What was reviewed:

  • Confirmed all three parse_version_number call sites live inside the b'0'..=b'9' arm's digit scan, so the all-digit/non-empty invariant the debug_assert! documents holds and the removed match arms were dead.
  • Checked the behavior change: 21+ digit and zero-padded >20-byte components now go through parse_ascii → unwrap_or(ZERO) like 20-digit ones already did, instead of falling through to None/wildcard.
  • Test uses Buffer.alloc(n, fill), covers the 20/21-byte boundary for both ^ and ~, and the leading-zero case pins that parse_ascii returns the actual value rather than clamping.
Extended reasoning...

Overview

The PR collapses parse_version_number from a ~40-line byte-by-byte loop with a 20-byte stack buffer down to a direct T::parse_ascii(input).unwrap_or(T::ZERO) call plus a debug_assert!. A new test in test/cli/install/semver.test.ts locks in that >20-byte version components are parsed numerically rather than treated as wildcards.

Correctness of the invariant

Grepping confirms the only three callers are the major/minor/patch assignments inside Version::parse's b'0'..=b'9' match arm, which sets part_start_i to the first digit and advances last_char_i past the last consecutive digit before slicing. So the slice passed in is always non-empty and 100% ASCII digits — the removed X/x/*, whitespace/., wildcard-default arms and the byte_i == 0 guard were all unreachable. The debug_assert! is the right mechanism here: the invariant is enforced structurally by the caller, not by user input, so a release-build check would be dead weight.

Behavior change

The only observable change is for components longer than 20 bytes. Previously the buffer bound made those return None (which Partial<T> interprets as a wildcard), while a 20-byte overflowing component already went through unwrap_or(T::ZERO). Now both paths return Some(_) — either the actual value (leading-zero-padded "5" → 5) or T::ZERO on genuine overflow. That removes the length-dependent flip and matches node-semver on the tested caret/tilde ranges. Keeping unwrap_or(T::ZERO) rather than rejecting on overflow preserves the existing 20-digit contract, so this is the minimal consistent fix. The return type staying Option<T> (now always Some) is fine since it's assigned straight into Partial<T>'s Option fields.

Security risks

None. This is pure-Rust integer parsing of an already-bounded byte slice; no unsafe, no allocation, no new untrusted-input surface. If anything the change removes an inconsistency that made adversarial range strings behave surprisingly.

Level of scrutiny

Low-to-medium. The function is on the bun install manifest-parsing hot path, so a regression would be visible, but the diff is a strict simplification whose precondition is verifiable by reading the single caller. The 27-test / 1810-assertion semver suite plus the two named regression tests give good coverage of the surrounding parser.

Other factors

The follow-up commit (1994a77) addressed my earlier nit about the 4-line test comment — it's now two lines stating the invariant plus the node-semver reference, and the same commit added the leading-zero case that distinguishes "clamp on overflow" from "wildcard". Test conventions (Buffer.alloc over .repeat, added alongside existing tests in the module's test file) are followed.

@robobun

robobun commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator Author

CI is red on lanes this diff does not touch:

  • test/js/web/timers/timer-heap-race.test.ts (debian x64-asan): LeakSanitizer leak in TimeoutObject::init_with. Timer code; this PR only edits src/semver/Version.rs. Also failing on main.
  • test/js/third_party/body-parser/express-memory-leak.test.ts (windows x64): memory-ratio flake, passed on retry.
  • Earlier run: test-worker-message-port-transfer-terminate.js (asan): pre-existing main failure.

The semver test suite itself passes on every lane that ran it. Diff is ready for review.

@Jarred-Sumner
Jarred-Sumner merged commit b22dbef into main Jul 18, 2026
73 of 76 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/15ed1e5c/semver-parse-version-number branch July 18, 2026 01:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants