Skip to content

terminal: add pause() and resume() for output flow control - #10

Merged
steipete merged 3 commits into
mainfrom
claude/terminal-pause-resume
Sep 28, 2026
Merged

steipete merged 3 commits into
mainfrom
claude/terminal-pause-resume

Conversation

@steipete

@steipete steipete commented Sep 27, 2026 •

Copy link
Copy Markdown

What does this PR do?

Adds output flow control to Bun.Terminal: terminal.pause() and terminal.resume(), named after Node's stream methods.

Bun.Terminal read the PTY master unconditionally (Terminal::on_read_chunk always returned true), so a consumer had no way to push back on a fast child. node-pty exposes pause()/resume() on its tty.ReadStream, and OpenClaw's Gateway terminal and node host rely on that: when a viewer's WebSocket falls behind, the PTY is paused, the kernel queue fills, and the child blocks in write(). On stock Bun a program like yes pushes about 10 MB/s through the PTY regardless of the consumer. drain only covers the input side.

  • pause() sets PAUSED and pauses the reader, which unregisters its poll. No data callback fires after pause() returns, including when it is called from inside a data callback: on_read_chunk returns false while paused, and the POSIX read loop in PipeReader.rs now stops when a pause lands during dispatch, even after HUP (it previously kept draining on hangup).
  • resume() re-arms on a later event-loop turn through a deferred task that holds a native reference; it never dispatches data synchronously. close()/dispose cancels a pending resume.
  • A terminal-owned KeepAlive bridges the interval where a paused reader's poll is inactive and honors the caller's ref()/unref().
  • Windows maps to the existing WindowsBufferedReader pause/unpause; close() unpauses so ConPTY can drain during shutdown.
  • bun.d.ts, docs/runtime/child-process.mdx, and the fork changelog document the API. While paused, a child blocks once the PTY queue fills, and the exit callback fires only after output resumes and drains. On macOS an exiting session-leader child also stays in exit until its PTY output is drained, so proc.exited may resolve only after resume().

The OpenClaw consumer is openclaw/openclaw#159447. It selects Bun's native terminal only when Terminal.prototype.pause exists, so every build that has pause() must also have the macOS exit fix from #11: without it, a paused-reader PTY child that exits before its kqueue watch is registered can block the event loop in wait4. This branch therefore carries #11's commit (cherry-picked as 1f43832), and the combined tree is byte-identical to the build used for OpenClaw's macOS Gateway proof. #11 can merge first or be closed as included; either order keeps pause() and the exit fix together.

How did you verify your code works?

