Skip to content

Fix running Bun.spawn on Vercel and GCP - #6724

Merged
Jarred-Sumner merged 9 commits into
mainfrom
jarred/fix-pdfdopen
Oct 27, 2023
Merged

Jarred-Sumner merged 9 commits into
mainfrom
jarred/fix-pdfdopen

Conversation

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

What does this PR do?

pidfd_open is not implemented by gVisor and by older Linux kernels. This implements a workaround where we spawn a thread, enqueue concurrent tasks and call waitpid on each Subprocess's pid. This workaround is very loosely based on libuv's default behavior.

Fixes #5803

Need to manually test that it does indeed fix the issue, but it should

How did you verify your code works?

I tested manually + added a hidden environment variable to let us manually enable this for testing purposes

Comment thread src/output.zig
if (Output.enable_ansi_colors_stderr) {
out.print(comptime prettyFmt("<r><d>[" ++ @tagName(tag) ++ "]<r> " ++ fmt, true), args) catch unreachable;
buffered_writer.flush() catch unreachable;
out.print(comptime prettyFmt("<r><d>[" ++ @tagName(tag) ++ "]<r> " ++ fmt, true), args) catch {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

this was to silence debug logs from throwing "PipeError"

}

pub fn shouldUseWaiterThread() bool {
return @atomicLoad(bool, &should_use_waiter_thread, .Monotonic);

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.

should be fine but why not use std.atomic and/or atomic store when setting

@github-actions

github-actions Bot commented Oct 26, 2023 •

Copy link
Copy Markdown
Contributor

❌ @Jarred-Sumner 2 files with test failures on linux-x64-baseline:

  • test/js/bun/spawn/spawn.test.ts
  • test/js/bun/util/filesink.test.ts

View test output

#b016c5ce86bf3ee6996a1b7d86e6637afe6df92e

@github-actions

github-actions Bot commented Oct 26, 2023 •

Copy link
Copy Markdown
Contributor

❌ @Jarred-Sumner 2 files with test failures on linux-x64:

  • test/js/bun/spawn/spawn.test.ts
  • test/js/bun/util/filesink.test.ts

View test output

#b016c5ce86bf3ee6996a1b7d86e6637afe6df92e

@github-actions

github-actions Bot commented Oct 26, 2023 •

Copy link
Copy Markdown
Contributor

❌ @Jarred-Sumner 5 files with test failures on bun-darwin-aarch64:

  • test/cli/install/bunx.test.ts
  • test/integration/next/default-pages-dir/test/dev-server.test.ts
  • test/js/bun/test/test-test.test.ts
  • test/js/bun/util/filesink.test.ts
  • test/js/node/watch/fs.watch.test.ts

View test output

#b016c5ce86bf3ee6996a1b7d86e6637afe6df92e

@github-actions

github-actions Bot commented Oct 26, 2023 •

Copy link
Copy Markdown
Contributor

❌ @Jarred-Sumner 6 files with test failures on bun-darwin-x64-baseline:

  • test/integration/next/default-pages-dir/test/dev-server.test.ts
  • test/js/bun/spawn/spawn-streaming-stdout.test.ts
  • test/js/node/fs/fs.test.ts
  • test/js/node/watch/fs.watchFile.test.ts
  • test/js/third_party/webpack/webpack.test.ts
  • test/js/web/timers/setTimeout.test.js

View test output

#b016c5ce86bf3ee6996a1b7d86e6637afe6df92e

@github-actions

github-actions Bot commented Oct 26, 2023 •

Copy link
Copy Markdown
Contributor

❌ @Jarred-Sumner 4 files with test failures on bun-darwin-x64:

  • test/js/node/fs/fs.test.ts
  • test/js/node/watch/fs.watchFile.test.ts
  • test/js/third_party/webpack/webpack.test.ts
  • test/js/web/timers/setTimeout.test.js

View test output

#b016c5ce86bf3ee6996a1b7d86e6637afe6df92e

@Jarred-Sumner
Jarred-Sumner merged commit 46a337c into main Oct 27, 2023
@Jarred-Sumner
Jarred-Sumner deleted the jarred/fix-pdfdopen branch October 27, 2023 07:03
robobun added a commit that referenced this pull request Aug 8, 2026
The baseline is a settle heuristic with no pre-spawn ground truth
(#6724 moved it after the first batch on purpose), and getMaxFD is a
max, so unchanged-for-10ms can still lock in a value above the true
floor. Poll the final count down only while it is above the baseline
and assert <=; a count below the baseline can never be a leak.
Jarred-Sumner pushed a commit that referenced this pull request Aug 8, 2026
)

### What does this PR do?

Fixes the `test/js/bun/spawn/spawn-streaming-stdin.test.ts` flake
(debian x64/aarch64, builds 89694, 89561, 88187):

```
68 |   // assert we didn't leak any file descriptors
69 |   expect(newMaxFD).toBe(maxFD);
Expected: 21
Received: 56
```

Nothing is leaked; the test samples too early. After `await
Promise.all(proms)` for the last batch of 16 subprocesses, every stream
has finished from JS's point of view (stdout EOF, `stdin.end()`
resolved, `exited` resolved), but a pipe fd that had a poll registered
is closed by `bun_io::Closer` on the work pool rather than on the JS
thread (`src/io/pipes.rs` `close_impl` → `Closer::close`, by design so a
blocking `close()` never stalls the loop). On a loaded machine those
pool tasks can lag the JS thread by a few ms, so the last batch's
stdin/stdout/pidfd descriptors (~44) are still open at the instant
`getMaxFD()` runs. Reproduced on Linux x64 with 2×nproc busy loops
running: 5 of 30 rounds of the same spawn/await/count loop saw `maxFD 7
-> 51` immediately after the await and `7` again 10 ms later; 0/30 idle,
and macOS didn't reproduce at all (which matches the CI distribution).

The assertion is unchanged; it now polls for the count to return to the
baseline (10 ms steps, up to 1 s) before asserting, the same way
`expectMaxObjectTypeCount` right below it already waits for object
counts. With that loop the loaded Linux reproduction is 0/40.

Review pointed out that `spawn-streaming-stdout.test.ts` has the same
shape, at both sample points: the final count is read right after the
last batch's `Promise.all`, and the baseline is read right after batch
1's, so in-flight closes can inflate the baseline as well (a failure the
final poll alone can't recover from). That file now settle-polls the
baseline, then polls the final count down only while it is above the
baseline and asserts `<=` instead of exact equality: the baseline there
is a heuristic with no pre-spawn ground truth (46a337c in #6724 moved it
after the first batch on purpose), so a count below it is not a leak,
and a max-based settle check can rarely stop a little high. The stdin
test keeps its exact `toBe` since its baseline is taken before any
spawn.

### How did you verify your code works?

Reproduction/verification above (release binary on Linux); `bun bd test
test/js/bun/spawn/spawn-streaming-stdin.test.ts` passes locally. Both
test files also pass under a debug ASAN build and 8/8 rounds each under
2×nproc CPU load on the release binary.

<!-- robobun:evidence:begin -->

---

**[stamp-90s]** gate passed · iteration 3 · 2 files touched

<details><summary>passes on PR (with fix)</summary>

```console
Test-only change.

Debug/ASAN (expected pass):
$ bun bd test 'test/js/bun/spawn/spawn-streaming-stdin.test.ts' 'test/js/bun/spawn/spawn-streaming-stdout.test.ts'
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test test/js/bun/spawn/spawn-streaming-stdin.test.ts test/js/bun/spawn/spawn-streaming-stdout.test.ts
bun test v1.4.0 (10c944d)

test/js/bun/spawn/spawn-streaming-stdout.test.ts:
{
  objects: {
    "Array Iterator": 1,
    Array: 85,
    ArrayBuffer: 2,
    AsyncDisposableStack: 1,
    AsyncFromSyncIterator: 1,
    AsyncFunction: 111,
    AsyncFunctionGenerator: 14,
    AsyncGenerator: 1,
    AsyncGeneratorFunction: 2,
    AsyncIterator: 1,
    BigInt: 3,
    BigInt64ArrayPrototype: 1,
    BigUint64ArrayPrototype: 1,
    Blob: 1,
    Boolean: 1,
    Buffer: 1,
    Bun: 1,
    Callee: 3,
    "Cell Butterfly": 32,
    CustomEvent: 2,
    CustomGetterSetter: 83,
    DOMAttributeGetterSetter: 89,
    Dirent: 2,
    DisposableStack: 1,
    Error: 6,
    ErrorCodeCache: 1,
    Event: 2,
    EventEmitter: 1,
    EventTarget: 2,
    Expect: 1,
    ExpectStatic: 1,
    ExpectTypeOf: 1,
    FileInternalReadableStreamSource: 14,
    FileSink: 3,
    FinalizationRegistry: 1,
    Float16ArrayPrototype: 1,
    Float32ArrayPrototype: 1,
    Float64ArrayPrototype: 1,
    FrameworkFileSystemRouter: 1,
    FullPromiseReaction: 15,
    Function: 2668,
    FunctionCodeBlock: 135,
    FunctionExecutable: 1441,
    FunctionRareData: 264,
    Generator: 1,
    GeneratorFunction: 2,
    GetterSetter: 191,
    GlobalObject: 1,
    ImportMeta: 3,
    Int16ArrayPrototype: 1,
    Int32ArrayPrototype: 1,
    Int8Array: 1,
    Int8ArrayPrototype: 1,
    InternalFieldTuple: 24,
    InternalModuleRegistry: 1,
    Intl: 1,
    "Iterator Helper": 1,
    Iterator: 2,
    JSAsyncGeneratorFunction: 8,
    JSGlobalLexicalEnvironment: 1,
    JSGlobalProxy: 1,
    JSLexicalEnvironment: 241,
    JSModuleEnvironment: 11,
    JSON: 1,
    JSPropertyNameEnumerator: 5,
    JSSourceCode: 11,
    "Map Iterator": 1,
    Map: 6,
    Math: 1,
    Module: 3,
    ModuleLoader: 1,
    ModuleNamespaceObject: 4,
    ModuleProgramCode
... (truncated)
Exit: 0
```

</details>

<details><summary>diff hotspot</summary>

```
test/js/bun/spawn/spawn-streaming-stdin.test.ts  |  8 +++++++-
 test/js/bun/spawn/spawn-streaming-stdout.test.ts | 21 +++++++++++++++++++--
 2 files changed, 26 insertions(+), 3 deletions(-)
```

</details>

**gate history** · 4 passed · 0 rejected · iteration 3

<details><summary>evidence per changed file</summary>

```
file                                              reads  edits  tests
test/js/bun/spawn/spawn-streaming-stdin.test.ts       1      0      0
test/js/bun/spawn/spawn-streaming-stdout.test.ts      1      2      0
```

</details>

<!-- robobun:evidence:end -->

---------

Co-authored-by: robobun <117481402+robobun@users.noreply.github.com>
springmin pushed a commit to springmin/bun that referenced this pull request Aug 8, 2026
…n-sh#37207)

### What does this PR do?

Fixes the `test/js/bun/spawn/spawn-streaming-stdin.test.ts` flake
(debian x64/aarch64, builds 89694, 89561, 88187):

```
68 |   // assert we didn't leak any file descriptors
69 |   expect(newMaxFD).toBe(maxFD);
Expected: 21
Received: 56
```

Nothing is leaked; the test samples too early. After `await
Promise.all(proms)` for the last batch of 16 subprocesses, every stream
has finished from JS's point of view (stdout EOF, `stdin.end()`
resolved, `exited` resolved), but a pipe fd that had a poll registered
is closed by `bun_io::Closer` on the work pool rather than on the JS
thread (`src/io/pipes.rs` `close_impl` → `Closer::close`, by design so a
blocking `close()` never stalls the loop). On a loaded machine those
pool tasks can lag the JS thread by a few ms, so the last batch's
stdin/stdout/pidfd descriptors (~44) are still open at the instant
`getMaxFD()` runs. Reproduced on Linux x64 with 2×nproc busy loops
running: 5 of 30 rounds of the same spawn/await/count loop saw `maxFD 7
-> 51` immediately after the await and `7` again 10 ms later; 0/30 idle,
and macOS didn't reproduce at all (which matches the CI distribution).

