Skip to content

Run disconnect cleanup on every gateway connection loss #2074

Closed

Description

@shanselman

Lane 1 of 5 for #2071. Filed by a Copilot agent.

Problem:

  • WebSocketClientBase.ListenForMessagesAsync calls OnDisconnected only on a Close frame, a premature close, or a keepalive OCE. It skips it in two cases:
    • a client-initiated abort (AbortCurrentWebSocket, for example from a bad chat stream), which is filtered by _clientAbortedGeneration
    • the oversized-message CloseAsync(MessageTooBig) + break path
  • In both cases it goes straight to ReconnectWithBackoffAsync, so OpenClawGatewayClient.OnDisconnected never runs. In-flight requests (chat send, etc.) wait for their full timeout instead of failing fast with GatewayConnectionLostException, and the handshake snapshot, MainSessionKey and advertised methods stay stale until the next connect.
  • OnError (OpenClawGatewayClient.cs ~415) only drains pending requests.
  • CheckHealthAsync (~636-664) calls ReconnectWithBackoffAsync() with no owner. A (null, 0) owner always passes IsReconnectOwnerLocked, so after the delay the loop can dispose a socket the manager has just connected.

Fix:

  • Report the connection loss exactly once per current connection on every listen-loop exit, using one invalidate path shared by OnError.
  • Pass the current socket and generation as the owner from CheckHealthAsync.

Coordinate with: #1574, which concerns the same reconnect loop.

Done when: a WebSocketClientBaseTests regression test shows OnDisconnected runs after AbortCurrentWebSocket and after an oversized message, and the required validation passes.

Activity

  1. self-assigned this
    on Nov 8, 2026
  2. added
    lever
    on Nov 8, 2026
  3. added
    clawsweeper:intake:bug
    clawsweeper:intake:needs-environment
    clawsweeper:intake:needs-repro
    P2
    clawsweeper:fix-shape-clear
    clawsweeper:queueable-fix
    clawsweeper:source-repro
    impact:session-state
    impact:ux-friction
    issue-rating: 🦞 diamond lobster
    no-stale
    and removed
    clawsweeper:intake:bug
    clawsweeper:intake:needs-environment
    clawsweeper:intake:needs-repro
    on Nov 8, 2026
  4. clawsweeper commented on Nov 8, 2026

    @clawsweeper

    Codex review: this still needs some work.

    Summary
    Keep this issue open: current main still skips disconnect cleanup on the reported paths and permits health retries to replace a newer connection; collaborator authorship also prevents automatic closure.

    Reproducibility: Current source establishes both skipped cleanup paths and the unowned health retry; existing loopback fixtures can exercise them, but no tests or live reproduction ran during this read-only review.

    Next step
    Fix generation-bound loss cleanup and health-retry ownership after establishing failing regressions for abort, oversized input, error invalidation and superseded retries.

    Review details

    Best possible solution:

    Use one generation-fenced loss cleanup path and capture health-retry ownership before any asynchronous work.

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

    Current source establishes both skipped cleanup paths and the unowned health retry; existing loopback fixtures can exercise them, but no tests or live reproduction ran during this read-only review.

    Is this the best way to solve the issue?

    The proposed cleanup and ownership repair fits the existing contracts, provided it preserves request-specific exceptions, stale-generation isolation and terminal retry policies.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • The shared disconnect hook also cancels node invocations and updates pairing state; cleanup must preserve terminal pairing and authentication retry policies.
    • Client aborts were deliberately kept quiet by prior work, so cleanup must avoid introducing misleading keepalive warnings or invalidating a replacement connection.

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

    Label changes

    Label changes:

    • add P2: Current source establishes bounded disconnect and retry defects without evidence of a widespread outage or blocked first-use flow.
    • add impact:session-state: Handshake identity, canonical session key and advertised capabilities remain stale after affected transport losses.
    • add impact:ux-friction: Pending chat sends can wait for their 30-second timeout, and stale health retries can interrupt a recovered connection.
    • add issue-rating: 🦞 diamond lobster: Current issue advisory state selects this label.
    • add clawsweeper:source-repro: Current issue advisory state selects this label.
    • add clawsweeper:queueable-fix: Current issue advisory state selects this label.
    • add clawsweeper:fix-shape-clear: Current issue advisory state selects this label.

    Label justifications:

    • P2: Current source establishes bounded disconnect and retry defects without evidence of a widespread outage or blocked first-use flow.
    • impact:session-state: Handshake identity, canonical session key and advertised capabilities remain stale after affected transport losses.
    • impact:ux-friction: Pending chat sends can wait for their 30-second timeout, and stale health retries can interrupt a recovered connection.
    Evidence reviewed

    Acceptance criteria:

    • dotnet test ./tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj --filter 'FullyQualifiedNameWebSocketClientBaseTests|FullyQualifiedNameWebSocketInboundLimitTests|FullyQualifiedNameOpenClawGatewayClientTests|FullyQualifiedNamePendingRequestRegistryTests'
    • ./build.ps1
    • dotnet test ./tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj --no-restore
    • dotnet test ./tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj --no-restore
    • dotnet test ./tests/OpenClaw.Connection.Tests/OpenClaw.Connection.Tests.csproj

    What I checked:

    • Verified current default branch: GitHub identifies main as the default branch, and its SHA matches the clean review checkout. (e70292487958)
    • Missing loss callbacks: Oversized fragmented messages close and break without OnDisconnected; client-aborted generations bypass the keepalive cancellation handler, and the common exit only returns buffers before reconnecting. (src/OpenClaw.Shared/WebSocketClientBase.cs:551, e70292487958)
    • Skipped gateway invalidation: OnDisconnected clears the canonical session key, signing identity, handshake snapshot and advertised features, then drains requests; OnError only drains requests. (src/OpenClaw.Shared/OpenClawGatewayClient.cs:381, e70292487958)
    • Health retry ownership hole: Both CheckHealthAsync retry calls omit ownership; the default null socket and zero generation always pass IsReconnectOwnerLocked, allowing the retry to dispose the socket current after backoff. (src/OpenClaw.Shared/OpenClawGatewayClient.cs:640, e70292487958)
    • Existing coverage preserves the gap: The abort test explicitly expects zero disconnect callbacks; inbound-limit tests exercise accumulation helpers rather than cleanup through the receive loop, while existing reconnect race tests cover retries that already have an owner. (tests/OpenClaw.Shared.Tests/WebSocketClientBaseTests.cs:293, e70292487958)
    • Preserve existing request exception contracts: Chat-send entries drain with OperationCanceledException; only wizard entries use the supplied GatewayConnectionLostException, so the report overstates the existing typed exception contract for chat. (src/OpenClaw.Shared/PendingRequestRegistry.cs:270, e70292487958)
    How this review workflow works
    • 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; those execution lanes are retired.
    • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

    Reviewed November 8, 2026, 1:29 AM ET / 06:29 UTC.

  5. locked as resolved and limited conversation to collaborators on Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P2clawsweeper:fix-shape-clearclawsweeper:queueable-fixclawsweeper:source-reproimpact:session-stateimpact:ux-frictionissue-rating: 🦞 diamond lobsterleverno-stale

Type

No type

Fields

Priority

None yet

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions