Skip to content

fix(install): change semver core numbers to u64 - #22889

Merged
Jarred-Sumner merged 9 commits into
mainfrom
dylan/fix-large-semver-core-numbers
Sep 23, 2025
Merged

Jarred-Sumner merged 9 commits into
mainfrom
dylan/fix-large-semver-core-numbers

Conversation

@dylan-conway

@dylan-conway dylan-conway commented Sep 22, 2025 •

Copy link
Copy Markdown
Member

What does this PR do?

Sometimes packages will use very large numbers exceeding max u32 for major/minor/patch (usually patch). This pr changes each core number in bun to u64.

Because we serialize package information to disk for the binary lockfile and package manifests, this pr bumps the version of each. We don't need to change anything other than the version for serialized package manifests because they will invalidate and save the new version. For old binary lockfiles, this pr adds logic for migrating to the new version. Even if there are no changes, migrating will always save the new lockfile. Unfortunately means there will be a one time invisible diff for binary lockfile users, but this is better than installs failing to work.

fixes #22881
fixes #21793
fixes #16041
fixes #22891

resolves BUN-7MX, BUN-R4Q, BUN-WRB

How did you verify your code works?

Manually, and added a test for migrating from an older binary lockfile.

@robobun

robobun commented Sep 22, 2025 •

Copy link
Copy Markdown
Collaborator
Updated 6:04 PM PT - Sep 22nd, 2025

❌ @dylan-conway, your commit a35a08c has some failures in Build #26636 (All Failures)


🧪   To try this PR locally:

bunx bun-pr 22889

That installs a local version of the PR into your bun-22889 executable, so you can run:

bun-22889 --bun

@coderabbitai

coderabbitai Bot commented Sep 22, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

💤 Files selected but had no reviewable changes (1)
  • src/install/lockfile/Package.zig
⛔ Files ignored due to path filters (4)
  • test/cli/install/__snapshots__/bun-workspaces.test.ts.snap is excluded by !**/*.snap
  • test/integration/next-pages/test/__snapshots__/dev-server-ssr-100.test.ts.snap is excluded by !**/*.snap
  • test/integration/next-pages/test/__snapshots__/dev-server.test.ts.snap is excluded by !**/*.snap
  • test/integration/next-pages/test/__snapshots__/next-build.test.ts.snap is excluded by !**/*.snap

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Adds FormatVersion v3 and lockfile v2→v3 migration detection and saving; parameterizes semver/Version/VersionedURL/Resolution over integer width (u64 primary, u32 legacy); bumps npm manifest cache version; widens semver query integer widths; adds a test validating bun.lockb v2→v3 migration and idempotency.

Changes

Cohort / File(s) Summary
Lockfile versioning & migration
src/install/lockfile.zig, src/install/lockfile/bun.lockb.zig, src/install/PackageManager/install_with_manager.zig, test/cli/install/migrate-bun-lockb-v2.test.ts
Add FormatVersion.v3 and set current to v3; add migrated_from_lockb_v2: bool to SerializerLoadResult; detect/propagate migrate-from-v2 during load; save lockfile when migration occurred; include test for v2→v3 migration and idempotency.
Semver / Version / VersionedURL / Resolution refactor
src/semver/Version.zig, src/semver.zig, src/install/versioned_url.zig, src/install/resolution.zig
Convert concrete types to generic factories parameterized by integer type (u64 primary, u32 legacy): VersionType, VersionedURLType, ResolutionType; expose aliases (Version = VersionType(u64), OldV2Version = VersionType(u32), etc.); add migrate helpers; update methods to use generic This; expand parsing/formatting/comparison APIs.
Semver query widening
src/semver/SemverQuery.zig
Replace u32 with u64 for generated range endpoints in Token.toRange wildcard branches (.major, .minor, .patch).
NPM manifest serializer version bump
src/install/npm.zig
Bump PackageManifest.Serializer version string to "bun-npm-manifest-cache-v0.0.6\n" and document semver components now use u64.

