Skip to content

fix(gateway): prevent silent delivery loss on closing connections - #128144

Merged
steipete merged 2 commits into
mainfrom
codex/autoqa-gateway-ws-closing-20260823
Aug 23, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/autoqa-gateway-ws-closing-20260823

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where operators using the Gateway or Control UI would silently lose responses, live updates, and worker connection handshakes when a WebSocket entered its closing state before the close event reached the Gateway. The existing WebSocket dependency accepts those send calls without throwing even though it never delivers the frames, so callers previously reported successful delivery and broadcasts consumed misleading sequence numbers.

Why This Change Was Made

Admit direct responses and fanout only while the actual WebSocket is OPEN, stop worker handshake progression before recreating a credential-expiry timer after synchronous transport closure, and keep unavailable broadcasts from advancing healthy-client sequencing. Connection ownership remains with the Gateway: closing nodes with admitted lifecycle work stay discoverable throughout their existing drain so device-pairing and token revocation can still fence the exact live node before the owner retires it.

User Impact

Operators receive truthful delivery outcomes when a Gateway connection disappears, healthy peers continue receiving ordered live updates, and workers no longer appear connected or leave expiry timers behind after their hello cannot be delivered. Existing node result delivery and pairing/token revocation behavior remain intact while disconnect cleanup drains pending work.

Evidence

  • Regression-first proof on the unmodified owners failed for both CLOSING and CLOSED transports, including real loopback WebSocket peers: direct responses incorrectly returned sent, broadcast silently accumulated 79 discarded bytes, and closed worker hellos still advanced to ready.

  • A separate regression proved that prematurely deleting a closing node prevents pairing/token revocation from finding it while an admitted node result is still draining. The repaired owner retains that exact node through both pre-close and close-drain fanout and removes it only after the lifecycle work completes.

  • Final focused and sibling proof: 20 Vitest project files, 340 tests passed, including real healthy/closing peers, async WebSocket callbacks, direct responses, targeted and global fanout, sequence continuity, slow-consumer backpressure, worker timer cleanup, and the existing real pairing-revocation-during-node-drain integration:

    node scripts/run-vitest.mjs src/gateway/server/ws-connection.test.ts src/gateway/server-broadcast.serialization.test.ts src/gateway/server/ws-connection/message-handler.worker.test.ts src/gateway/server-broadcast.board.test.ts src/gateway/gateway-misc.test.ts src/gateway/device-pair-setup-completion.test.ts src/gateway/server-methods/portals.test.ts src/gateway/talk-transcription-relay.test.ts src/gateway/node-registry.ws-lifecycle.test.ts src/gateway/server.node-result-close.test.ts
    
  • Core production typecheck, assertion-safety ratchet, max-lines ratchet, focused oxlint, formatting, git diff --check, independent source review, and authenticated committed-branch Codex review all passed.

  • The broader core-test typecheck reaches only pre-existing shared-install dependency gaps unrelated to this change: missing @panzoom/panzoom and @types/pako. Focused Gateway tests and touched-source lint are green; no dependency install or reconciliation was performed in the linked worktree.

@clawsweeper

clawsweeper Bot commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Aug 23, 2026
@steipete
steipete marked this pull request as ready for review August 23, 2026 07:46
@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. labels Aug 23, 2026
@clawsweeper

clawsweeper Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 23, 2026, 4:37 AM ET / 08:37 UTC.

ClawSweeper review

What this changes

The PR prevents Gateway direct replies and broadcasts from treating closing WebSockets as deliverable, while preserving node drain and worker-handshake cleanup.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open for maintainer handling: current main still reports sends to closing transports as successful, while the PR adds the missing readiness admission at the direct-response and fanout owners. No blocking patch defect was found; merge should wait for a current-main refresh and exact-head checks.

Priority: P1
Reviewed head: ba8c8b3a6f60c33e8e492448eea16a81aa2ce71f
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch has a focused owner-boundary design and strong regression coverage, with final confidence awaiting refreshed exact-head CI.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless records focused real-loopback transport coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless records focused real-loopback transport coverage.
Evidence reviewed 10 items Current-main gap: Current main checks only the local closed flag and buffer before calling send, so a CLOSING transport can still produce a sent result; the PR head adds the OPEN-state admission before that path.
Fanout owner boundary: The branch filters non-open sockets before scope checks, frame construction, and sequence consumption, preserving healthy-peer sequence continuity.
Lifecycle sibling: Node registry already rejects non-open sockets before both normal and raw node event sends; the PR extends that existing invariant to generic direct responses and fanout.
Findings None None.
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs src/gateway/server-broadcast.serialization.test.ts src/gateway/server/ws-connection.test.ts

