Skip to content

fix(gateway): flush slow-consumer 1008 close frame before terminating socket - #147707

Merged
vincentkoc merged 4 commits into
openclaw:mainfrom
SunnyShu0925:fix/slow-consumer-1008-grace-146419
Sep 14, 2026
Merged

vincentkoc merged 4 commits into
openclaw:mainfrom
SunnyShu0925:fix/slow-consumer-1008-grace-146419

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Closes #146419

What Problem This Solves

Slow-consumer shutdown queued a WebSocket 1008 close frame and then terminated the transport before the peer could reliably receive the policy reason. The direct-response and node-delivery paths had the same abrupt-close behavior, and the broadcast fallback could target a replacement socket through the mutable client reference.

Graceful-close ownership also needed to span lifecycle callers. An ordinary close could leave Gateway shutdown waiting on the WebSocket library's longer default, while a broadcast slow-consumer close followed by shutdown could create a second close frame and fallback for the same socket.

Solution

  • Add one transport helper that listens for close, queues the requested close frame, and terminates only after the existing one-second grace period if the socket remains stalled.
  • Capture and retire the exact broadcast and node sockets that exceeded the buffer limit.
  • Route direct slow-response, ordinary connection closure, and Gateway shutdown through the bounded graceful-close path.
  • Give each exact socket one graceful-close owner so later callers reuse its close reason, deadline, listener, fallback, and termination.
  • Cancel and release ownership when close completes; if close() throws, terminate immediately while preventing duplicate fallback ownership.
  • Preserve immediate termination for send failures, heartbeat failures, replacement invalidation, and dropIfSlow.

The one-second grace period is best effort: recoverable peers receive code 1008 with reason slow consumer; permanently stalled transports are still terminated after the grace expires.

Evidence

  • Pre-repair regression proof reproduced abnormal 1006 closure, synchronous direct/node termination, the replacement-socket race, and uncancelled fallbacks.
  • A broadcast slow-consumer close followed by GatewayConnectionWork.drain() reproduced a second close() call before the repair; the regression now proves one close frame, one fallback owner, one termination, and bounded drain.
  • Repair commit 024452cb28e4ae908eb9b689a97ee44114c4b0ee: 298 tests passed across the seven focused Gateway suites, including the read-only connection transport suite.
  • Final head 72e1a23cc3fddd79ed809aaa076a4411f60033b7 refreshes onto current main while preserving the exact reviewed ten-file patch ID.
  • Changed-file validation passed for format, core and test typechecks, lint, dead-export, boundary, ratchet, and diff checks.
  • Secretless real-WebSocket proof observed 1008 / slow consumer for broadcast, direct-response, and node-delivery peers; a deliberately stalled socket terminated after grace, ordinary-close shutdown remained bounded, and a replacement socket remained open.
  • Structured P2 autoreview reported no actionable findings.

@clawsweeper

clawsweeper Bot commented Sep 14, 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.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XS labels Sep 14, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 14, 2026, 4:23 AM ET / 08:23 UTC (Revision 9).

ClawSweeper review

What this changes

Give overloaded Gateway sockets one shared, bounded grace period to deliver their disconnect reason before forced termination, with regression coverage for shutdown and replacement sockets.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: current main and the latest release retain the premature termination sequence. The previous shutdown blocker is resolved, the refreshed files preserve the reviewed repair, and no actionable correctness defect remains.

Priority: P2
Reviewed head: 72e1a23cc3fddd79ed809aaa076a4411f60033b7

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused transport repair with relevant real-WebSocket observations and lifecycle regression coverage; the prior blocker is resolved.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured body records secretless real-WebSocket observations through all three changed delivery owners: intended 1008 reasons reached peers, stalled sockets terminated after grace, shutdown stayed bounded, and replacement sockets survived. The refreshed head preserves those reviewed files; these are reported observations rather than reviewer execution.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured body records secretless real-WebSocket observations through all three changed delivery owners: intended 1008 reasons reached peers, stalled sockets terminated after grace, shutdown stayed bounded, and replacement sockets survived. The refreshed head preserves those reviewed files; these are reported observations rather than reviewer execution.
Evidence reviewed 9 items Current main still needs the fix: Fetched main still calls close(1008, "slow consumer") followed immediately by terminate() in the broadcaster.
Latest release retains abrupt closure: GitHub source inspection of v2026.9.4 confirms the same close-then-terminate sequence. This is not an already-shipped repair.
Single close owner and resolved shutdown blocker: The shared helper deduplicates by physical socket, cancels its fallback on close, and terminates immediately when close throws. Ordinary connection closure now arms this same deadline before logical retirement prevents later shutdown calls.
Findings None None.
Security None None.

How this fits together

The Gateway sends responses and events to connected apps and nodes over WebSockets. Its transport lifecycle handles overloaded connections and coordinates their retirement during shutdown.

flowchart TD
  A[Responses and events] --> B[Gateway delivery]
  B --> C{Socket overloaded?}
  C -->|No| D[Send to peer]
  C -->|Yes| E[Retire delivery and request close]
  F[Connection close or shutdown] --> E
  E --> G[One deadline per socket]
  G --> H[Peer closes or forced termination]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +26, Tests +167. Total +193 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 4 63 37 +26
Tests 6 223 56 +167
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 286 93 +193

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #146419
Summary: This PR is the candidate implementation for the linked slow-consumer disconnect defect; the issue remains open until a fix lands.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Maintain one bounded close owner per physical socket while preserving immediate delivery retirement and eventual connection cleanup.

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

Yes: exceeding the outbound buffer limit reaches immediate close-then-terminate on current main, and the ws implementation confirms premature socket destruction; this review did not execute a runtime reproduction.

Is this the best way to solve the issue?

Yes: reusing the existing one-second grace through a shared socket owner fixes the delivery window and shutdown interaction without adding configuration or competing deadlines.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This repairs disconnect signaling for overloaded Gateway connections without evidence of a widespread urgent outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured body records secretless real-WebSocket observations through all three changed delivery owners: intended 1008 reasons reached peers, stalled sockets terminated after grace, shutdown stayed bounded, and replacement sockets survived. The refreshed head preserves those reviewed files; these are reported observations rather than reviewer execution.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured body records secretless real-WebSocket observations through all three changed delivery owners: intended 1008 reasons reached peers, stalled sockets terminated after grace, shutdown stayed bounded, and replacement sockets survived. The refreshed head preserves those reviewed files; these are reported observations rather than reviewer execution.

Evidence

What I checked:

  • Current main still needs the fix: Fetched main still calls close(1008, "slow consumer") followed immediately by terminate() in the broadcaster. (src/gateway/server-broadcast.ts:518, e27efbd2ed47)
  • Latest release retains abrupt closure: GitHub source inspection of v2026.9.4 confirms the same close-then-terminate sequence. This is not an already-shipped repair. (src/gateway/server-broadcast.ts:499, 3a9d69db306c)
  • Single close owner and resolved shutdown blocker: The shared helper deduplicates by physical socket, cancels its fallback on close, and terminates immediately when close throws. Ordinary connection closure now arms this same deadline before logical retirement prevents later shutdown calls. (src/gateway/server/connection.ts:281, 72e1a23cc3fd)
  • Regression coverage and review continuity: Inspected coverage exercises direct-response closure, fallback cancellation, close exceptions, broadcast followed by shutdown, ordinary preauth closure followed by drain, and replacement isolation. Comparing all ten touched files with the previous reviewed head produced no differences. Diff whitespace validation passed; tests were not executed in this read-only review. (src/gateway/server/ws-connection.test.ts:549, 72e1a23cc3fd)
  • Recorded real-WebSocket observations: The complete captured PR body, context sourceRevision c41cfe61bf58e8c705fdd20d102b6f3cf0fcf4db41da294bc68cc81e2a70c580, reports secretless real-WebSocket runs through broadcast, direct-response, and node-delivery owners: peers received 1008 / slow consumer, a stalled transport terminated after grace, shutdown remained bounded, and a replacement stayed open. These are reported runtime observations, not reviewer execution. (024452cb28e4)
  • Applicable transport dependency: The physical ingress adapter passes a ws socket into the changed connection owner, and package.json pins ws 8.21.3. This establishes the dependency contract relevant to close-frame delivery; no Codex runtime dependency is involved. (src/gateway/server/ws-connection.ts:66, 72e1a23cc3fd)