Suggested reviewers

  • Jarred-Sumner
  • zackradisic

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title Check ✅ Passed The title "fix(install): change semver core numbers to u64" is a concise, single-sentence description that correctly highlights the primary change—widening semver core numbers to u64 in install/semver-related code. It follows conventional-commit style, is directly related to the diff, and is clear enough for a reviewer scanning history to understand the main intent. No misleading or extraneous content is present.
Linked Issues Check ✅ Passed The linked issue #22881 reports a crash caused by semver components exceeding u32; this PR systematically widens semver core fields to u64 across semver types, VersionedURL, Resolution, SemverQuery, and updates serialization and lockfile migration logic, plus adds a migration test. Those code changes directly target the coding objective of preventing the crash by supporting larger version components and ensuring older lockfiles are migrated. I therefore judge the PR compliant with the linked issue's coding objective, though platform-specific verification is recommended.
Out of Scope Changes Check ✅ Passed I do not find changes that are unrelated to the stated objective; modified files, serialization/version bumps, and the added migration/test all align with converting semver core numbers to u64 and supporting migration. The PR introduces broad public-API refactors (parametric/generic types and aliases) but these appear to be direct consequences of widening the integer widths rather than unrelated feature additions. Those public-surface changes should receive careful compatibility review but are not out-of-scope.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
Description Check ✅ Passed The PR description follows the repository template by including both "What does this PR do?" and "How did you verify your code works?" sections. The "What" section gives a clear, specific explanation of the u32→u64 semver change, serialization/version bumps, lockfile migration behavior, and lists linked issues and resolution IDs. The "How" section states manual verification and an added migration test, which together make the description sufficiently informative for reviewers.

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

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

Actionable comments posted: 6

🧹 Nitpick comments (7)
src/install/versioned_url.zig (1)

29-37: Consider adding a reverse migration method for completeness.

While the current implementation only needs forward migration from u32 to u64, consider whether a reverse migration method might be useful for testing or debugging purposes.

        pub fn migrate(this: @This()) VersionedURLType(u64) {
            if (comptime SemverIntType != u32) {
                @compileError("unexpected SemverIntType");
            }
            return .{
                .url = this.url,
                .version = this.version.migrate(),
            };
        }
+
+       // For testing/debugging purposes only
+       pub fn downgrade(this: @This()) VersionedURLType(u32) {
+           if (comptime SemverIntType != u64) {
+               @compileError("unexpected SemverIntType");
+           }
+           return .{
+               .url = this.url,
+               .version = this.version.downgrade(),
+           };
+       }
    };
src/install/lockfile/bun.lockb.zig (1)

275-289: Confirm lockfile version handling; log unexpected version for debugging

  • Verified: FormatVersion enum defines v0..v3 and pub const current = v3 (src/install/lockfile.zig:1579–1591). bun.lockb.zig checks the format, rejects formats > current, and only allows migrating from v2 (src/install/lockfile/bun.lockb.zig:277–289).
  • Recommendation (optional refactor): make the "Unexpected lockfile version" error include the numeric format for debugging — since load() has a log: *logger.Log parameter, log the unexpected value before returning, or return a distinct error that carries the version.
src/semver/Version.zig (3)

57-59: Saturate u32 addition to avoid overflow

Edge-case but cheap to fix.

-            return this.tag.build.len + this.tag.pre.len;
+            return std.math.add(u32, this.tag.build.len, this.tag.pre.len) catch std.math.maxInt(u32);

269-271: Nit: symmetry/readability in equality

No behavior change; call lhs.tag.eql(rhs.tag).

-            return lhs.major == rhs.major and lhs.minor == rhs.minor and lhs.patch == rhs.patch and rhs.tag.eql(lhs.tag);
+            return lhs.major == rhs.major and lhs.minor == rhs.minor and lhs.patch == rhs.patch and lhs.tag.eql(rhs.tag);

1-2: Optional: add scoped debug logger

For traceability during migrations/parsing:

Add near the imports:

const log = bun.Output.scoped(.semver, false);

Use e.g. log("parsed {s}: {any}", .{ slice, result }); behind debug guards.

src/install/resolution.zig (2)

64-71: Use InvalidSemver for semver parse failures

Distinguish malformed semver from unexpected resolution kinds.

-                    if (!parsed.valid) {
-                        return error.UnexpectedResolution;
-                    }
+                    if (!parsed.valid) {
+                        return error.InvalidSemver;
+                    }
@@
-                    if (parsed.version.major == null or parsed.version.minor == null or parsed.version.patch == null) {
-                        return error.UnexpectedResolution;
-                    }
+                    if (parsed.version.major == null or parsed.version.minor == null or parsed.version.patch == null) {
+                        return error.InvalidSemver;
+                    }

1-6: Optional: add scoped debug logger

Helpful for fromTextLockfile failure paths and odd resolutions.

Add near imports:

const log = bun.Output.scoped(.resolution, false);

Use e.g. log("fromTextLockfile: '{s}' -> {s}", .{ res_str, @tagName(result.tag) }); under debug.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 0b54932 and 72af711.

📒 Files selected for processing (9)
  • src/install/PackageManager/install_with_manager.zig (1 hunks)
  • src/install/lockfile.zig (2 hunks)
  • src/install/lockfile/bun.lockb.zig (3 hunks)
  • src/install/npm.zig (1 hunks)
  • src/install/resolution.zig (1 hunks)
  • src/install/versioned_url.zig (1 hunks)
  • src/semver.zig (1 hunks)
  • src/semver/Version.zig (1 hunks)
  • test/cli/install/migrate-bun-lockb-v2.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