Result: PASS (completed)

node scripts/run-vitest.mjs src/gateway/server-broadcast.serialization.test.ts src/gateway/server/ws-connection.test.ts
runner@runnervm76f27:/tmp/clawsweeper-live-proof-128144-LL8Kvh/target$ node scripts/run-vitest.mjs src/gateway/server-broadcast.serialization.test.ts src/gatewa
y/server/ws-connection.test.ts
node scripts/run-vitest.mjs src/gateway/server-broadcast.serialization.test.ts src/gateway/server/ws-connection.test.ts
[test] starting test/vitest/vitest.gateway.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-128144-LL8Kvh/target

 ✓  gateway-server-isolated  ../../src/gateway/server-broadcast.serialization.test.ts (5 tests) 138ms
 ✓  gateway-server-isolated  ../../src/gateway/server/ws-connection.test.ts (25 tests) 153ms
 ✓  gateway-core  ../../src/gateway/server/ws-connection.test.ts (25 tests) 187ms
 ✓  gateway-server  ../../src/gateway/server-broadcast.serialization.test.ts (5 tests) 177ms

 Test Files  4 passed (4)
      Tests  60 passed (60)
   Start at  08:38:27
   Duration  23.52s (transform 19.79s, setup 1.87s, import 22.37s, tests 655ms, environment 0ms)

[test] passed 1 Vitest shard in 28.89s
runner@runnervm76f27:/tmp/clawsweeper-live-proof-128144-LL8Kvh/target$ node scripts/run-vitest.mjs src/gateway/server-broadcast.serialization.test.ts src/gatewa
y/server/ws-connection.test.ts






























Assertions:

  • PASS expect_output: Test Files

How this fits together

Gateway WebSocket connections carry direct RPC responses and ordered event fanout to Control UI clients and nodes. The connection handler owns direct-send availability, and the broadcaster owns per-client event sequencing and delivery eligibility.

flowchart LR
A[Gateway RPC or event] --> B[Direct response handler]
A --> C[Event broadcaster]
B --> D[WebSocket readiness check]
C --> D
D --> E[Open transport]
D --> F[Closing transport]
E --> G[Response or ordered event]
F --> H[Node drain and cleanup]
Loading

Decision needed

Question Recommendation
After refreshing against current main and obtaining green exact-head checks, should this maintainer-owned Gateway delivery repair be merged? Merge after refresh: Rebase or merge current main, confirm the focused loopback regressions and required checks on the resulting head, then merge.

Why: The protected maintainer label requires an explicit maintainer merge decision even though the review found no blocking correctness defect.

Before merge

  • Resolve merge risk (P1) - The branch is behind current main and checks are still in progress; refresh it and require green exact-head checks before landing.
  • Resolve merge risk (P1) - This checkout has no node_modules and DNS prevented an independent upstream ws source read or local test run; exact-head CI should provide the final package-backed validation.
  • Complete next step (P2) - No mechanical repair remains; refresh the branch and complete normal maintainer exact-head validation before deciding to merge.
Agent review details

Security

None.

PR surface

Source +15, Tests +293. Total +308 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 6 19 4 +15
Tests 8 299 6 +293
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 318 10 +308

Review metrics

Metric Value Why it matters
Production versus test delta production +17/-4 (net +13); tests +301/-6 (net +295) The production growth is limited to two owner-boundary readiness checks and a shared constant that removes Node registry’s duplicate literal; most of the change is regression coverage.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep the shared OPEN-state invariant at the direct-response and broadcast owners, preserve node-drain retention, then merge only after a current-main refresh and green exact-head validation.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep the shared OPEN-state invariant at the direct-response and broadcast owners, preserve node-drain retention, then merge only after a current-main refresh and green exact-head validation.

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

Yes—current-main source exposes the missing direct and broadcast readiness checks, and the branch contains focused closing/closed and real-loopback regressions; this review could not rerun them locally because dependencies are absent.

Is this the best way to solve the issue?

Yes—the shared OPEN-state admission extends the existing Node registry invariant at the actual generic send owners, while retaining the node-drain lifecycle contract rather than deleting a closing node early.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 2175a1502099.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless records focused real-loopback transport coverage.
  • remove proof: sufficient: Current real behavior proof status is not_applicable, not sufficient.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 automation: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The current behavior can silently lose Gateway responses and live updates for connected operators.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless records focused real-loopback transport coverage.

Evidence

What I checked:

Likely related people:

  • steipete: Recent history shows repeated ownership of broadcast sequencing, node-drain, worker recovery, and this PR’s current implementation. (role: long-running Gateway delivery and lifecycle contributor; confidence: high; commits: 1cf1af4aed3d, 86adb6e67ea5, 5bbbdcb223fe; files: src/gateway/server-broadcast.ts, src/gateway/server/ws-connection.ts, src/gateway/node-registry.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Refresh against current main and obtain green exact-head checks, including the focused loopback Gateway tests.

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 (1 earlier review cycle)
  • reviewed 2026-08-23T07:52:58.732Z sha 56c28f1 :: needs changes before merge. :: [P2] Initialize the authorization fixture as an open WebSocket

@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 proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 23, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

ClawSweeper rank-up follow-through: the required exact-head CI gate is now green for ba8c8b3, and the focused real-WebSocket and Gateway lifecycle suites pass.

Skipping the suggested moving-main refresh because this PR remains mergeable and nonconflicting, the affected Gateway owners are unchanged, and repository maintainer policy explicitly says not to rebase solely because main advanced. Refreshing would invalidate the already-reviewed, green exact head without reducing merge risk.

Verification: 596 focused Gateway and lifecycle tests passed; 67 plugin-list cold-import and routing tests passed; the independent ClawSweeper real-WebSocket proof passed all 60 tests. The earlier startup-memory failure was independently shown to be runner variance and passed on a failed-jobs-only rerun without code or threshold changes.

@steipete
steipete merged commit 7700a3b into main Aug 23, 2026
408 of 410 checks passed
@steipete
steipete deleted the codex/autoqa-gateway-ws-closing-20260823 branch August 23, 2026 09:55
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 24, 2026
…enclaw#128144)

* fix(gateway): reject sends on closing websocket transports

* fix(gateway): share websocket readiness without eager imports
steipete added a commit that referenced this pull request Aug 24, 2026
- Break import cycles: extract GatewayOperatorRoleActor leaf contract; merge
  session-group-mutation-targets into session-sharing-target-input.
- Split sessions-suggestions.test.ts (max-lines) into a visibility suite.
- Add users.setRole to the 2026.8 train registry test and regenerate the
  Kotlin protocol client.
- Startup UNAVAILABLE gating now precedes session authorization: session
  stores are not loaded during startup, so authorization reads would deny
  with a misleading non-retryable error.
- sessions.assignOwner keeps its documented visibility-authorized contract
  when no operator role caps the caller; view/suggest-capped roles still
  cannot reassign foreign session ownership.
- Test stubs updated for main's socket readyState guard (#128144) and the
  system-authority arg on channel-native resets.
steipete added a commit that referenced this pull request Aug 24, 2026
- Break import cycles: extract GatewayOperatorRoleActor leaf contract; merge
  session-group-mutation-targets into session-sharing-target-input.
- Split sessions-suggestions.test.ts (max-lines) into a visibility suite.
- Add users.setRole to the 2026.8 train registry test and regenerate the
  Kotlin protocol client.
- Startup UNAVAILABLE gating now precedes session authorization: session
  stores are not loaded during startup, so authorization reads would deny
  with a misleading non-retryable error.
- sessions.assignOwner keeps its documented visibility-authorized contract
  when no operator role caps the caller; view/suggest-capped roles still
  cannot reassign foreign session ownership.
- Test stubs updated for main's socket readyState guard (#128144) and the
  system-authority arg on channel-native resets.
steipete added a commit that referenced this pull request Aug 24, 2026
)

* feat(gateway): generic operator roles for non-maintainer access

Adds gateway.roles: named role bundles over a closed capability set —
sessions.others (none/view/suggest/write), an agents allowlist, and an
operator-scope ceiling. Roles are person-level (additive user_profiles.role
column, SQLite stays at v9); users.setRole (admin-only) assigns them. With
no gateway.roles config, behavior is unchanged for solo deployments.

Enforcement is deny-by-default from a host-minted actor identity
(system vs operator+profileId on server-only client.internal, never
accepted from the wire) and covers every entry point: WS RPCs, OpenAI-compat
and Responses HTTP, tools invocation, cron, questions, usage, task
suggestions, session catalog/sharing/reads. The agents allowlist gates both
session creation and run-start on existing sessions. Subagent completion
announce and descendant wake mint explicit system authority so role
boundaries never silently drop parent notifications.

The enforcement surface is expressed through a narrow policy vocabulary
(operatorSessionCap, hasOperatorBoundary, authorizeSessionSharing) rather
than per-handler policy internals.

* fix(gateway): heal PR CI after rebase onto main

- Break import cycles: extract GatewayOperatorRoleActor leaf contract; merge
  session-group-mutation-targets into session-sharing-target-input.
