Repository navigation
fix(windows): handle UV_ENOTCONN gracefully when spawning with long cwd - #23344
Conversation
|
Updated 3:03 PM PT - Oct 7th, 2025
❌ @pfgithub, your commit d55ab2b has 2 failures in
🧪 To try this PR locally: bunx bun-pr 23344That installs a local version of the PR into your bun-23344 --bun |
78ecc40 to
f40abb6
Compare
Fixes #23316, #23330, #23332, #23339, #23342 ## Problem When spawning a subprocess on Windows with a cwd >= MAX_PATH (260 chars), libuv 1.51.0 (upgraded in v1.2.23) attempts to shorten the path using GetShortPathNameW(). If this fails (commonly because 8.3 short names are disabled on modern Windows), libuv returns an error after the stdio pipes have already been created. When Bun tries to call .start() on these pipes, uv_read_start() checks if UV_HANDLE_READABLE is set. The pipes are in an inconsistent state, so it returns UV_ENOTCONN. The .assert() calls would panic instead of handling this error gracefully. ## Root Cause This is triggered by a Windows API limitation: CreateProcess() does not support long paths for the cwd parameter, even with longPathAware support. libuv commit 23632e91 (in v1.51.0) added a workaround to call GetShortPathNameW() to convert long paths to 8.3 short names. However: - Modern Windows often has 8.3 short names disabled for performance/security - Enterprise environments disable them via Group Policy - Network shares don't support short names - SSDs/modern filesystems ship with short names disabled When GetShortPathNameW() fails, the spawn fails AFTER stdio pipes are already created (line 1005 in libuv's process.c) but BEFORE the process spawns, leaving pipes in an invalid state. ## Solution Replace .assert() calls with proper error handling using .asErr() to return errors to JavaScript instead of panicking. ## Test Plan Added regression test and minimal reproduction script. On Windows with long cwd (>= 260 chars) or with 8.3 short names disabled, spawning should now fail gracefully with a proper error instead of panicking. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
f40abb6 to
c6baebb
Compare
WalkthroughReplaced assert-based stdio start handling in subprocess code with explicit error checks that kill the subprocess and return JS errors; added Windows-only regression tests for spawning with very long cwd paths; introduced and propagated a new Changes
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/bun.js/webcore/blob/write_file.zig (1)
367-409: Fix unbalanced EventLoop ref/unref on sync-fail paths (risk: negative refcount / shutdown race)onFinish() unrefs the loop (Line 542) but createWithCtx() refs only at the end (Line 407). If open() fails synchronously (Lines 422–441) or doWriteLoop() returns immediately (e.g., empty input, Lines 592–594), onFinish runs before the loop is ref’d, causing an unbalanced unref.
Move event_loop.refConcurrently() to before any operation that can call onFinish, and drop the trailing ref.
Apply this diff in createWithCtx:
@@ const write_file = WriteFileWindows.new(.{ .file_blob = file_blob, .bytes_blob = bytes_blob, .onCompleteCtx = onWriteFileContext, .onCompleteCallback = onCompleteCallback, .mkdirp_if_not_exists = mkdirp_if_not_exists and file_blob.store.?.data.file.pathlike == .path, .io_request = std.mem.zeroes(uv.fs_t), .uv_bufs = .{.{ .base = undefined, .len = 0 }}, .event_loop = event_loop, }); file_blob.store.?.ref(); bytes_blob.store.?.ref(); write_file.io_request.loop = event_loop.virtual_machine.event_loop_handle.?; write_file.io_request.data = write_file; + // Ensure we hold a ref before any operation that may synchronously call onFinish() + write_file.event_loop.refConcurrently(); + switch (file_blob.store.?.data.file.pathlike) { .path => { try write_file.open(); }, .fd => { write_file.fd = brk: { if (event_loop.virtual_machine.rare_data) |rare| { if (file_blob.store == rare.stdout_store) { break :brk 1; } else if (file_blob.store == rare.stderr_store) { break :brk 2; } else if (file_blob.store == rare.stdin_store) { break :brk 0; } } break :brk file_blob.store.?.data.file.pathlike.fd.uv(); }; try write_file.doWriteLoop(write_file.loop()); }, } - write_file.event_loop.refConcurrently(); return write_file;This keeps mkdirp’s extra ref/unref balanced and prevents a premature unref when open()/doWriteLoop() fail synchronously.
Also applies to: 541-549, 569-573, 588-596
🧹 Nitpick comments (1)
src/bun.js/webcore/blob/write_file.zig (1)
502-506: Avoid dangling path pointer in stored error (minor safety)In onMkdirpComplete you assign this.err = err_ and then free err_.path (Line 503). toSystemError later rewrites the path via pathlike switch (Lines 579–581), so it likely won’t dereference the freed pointer—but holding a freed pointer in this.err is brittle.
Replace the stored error with a minimal copy that omits the owned path before freeing:
- defer bun.default_allocator.free(err_.path); - switch (this.throw(err_)) { + const e_min = bun.sys.Error{ .errno = err_.errno, .syscall = err_.syscall }; + bun.default_allocator.free(err_.path); + switch (this.throw(e_min)) { error.WriteFileWindowsDeinitialized => {}, }This avoids any chance of accidental use of a freed path while keeping toSystemError’s path/fd enrichment behavior.
Also applies to: 576-585
📜 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.
📒 Files selected for processing (2)
src/bun.js/webcore/Blob.zig(1 hunks)src/bun.js/webcore/blob/write_file.zig(11 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})In Zig code, manage memory carefully and use defer for cleanup of allocations/resources
src/**/*.zig: Use the # prefix to declare private fields in Zig structs (e.g., struct { #foo: u32 })
Prefer decl literals when initializing values in Zig (e.g., const decl: Decl = .{ .binding = 0, .value = 0 })
Place @import directives at the bottom of Zig files
Use @import("bun") instead of @import("root").bun
Files:
src/bun.js/webcore/Blob.zigsrc/bun.js/webcore/blob/write_file.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
Files:
src/bun.js/webcore/Blob.zigsrc/bun.js/webcore/blob/write_file.zig
src/bun.js/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/zig-javascriptcore-classes.mdc)
src/bun.js/**/*.zig: In Zig binding structs, expose generated bindings via pub const js = JSC.Codegen.JS and re-export toJS/fromJS/fromJSDirect
Constructors and prototype methods should return bun.JSError!JSC.JSValue to integrate Zig error handling with JS exceptions
Use parameter name globalObject (not ctx) and accept (*JSC.JSGlobalObject, *JSC.CallFrame) in binding methods/constructors
Implement getters as get(this, globalObject) returning JSC.JSValue and matching the .classes.ts interface
Provide deinit() for resource cleanup and finalize() that calls deinit(); use bun.destroy(this) or appropriate destroy pattern
Access JS call data via CallFrame (argument(i), argumentCount(), thisValue()) and throw errors with globalObject.throw(...)
For properties marked cache: true, use the generated Zig accessors (NameSetCached/GetCached) to work with GC-owned values
In finalize() for objects holding JS references, release them using .deref() before destroy
Files:
src/bun.js/webcore/Blob.zigsrc/bun.js/webcore/blob/write_file.zig
🧠 Learnings (1)
📓 Common learnings
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-04T09:51:30.294Z
Learning: Applies to test/**/*.test.{ts,tsx} : Use Bun.spawn with proper stdio handling and await proc.exited in process-spawning tests
🔇 Additional comments (4)
src/bun.js/webcore/Blob.zig (1)
1011-1023: Swallowing the sentinel error is correct; promise lifecycle is safeCatching only error.WriteFileWindowsDeinitialized here is appropriate. The promise is established before create(), and WriteFileWindows guarantees resolve/reject + deinit before returning this sentinel.
Please confirm WriteFileWindowsError contains only WriteFileWindowsDeinitialized so other errors won’t be dropped.
src/bun.js/webcore/blob/write_file.zig (3)
358-360: New sentinel error type looks goodUsing WriteFileWindowsError = error{WriteFileWindowsDeinitialized} to signal “already handled (callback + deinit)” is a clean control flow boundary.
415-444: Open error propagation is consistent with new sentinelopen() returning WriteFileWindowsError and funneling failures through throw() → onFinish() → runFromJSThread() is consistent. Once the ref/unref ordering is fixed (see above), this is solid.
Please confirm libuv won’t invoke onOpen synchronously before createWithCtx can ref the loop in the current ordering; the proposed ref placement eliminates this concern.
588-616: doWriteLoop error-path exit is correctReturning this.onFinish() when done or on error aligns with the sentinel error pattern and ensures single-shot completion.
|
An 0xFFFFFFF crash: I fixed this by making it so these functions can error and createWithCtx will early-return if the WriteFileWindows gets deinitialized Alternatively maybe we should switch WriteFileWindows to live past runFromJSThread() so it doesn't ever deinitialize inside of create() |
Applies the same ENOTCONN fix from PR #23344 to the shell subprocess implementation. ## Problem The shell's subproc.zig has the same `.assert()` calls that were fixed in subprocess.zig for the JS API. When spawning fails due to UV_ENOTCONN (commonly from libuv's GetShortPathNameW() failing on Windows with long paths or disabled 8.3 short names), the shell would panic instead of handling the error gracefully. ## Solution Replace `.assert()` calls with proper error handling: - Check for errors using `.asErr()` - Kill the subprocess with SIGTERM before returning - Return a shell error using `.toShellSystemError()` This matches the pattern used in subprocess.zig:882-907 but adapted for the shell's error handling (returns ShellErr instead of throwing JS errors). ## Test Plan Added test/regression/issue/23316-long-path-spawn-shell.test.ts covering: - Shell spawning with cwd >= MAX_PATH (260 chars) - Shell spawning with paths where 8.3 short names are unavailable - Verified build succeeds with `bun bd` - Test syntax verified with --dry-run 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
What does this PR do?
Fixes #23316, #23330, #23332, #23339, #23342
Replaces
.assert()calls with proper error handling when starting stdio pipes during subprocess spawn on Windows. When pipe initialization fails (e.g.,UV_ENOTCONNdue to libuv'sGetShortPathNameW()failing on long paths), the subprocess is now killed and a proper JavaScript error is thrown instead of panicking.Root Cause:
Bun v1.2.23 upgraded to libuv 1.51.0, which includes a workaround for Windows'
CreateProcessAPI not supporting long paths (>= 260 chars) for thecwdparameter. When the path is too long, libuv callsGetShortPathNameW()to convert to 8.3 short names. However, this commonly fails on modern Windows because:When
GetShortPathNameW()fails, the spawn fails after stdio pipes are created but before the process spawns, leaving pipes in an invalid state. When Bun tries to call.start()on these pipes,uv_read_start()returnsUV_ENOTCONN, which was causing a panic.How did you verify your code works?
test/regression/issue/23316-long-path-spawn.test.tscovering:bun run zig:check-all(49/49 steps succeeded)subprocess.zig:1518-1527The tests verify that spawn either succeeds or fails gracefully with a proper error, never panicking with
UV_ENOTCONN.🤖 Generated with Claude Code
Co-Authored-By: Claude noreply@anthropic.com