Files:

  • src/install/PackageManager/install_with_manager.zig
  • src/install/lockfile/bun.lockb.zig
  • src/install/lockfile.zig
  • src/semver.zig
  • src/install/npm.zig
  • src/install/versioned_url.zig
  • src/semver/Version.zig
  • src/install/resolution.zig
**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)

**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue

**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup

Files:

  • src/install/PackageManager/install_with_manager.zig
  • src/install/lockfile/bun.lockb.zig
  • src/install/lockfile.zig
  • src/semver.zig
  • src/install/npm.zig
  • src/install/versioned_url.zig
  • src/semver/Version.zig
  • src/install/resolution.zig
test/**

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

Place all tests under the test/ directory

Files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
test/cli/**/*.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes

Files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
test/**/*.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable

Files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
test/**/*.test.ts

📄 CodeRabbit inference engine (test/CLAUDE.md)

test/**/*.test.ts: Name test files *.test.ts and use bun:test
Do not write flaky tests: never wait for arbitrary time; wait for conditions instead
Never hardcode port numbers in tests; use port: 0 to get a random port
When spawning Bun in tests, use bunExe() and bunEnv from harness
Prefer async/await in tests; for a single callback, use Promise.withResolvers()
Do not set explicit test timeouts; rely on Bun’s built-in timeouts
Use tempDir/tempDirWithFiles from harness for temporary files and directories in tests
For large/repetitive strings in tests, prefer Buffer.alloc(count, fill).toString() over "A".repeat(count)
Import common test utilities from harness (e.g., bunExe, bunEnv, tempDirWithFiles, tmpdirSync, platform checks, GC helpers)
In error tests, assert non-zero exit codes for failing processes and use toThrow for synchronous errors
Use describe blocks for grouping, describe.each for parameterized tests, snapshots with toMatchSnapshot, and lifecycle hooks (beforeAll, beforeEach, afterEach); track resources for cleanup in afterEach
Use using/await using with Bun resources (e.g., Bun.listen/connect/spawn/serve) to ensure cleanup in tests

Files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
test/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

test/**/*.test.{ts,tsx}: Test files must be placed under test/ and end with .test.ts or .test.tsx
In tests, always use port: 0; do not hardcode ports or use custom random port functions
In tests, use normalizeBunSnapshot when asserting snapshots
Never write tests that merely assert absence of "panic" or "uncaught exception" in output
Avoid shell commands (e.g., find, grep) in tests; use Bun.Glob and built-ins instead
Prefer snapshot tests over exact stdout equality assertions

Files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Format JavaScript/TypeScript files with Prettier (bun run prettier)

Files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
🧠 Learnings (10)
📚 Learning: 2025-08-30T09:09:18.384Z
Learnt from: Jarred-Sumner
PR: oven-sh/bun#22231
File: src/bundler/bundle_v2.zig:48-48
Timestamp: 2025-08-30T09:09:18.384Z
Learning: In Zig, when a module exports a top-level struct, import("./Module.zig") directly returns that struct type and can be used as a type alias without needing to access a field within the module. This is a common pattern in the Bun codebase.

Applied to files:

  • src/semver.zig
  • src/install/resolution.zig
📚 Learning: 2025-08-30T00:11:00.890Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/javascriptcore-class.mdc:0-0
Timestamp: 2025-08-30T00:11:00.890Z
Learning: Applies to **/*.zig : Declare the extern C symbol in Zig and export a Zig-friendly alias for use

Applied to files:

  • src/semver.zig
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/js/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)

Applied to files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
📚 Learning: 2025-09-03T17:10:13.486Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.486Z
Learning: Applies to test/**/*.test.ts : Name test files `*.test.ts` and use `bun:test`

Applied to files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/cli/**/*.{js,ts} : Place CLI command tests (e.g., bun install, bun init) under test/cli/

Applied to files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes

Applied to files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/**/*.{js,ts} : Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test

Applied to files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
📚 Learning: 2025-09-03T17:10:13.486Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.486Z
Learning: Applies to test/**/*.test.ts : When spawning Bun in tests, use `bunExe()` and `bunEnv` from `harness`

Applied to files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
📚 Learning: 2025-09-08T00:41:12.052Z
Learnt from: CR
PR: oven-sh/bun#0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-09-08T00:41:12.052Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add a corresponding test case in test/v8/v8.test.ts that invokes checkSameOutput with the new function

Applied to files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Do not use node:fs APIs in tests; mutate files via dev.write, dev.patch, and dev.delete

Applied to files:

  • test/cli/install/migrate-bun-lockb-v2.test.ts
🧬 Code graph analysis (1)
test/cli/install/migrate-bun-lockb-v2.test.ts (2)
src/js/internal-for-testing.ts (1)
  • install_test_helpers (81-86)
