Skip to content

fix: desktop stream hangs when the gateway never acknowledges close - #165806

Merged
obviyus merged 21 commits into
openclaw:mainfrom
SebTardif:fix/node-stream-close-ack-timeout
Oct 7, 2026
Merged

obviyus merged 21 commits into
openclaw:mainfrom
SebTardif:fix/node-stream-close-ack-timeout

Conversation

@SebTardif

@SebTardif SebTardif commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A desktop or portal stream used to stay open when the local target ended and the gateway never finished the WebSocket close. The short acknowledgement that fixed that hang also settled the node command while a proxy could still be holding the tail. Settling the command destroys the gateway receive stream, so those bytes never arrive.

A size cutoff does not fix that. Forwards of 64 KiB or less still took the 5 second path. Any fixed wait after the local buffer drains has the same hole: bufferedAmount === 0 means the kernel accepted the bytes, not that the gateway has read them.

Evidence

Gateway close that withholds TCP FIN: 1f7ec3a

ws owns the close handshake. The multi-day closeTimeout override is gone, and so is the extra node timer that fired 30 seconds after drain. An empty close still uses the 5 second acknowledgement. A send buffer that is still shrinking still waits before close().

Local production call on macOS 26.6.2 arm64 (Darwin 25.6.0), Node v26.10.0. A TCP peer with allowHalfOpen completed the WebSocket upgrade, wrote close code 1000 after the metadata frame, and did not send FIN. Default timers. No enrolled gateway. The 12 MiB enrolled-node run was not repeated.

peer_data 243 upgraded false
upgraded
peer_data 17 upgraded true
sent_close_frame
peer_data 8 upgraded true
peer_end 18
tick 5004
tick 10005
tick 15007
tick 20008
tick 25008
tick 30008
[node-host/stream] node stream closed
settled 30121

peer_end 18 is the client's close-handshake write FIN. The command settled at 30121 ms, and the library logged the socket close. A second local peer sent invalid opcode 3. The command rejected at 17 ms, the peer saw peer_end at 17 ms, and the same close log followed the 30008 ms tick. That default-timer run stays outside the ordinary test file. node scripts/run-vitest.mjs src/node-host/node-stream-transport.test.ts passed 26 tests in 1.44 s, with no real 30 second wait. The empty-close case waits for the diagnostic close record, then flushes once.

Test-only follow-up: 4b10b22

The protocol-error regression on that head uses a TCP peer with allowHalfOpen: true and withholds FIN. It sends invalid opcode 3, fires the injected cleanup callback, observes the real client terminate() call, then awaits that client's close event and verifies CLOSED before peer teardown. No sleeps or polling were added. Production code on that head was unchanged from the runtime-proven e5cb252.

  • Negative control: temporarily removed the cleanup callback's CLOSING branch inside isolated Docker only. The regression failed: expected "terminate" to be called once, but got 0 times (53 ms). The mutation was restored and never committed.
  • Candidate: pnpm test src/node-host/node-stream-transport.test.ts --maxWorkers=1 passed 26/26, 5.349 s wall time (Vitest 3.92 s; repaired case 5 ms), in secretless node:24.16.0-bookworm.
  • git diff --check passed. No overlap with Pash/Sarah changes.

The previous test-only head failed TypeScript because a spy context is unknown. This head replaces the non-narrowing expectation with an instanceof WebSocket guard. The affected type graph passes: node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.gateway-other.json --noEmit (exit 0).

Exact-head verification: e5cb252

Fresh isolated Docker proof on this head:

  • Production transport boundary, default timers, invalid opcode 3 with a TCP-half-open silent peer: command rejected at 1 ms; the actual client WebSocket close event occurred at 30,009 ms. This observes socket retirement, not just timer scheduling. The same peer on base closed at 30,139 ms; the previous candidate remained unclosed at the 40-second cap.
  • Non-empty 1 KiB silent peer: settled without abort in 30,093 ms. Empty silent peer: 5,140 ms. Application-level invalid text frame: failed-command socket cleanup at 30,021 ms.
  • Built Gateway + enrolled node, synthetic RFB target, 12,582,912 bytes at at most 16 KiB per 64 ms: acknowledged and withheld-acknowledgement cases both delivered every byte without corruption. Acknowledged close completed at 86.779 s. With acknowledgement and TCP EOF withheld, all bytes arrived by 85.095 s, and the observer closed at 101.003 s. The finite retirement did not truncate this tested tail.
  • Normal acknowledged 65,536-byte close: complete payload, close at 191 ms. Active stream: marker arrived at 7.254 s; still open until deliberate 12-second cleanup.
  • One real Gateway-backed gpt-5-mini call, reasoning low, output budget 4096: P165806_LIVE_OK, status ok, exit 0.