macOS arm64, release build of this branch on openclaw/main 9e3414b:

  • bun run build:release test test/js/bun/terminal/: 138 passed, 4 skipped, 0 failed across 3 files.
  • New cases in terminal-spawn.test.ts (Bun.Terminal output flow control): backpressure with pause inside data plus asynchronous resume (4 MiB, exact bytes), tail preservation across a child that finishes while paused, close/async disposal while paused, and ref/unref liveness while paused. USE_SYSTEM_BUN=1 bun test ... -t 'output flow control': 0 passed, 5 failed (missing API), as expected.
  • Shared-reader regression check for the PipeReader.rs change, same selection against the unmodified base build and this build: identical results, 984 passed, 0 failed, 42 skipped, 4 todo on both (spawn/readablestream-helpers, spawn-maxbuf, spawn-noread-leak, spawn-pipe-*, spawn.test.ts, spawn-stdout-filereader-gc-uaf, util/bun-file-read, util/bun-file-fd-read, web/streams/* (4 files), http/bun-serve-file).
  • Windows x64 and arm64: rust:check-all type-check only; no Windows runtime execution.
  • End to end: an OpenClaw Gateway on this build (combined with the ESRCH fix PR) paused a 100 MiB writer at about 4 MiB while its viewer's socket was stalled, then delivered every byte after resume. The same run on stock Bun 1.4.2 let the writer finish while stalled and grew Gateway RSS by about 480 MB.
  • Independent P0-P2 review: no actionable findings.

steipete added a commit to openclaw/openclaw that referenced this pull request Sep 27, 2026
Resolve ClawSweeper's P1s for supported stock Bun: preserve output
backpressure and avoid the macOS wait4 event-loop deadlock after fast PTY
child exit. Gate the native adapter on Terminal.prototype.pause, supplied
by the OpenClaw Bun fork carrying openclaw/bun#10 and #11. Other POSIX Bun
builds keep main's Node helper with raw parameters and launch-authority
checks; Node and Windows retain node-pty.

Restore the helper, worker, protocol, tests, and runtime entrypoint
byte-identically from origin/main. Require pause/resume in the gated
native adapter while preserving output replay, teardown drain, EOF grace,
and exit ordering. Update runtime and terminal docs without a changelog edit.

Resolve the P2 replay-test issue with controlled Bun.spawn callbacks,
without sleeps or a production test hook. Cover capability routing and a
real stock-Bun Node-helper terminal; retain CI routing with native PTY
cases skipped until its Bun pin gains the capability.

Validation: Node product suites 550 passed; fork Bun 16 passed; stock Bun
9 passed with all 8 native cases skipped. Typechecks, scoped lint,
formatting, assertion-safety ratchet, and docs syntax pass. The requested
combined Node command reports only the known lint-suppression mismatch
already fixed on main by b8fa8dc (#159553); leave that file untouched.
Retry unreapable macOS process exits with a 10ms one-shot kqueue timer on the existing FilePoll. Preserve process and event-loop references without growing Process (120 bytes before and after on macOS arm64).

A deterministic terminal test delays real EVFILT_PROC registration until child exit; the supplied baseline blocks until SIGKILL, while the fixed release build drains 512 bytes and returns exit code 3. Release validation: 325 passed, 29 skipped, 0 failed across 11 files. Windows x64 and arm64 workspace type checks pass.

(cherry picked from commit c45701b)
steipete added a commit to openclaw/openclaw that referenced this pull request Sep 28, 2026
…t installed (#159447)

* fix(terminal): run PTYs on Bun's native terminal

Under Bun on macOS and Linux, spawnTerminalPty launched a Node worker
because Bun closes node-pty's nonblocking tty.ReadStream on EAGAIN, so
terminals failed on Bun-only installs without Node. Replace the bridge
with an adapter over Bun.spawn({ terminal }) behind TerminalPtyHandle and
delete the worker, its IPC protocol, their tests, and the terminalPty
runtime entrypoint. Node and Windows keep node-pty.

The adapter keeps node-pty's contract: TERM/PWD handling, UTF-8 string
output, exit after PTY EOF with a 200 ms fallback, signalled exits as
exit code 0 plus the signal number, and session-tree kills. One ordered
queue replays pre-subscription output and honors pause; the OpenClaw Bun
fork's Terminal.pause()/resume() (openclaw/bun#10) supplies real output
backpressure and is feature-detected. A terminating kill keeps reading to
EOF and drains output before exit so a paused consumer cannot hold up
teardown.

The CI process lane runs the new Bun suite on Bun and keeps its siblings
on Node.

* fix(terminal): use Bun’s native PTY on Windows

Route Bun terminal creation through the native adapter on every platform while preserving Windows batch command lines, environment inheritance, and direct kill behavior. Keep node-pty for Node and preserve existing output lifecycle handling.

Add Windows ConPTY coverage and portable spawn-contract regressions; document Windows flow-control availability. Validation: 546 Node tests passed, fork Bun passed 9 tests, stock Bun passed 6, typechecks/lint/format/assertion safety passed, and independent review found no actionable issues. Real Windows ConPTY tests remain unexecuted on this macOS host.

* revert(terminal): keep node-pty for Bun on Windows

Bun.Terminal on Windows does not deliver Ctrl-C to the foreground program; node-pty does on the same host. Restore node-pty for Bun on Windows while retaining Bun native PTYs on macOS and Linux and node-pty for Node on every platform.

* fix(terminal): keep the Node helper on Bun builds without Terminal.pause

Resolve ClawSweeper's P1s for supported stock Bun: preserve output
backpressure and avoid the macOS wait4 event-loop deadlock after fast PTY
child exit. Gate the native adapter on Terminal.prototype.pause, supplied
by the OpenClaw Bun fork carrying openclaw/bun#10 and #11. Other POSIX Bun
builds keep main's Node helper with raw parameters and launch-authority
checks; Node and Windows retain node-pty.

Restore the helper, worker, protocol, tests, and runtime entrypoint
byte-identically from origin/main. Require pause/resume in the gated
native adapter while preserving output replay, teardown drain, EOF grace,
and exit ordering. Update runtime and terminal docs without a changelog edit.

Resolve the P2 replay-test issue with controlled Bun.spawn callbacks,
without sleeps or a production test hook. Cover capability routing and a
real stock-Bun Node-helper terminal; retain CI routing with native PTY
cases skipped until its Bun pin gains the capability.

Validation: Node product suites 550 passed; fork Bun 16 passed; stock Bun
9 passed with all 8 native cases skipped. Typechecks, scoped lint,
formatting, assertion-safety ratchet, and docs syntax pass. The requested
combined Node command reports only the known lint-suppression mismatch
already fixed on main by b8fa8dc (#159553); leave that file untouched.

* fix(terminal): never deliver unsubscribed Bun PTY output after exit

Output queued with no data subscriber stayed in the adapter's queue when
exit was published, so a later onData subscription received it after
exit. Drop it at exit, as node-pty drops output nobody listens to, and
cover a late subscriber with a deterministic controlled-callback test.
# Conflicts:
#	CHANGELOG.md
#	test/js/bun/terminal/terminal-spawn.test.ts
@steipete
steipete merged commit 3240419 into main Sep 28, 2026
11 checks passed
@steipete
steipete deleted the claude/terminal-pause-resume branch September 28, 2026 01:06
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 28, 2026
…t installed (openclaw#159447)

* fix(terminal): run PTYs on Bun's native terminal

Under Bun on macOS and Linux, spawnTerminalPty launched a Node worker
because Bun closes node-pty's nonblocking tty.ReadStream on EAGAIN, so
terminals failed on Bun-only installs without Node. Replace the bridge
with an adapter over Bun.spawn({ terminal }) behind TerminalPtyHandle and
delete the worker, its IPC protocol, their tests, and the terminalPty
runtime entrypoint. Node and Windows keep node-pty.

The adapter keeps node-pty's contract: TERM/PWD handling, UTF-8 string
output, exit after PTY EOF with a 200 ms fallback, signalled exits as
exit code 0 plus the signal number, and session-tree kills. One ordered
queue replays pre-subscription output and honors pause; the OpenClaw Bun
fork's Terminal.pause()/resume() (openclaw/bun#10) supplies real output
backpressure and is feature-detected. A terminating kill keeps reading to
EOF and drains output before exit so a paused consumer cannot hold up
teardown.

The CI process lane runs the new Bun suite on Bun and keeps its siblings
on Node.

* fix(terminal): use Bun’s native PTY on Windows

Route Bun terminal creation through the native adapter on every platform while preserving Windows batch command lines, environment inheritance, and direct kill behavior. Keep node-pty for Node and preserve existing output lifecycle handling.

Add Windows ConPTY coverage and portable spawn-contract regressions; document Windows flow-control availability. Validation: 546 Node tests passed, fork Bun passed 9 tests, stock Bun passed 6, typechecks/lint/format/assertion safety passed, and independent review found no actionable issues. Real Windows ConPTY tests remain unexecuted on this macOS host.

* revert(terminal): keep node-pty for Bun on Windows

Bun.Terminal on Windows does not deliver Ctrl-C to the foreground program; node-pty does on the same host. Restore node-pty for Bun on Windows while retaining Bun native PTYs on macOS and Linux and node-pty for Node on every platform.

* fix(terminal): keep the Node helper on Bun builds without Terminal.pause

Resolve ClawSweeper's P1s for supported stock Bun: preserve output
backpressure and avoid the macOS wait4 event-loop deadlock after fast PTY
child exit. Gate the native adapter on Terminal.prototype.pause, supplied
by the OpenClaw Bun fork carrying openclaw/bun#10 and openclaw#11. Other POSIX Bun
builds keep main's Node helper with raw parameters and launch-authority
checks; Node and Windows retain node-pty.

Restore the helper, worker, protocol, tests, and runtime entrypoint
byte-identically from origin/main. Require pause/resume in the gated
native adapter while preserving output replay, teardown drain, EOF grace,
and exit ordering. Update runtime and terminal docs without a changelog edit.

Resolve the P2 replay-test issue with controlled Bun.spawn callbacks,
without sleeps or a production test hook. Cover capability routing and a
real stock-Bun Node-helper terminal; retain CI routing with native PTY
cases skipped until its Bun pin gains the capability.

Validation: Node product suites 550 passed; fork Bun 16 passed; stock Bun
9 passed with all 8 native cases skipped. Typechecks, scoped lint,
formatting, assertion-safety ratchet, and docs syntax pass. The requested
combined Node command reports only the known lint-suppression mismatch
already fixed on main by 4a34b87 (openclaw#159553); leave that file untouched.

* fix(terminal): never deliver unsubscribed Bun PTY output after exit

Output queued with no data subscriber stayed in the adapter's queue when
exit was published, so a later onData subscription received it after
exit. Drop it at exit, as node-pty drops output nobody listens to, and
cover a late subscriber with a deterministic controlled-callback test.
steipete pushed a commit to fuller-stack-dev/bun that referenced this pull request Oct 20, 2026
…module-graph.test.ts (oven-sh#45674)

### What does this PR do?

Fixes the flaky "50 graphs alive at once, each with its own state, then
all exit and are collected" in
`test/js/bun/module-graph/module-graph.test.ts`. It failed in 2 of 31
builds of main, 125686 to 127114 (Ubuntu 25.04 x64, Windows 11 aarch64)
and passed on the retry.

The test registered one array, `graphs[25].big`, with a
`FinalizationRegistry` and failed if 100 collections did not finalize
it. It now tracks the array of every one of the 50 graphs with
`Lifetimes` from `module-graph-lifetimes.ts`, as
`module-graph-gc.test.ts` does. There, an object that is not finalized
counts as kept alive only if a root reaches it in the debugging heap
snapshot, and the failure message is the path from that root.

Two things change with the helper, and the first is what makes the runs
below pass:

1. **Where the collection runs.** The helper calls `Bun.gc(true)` from a
timer callback, main's `collected()` from the continuation of the async
test. The `runInternalMicrotask` frame that holds the stale word
(artifact 2) is not on the stack in a timer callback. In 240 of 240 runs
all 50 arrays were finalized by the first collection.
2. **What is asserted if one is left.** Not that it was finalized, but
that no root reaches it.

### Why it failed

On main one of the 50 graphs outlives the collections in almost every
run, and the test fails when that one is number 25. Whole file, CI's
environment, 840 runs:

| graphs left after the collections | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| runs | 2 | 802 | 3 | 33 |

12 of the 840 failed. In the failing runs looked at (9 heap snapshots,
12 stack dumps) nothing in the heap holds the one that is left, and one
word on the native stack points at it.

All of what follows is the Linux x64 binary that CI built for main at
7f3bc6a, with `BUN_GARBAGE_COLLECTOR_LEVEL=1
BUN_RUNTIME_TRANSPILER_CACHE_PATH=0` as in `scripts/runner.node.ts`. The
failure needs both that environment and the whole file: 0 of 240 without
the environment, 0 of 1600 with the test alone. I did not look at the
Windows failure.

<details><summary>Artifact 1: the heap snapshot</summary>

`generateHeapSnapshotForDebugging()` right after the 100 collections.
These are the array and every cell from which it can be reached:

```
snapshot: 27033 cells, 99750 edges, 586 roots; arrays named `big` still in it: 1
  cell   1532 Promise                0x34cf520fa40  incoming edges 0  in `roots` no  a root reaches it no
  cell   1555 ModuleRecord           0x34cf527e980  incoming edges 3  in `roots` no  a root reaches it no
  cell   1573 ModuleNamespaceObject  0x34cef51dd50  incoming edges 3  in `roots` no  a root reaches it no
  cell   1591 JSModuleEnvironment    0x34cf5278950  incoming edges 3  in `roots` no  a root reaches it no
  cell   1626 Array                  0x34cef3755a0  incoming edges 2  in `roots` no  a root reaches it no
  cell   1631 Function               0x34cef45a100  incoming edges 2  in `roots` no  a root reaches it no
  cell   1653 Function               0x34cef45a0e0  incoming edges 2  in `roots` no  a root reaches it no
```

The snapshots of 8 other failing runs have the same seven kinds of cell,
with the `Promise` (fulfilled with the `ModuleRecord`) as the only one
without an incoming edge.
</details>

<details><summary>Artifact 2: the stack word and the frame that owns it
(gdb, same run as artifact 1)</summary>

The test writes the snapshot and sends itself SIGUSR2, and gdb stops
there.

```
Thread 1 "bun-profile" received signal SIGUSR2, User defined signal 2.
(gdb) info registers rsp rbp
rsp            0x7fffffffa0c8
rbp            0x7fffffffa240

words in [rsp, end of stack) = [0x7fffffffa0c8, 0x7ffffffff000) that point into one of those cells: 1
  0x7fffffffa8a0 holds 0x34cf520fa40 = Promise+0; it lies in the frame with rbp 0x7fffffffa8f0, at rbp-0x50
(gdb) x/gx 0x7fffffffa8a0
0x7fffffffa8a0:	0x0000034cf520fa40
(gdb) info symbol 0x1bccee0        # where that frame's callee returns to
JSC::runInternalMicrotask(...) + 6976

rbp chain
  openclaw#3  rbp 0x7fffffffa540  Bun::Process_functionKill
  openclaw#4  rbp 0x7fffffffa550  (JIT code)
  openclaw#5  rbp 0x7fffffffa5d0  op_call_ignore_result_return_location
  openclaw#6  rbp 0x7fffffffa680  llint_call_javascript
  openclaw#7  rbp 0x7fffffffa7e0  JSC::asyncFunctionGeneratorBodyCall
  openclaw#8  rbp 0x7fffffffa8f0  JSC::runInternalMicrotask            <- owns 0x7fffffffa8a0
  openclaw#9  rbp 0x7fffffffab70  JSC::MicrotaskQueue::drainWithUseCallOnEachMicrotask
  openclaw#10 rbp 0x7fffffffac00  JSC::VM::drainMicrotasks
  openclaw#11 rbp 0x7fffffffac20  Zig::GlobalObject::drainMicrotasks
  openclaw#12 rbp 0x7fffffffac50  <bun_jsc::event_loop::EventLoop>::exit
  openclaw#13 rbp 0x7fffffffacf0  TimerObjectInternals::fire
```

12 failing runs that dumped their own stack from `/proc/self/mem` show
the same: one word, `Promise+0`, at `rbp-0x50` of
`runInternalMicrotask`. In the 5 of them where I looked for it, the
frame's callee returns to the same `0x1bccee0`, which is
`JSMicrotask.cpp:2053`.

**Who wrote it.** A hardware watchpoint on `0x7fffffffa8a0`, set at the
first line of the test, sees 10 writes. The last one is the `Promise`:
`pushq %r14` in the prologue of `JSC::ModuleGraphLoadingState::create`
(`ModuleGraphLoadingState.cpp:71`, rbp `0x7fffffffa8b0`), which saves a
register of its caller.

**Why it stays.** The 100 collections run in the continuation of an
async function, so each runs under a `runInternalMicrotask` frame at
that same address. In the disassembly the function has 9 stores to
`-0x50(%rbp)`. Following the jump table and every branch, only case 14
of the switch (resume an async function) reaches the call at
`JSMicrotask.cpp:2053`, and none of the 9 stores is on a way to it. The
slot is inside a live frame, so stack sanitizing does not cover it.

So the graph that is left is the one whose load called `create` last at
that depth.
</details>

### How did you verify your code works?

**Failure rate.** Whole file, 12 copies side by side, main and this PR
in alternating rounds:

| | main | this PR |
|---|---|---|
| runs that failed | 12 of 1200 (all this test) | 0 of 1200 |

**What the snapshot says about a survivor.** With this PR there was none
to ask about: in those 240 runs, with a logging copy of the helper, the
snapshot was never taken. So this is main's test as it is, followed by
the helper's `Heap` asked about the 50 addresses, 1080 runs. The old
assertion failed in 12 of them. In 11 the array was in the snapshot with
no root reaching it, in 1 it was gone by then, in 0 a root reached it.

In 7 of the 1080 runs a root did reach two other arrays. In the one run
whose paths were printed, both start at `root(JITWorkList)`, a
compilation that is still running. `stillAlive` goes on collecting while
a root reaches something.

**Real references must fail.** One line added before `graphs.length =
0`. All 9 fail, with these messages:

| graph 25 is held by | message |
|---|---|
| a global, the namespace | `root(ProtectedValues) GlobalObject
-Property:held-> ModuleNamespaceObject -> ModuleRecord ->
JSModuleEnvironment -> Array` |
| a global closure over `inc` | `root(ProtectedValues) GlobalObject
-Property:held-> Function -> JSLexicalEnvironment -Variable:inc->
Function(inc) -> JSModuleEnvironment -> Array` |
| a local of the suspended test | `root(Output) FunctionCodeBlock -> ...
-Variable:pendingHeap-> Promise -> AsyncFunctionGenerator -> ...` |
| `setInterval(inc)` | `root(StrongHandles) StrongRootBlock -> Timeout
-Property:callback-> Function(inc) -> JSModuleEnvironment
-Variable:big-> Array` |
| `process.on(..., inc)` | `root(ProtectedValues) GlobalObject ->
Process -> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` |
| a reaction of a pending promise | `root(ProtectedValues) GlobalObject
-Property:held-> Promise -> Function(inc) -> JSModuleEnvironment
-Variable:big-> Array` |
| a `FinalizationRegistry` held value | `root(ProtectedValues)
GlobalObject -Property:held-> FinalizationRegistry -> Array` |
| a `WeakMap` value of a live key | `root(Output) Array` |
| an `AbortSignal` listener | `root(WeakSets) AbortSignal ->
Function(inc) -> JSModuleEnvironment -Variable:big-> Array` |

With `globalThis.held = graphs[7]` instead, main's test passes 5 of 5
and this PR's fails 5 of 5.

**Debug build**, default timeout: the test passes 6 of 6 alone and in 6
of 6 runs of the whole file.
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.

1 participant