test/harness.ts (1)
  • tempDir (277-284)
🔇 Additional comments (10)
src/semver.zig (1)

5-5: LGTM!

The addition of the VersionType re-export aligns with the parametric version type factory pattern used across the PR to support both u32 (legacy) and u64 (current) semver components.

src/install/PackageManager/install_with_manager.zig (1)

785-785: LGTM!

The addition of migrated_from_lockb_v2 to the lockfile save condition ensures that migrated lockfiles are always persisted, even when no substantive changes occurred. This is essential for completing the one-time migration from lockfile v2 to v3 format.

src/install/lockfile.zig (1)

1586-1590: LGTM!

The lockfile format version has been correctly incremented to v3, and the public Package export has been parameterized with u64 to support the expanded semver component width. This aligns with the PR's goal of supporting packages with version numbers exceeding u32 limits.

src/install/npm.zig (1)

931-932: LGTM!

The manifest cache version has been correctly incremented to v0.0.6 to reflect the semver component type change from u32 to u64. This ensures old cached manifests will be invalidated and regenerated with the new format.

src/install/lockfile/bun.lockb.zig (2)

256-256: LGTM!

The addition of the migrated_from_lockb_v2 field to SerializerLoadResult correctly tracks when a lockfile has been migrated from the v2 format.


305-311: LGTM!

The migration flag is correctly propagated through the package loading process and into the final result structure, ensuring the migration status is available to callers.

test/cli/install/migrate-bun-lockb-v2.test.ts (1)

9-63: LGTM! Comprehensive migration test.

The test thoroughly validates the v2 to v3 lockfile migration:

  1. Correctly sets up the test environment with saveTextLockfile = false to ensure binary format
  2. Verifies the lockfile is saved after migration (line 37)
  3. Confirms the raw bytes differ due to semver size changes (line 43)
  4. Ensures the parsed structure remains equivalent (line 45)
  5. Validates idempotency - subsequent installs don't re-save the lockfile (lines 48-62)
src/install/versioned_url.zig (1)

1-39: LGTM! Well-designed generic approach for supporting multiple semver integer types.

The parametric VersionedURLType factory elegantly handles both u32 (legacy) and u64 (current) semver components:

  • Clean separation between the old v2 format (OldV2VersionedURL) and the current format (VersionedURL)
  • All methods correctly use @This() for generic self-reference
  • The migrate method properly enforces compile-time constraints
src/semver/Version.zig (1)

9-9: ABI check: zero-length array in extern struct

_tag_padding becomes [0]u8 for u64. Zero-sized fields may be problematic for extern layout depending on Zig version/target C ABI. Please confirm CI coverage across all targets and Zig version used.

Run to compare object layouts across targets (darwin/linux/windows) in your CI matrix and ensure no compile warnings/errors around zero-sized extern fields. If needed, we can wrap the field in a comptime if (IntType == u32) to only emit it for u32.

src/install/resolution.zig (1)

388-434: Resolve — Tag discriminants unchanged.
The Tag enum in src/install/resolution.zig is identical between origin/main and this PR; discriminants did not change, so no v2→v3 remapping is required.

Comment on lines +234 to 279
return switch (lhs.tag) {
.root => true,
.npm => lhs.value.npm.eql(rhs.value.npm),
.local_tarball => lhs.value.local_tarball.eql(
rhs.value.local_tarball,
lhs_string_buf,
rhs_string_buf,
),
.folder => lhs.value.folder.eql(
rhs.value.folder,
lhs_string_buf,
rhs_string_buf,
),
.remote_tarball => lhs.value.remote_tarball.eql(
rhs.value.remote_tarball,
lhs_string_buf,
rhs_string_buf,
),
.workspace => lhs.value.workspace.eql(
rhs.value.workspace,
lhs_string_buf,
rhs_string_buf,
),
.symlink => lhs.value.symlink.eql(
rhs.value.symlink,
lhs_string_buf,
rhs_string_buf,
),
.single_file_module => lhs.value.single_file_module.eql(
rhs.value.single_file_module,
lhs_string_buf,
rhs_string_buf,
),
.git => lhs.value.git.eql(
&rhs.value.git,
lhs_string_buf,
rhs_string_buf,
),
.github => lhs.value.github.eql(
&rhs.value.github,
lhs_string_buf,
rhs_string_buf,
),
else => unreachable,
};
}

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.

⚠️ Potential issue

Avoid unreachable for .uninitialized in eql

Two .uninitialized values could reach here and panic. Gracefully return false.