Boundary replays above invoke the actual source-level transport against real TCP peers with default timers; they are not built-Gateway proofs. The delivery/control cases use the built Gateway and enrolled node. No physical desktop was used. This is bounded evidence for the stated rates and payloads, not a claim that every arbitrarily delayed tail is preserved.

Historical observations (not current-head claims)

On head f85d55f8c56, a built Gateway, an enrolled node, and a throttled proxy delivered all 12,582,912 bytes of a 12 MiB stream paced at 16 KiB per 64 ms, and the proxy forwarded the close frame. That measurement is the maintainer's. The exact-head repeat is recorded above.

Historical trace from 2dc5166a082, before the current finite post-drain deadline: production runNodeStreamTransport connected to a local gateway through a TCP proxy on 127.0.0.1. The proxy forwarded the HTTP upgrade, read the rest from the node, and held those bytes for 35 seconds before writing them to the gateway. The local target wrote 1024 bytes and ended. The production close budget was left in place.

At 32 seconds the command was still pending and the gateway had not received the payload. After the proxy released the bytes, the gateway counted 1024 payload bytes and the command settled at 35080 ms. That is past both the 5 second acknowledgement and the library's 30 second close timer.

midpoint elapsed_ms=32002 settled=false payload_bytes=0
proxy_release payload_bytes=0
command_settled elapsed_ms=35080 payload_bytes=1024
final elapsed_ms=35080 settled=true payload_bytes=1024 released=true
PROOF_OK small_forward_held_until_gateway_close

An empty close still uses the 5 second acknowledgement. In an earlier revision the production default was left in place, the target ended without writing a payload, and the silent gateway never completed the close. The command settled at 5013 ms.

{"event":"empty_close","settled":true,"elapsedMs":5013}

On historical head 7532b772cd8, a local gateway read 64 payload bytes and then stayed silent. The production budgets were left in place. The command settled at 30014 ms.

{"event":"silent_close_after_forward","payloadBytes":64,"settled":true,"elapsedMs":30014}

A send buffer that stops shrinking for 30 seconds still retires, because those bytes have not left this process. The historical 35-second hold does not establish delivery under the current finite post-drain deadline; current-head delivery evidence is reported above.

On an earlier head, a local peer sent a frame with RSV1 set. The command rejected while that peer held the TCP connection open, and a scheduled cleanup terminated the socket. The current head leaves that handshake to ws.

Real behavior proof

Behavior addressed: A gateway close frame that withholds TCP FIN retires through the library close timer. The node does not add a second post-close timer or a multi-day closeTimeout override.
Real environment tested: macOS 26.6.2 arm64, Darwin 25.6.0, Node v26.10.0. Local process calling production runNodeStreamTransport. No enrolled gateway and no physical desktop.
Exact steps or command run after this patch: pnpm exec tsx ran a local script that is not in the commit. The script listened on 127.0.0.1 with allowHalfOpen, answered the WebSocket upgrade, and on the next payload wrote bytes 88 02 03 e8. It imported runNodeStreamTransport from src/node-host/node-stream-transport.ts and used default timers with an open Duplex target.
Evidence after fix: terminal output copied below.

peer_data 243 upgraded false
upgraded
peer_data 17 upgraded true
sent_close_frame
peer_data 8 upgraded true
peer_end 18
tick 5004
tick 10005
tick 15007
tick 20008
tick 25008
tick 30008
[node-host/stream] node stream closed
settled 30121

Observed result after fix: The command settled at 30121 ms and the library logged the socket close. The peer logged peer_end at 18 ms. Earlier Docker and 12 MiB results above are for e5cb252 and were not repeated.
What was not tested: a live enrolled gateway, a physical desktop or portal, and the 12 MiB paced transfer. That transfer already passed on e5cb252 and was not repeated.

Summary

