Skip to content

fix(gateway): drain admitted node results before disconnect - #119246

Merged
steipete merged 4 commits into
mainfrom
codex/qa-node-result-close-drain
Aug 4, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/qa-node-result-close-drain

Conversation

@steipete

@steipete steipete commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Closes #116363

What Problem This Solves

A node could send a valid terminal node.invoke.result and then close its WebSocket, but disconnect cleanup could synchronously settle the operator invocation as DISCONNECTED while the already-received result was still awaiting pairing validation. Retrying the apparently failed operation could repeat a remote side effect.

Root Cause

Authenticated WebSocket request dispatch intentionally runs asynchronously so one connection can process independent requests concurrently. The physical-close handler, however, immediately unregistered the node and consumed every pending invoke. That let cleanup overtake a terminal result frame whose dispatch had already been admitted from the same connection.

The deterministic current-main reproduction holds the result's persisted-pairing read after frame admission, terminates the real authenticated socket, and lets disconnect cleanup run. Current main returns:

DISCONNECTED: node disconnected (camera.list)

The result handler later sees the pairing/session as stale and cannot recover the already-consumed invocation.

What Changed

  • Each Gateway WebSocket connection owns a tracker for admitted node lifecycle requests.
  • Only node-role node.invoke.progress and node.invoke.result requests enter that tracker; unrelated RPCs retain their existing concurrency and no new request queue is introduced.
  • Physical close retires transport I/O first, then drains the already-admitted lifecycle work for at most one second before unregistering the node and rejecting unresolved invokes.
  • The retired transport remains discoverable to pairing/token revocation until drain and unregister complete, so authority changes still fence admitted work.
  • Idle node disconnects keep the prior synchronous cleanup path; the asynchronous boundary exists only when lifecycle work is actually active.
  • If the bounded drain expires, existing disconnect behavior wins and cleanup continues with a warning.
  • Replacement and revocation still invalidate/unregister the old connection before physical-close cleanup, so stale results cannot settle a new or revoked pairing.

No grace sleep, pairing-check bypass, config, protocol, storage, dependency, or user-data contract change.

Observed Behavior

The real-WebSocket regression now proves:

  1. an operator dispatches node.invoke;
  2. the node's terminal result reaches the Gateway and blocks inside the real persistent-pairing check;
  3. the node socket physically terminates;
  4. close cleanup enters the bounded lifecycle drain;
  5. pairing validation completes and the admitted result settles the operator successfully;
  6. the node is then projected disconnected.

Evidence

Exact head: 75b99b29d4aa83e2d628ad6ebd0878c8efd7082e.

  • Exact-head focused local proof:
    • node scripts/run-vitest.mjs src/gateway/server/ws-connection.test.ts src/gateway/server/ws-connection/node-lifecycle-dispatch.test.ts src/gateway/server.node-result-close.test.ts src/gateway/server/ws-connection/message-handler.post-connect-health.test.ts src/gateway/server/ws-connection/message-handler.suspension-admission.test.ts
    • 5 files / 65 tests passed.
    • The ordering-sensitive real-WebSocket and tracker files passed 10/10 repeated runs (40/40 tests), including close → pairing removal → result release.
  • Focused Blacksmith Testbox tbx_01kz6dajj97ncjadh7r6r2bdes, https://github.com/openclaw/openclaw/actions/runs/30911085825:
    • 8 Gateway/registry/message-dispatch files / 154 tests passed.
    • 3 real Gateway-node E2E files / 3 scenarios passed: control-plane invoke/presence, pending-work reconnect replay, and replacement-connection exec approval ownership.
  • Broad candidate-diff Blacksmith Testbox tbx_01kz6etnqnqsaam9a9e9pf8dvm, https://github.com/openclaw/openclaw/actions/runs/30913200657:
    • pnpm check:changed passed the core and coreTests lanes.
    • pnpm build passed, including the production Control UI build and performance guard.
  • The first hosted CI run, https://github.com/openclaw/openclaw/actions/runs/30914951865, found two existing close-handler tests that require idle disconnect cleanup to remain synchronous. The follow-up commit restored that fast path, and exact-head CI https://github.com/openclaw/openclaw/actions/runs/30916683149 passed every selected job, including the previously failing shard and openclaw/ci-gate.
  • Exact-head ClawSweeper found that retiring the client from the shared set before drain weakened the pairing/token revocation fence. The corrected head retires I/O immediately while retaining revocation visibility through drain and unregister; the adversarial real-WebSocket regression proves a pairing removal rejects the operator invocation. The branch is rebased onto current main; targeted oxlint is green without a max-lines suppression. Fresh exact-head CI and ClawSweeper re-review are pending.
  • Fresh exact-head AutoReview: clean, no accepted/actionable findings, overall correctness 0.98. The focused revocation-fence delta was independently clean at 0.98, and the line-budget simplification at 0.99.
  • git diff --check, targeted oxfmt, targeted oxlint, and the focused tests passed.
  • Public model-identifier audit: PASS; the diff, tests, proof, and public text contain no model identifiers.

Repair Doctrine Summary

  • Root cause: physical-close cleanup consumed pending invokes before already-admitted terminal dispatch completed.
  • Architectural owner: the WebSocket connection owns both admitted request lifetime and physical disconnect cleanup.
  • Canonical fix: connection-owned tracking plus a bounded drain of the exact admitted lifecycle set.
  • Removed/avoided paths: no retry, grace delay, pairing bypass, fallback, or second result path.
  • Production delta: +109/-15 (net +94), paying for one explicit connection-lifecycle ownership boundary, bounded cleanup contract, revocation visibility, and preservation of the existing idle fast path.
  • Test delta: +273/-0, including deterministic real-WebSocket success and revocation ordering proof, tracker timeout coverage, and idle-state assertions.
  • Sibling coverage: progress and terminal result methods share the tracker; ordinary RPC concurrency, idle disconnect cleanup, pairing/token invalidation, replacement connection ownership, pending work, invoke cancellation, and pairing-generation tests pass.
  • Risk: medium-low. The change delays node unregister by at most one second only when admitted result/progress work is still active; all security and generation checks remain authoritative.

AI-assisted: yes.

@steipete
steipete requested a review from a team as a code owner August 4, 2026 13:39
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Aug 4, 2026
@steipete

steipete commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 4, 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 repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@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: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Aug 4, 2026
@clawsweeper

clawsweeper Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 4, 2026, 12:09 PM ET / 16:09 UTC.

ClawSweeper review

What this changes

The PR drains already-admitted node progress and result handling briefly during Gateway WebSocket close so a valid terminal result can settle before unresolved invokes are rejected.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Needs maintainer review before merge - 4 items remain

Keep this protected Gateway repair open for maintainer review. The supplied exact-head evidence supports the repair and prior review found no remaining defect, but local source/history inspection was blocked before execution and the delayed-unregister authority boundary needs an owner decision.

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

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The supplied runtime proof is strong and the patch is coherent, but protected-label owner confirmation and independent inspection remain outstanding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body supplies exact-head real-WebSocket ordering evidence, repeated focused runs, Gateway E2E scenarios, and successful real-behavior-proof checks.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body supplies exact-head real-WebSocket ordering evidence, repeated focused runs, Gateway E2E scenarios, and successful real-behavior-proof checks.
Evidence reviewed 4 items Exact-head repair scope: The supplied PR diff adds a per-connection lifecycle tracker and routes node progress/result dispatch through it before close cleanup drains active work.
Ordering and revocation proof: The supplied PR body reports deterministic real-WebSocket coverage for result-before-close success and pairing removal during the drain, plus repeated focused runs and Gateway E2E scenarios.
Prior exact-head review: The provided previous ClawSweeper review covered this same head, recorded no findings, and identified only maintainer review of the lifecycle/security boundary.
Findings None None.
Security None None.

How this fits together

Gateway node connections deliver lifecycle messages that settle operator-initiated remote work. Connection teardown normally unregisters the node and rejects pending work; this change coordinates that teardown with lifecycle messages already admitted from the socket.

flowchart LR
  A[Paired node] --> B[Gateway WebSocket]
  B --> C[Admitted progress or result]
  C --> D[Pairing and generation validation]
  D --> E[Operator invocation outcome]
  B --> F[Physical socket close]
  F --> G[Bounded lifecycle drain]
  G --> H[Unregister node and reject unresolved work]
Loading

Decision needed

Question Recommendation
Should Gateway retain a closing node client as revocable authority state until the bounded admitted-lifecycle drain completes? Approve the bounded authority window: Accept the one-second maximum retained-client window because pairing removal, token revocation, and replacement continue to fence admitted work.

Why: This is an intentional teardown and authority-lifetime contract, not a mechanical correctness choice that can be resolved from the supplied diff alone.

Before merge

  • Resolve merge risk (P1) - The retained node client remains authority-visible for up to one second while teardown drains admitted work; maintainers should explicitly accept that pairing revocation and replacement fencing remain authoritative.
  • Resolve merge risk (P1) - Several exact-head checks are still in progress, and the review sandbox prevented independent current-source and history verification.
  • Complete next step (P2) - The protected maintainer label and intentional security-boundary lifetime change require Gateway-owner confirmation rather than an automated repair lane.
Agent review details

Security

None.

PR surface

Source +94, Tests +273. Total +367 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 4 109 15 +94
Tests 4 273 0 +273
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 382 15 +367

Review metrics

Metric Value Why it matters
Production vs test delta production +94 net, tests +273 The reported production growth establishes an explicit connection-lifecycle ownership boundary and is accompanied by substantial ordering coverage.

Merge-risk options

Maintainer options:

  1. Approve after boundary confirmation (recommended)
    Merge after a Gateway owner confirms the bounded drain preserves pairing revocation and replacement fencing and the remaining exact-head checks pass.
  2. Pause for lifecycle redesign
    Pause if maintainers do not want a closing transport retained in authority-visible state during teardown.

Technical review

Best possible solution:

Land the bounded, per-connection drain only after the Gateway owner confirms the retained-client revocation contract and the exact-head checks complete successfully.

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

Unclear. The supplied PR describes a deterministic real-WebSocket reproduction and focused regression proof, but this review could not independently run or inspect the current-head path because the read-only sandbox failed before command execution.

Is this the best way to solve the issue?

Unclear. The supplied design is narrowly scoped to already-admitted lifecycle work and prior exact-head review found no defect, but independent owner-boundary and history verification was unavailable.

AGENTS.md: unclear because the file could not be read completely.

Codex review notes: model internal, reasoning high; reviewed against 50a30b7373d7.

Labels

Label justifications:

  • P1: A valid terminal node result can otherwise be reported as disconnected, making an operator retry capable of repeating a remote side effect.
  • merge-risk: 🚨 security-boundary: The PR changes when a closing node remains visible to pairing revocation and replacement logic.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; 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 (live_output): The PR body supplies exact-head real-WebSocket ordering evidence, repeated focused runs, Gateway E2E scenarios, and successful real-behavior-proof checks.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies exact-head real-WebSocket ordering evidence, repeated focused runs, Gateway E2E scenarios, and successful real-behavior-proof checks.

Evidence

What I checked:

  • Exact-head repair scope: The supplied PR diff adds a per-connection lifecycle tracker and routes node progress/result dispatch through it before close cleanup drains active work. (src/gateway/server/ws-connection.ts:322, 75b99b29d4aa)
  • Ordering and revocation proof: The supplied PR body reports deterministic real-WebSocket coverage for result-before-close success and pairing removal during the drain, plus repeated focused runs and Gateway E2E scenarios. (src/gateway/server.node-result-close.test.ts:1, 75b99b29d4aa)
  • Prior exact-head review: The provided previous ClawSweeper review covered this same head, recorded no findings, and identified only maintainer review of the lifecycle/security boundary. (75b99b29d4aa)
  • Inspection limitation: Read-only repository commands failed before launch with bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted, so current-source, scoped-policy, and git-history evidence could not be independently verified.

Likely related people:

  • steipete: All four supplied commits for the current repair are attributed to this person; current-main ownership history could not be inspected. (role: Gateway lifecycle repair contributor; confidence: low; commits: cb7f339422b5, b65bb0c00b9a, 4b8a9dbbeb26; files: src/gateway/server/ws-connection.ts, src/gateway/server/ws-connection/node-lifecycle-dispatch.ts)

Rank-up moves

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

  • Obtain Gateway-owner confirmation of the bounded retained-client revocation contract.
  • Wait for the remaining exact-head checks, then refresh review only if the head changes.

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 (3 earlier review cycles)
  • reviewed 2026-08-04T14:36:39.828Z sha 9a2d969 :: needs changes before merge. :: [P1] Keep the node client revocable until the lifecycle drain ends
  • reviewed 2026-08-04T15:18:40.314Z sha 9057ca45e1555f4a4e75d7fe74594f34ab29121c :: needs maintainer review before merge. :: none
  • reviewed 2026-08-04T16:04:44.519Z sha 75b99b2 :: needs maintainer review before merge. :: none

@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 Aug 4, 2026
@steipete
steipete force-pushed the codex/qa-node-result-close-drain branch from 9057ca4 to 75b99b2 Compare August 4, 2026 15:39
@steipete

steipete commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 4, 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 repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 4, 2026
@steipete

steipete commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Land-ready proof for exact head 75b99b29d4aa83e2d628ad6ebd0878c8efd7082e.

The root cause is physical-close cleanup unregistering a node before an already-admitted terminal result finished asynchronous pairing validation. The connection now owns a bounded drain for only admitted node.invoke.progress and node.invoke.result work; ordinary RPC concurrency is unchanged, idle disconnect cleanup stays synchronous, and a one-second timeout preserves the established disconnect outcome.

ClawSweeper found one P1 in the initial candidate: removing the client from the shared set before the drain weakened pairing/token revocation. The corrected head retires transport I/O immediately but retains the client in the revocation index until drain and unregister complete. The real-WebSocket regression now proves both sides of the contract: result-before-close succeeds, while close followed by pairing removal rejects the invocation with the pairing-changed outcome. Replacement-connection ownership and generation fences remain covered.

Owner-boundary decision: accept the bounded retained-client window. It exists only while admitted lifecycle work is active, is capped at one second, cannot admit new socket I/O, and preserves pairing/token/replacement authority throughout. This is the narrowest safe connection-lifecycle owner boundary and introduces no protocol, config, storage, fallback, or retry surface.

Proof:

Final surface: 8 files, production +109/-15 (net +94), tests +273/-0. Risk is medium-low: teardown is delayed only for admitted lifecycle work, bounded to one second, and all authority fences remain active.

@steipete
steipete merged commit 1cf1af4 into main Aug 4, 2026
136 of 144 checks passed
@steipete
steipete deleted the codex/qa-node-result-close-drain branch August 4, 2026 16:25
@steipete

steipete commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

* fix(gateway): drain admitted node results on close

* fix(gateway): keep idle node cleanup synchronous

* fix(gateway): preserve node revocation during drain

* refactor(gateway): keep websocket handler within line budget
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 merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

Node invoke results can lose to immediate socket close

1 participant