-                else => unreachable,
+                .uninitialized => false,
+                else => unreachable,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return switch (lhs.tag) {
.root => true,
.npm => lhs.value.npm.eql(rhs.value.npm),
.local_tarball => lhs.value.local_tarball.eql(
rhs.value.local_tarball,
lhs_string_buf,
rhs_string_buf,
),
.folder => lhs.value.folder.eql(
rhs.value.folder,
lhs_string_buf,
rhs_string_buf,
),
.remote_tarball => lhs.value.remote_tarball.eql(
rhs.value.remote_tarball,
lhs_string_buf,
rhs_string_buf,
),
.workspace => lhs.value.workspace.eql(
rhs.value.workspace,
lhs_string_buf,
rhs_string_buf,
),
.symlink => lhs.value.symlink.eql(
rhs.value.symlink,
lhs_string_buf,
rhs_string_buf,
),
.single_file_module => lhs.value.single_file_module.eql(
rhs.value.single_file_module,
lhs_string_buf,
rhs_string_buf,
),
.git => lhs.value.git.eql(
&rhs.value.git,
lhs_string_buf,
rhs_string_buf,
),
.github => lhs.value.github.eql(
&rhs.value.github,
lhs_string_buf,
rhs_string_buf,
),
else => unreachable,
};
}
return switch (lhs.tag) {
.root => true,
.npm => lhs.value.npm.eql(rhs.value.npm),
.local_tarball => lhs.value.local_tarball.eql(
rhs.value.local_tarball,
lhs_string_buf,
rhs_string_buf,
),
.folder => lhs.value.folder.eql(
rhs.value.folder,
lhs_string_buf,
rhs_string_buf,
),
.remote_tarball => lhs.value.remote_tarball.eql(
rhs.value.remote_tarball,
lhs_string_buf,
rhs_string_buf,
),
.workspace => lhs.value.workspace.eql(
rhs.value.workspace,
lhs_string_buf,
rhs_string_buf,
),
.symlink => lhs.value.symlink.eql(
rhs.value.symlink,
lhs_string_buf,
rhs_string_buf,
),
.single_file_module => lhs.value.single_file_module.eql(
rhs.value.single_file_module,
lhs_string_buf,
rhs_string_buf,
),
.git => lhs.value.git.eql(
&rhs.value.git,
lhs_string_buf,
rhs_string_buf,
),
.github => lhs.value.github.eql(
&rhs.value.github,
lhs_string_buf,
rhs_string_buf,
),
.uninitialized => false,
else => unreachable,
};
}
🤖 Prompt for AI Agents
In src/install/resolution.zig around lines 234 to 279, the switch currently uses
`else => unreachable`, which will panic if two `.uninitialized` values are
compared; change the switch to explicitly handle `.uninitialized` (or replace
the `else` with `|.uninitialized => false`) so that comparing two uninitialized
variants returns false instead of crashing, keeping all other arms the same.