Forwarded streams send the close only after the outbound buffer drains. ws then owns the handshake, including a gateway close that withholds TCP FIN. An empty close still uses the 5 second bound. A send buffer that stops shrinking still waits before close. A failed command rejects without a second node handshake timer.

After the local target ends, a gateway that never completes the WebSocket
close handshake held the stream command for the library's 30s close
timer. The command now finishes and the socket is terminated after 5s.

Signed-off-by: Sebastien Tardif <[email protected]>
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 6:20 PM ET / 22:20 UTC (Revision 23).

ClawSweeper review

What this changes

The PR bounds empty desktop and portal stream shutdown, waits for outgoing data to drain before closing, and adds transport regressions for unresponsive peers.

Merge readiness

✅ Ready for maintainer review

Keep open: the shutdown improvement remains absent from current main and the latest release. The latest regression test addresses the documented coverage gap; no blocking correctness finding remains.

Priority: P2
Reviewed head: 0ebfd8f13f122a3347c6fbd952f72e98ab58e1bf

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The focused repair has strong real transport evidence and now includes a mutation-sensitive, event-driven regression without a real 30-second test wait.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The unchanged production transport was exercised against real TCP peers with default timers, observing finite client closure and command settlement; built Gateway/enrolled-node controls preserved complete throttled payload delivery. The latest commit adds regression coverage only. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The unchanged production transport was exercised against real TCP peers with default timers, observing finite client closure and command settlement; built Gateway/enrolled-node controls preserved complete throttled payload delivery. The latest commit adds regression coverage only. No stored-data contract changes.
Evidence reviewed 8 items Introduced production behavior: The pinned merge-base-to-head delta adds a five-second empty-stream deadline and a progress-aware drain wait before invoking the existing WebSocket handshake. It retains the library's default handshake timeout.
Current main still lacks the improvement: Current main closes immediately after target EOF and relies on the library handshake deadline; it has neither the five-second empty-stream bound nor the introduced drain-progress path.
Latest release comparison: The source at the supplied latest release v2026.9.8 also invokes close immediately after target EOF and lacks the new shutdown budgets.
Findings None None.
Security None None.

How this fits together

The node stream transport connects a local desktop or portal service to the Gateway through an authenticated WebSocket. Its completion controls when the Gateway retires the receiving stream.

flowchart LR
  A[Local desktop or portal] --> B[Node stream transport]
  B --> C[Outgoing buffer]
  C --> D{Empty or forwarded data}
  D --> E[Bounded empty shutdown]
  D --> F[Drain before handshake]
  E --> G[Gateway receiving stream]
  F --> G
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +76, Tests +499. Total +575 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 81 5 +76
Tests 1 501 2 +499
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 582 7 +575

Review metrics

None.

Technical review

Best possible solution:

Keep bounded empty-stream retirement and drain-aware forwarding while leaving the close handshake with the installed WebSocket library.

Do we have a high-confidence way to reproduce the issue?

Yes: a real TCP peer that completes attachment but withholds close acknowledgement exposes the shutdown delay, with recorded comparative transport traces. This read-only review inspected the source and supplied observations without executing a reproduction.

Is this the best way to solve the issue?

Yes: distinguishing empty shutdown from forwarded data preserves delivery while reusing the library's handshake owner; the latest fake-timer regression protects finite socket retirement.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 51f772aeefbc.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded desktop and portal shutdown reliability improvement with passing recorded delivery controls.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The unchanged production transport was exercised against real TCP peers with default timers, observing finite client closure and command settlement; built Gateway/enrolled-node controls preserved complete throttled payload delivery. The latest commit adds regression coverage only. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The unchanged production transport was exercised against real TCP peers with default timers, observing finite client closure and command settlement; built Gateway/enrolled-node controls preserved complete throttled payload delivery. The latest commit adds regression coverage only. No stored-data contract changes.

Evidence

What I checked:

  • Introduced production behavior: The pinned merge-base-to-head delta adds a five-second empty-stream deadline and a progress-aware drain wait before invoking the existing WebSocket handshake. It retains the library's default handshake timeout. (src/node-host/node-stream-transport.ts:181, 0ebfd8f13f12)
  • Current main still lacks the improvement: Current main closes immediately after target EOF and relies on the library handshake deadline; it has neither the five-second empty-stream bound nor the introduced drain-progress path. (src/node-host/node-stream-transport.ts, 51f772aeefbc)
  • Latest release comparison: The source at the supplied latest release v2026.9.8 also invokes close immediately after target EOF and lacks the new shutdown budgets. (src/node-host/node-stream-transport.ts:184, fc23bc864e45)
  • Latest regression addresses the concrete proof gap: The new test sends a valid close frame from a TCP-half-open peer, waits for the client's FIN, advances fake timers by 30 seconds, and observes CLOSED, the actual close event, and command settlement. The contributor reports that restoring the multi-day closeTimeout makes this assertion fail, with 27 tests completing in about two seconds. (src/node-host/node-stream-transport.test.ts:821, 0ebfd8f13f12)
  • Real production-path evidence remains applicable: The supplied discussion at fix: desktop stream hangs when the gateway never acknowledges close #165806 (comment) records default-timer production transport runs on 4a1fb57: silent, protocol-error, and valid-close/withheld-FIN cases retire around 30 seconds; empty streams finish around five seconds. Built Gateway and enrolled-node runs delivered all 12,582,912 bytes intact through a throttled proxy in both acknowledged and withheld-ack cases. The production file has no delta between that revision and the reviewed head. These are transport and synthetic RFB observations, without a physical desktop. (src/node-host/node-stream-transport.ts, 0ebfd8f13f12)
  • Verified dependency handshake owner: Repository ownership and the 8.21.3 tag commit were verified through GitHub. close() starts the destruction timer; valid received close frames and protocol errors invoke close(). The default CLOSE_TIMEOUT is 30000 milliseconds. This contract applies because the changed transport uses the installed ws implementation and explicitly relies on its timer. (lib/websocket.js:1309, c791e707eab3)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (22 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-06T14:21:13.080Z sha 9554c0f :: needs changes before merge. :: [P2] Keep the protocol-error peer half-open and observe client retirement
  • reviewed 2026-10-06T15:18:26.680Z sha cbcedcc :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T16:20:22.809Z sha 4b10b22 :: blocked before merge. :: [P2] [P2] Preserve bounded cleanup for peer-initiated close
  • reviewed 2026-10-06T18:15:32.404Z sha 1b98f84 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T18:37:48.290Z sha c51b0eb :: needs changes before merge. :: [P1] Use the existing WebSocket handshake timeout owner | [P3] Replace the added polling waits with completion signals
  • reviewed 2026-10-06T19:10:21.402Z sha 6b01aa5 :: needs changes before merge. :: [P1] Use the existing WebSocket handshake timeout owner | [P3] Replace the added polling waits with completion signals
  • reviewed 2026-10-06T20:11:30.405Z sha 4a1fb57 :: needs changes before merge. :: [P2] Keep the handshake regression off the real 30-second clock | [P3] Replace the remaining added log polling with a close signal
  • reviewed 2026-10-06T20:30:06.901Z sha 1f7ec3a :: needs maintainer review before merge. :: none

The socket data callback was string or Buffer, so Buffer.concat failed
check-test-types-core-1. The other listener in this file already types
the chunk as Buffer.

Signed-off-by: Sebastien Tardif <[email protected]>
ws.close() returns while the last payload and the close frame can
still be queued. The 5 second budget now starts after that buffer
drains. A flush that stays queued keeps the 30 second allowance.

A local gateway that stopped reading left the command pending past
a 40 ms budget. It settled 59 ms after the gateway resumed.

Signed-off-by: Sebastien Tardif <[email protected]>
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 6, 2026
The paused gateway kept the command pending on this machine and
settled immediately in CI. The acknowledgement budget test stays
on a real socket with a 40 ms deadline.

Signed-off-by: Sebastien Tardif <[email protected]>
SebTardif and others added 2 commits October 5, 2026 17:49
The regression waited on a two-second wall clock against a 40 ms
timer. It now waits until the close path schedules that callback,
then runs the callback.

Signed-off-by: Sebastien Tardif <[email protected]>
@obviyus

obviyus commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

@SebTardif the built Gateway + enrolled node runtime comparison found a slow-stream regression on 323449be7410bf32fc96562f4e0aa2f3acc90e59 versus merge-base 282f796dfa057e1e21fcdd0f3686712578b0c0e9:

  • The synthetic RFB target sent a final 12 MiB (12,582,912-byte) payload and ended.
  • A test-only TCP proxy throttled the node-to-Gateway attach connection to at most 16 KiB every 64 ms, pausing upstream reads between chunks. It withheld the Gateway's WebSocket close acknowledgement and TCP EOF.
  • Base: the observer received all 12,582,912 bytes, and the proxy forwarded the final close frame.
  • Candidate: the observer received only 10,518,475 bytes and closed at 72.953 s, before the proxy forwarded the close frame. Both completed comparisons had a 130 s driver deadline, so this candidate close was not driver cleanup.

Please make the acknowledgement timer start only once the socket's buffered bytes have drained, so the final payload and close frame survive this slow path. The current bufferedAmount check did not preserve delivery in this end-to-end scenario; the exact interaction with Gateway stream teardown still needs investigation.

The ordinary acknowledged-close and active-stream controls passed, the withheld-ack timeout behaved as intended for the small payload, and the regression test is red on base / green on the candidate. Those passes do not override this truncation. The PR's Evidence section now records the full comparison; this PR should not land as-is.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 6, 2026
bufferedAmount 0 only means the kernel accepted the bytes. After more
than 64 KiB, the close acknowledgement uses the 30s flush budget
instead of 5s, so a slow attach can finish reading before the node
command retires the gateway stream.

Signed-off-by: Sebastien Tardif <[email protected]>
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 6, 2026
Core lint stripe 5 rejects createDeferred<void>() because void is already
the default type parameter.

Signed-off-by: Sebastien Tardif <[email protected]>
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 6, 2026
A received close still retires on the 30 second flush. The library
closeTimeout override stays, so a forwarded stream is not destroyed
while a proxy holds the tail.

Signed-off-by: Sebastien Tardif <[email protected]>
The multi-day closeTimeout and the extra post-close timer retired the
same handshake. Empty closes still use five seconds, and a stalled
send buffer still waits before close.

Signed-off-by: Sebastien Tardif <[email protected]>
The ordinary suite waits for the close record instead of polling logs.
The default-timer withheld-FIN measurement stays in the pull request
body, outside this file.

Signed-off-by: Sebastien Tardif <[email protected]>
@obviyus

obviyus commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

@SebTardif, thanks for consolidating handshake ownership in ws. We'll stay off your branch while you iterate; no further maintainer changes have been pushed.

I pinned your 4a1fb572a893cfbf2e00c13e1348aec9a5e23843 and re-ran the isolated harness. The comparison below uses the already-measured, unchanged main baseline 76beb568588720ed7d9cfafc4c8730637afe7532. Both use secretless node:24.16.0-bookworm; installed ws is 8.21.3, whose default close timer is 30,000 ms.

Case / observed completion Main baseline Your head
1 KiB stream, silent peer: command settles 30.090 s 30.046 s
Empty stream, silent peer: command settles 30.188 s 5.010 s
Command failure (invalid text): actual client closes 30.003 s 30.083 s
Protocol error (opcode 3), half-open peer: actual client closes 30.040 s 30.007 s
Valid Gateway close, TCP FIN withheld: actual client closes 30.028 s 30.029 s
Same valid-close case: command settles 30.085 s 30.069 s
Normal acknowledged close, 65,536 bytes: viewer closes 0.103 s 0.132 s
Active control: still open at deliberate teardown 12.139 s 12.153 s
Slow 12 MiB, acknowledged: complete payload / viewer closes 86.183 s 86.014 s
Slow 12 MiB, close acknowledgement withheld: complete payload / viewer closes 92.020 s 95.953 s

Both slow cases delivered all 12,582,912 bytes with zero corrupt bytes, on both revisions. Those runs use the built Gateway, an enrolled node, synthetic RFB target, and a proxy forwarding at at most 16 KiB per 64 ms. Your active control delivered its 15-byte marker at 7.117 s and remained open until deliberate cleanup. The other shutdown cases invoke the actual source transport against real TCP peers with production default timers; they are not represented as built-Gateway runs. No shutdown-boundary case hung past the 40-second cap. Removing the duplicate post-drain/command-failure timers remained bounded in these cases via ws.

Concrete coverage gap: your rejects a protocol error without a node handshake timer test still passes when I restore closeTimeout: 2_147_483_647 in an isolated mutation (12 ms, exit 0). That disables practical socket retirement without delaying error rejection, so the < 2 s assertion protects rejection latency, not client cleanup. The mutation was restored and was never committed or pushed.

Your unmodified file passes 27/27 in 33.402 s wall time; the valid-close case consumes 30.035 s. The affected tsconfig.core.test.gateway-other.json graph also passes using the repo's run-tsgo.mjs wrapper.

Below is an optional test-only suggestion against your pinned head for the remaining polling/real-timer findings. It waits for actual close events, advances fake time only after the peer receives FIN, and leaves production untouched. In isolation this patch passed 27/27 in 3.836 s wall time, passed the affected type graph, and its valid-close test failed under the same multi-day-timeout mutation (CLOSING 2 instead of CLOSED 3). It does not change the protocol-error test's narrower rejection-only assertion.

Suggested event-driven test patch (not pushed)
--- a/src/node-host/node-stream-transport.test.ts
+++ b/src/node-host/node-stream-transport.test.ts
@@ -1,12 +1,14 @@
 import { createHash, X509Certificate } from "node:crypto";
+import { once } from "node:events";
 import { createServer as createHttpServer } from "node:http";
 import { createServer as createHttpsServer } from "node:https";
 import net, { type AddressInfo } from "node:net";
 import { Duplex } from "node:stream";
 import { rawDataToString } from "@openclaw/gateway-client/websocket-data";
 import { installGlobalProxy } from "@openclaw/proxyline";
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
 import { WebSocketServer } from "ws";
+import { WebSocket } from "../../packages/gateway-client/src/websocket.js";
 import { createDeferred } from "../../test/helpers/promise.js";
 import { TEST_TLS_CERT_PEM, TEST_TLS_KEY_PEM } from "../../test/helpers/tls-fixture.js";
 import { createSuiteLogPathTracker } from "../logging/log-test-helpers.js";
@@ -308,7 +310,6 @@
       gateway.listen(0, "127.0.0.1", resolve);
     });
     const controller = new AbortController();
-    let settled = false;
     const running = runNodeStreamTransport({
       gatewayUrl: `ws://127.0.0.1:${(gateway.address() as AddressInfo).port}`,
       attachPath: `/node-${streamName}/attach`,
@@ -317,14 +318,11 @@
       metadata: { ok: true },
       streamName,
       signal: controller.signal,
-    }).then(() => {
-      settled = true;
     });
     try {
       await wrote.promise;
       target.push(Buffer.from("terminal-response"));
       target.push(null);
-      await expect.poll(() => settled).toBe(true);
       await running;
       expect(frames).toEqual([JSON.stringify({ ok: true }), "terminal-response"]);
       expect(writes).toBe(1);
@@ -350,6 +348,7 @@
     const logCapture = createDiagnosticLogRecordCapture();
     logCaptures.push(logCapture);
     const gotFrame = createDeferred();
+    const terminate = vi.spyOn(WebSocket.prototype, "terminate");
     const gateway = net.createServer((socket) => {
       let buffer = Buffer.alloc(0);
       let upgraded = false;
@@ -435,12 +434,12 @@
       ack?.();
       await running;
       expect(failure).toBeUndefined();
-      await expect
-        .poll(async () => {
-          await logCapture.flush();
-          return logCapture.records.find((record) => record.message === "node stream closed");
-        })
-        .toBeTruthy();
+      const client = terminate.mock.contexts[0];
+      if (!(client instanceof WebSocket)) {
+        throw new Error("Expected cleanup to terminate the client WebSocket");
+      }
+      await once(client, "close");
+      await logCapture.flush();
       expect(
         logCapture.records.find((record) => record.message === "node stream closed")?.attributes,
       ).toMatchObject({
@@ -452,6 +451,7 @@
       controller.abort();
       await running;
       targetPeer?.destroy();
+      terminate.mockRestore();
       await new Promise<void>((resolve) => {
         targetServer.close(() => resolve());
       });
@@ -747,9 +747,12 @@
 
   it("bounds a gateway close that withholds TCP FIN", async () => {
     let peer: net.Socket | undefined;
+    const close = vi.spyOn(WebSocket.prototype, "close");
+    const receivedFin = createDeferred();
     const gateway = net.createServer({ allowHalfOpen: true }, (socket) => {
       peer = socket;
       socket.on("error", () => undefined);
+      socket.once("end", () => receivedFin.resolve());
       let buffer = Buffer.alloc(0);
       let upgraded = false;
       let sentClose = false;
@@ -794,29 +797,43 @@
         callback();
       },
     });
+    vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
     const controller = new AbortController();
-    const started = Date.now();
+    let failure: unknown;
+    const running = runNodeStreamTransport({
+      gatewayUrl: `ws://127.0.0.1:${(gateway.address() as AddressInfo).port}`,
+      attachPath: "/node-desktop/attach",
+      expectedAttachPath: "/node-desktop/attach",
+      target: { stream: target },
+      metadata: { ok: true },
+      streamName: "desktop",
+      signal: controller.signal,
+    }).catch((error: unknown) => {
+      failure = error;
+    });
     try {
-      await runNodeStreamTransport({
-        gatewayUrl: `ws://127.0.0.1:${(gateway.address() as AddressInfo).port}`,
-        attachPath: "/node-desktop/attach",
-        expectedAttachPath: "/node-desktop/attach",
-        target: { stream: target },
-        metadata: { ok: true },
-        streamName: "desktop",
-        signal: controller.signal,
-      });
-      const elapsed = Date.now() - started;
+      await receivedFin.promise;
       expect(target.readableEnded).toBe(false);
-      expect(elapsed).toBeGreaterThan(20_000);
-      expect(elapsed).toBeLessThan(40_000);
+      const client = close.mock.contexts[0];
+      if (!(client instanceof WebSocket)) {
+        throw new Error("Expected a client WebSocket close handshake");
+      }
+      const closed = once(client, "close");
+      await vi.advanceTimersByTimeAsync(30_000);
+      expect(client.readyState).toBe(WebSocket.CLOSED);
+      await closed;
+      await running;
+      expect(failure).toBeUndefined();
     } finally {
       controller.abort();
       target.destroy();
       peer?.destroy();
+      await running;
+      close.mockRestore();
+      vi.useRealTimers();
       await new Promise<void>((resolve) => {
         gateway.close(() => resolve());
       });
     }
-  }, 50_000);
+  });
 });