- Split sessions-suggestions.test.ts (max-lines) into a visibility suite.
- Add users.setRole to the 2026.8 train registry test and regenerate the
  Kotlin protocol client.
- Startup UNAVAILABLE gating now precedes session authorization: session
  stores are not loaded during startup, so authorization reads would deny
  with a misleading non-retryable error.
- sessions.assignOwner keeps its documented visibility-authorized contract
  when no operator role caps the caller; view/suggest-capped roles still
  cannot reassign foreign session ownership.
- Test stubs updated for main's socket readyState guard (#128144) and the
  system-authority arg on channel-native resets.

* test(gateway): chat.send pending-profile dispatch carries its required session target

chat.send requires a non-empty sessionKey at the protocol level; the mutation
pipeline now rejects targetless frames before profile-dependent dispatch, so
the pending-profile test must send a realistic frame.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 25, 2026
…claw#128548)

* feat(gateway): generic operator roles for non-maintainer access

Adds gateway.roles: named role bundles over a closed capability set —
sessions.others (none/view/suggest/write), an agents allowlist, and an
operator-scope ceiling. Roles are person-level (additive user_profiles.role
column, SQLite stays at v9); users.setRole (admin-only) assigns them. With
no gateway.roles config, behavior is unchanged for solo deployments.

Enforcement is deny-by-default from a host-minted actor identity
(system vs operator+profileId on server-only client.internal, never
accepted from the wire) and covers every entry point: WS RPCs, OpenAI-compat
and Responses HTTP, tools invocation, cron, questions, usage, task
suggestions, session catalog/sharing/reads. The agents allowlist gates both
session creation and run-start on existing sessions. Subagent completion
announce and descendant wake mint explicit system authority so role
boundaries never silently drop parent notifications.

The enforcement surface is expressed through a narrow policy vocabulary
(operatorSessionCap, hasOperatorBoundary, authorizeSessionSharing) rather
than per-handler policy internals.

* fix(gateway): heal PR CI after rebase onto main

- Break import cycles: extract GatewayOperatorRoleActor leaf contract; merge
  session-group-mutation-targets into session-sharing-target-input.
- Split sessions-suggestions.test.ts (max-lines) into a visibility suite.
- Add users.setRole to the 2026.8 train registry test and regenerate the
  Kotlin protocol client.
- Startup UNAVAILABLE gating now precedes session authorization: session
  stores are not loaded during startup, so authorization reads would deny
  with a misleading non-retryable error.
- sessions.assignOwner keeps its documented visibility-authorized contract
  when no operator role caps the caller; view/suggest-capped roles still
  cannot reassign foreign session ownership.
- Test stubs updated for main's socket readyState guard (openclaw#128144) and the
  system-authority arg on channel-native resets.

* test(gateway): chat.send pending-profile dispatch carries its required session target

chat.send requires a non-empty sessionKey at the protocol level; the mutation
pipeline now rejects targetless frames before profile-dependent dispatch, so
the pending-profile test must send a realistic frame.
jfy9606 pushed a commit to jfy9606/openclaw that referenced this pull request Aug 25, 2026
…eam features

- Dockerfile: adopt upstream bun 1.4.0, keep fork NPM_REGISTRY mirror config
- gateway ws-connection: merge controlUi auth params (fork) + workerNodeSetup (upstream)
- gateway ws-connection send: adopt upstream fix for silent delivery loss (openclaw#128144)
- connect-auth: use upstream device-pairing-tokens import + pendingSharedAuthFailure,
  keep fork controlUiAuthPolicy in return type alongside upstream startupPending
- server-startup-finish: adopt upstream pluginRuntimeClaim architecture,
  merge controlUi + workerNodeSetup params
- message-handler-types: merge all three auth param fields + both return fields
jfy9606 pushed a commit to jfy9606/openclaw that referenced this pull request Aug 25, 2026
… features

- Dockerfile: adopt upstream bun 1.4.0, keep fork NPM_REGISTRY mirror config
- gateway ws-connection: merge controlUi auth params (fork) + workerNodeSetup (upstream)
- gateway ws-connection send: adopt upstream fix for silent delivery loss (openclaw#128144)
- connect-auth: use upstream device-pairing-tokens import + pendingSharedAuthFailure,
  keep fork controlUiAuthPolicy in return type alongside upstream startupPending
- server-startup-finish: adopt upstream pluginRuntimeClaim architecture,
  merge controlUi + workerNodeSetup params
- message-handler-types: merge all three auth param fields + both return fields
- plugin-sdk-surface-report: keep zerotoken branch export counts (web-model, browser auth)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. 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.

1 participant