Comment thread src/semver/Version.zig
Comment on lines +65 to +67
pub fn format(formatter: Formatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
const self = formatter.version;
try std.fmt.format(writer, "{?d}.{?d}.{?d}", .{ self.major, self.minor, self.patch });

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.

⚠️ Potential issue

Fix formatting: {?d} on non-optionals will not compile

self.major/minor/patch are plain integers, not optionals. Use {d}.

-                try std.fmt.format(writer, "{?d}.{?d}.{?d}", .{ self.major, self.minor, self.patch });
+                try std.fmt.format(writer, "{d}.{d}.{d}", .{ self.major, self.minor, self.patch });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn format(formatter: Formatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
const self = formatter.version;
try std.fmt.format(writer, "{?d}.{?d}.{?d}", .{ self.major, self.minor, self.patch });
pub fn format(formatter: Formatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
const self = formatter.version;
try std.fmt.format(writer, "{d}.{d}.{d}", .{ self.major, self.minor, self.patch });
🤖 Prompt for AI Agents
In src/semver/Version.zig around lines 65 to 67, the format string uses the
optional-specifier `{?d}` for self.major/minor/patch which are plain integers
and will not compile; change the format specifiers to `{d}` (e.g. "{d}.{d}.{d}")
and keep the argument list as .{ self.major, self.minor, self.patch } so the
formatter matches the non-optional integer types.

Comment thread src/semver/Version.zig
Comment on lines +398 to +410
// Skip remaining valid pre/build tag characters and whitespace.
// Does not validate whitespace used inside pre/build tags.
if (!validPreOrBuildTagCharacter(d) or std.ascii.isWhitespace(d)) return .major;
i += 1;

// patch is done and at input end, valid
// at this point the semver is valid so we can return true if it ends
if (i >= version.len) return pinned;
d = version[i];
}

// Skip remaining valid pre/build tag characters and whitespace.
// Does not validate whitespace used inside pre/build tags.
if (!validPreOrBuildTagCharacter(d) or std.ascii.isWhitespace(d)) return .major;
i += 1;
while (validPreOrBuildTagCharacter(d) and !std.ascii.isWhitespace(d)) {
i += 1;
if (i >= version.len) return pinned;
d = version[i];
}

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.

⚠️ Potential issue

Correct whichVersionIsPinned tag/whitespace check (logic bug)

Intent is “allow valid tag chars or whitespace; otherwise, bail.” Current or turns valid whitespace into failure.

-            if (!validPreOrBuildTagCharacter(d) or std.ascii.isWhitespace(d)) return .major;
+            if (!validPreOrBuildTagCharacter(d) and !std.ascii.isWhitespace(d)) return .major;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Skip remaining valid pre/build tag characters and whitespace.
// Does not validate whitespace used inside pre/build tags.
if (!validPreOrBuildTagCharacter(d) or std.ascii.isWhitespace(d)) return .major;
i += 1;
// patch is done and at input end, valid
// at this point the semver is valid so we can return true if it ends
if (i >= version.len) return pinned;
d = version[i];
}
// Skip remaining valid pre/build tag characters and whitespace.
// Does not validate whitespace used inside pre/build tags.
if (!validPreOrBuildTagCharacter(d) or std.ascii.isWhitespace(d)) return .major;
i += 1;
while (validPreOrBuildTagCharacter(d) and !std.ascii.isWhitespace(d)) {
i += 1;
if (i >= version.len) return pinned;
d = version[i];
}
// Skip remaining valid pre/build tag characters and whitespace.
// Does not validate whitespace used inside pre/build tags.
if (!validPreOrBuildTagCharacter(d) and !std.ascii.isWhitespace(d)) return .major;
i += 1;
// at this point the semver is valid so we can return true if it ends
if (i >= version.len) return pinned;
d = version[i];
while (validPreOrBuildTagCharacter(d) and !std.ascii.isWhitespace(d)) {
i += 1;
if (i >= version.len) return pinned;
d = version[i];
}
🤖 Prompt for AI Agents
In src/semver/Version.zig around lines 398-410 the check `if
(!validPreOrBuildTagCharacter(d) or std.ascii.isWhitespace(d)) return .major;`
wrongly treats whitespace as an error; change the boolean so we only bail when
the character is neither a valid pre/build tag char nor whitespace (i.e.,
replace the `or` with an `and` between the negations) so the condition becomes:
if the character is not a valid tag character and is not whitespace then return
.major.

Comment thread src/semver/Version.zig
Comment on lines +691 to +694
if (comptime Environment.isDebug) {
assert(!strings.containsChar(result.tag.build.slice(sliced_string.buf), '-'));
}
state = State.none;

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.

⚠️ Potential issue

Allow '-' in build metadata (SemVer spec compliance)

The SemVer spec permits hyphen in build identifiers. This debug assert would incorrectly reject valid versions.

-                                    if (comptime Environment.isDebug) {
-                                        assert(!strings.containsChar(result.tag.build.slice(sliced_string.buf), '-'));
-                                    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (comptime Environment.isDebug) {
assert(!strings.containsChar(result.tag.build.slice(sliced_string.buf), '-'));
}
state = State.none;
state = State.none;
🤖 Prompt for AI Agents
In src/semver/Version.zig around lines 691 to 694, the debug-only assert forbids
'-' characters in the build metadata which violates the SemVer spec; remove or
relax that assert so build metadata may contain hyphens (either delete the
assert entirely or change it to validate only illegal characters per the spec,
not '-' ), and keep state = State.none unchanged.

Comment thread src/semver/Version.zig
Comment on lines 809 to 821
switch (part_i) {
0 => {
result.wildcard = Query.Token.Wildcard.major;
result.version.major = parseVersionNumber(input[part_start_i..last_char_i]);
part_i = 1;
},
1 => {
result.wildcard = Query.Token.Wildcard.minor;
result.version.minor = parseVersionNumber(input[part_start_i..last_char_i]);
part_i = 2;
},
2 => {
result.wildcard = Query.Token.Wildcard.patch;
result.version.patch = parseVersionNumber(input[part_start_i..last_char_i]);
part_i = 3;
},

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.

⚠️ Potential issue

Mark parse result invalid when a numeric core fails to parse

parseVersionNumber() can now return null for overflow/invalid. Propagate it by setting result.valid = false.

-                            0 => {
-                                result.version.major = parseVersionNumber(input[part_start_i..last_char_i]);
-                                part_i = 1;
-                            },
+                            0 => {
+                                if (parseVersionNumber(input[part_start_i..last_char_i])) |maj| {
+                                    result.version.major = maj;
+                                } else {
+                                    result.valid = false;
+                                    break;
+                                }
+                                part_i = 1;
+                            },
@@
-                            1 => {
-                                result.version.minor = parseVersionNumber(input[part_start_i..last_char_i]);
-                                part_i = 2;
-                            },
+                            1 => {
+                                if (parseVersionNumber(input[part_start_i..last_char_i])) |min| {
+                                    result.version.minor = min;
+                                } else {
+                                    result.valid = false;
+                                    break;
+                                }
+                                part_i = 2;
+                            },
@@
-                            2 => {
-                                result.version.patch = parseVersionNumber(input[part_start_i..last_char_i]);
-                                part_i = 3;
-                            },
+                            2 => {
+                                if (parseVersionNumber(input[part_start_i..last_char_i])) |pat| {
+                                    result.version.patch = pat;
+                                } else {
+                                    result.valid = false;
+                                    break;
+                                }
+                                part_i = 3;
+                            },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
switch (part_i) {
0 => {
result.wildcard = Query.Token.Wildcard.major;
result.version.major = parseVersionNumber(input[part_start_i..last_char_i]);
part_i = 1;
},
1 => {
result.wildcard = Query.Token.Wildcard.minor;
result.version.minor = parseVersionNumber(input[part_start_i..last_char_i]);
part_i = 2;
},
2 => {
result.wildcard = Query.Token.Wildcard.patch;
result.version.patch = parseVersionNumber(input[part_start_i..last_char_i]);
part_i = 3;
},
switch (part_i) {
0 => {
if (parseVersionNumber(input[part_start_i..last_char_i])) |maj| {
result.version.major = maj;
} else {
result.valid = false;
break;
}
part_i = 1;
},
1 => {
if (parseVersionNumber(input[part_start_i..last_char_i])) |min| {
result.version.minor = min;
} else {
result.valid = false;
break;
}
part_i = 2;
},
2 => {
if (parseVersionNumber(input[part_start_i..last_char_i])) |pat| {
result.version.patch = pat;
} else {
result.valid = false;
break;
}
part_i = 3;
},
🤖 Prompt for AI Agents
In src/semver/Version.zig around lines 809 to 821, the code assigns the return
of parseVersionNumber() directly to the numeric fields, but parseVersionNumber()
can return null on overflow/invalid; update each branch to check the optional
result, and if it is null set result.valid = false (and avoid assigning to the
numeric field), otherwise assign the parsed number to
result.version.(major|minor|patch). Ensure you do this for part_i == 0, 1, and 2
so invalid numeric cores propagate by marking result.valid = false.

Comment thread src/semver/Version.zig
Comment on lines +966 to +978
if (comptime Environment.isDebug) {
return std.fmt.parseInt(IntType, bytes[0..byte_i], 10) catch |err| {
Output.prettyErrorln("ERROR {s} parsing version: \"{s}\", bytes: {s}", .{
@errorName(err),
input,
bytes[0..byte_i],
});
return 0;
};
}

return std.fmt.parseInt(IntType, bytes[0..byte_i], 10) catch 0;
}

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.

⚠️ Potential issue

Treat parse overflow/invalid as invalid, not zero

Returning 0 on parse error mis-parses out-of-range core numbers (esp. for OldV2Version/u32). Return null and let callers mark invalid.

-            if (comptime Environment.isDebug) {
-                return std.fmt.parseInt(IntType, bytes[0..byte_i], 10) catch |err| {
-                    Output.prettyErrorln("ERROR {s} parsing version: \"{s}\", bytes: {s}", .{
-                        @errorName(err),
-                        input,
-                        bytes[0..byte_i],
-                    });
-                    return 0;
-                };
-            }
-
-            return std.fmt.parseInt(IntType, bytes[0..byte_i], 10) catch 0;
+            if (comptime Environment.isDebug) {
+                return std.fmt.parseInt(IntType, bytes[0..byte_i], 10) catch |err| {
+                    Output.prettyErrorln("ERROR {s} parsing version: \"{s}\", bytes: {s}", .{
+                        @errorName(err),
+                        input,
+                        bytes[0..byte_i],
+                    });
+                    return null;
+                };
+            }
+
+            return std.fmt.parseInt(IntType, bytes[0..byte_i], 10) catch null;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (comptime Environment.isDebug) {
return std.fmt.parseInt(IntType, bytes[0..byte_i], 10) catch |err| {
Output.prettyErrorln("ERROR {s} parsing version: \"{s}\", bytes: {s}", .{
@errorName(err),
input,
bytes[0..byte_i],
});
return 0;
};
}
return std.fmt.parseInt(IntType, bytes[0..byte_i], 10) catch 0;
}
if (comptime Environment.isDebug) {
return std.fmt.parseInt(IntType, bytes[0..byte_i], 10) catch |err| {
Output.prettyErrorln("ERROR {s} parsing version: \"{s}\", bytes: {s}", .{
@errorName(err),
input,
bytes[0..byte_i],
});
return null;
};
}
return std.fmt.parseInt(IntType, bytes[0..byte_i], 10) catch null;
}
🤖 Prompt for AI Agents
In src/semver/Version.zig around lines 966 to 978, the current parseInt error
handling returns 0 on failure which incorrectly treats overflow/invalid parses
as zero; change both the debug branch and the non-debug branch to return null on
parse errors instead of 0, so callers can detect invalid parses and mark the
version invalid; update the function's return type to a nullable integer if
necessary and adjust any callers that expect 0 to instead handle null as an
invalid parse.

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/semver/SemverQuery.zig (2)

346-346: Avoid hardcoding u64; derive the component type and reuse MAX.

Future-proof this against any Version parametrization (e.g., legacy u32) and reduce duplication.

Apply:

 pub const Token = struct {
   tag: Tag = Tag.none,
   wildcard: Wildcard = Wildcard.none,

   pub fn toRange(this: Token, version: Version.Partial) Range {
+        const CompT = @typeInfo(@TypeOf(version.major)).Optional.child;
+        const MAX = std.math.maxInt(CompT);
         switch (this.tag) {
@@
             .major => .{
                 .left = .{ .op = .gte, .version = version.min() },
                 .right = .{
                     .op = .lte,
                     .version = .{
-                        .major = std.math.maxInt(u64),
-                        .minor = std.math.maxInt(u64),
-                        .patch = std.math.maxInt(u64),
+                        .major = MAX,
+                        .minor = MAX,
+                        .patch = MAX,
                     },
                 },
             },
             .minor => switch (this.tag) {
                 .lte => .{
                     .left = .{
                         .op = .lte,
                         .version = .{
                             .major = version.major orelse 0,
-                            .minor = std.math.maxInt(u64),
-                            .patch = std.math.maxInt(u64),
+                            .minor = MAX,
+                            .patch = MAX,
                         },
                     },
                 },
@@
                 .gt => .{
                     .left = .{
                         .op = .gt,
                         .version = .{
                             .major = version.major orelse 0,
-                            .minor = std.math.maxInt(u64),
-                            .patch = std.math.maxInt(u64),
+                            .minor = MAX,
+                            .patch = MAX,
                         },
                     },
                 },
@@
                 .lte => .{
                     .left = .{
                         .op = .lte,
                         .version = .{
                             .major = version.major orelse 0,
                             .minor = version.minor orelse 0,
-                            .patch = std.math.maxInt(u64),
+                            .patch = MAX,
                         },
                     },
                 },
@@
                 .gt => .{
                     .left = .{
                         .op = .gt,
                         .version = .{
                             .major = version.major orelse 0,
                             .minor = version.minor orelse 0,
-                            .patch = std.math.maxInt(u64),
+                            .patch = MAX,
                         },
                     },
                 },

Also applies to: 428-431, 440-441, 461-463, 486-486, 507-507


362-381: Edge case: '^0.0.' becomes unsatisfiable due to saturating patch+1.

When major==0 and minor==0 and patch==MAX, patch +| 1 saturates, yielding >=0.0.MAX && <0.0.MAX, which matches nothing. Expected behavior is equality to 0.0.MAX.

Consider:

-                            if (major == 0) {
-                                if (minor == 0) {
-                                    range.right.version.patch = patch +| 1;
-                                } else {
-                                    range.right.version.minor = minor +| 1;
-                                }
-                                break :done;
-                            }
+                            if (major == 0) {
+                                if (minor == 0) {
+                                    const next = patch +| 1;
+                                    if (next == patch) {
+                                        // overflow: collapse to equality
+                                        range.left.op = .eql;
+                                        range.right = .{};
+                                    } else {
+                                        range.right.version.patch = next;
+                                    }
+                                } else {
+                                    range.right.version.minor = minor +| 1;
+                                }
+                                break :done;
+                            }

Also consider tests for:

  • '^0.0.(2^64-1)' → only equals that exact version
  • '^0.(2^64-1).y' and tilde/caret near boundaries
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 72af711 and e978912.

📒 Files selected for processing (1)
  • src/semver/SemverQuery.zig (5 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

Files:

  • src/semver/SemverQuery.zig
**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)

**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue

**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup

Files:

  • src/semver/SemverQuery.zig
🔇 Additional comments (1)
src/semver/SemverQuery.zig (1)

428-431: u64 max component widening looks correct.

Using std.math.maxInt(u64) for wildcard upper bounds aligns with the repo-wide move to 64-bit semver components. No functional concerns here.

Also applies to: 440-441, 461-463, 486-486, 507-507

Comment thread src/install/lockfile/Package.zig Resolved
return error.@"Lockfile validation failed: unexpected number of package fields";
},
}
const begin_at = try reader.readInt(u64, .little);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the main change in this file is here in fn load(). fn loadFields() is a new function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants