Skip to content

fix(windows): handle UV_ENOTCONN gracefully when spawning with long cwd - #23344

Merged
Jarred-Sumner merged 5 commits into
mainfrom
claude/fix-uv-enotconn-panic
Oct 7, 2025
Merged

Jarred-Sumner merged 5 commits into
mainfrom
claude/fix-uv-enotconn-panic

Conversation

@robobun

@robobun robobun commented Oct 7, 2025 •

Copy link
Copy Markdown
Collaborator

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_ENOTCONN due to libuv's GetShortPathNameW() 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' CreateProcess API not supporting long paths (>= 260 chars) for the cwd parameter. When the path is too long, libuv calls GetShortPathNameW() to convert to 8.3 short names. However, this commonly fails on modern Windows because:

  • 8.3 short names are disabled by default for performance/security
  • Enterprise environments disable them via Group Policy
  • Network shares don't support short names
  • Modern SSDs/filesystems ship with short names disabled

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() returns UV_ENOTCONN, which was causing a panic.

How did you verify your code works?

  • Added regression test test/regression/issue/23316-long-path-spawn.test.ts covering:
    • Spawning with cwd >= MAX_PATH (260 chars)
    • Spawning with paths where 8.3 short names are unavailable
  • Verified cross-platform compilation with bun run zig:check-all (49/49 steps succeeded)
  • Error handling matches existing pattern in subprocess.zig:1518-1527
  • Subprocess is properly killed before throwing error to prevent resource leaks

The 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

@robobun

robobun commented Oct 7, 2025 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:03 PM PT - Oct 7th, 2025

❌ @pfgithub, your commit d55ab2b has 2 failures in Build #28411 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 23344

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

bun-23344 --bun

@github-actions github-actions Bot added the claude label Oct 7, 2025
@robobun
robobun force-pushed the claude/fix-uv-enotconn-panic branch 2 times, most recently from 78ecc40 to f40abb6 Compare October 7, 2025 15:04
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>
@robobun
robobun force-pushed the claude/fix-uv-enotconn-panic branch from f40abb6 to c6baebb Compare October 7, 2025 15:16
@Jarred-Sumner
Jarred-Sumner marked this pull request as ready for review October 7, 2025 15:19
@coderabbitai

coderabbitai Bot commented Oct 7, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Replaced 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 WriteFileWindowsError and swallowed WriteFileWindowsDeinitialized in Windows Blob write paths.

Changes

Cohort / File(s) Summary of changes
Subprocess stdio start error handling
src/bun.js/api/bun/subprocess.zig
Replaced assert-based handling for stdin.buffer.start, stdout.pipe.start, and stderr.pipe.start with explicit asErr() checks. On start errors, the code now kills the subprocess, converts the error to a JS error, and returns JSError. Read-all flow remains unchanged when starts succeed.
Windows long-path spawn regression tests
test/regression/issue/23316-long-path-spawn.test.ts
Added two Windows-only regression tests that create deeply nested directories (exceeding or near MAX_PATH) and spawn processes with such cwd, asserting operations do not panic and errors (if any) are surfaced as Error instances.
WriteFileWindows error propagation and Blob swallow
src/bun.js/webcore/blob/write_file.zig, src/bun.js/webcore/Blob.zig
Introduced WriteFileWindowsError = error{WriteFileWindowsDeinitialized} and updated WriteFileWindows APIs to return/propagate this error set. Call sites now use try/catch, many signatures changed to return the new error set, and WriteFileWindowsDeinitialized is swallowed in Windows writeFileWithSourceDestination paths.

Suggested reviewers

  • nektro
  • dylan-conway

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The PR also introduces extensive Blob writeFileWithSourceDestination and WriteFileWindows error‐handling changes unrelated to fixing UV_ENOTCONN in subprocess spawn, which fall outside the scope of issue #23316’s objectives. Consider splitting the Blob and WriteFileWindows error‐handling API changes into a separate PR so that this patch remains focused on the Windows spawn ENOTCONN fix.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly summarizes the key change by indicating that UV_ENOTCONN errors when spawning with a long working directory on Windows are now handled gracefully, directly reflecting the main intent of the patch without extraneous details.
Linked Issues Check ✅ Passed The changes in subprocess.zig and the new Windows regression tests directly address the ENOTCONN panic described in issue #23316 by replacing assert calls with proper error checks, killing the subprocess, and throwing a JavaScript error, satisfying the linked issue’s coding requirements.
Description Check ✅ Passed The description follows the repository template by providing both a “What does this PR do?” section detailing the error‐handling changes and root cause, and a “How did you verify your code works?” section listing regression tests, compilation checks, and behavior verification.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/fix-uv-enotconn-panic

📜 Recent 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 73a1ca1 and d55ab2b.

📒 Files selected for processing (1)
  • test/regression/issue/23316-long-path-spawn.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/regression/issue/23316-long-path-spawn.test.ts

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

@pfgithub pfgithub self-assigned this Oct 7, 2025

@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

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 1ad8159 and 73a1ca1.

📒 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 invoking log("...", .{})

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.zig
  • src/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.zig
  • src/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.zig
  • src/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 safe

Catching 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 good

Using WriteFileWindowsError = error{WriteFileWindowsDeinitialized} to signal “already handled (callback + deinit)” is a clean control flow boundary.


415-444: Open error propagation is consistent with new sentinel

open() 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 correct

Returning this.onFinish() when done or on error aligns with the sentinel error pattern and ensures single-shot completion.

@pfgithub

pfgithub commented Oct 7, 2025

Copy link
Copy Markdown
Contributor

An 0xFFFFFFF crash:

create calls createWithCtx
  createWithCtx creates WriteFileWindows $w
  createWithCtx calls open
    open calls toPosixPath, which throws
    open calls throw
      throw calls onFinish
        onFinish calls runFromJSThread
          runFromJSThread calls deinit
          $w is dead
  createWithCtx accesses $w.event_loop and returns $w

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()

robobun pushed a commit that referenced this pull request Oct 12, 2025
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>
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.

crash has occured while claude executing in terminal

3 participants