Likely related people:

  • Vincent Koc: Raw commit b652eeb adds src/gateway/server/connection.ts:271 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b652eeb36129; files: src/gateway/server/connection.ts)
  • 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 (8 earlier review cycles)
  • reviewed 2026-09-14T02:07:42.570Z sha 3d5d102175f58dcfb63ec7df7849bfa62d7ef3e1 :: needs real behavior proof before merge. :: [P3] Remove the unused afterEach import
  • reviewed 2026-09-14T02:51:15.171Z sha 651581a1b423fa2a8479979d99d2724104a7a5d4 :: needs changes before merge. :: [P3] Preserve the existing test-file size limit
  • reviewed 2026-09-14T03:04:53.076Z sha 08c4ac58592a8ee3bbeb85c474dd513d87ba08cf :: needs changes before merge. :: [P3] Preserve the existing test-file size limit
  • reviewed 2026-09-14T03:19:58.368Z sha e7986f0936c7e8fc511d3d8b52b4361c5e42c643 :: needs changes before merge. :: none
  • reviewed 2026-09-14T03:34:35.306Z sha 64ed0f3747e325223444cfd5f52edf75a39a0091 :: needs changes before merge. :: none
  • reviewed 2026-09-14T05:59:51.422Z sha 8463962d0253d3974cc88d017119a56298f8fcc3 :: blocked before merge. :: [P2] [P2] Preserve shutdown termination for already-closing connections
  • reviewed 2026-09-14T06:12:58.967Z sha 8463962d0253d3974cc88d017119a56298f8fcc3 :: blocked before merge. :: [P2] Preserve shutdown termination for already-closing connections
  • reviewed 2026-09-14T07:55:08.352Z sha 024452c :: needs maintainer review before merge. :: none

@SunnyShu0925
SunnyShu0925 force-pushed the fix/slow-consumer-1008-grace-146419 branch from 3d5d102 to 651581a Compare September 14, 2026 02:39
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 14, 2026
@SunnyShu0925
SunnyShu0925 force-pushed the fix/slow-consumer-1008-grace-146419 branch 2 times, most recently from 08c4ac5 to e7986f0 Compare September 14, 2026 03:12
… socket

Slow-consumer disconnect called socket.close(1008) immediately followed
by socket.terminate() in the same tick, so the 1008 close frame was
never flushed and peers observed 1006 (abnormal closure) instead.

Delay terminate() by WEBSOCKET_CLOSE_GRACE_MS (1s, matching the existing
server-close.ts pattern) so the close handshake completes before the TCP
connection is destroyed.

Closes openclaw#146419
@vincentkoc
vincentkoc force-pushed the fix/slow-consumer-1008-grace-146419 branch from 5f778c7 to 8463962 Compare September 14, 2026 05:47
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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 Sep 14, 2026
@vincentkoc vincentkoc self-assigned this Sep 14, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Sep 14, 2026
@vincentkoc
vincentkoc force-pushed the fix/slow-consumer-1008-grace-146419 branch from 8463962 to 024452c Compare September 14, 2026 07:37
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Sep 14, 2026
@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: 🚨 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 Sep 14, 2026
* commit '069710f909f0a7158777d0fc0bf1eab84e20c699': (45 commits)
  refactor(infra): consolidate update campaign reset ownership (openclaw#146555)
  refactor: simplify Gateway health response parsing (openclaw#147834)
  fix: avoid Gateway stalls when renaming sessions (openclaw#147869)
  refactor(plugins): reuse worker optional-method validation (openclaw#147925)
  refactor(infra): remove unreachable firewall diagnostic fallback (openclaw#147882)
  fix(ui): open attached automations from session hovercards (openclaw#147749)
  refactor(reply): share usage-bar numeric coercion (openclaw#147863)
  fix(doctor): report warnings for keyed agent configs (openclaw#123058)
  perf(plugins): reuse complete registry comparisons (openclaw#147893)
  fix(workboard): await lifecycle sweep completion in tests (openclaw#147950)
  fix: reduce stalls when browsing large session inventories (openclaw#147911)
  refactor(onboard): share custom model definition (openclaw#147915)
  feat(ios): collapse completed chat work above replies (openclaw#148002)
  fix(voice-call): retain state runtime for deferred streams (openclaw#147689)
  test(qa): compare Telegram entities semantically (openclaw#147752)
  fix(plugins): preserve runtime scope for deferred CLI actions (openclaw#147688)
  test(qa): keep Slack progress marker visible (openclaw#147748)
  test(qa): finish channel picker prompts (openclaw#147730)
  test(tui): handle auth restriction prompt (openclaw#147729)
  fix(qa): retain onboarding prompts across redraw bursts (openclaw#147687)
  ...
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@vincentkoc
vincentkoc merged commit 769de2e into openclaw:main Sep 14, 2026
382 of 385 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@vincentkoc Thanks for fixing and merging!
can you take a look at 141875 if you have a chance?

vincentkoc added a commit that referenced this pull request Sep 14, 2026
* commit 'a08cdc50bc049074ed7ad2db9e18e0ed3f5415ec': (81 commits)
  perf: reuse stateless plugin scope defaults (#148080)
  fix(gateway): flush slow-consumer 1008 close frame before terminating socket (#147707)
  fix: keep model catalogs loading during other session updates (#147878)
  fix: show queued external chat messages and their source (#147848)
  refactor(chat): share math label configuration (#148073)
  perf(ui): trim eager debug overlay icon payload (#147954)
  improve(logbook): sample batch frame metadata in SQLite (#147999)
  fix(ui): dismiss suggested task cards without waiting (#148021)
  fix(maturity): cover governance, interoperability, fleet, and state (#143528)
  chore(ui): restore core lint and startup budget checks (#148010)
  fix: chat startup loads unnecessary session setup text (#147973)
  perf: speed up fresh cloud worker activation (#147945)
  fix: recover PR preparation after committed merge conflicts (#148063)
  test(plugins): isolate ClawHub Docker fixture identity (#148074)
  fix(release): acknowledge ClawHub risk on moving installs (#148041)
  fix: restore context reads for installed official Discord and Slack plugins (#143341)
  fix: identify source capsule filesystem failures (#147778)
  fix(linux): keep Quick Chat widgets bound to their Gateway (#146049)
  refactor(infra): consolidate update campaign reset ownership (#146555)
  refactor: simplify Gateway health response parsing (#147834)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 15, 2026
… socket (openclaw#147707)

* fix(gateway): flush slow-consumer 1008 close frame before terminating socket

Slow-consumer disconnect called socket.close(1008) immediately followed
by socket.terminate() in the same tick, so the 1008 close frame was
never flushed and peers observed 1006 (abnormal closure) instead.

Delay terminate() by WEBSOCKET_CLOSE_GRACE_MS (1s, matching the existing
server-close.ts pattern) so the close handshake completes before the TCP
connection is destroyed.

Closes openclaw#146419

* trigger CI re-run for flaky server-plugins test

* fix(gateway): preserve slow-consumer close reasons
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime 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: M 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.

[Bug]: Slow-consumer 1008 close is destroyed by immediate terminate()

2 participants