The assertion is unchanged; it now polls for the count to return to the
baseline (10 ms steps, up to 1 s) before asserting, the same way
`expectMaxObjectTypeCount` right below it already waits for object
counts. With that loop the loaded Linux reproduction is 0/40.

Review pointed out that `spawn-streaming-stdout.test.ts` has the same
shape, at both sample points: the final count is read right after the
last batch's `Promise.all`, and the baseline is read right after batch
1's, so in-flight closes can inflate the baseline as well (a failure the
final poll alone can't recover from). That file now settle-polls the
baseline, then polls the final count down only while it is above the
baseline and asserts `<=` instead of exact equality: the baseline there
is a heuristic with no pre-spawn ground truth (46a337c in oven-sh#6724 moved it
after the first batch on purpose), so a count below it is not a leak,
and a max-based settle check can rarely stop a little high. The stdin
test keeps its exact `toBe` since its baseline is taken before any
spawn.

### How did you verify your code works?

Reproduction/verification above (release binary on Linux); `bun bd test
test/js/bun/spawn/spawn-streaming-stdin.test.ts` passes locally. Both
test files also pass under a debug ASAN build and 8/8 rounds each under
2×nproc CPU load on the release binary.

<!-- robobun:evidence:begin -->

---

**[stamp-90s]** gate passed · iteration 3 · 2 files touched

<details><summary>passes on PR (with fix)</summary>

```console
Test-only change.

Debug/ASAN (expected pass):
$ bun bd test 'test/js/bun/spawn/spawn-streaming-stdin.test.ts' 'test/js/bun/spawn/spawn-streaming-stdout.test.ts'
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test test/js/bun/spawn/spawn-streaming-stdin.test.ts test/js/bun/spawn/spawn-streaming-stdout.test.ts
bun test v1.4.0 (10c944d)

test/js/bun/spawn/spawn-streaming-stdout.test.ts:
{
  objects: {
    "Array Iterator": 1,
    Array: 85,
    ArrayBuffer: 2,
    AsyncDisposableStack: 1,
    AsyncFromSyncIterator: 1,
    AsyncFunction: 111,
    AsyncFunctionGenerator: 14,
    AsyncGenerator: 1,
    AsyncGeneratorFunction: 2,
    AsyncIterator: 1,
    BigInt: 3,
    BigInt64ArrayPrototype: 1,
    BigUint64ArrayPrototype: 1,
    Blob: 1,
    Boolean: 1,
    Buffer: 1,
    Bun: 1,
    Callee: 3,
    "Cell Butterfly": 32,
    CustomEvent: 2,
    CustomGetterSetter: 83,
    DOMAttributeGetterSetter: 89,
    Dirent: 2,
    DisposableStack: 1,
    Error: 6,
    ErrorCodeCache: 1,
    Event: 2,
    EventEmitter: 1,
    EventTarget: 2,
    Expect: 1,
    ExpectStatic: 1,
    ExpectTypeOf: 1,
    FileInternalReadableStreamSource: 14,
    FileSink: 3,
    FinalizationRegistry: 1,
    Float16ArrayPrototype: 1,
    Float32ArrayPrototype: 1,
    Float64ArrayPrototype: 1,
    FrameworkFileSystemRouter: 1,
    FullPromiseReaction: 15,
    Function: 2668,
    FunctionCodeBlock: 135,
    FunctionExecutable: 1441,
    FunctionRareData: 264,
    Generator: 1,
    GeneratorFunction: 2,
    GetterSetter: 191,
    GlobalObject: 1,
    ImportMeta: 3,
    Int16ArrayPrototype: 1,
    Int32ArrayPrototype: 1,
    Int8Array: 1,
    Int8ArrayPrototype: 1,
    InternalFieldTuple: 24,
    InternalModuleRegistry: 1,
    Intl: 1,
    "Iterator Helper": 1,
    Iterator: 2,
    JSAsyncGeneratorFunction: 8,
    JSGlobalLexicalEnvironment: 1,
    JSGlobalProxy: 1,
    JSLexicalEnvironment: 241,
    JSModuleEnvironment: 11,
    JSON: 1,
    JSPropertyNameEnumerator: 5,
    JSSourceCode: 11,
    "Map Iterator": 1,
    Map: 6,
    Math: 1,
    Module: 3,
    ModuleLoader: 1,
    ModuleNamespaceObject: 4,
    ModuleProgramCode
... (truncated)
Exit: 0
```

</details>

<details><summary>diff hotspot</summary>

```
test/js/bun/spawn/spawn-streaming-stdin.test.ts  |  8 +++++++-
 test/js/bun/spawn/spawn-streaming-stdout.test.ts | 21 +++++++++++++++++++--
 2 files changed, 26 insertions(+), 3 deletions(-)
```

</details>

**gate history** · 4 passed · 0 rejected · iteration 3

<details><summary>evidence per changed file</summary>

```
file                                              reads  edits  tests
test/js/bun/spawn/spawn-streaming-stdin.test.ts       1      0      0
test/js/bun/spawn/spawn-streaming-stdout.test.ts      1      2      0
```

</details>

<!-- robobun:evidence:end -->

---------

Co-authored-by: robobun <117481402+robobun@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pidfd_open(2) system call is not supported

2 participants