The harness is retained; happy to repeat the affected checks on your next revision.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 6, 2026
@obviyus

obviyus commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

@SebTardif, thanks for removing the 30-second wait. Production at 1f7ec3a is unchanged from 4a1fb57, and our runtime numbers above still hold: every case is bounded at about 30 s, empty streams take 5 s, and slow 12 MiB transfers deliver every byte.

One gap remains: the tests no longer guard the bug this PR fixes. With closeTimeout: 2_147_483_647 put back into node-stream-transport.ts, the whole file still passes (26/26). The protocol-error test settles in 11 ms either way, and the valid-close-with-FIN-withheld regression was removed in this commit.

Could you add one fake-timer test that would fail on that mutation? For example, a valid Gateway close frame with a peer that keeps the TCP connection half-open (allowHalfOpen: true, never ends): advance fake timers past 30 s, then assert the client socket reaches CLOSED and the command settles. The suggestion patch in my earlier comment has an event-driven version that fails on the mutation (CLOSING 2 vs CLOSED 3) and runs the file in about 4 s; feel free to take it. Once that's in, this looks ready from our side.

A valid gateway close that keeps TCP half-open must reach CLOSED
after the library close deadline. Fake timers cover that bound, so
the suite fails if closeTimeout is raised to a multi-day value.

Signed-off-by: Sebastien Tardif <[email protected]>
@SebTardif

Copy link
Copy Markdown
Contributor Author

@obviyus Added one fake-timer test for a valid gateway close that withholds TCP FIN. Head 0ebfd8f13f1.

The peer keeps the connection half-open. After it sees the client FIN, the test advances 30 seconds and expects the client socket to be CLOSED and the command to settle. The file is 27 tests and finishes in about 2 seconds.

With closeTimeout set to 2147483647, that test fails because the socket stays CLOSING (readyState 2, expected 3). I restored the production file after that check. The mutation is not in this commit.

@obviyus

obviyus commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

Landed in a6051a2. Thanks @SebTardif for sticking with this one! On this head the withheld-FIN regression fails if the close timeout is removed, an empty close settles in ~5 s instead of ~30 s, and a slow 12 MiB payload still arrives intact.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

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

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants