Skip to content

fix: report gateway shutdown as a cancellation instead of chat/approval timeouts - #1026

Merged
steipete merged 3 commits into
openclaw:mainfrom
anagnorisis2peripeteia:fix/request-timeout-token
Jul 19, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
anagnorisis2peripeteia:fix/request-timeout-token

Conversation

@anagnorisis2peripeteia

Copy link
Copy Markdown
Contributor

Closes #1021
Related: #1010, #1018

Additional instructions

MUST: Keep Allow edits from maintainers enabled for this PR so maintainers
can help update the branch when needed.

What Problem This Solves

Fixes an issue where shutting down or disposing the gateway client while a chat message send or an exec-approval resolve was still awaiting its response logged a gateway timeout that never happened — "Timed out waiting for chat.send response from gateway" / "Timed out waiting for exec.approval.resolve response from gateway" — instead of a cancellation. #1018 fixed this misclassification for wizard requests; these are the two remaining sites named in #1021.

Why This Change Was Made

Both sites race the pending response against Task.Delay(timeoutMs, CancellationToken) on the client-lifetime token, and a cancelled delay completes Task.WhenAny exactly like an elapsed one. The fix classifies the cancelled-token case (CancellationToken.ThrowIfCancellationRequested()) immediately before each TimeoutException throw, the same disambiguation idiom as #1011/#1018. The exec-approval site's TryRemove-first and same-tick IsCompleted machinery is deliberately left untouched rather than restructured to #1018's WaitAsync shape — smallest reviewable diff, identical classification outcome; pending-map cleanup is unchanged on both exits.

User Impact

Disconnect or shutdown during an in-flight chat send or approval resolve now surfaces as a cancellation, so diagnostics no longer report a phantom gateway timeout and callers that branch on TimeoutException are not misled. Genuine timeouts behave exactly as before (the added check is a no-op on an uncancelled token). Callers already catch broadly per the ClearPendingRequests caller contract, so the approval-banner retry path is preserved.

Evidence

  • Deterministic red/green regression tests (GatewayRequestShutdownClassificationTests): each classification test starts a real request against a loopback WebSocket gateway that never responds, waits until the server observes the request frame on the wire (so all connectivity guards have passed and the request is parked on its response wait), then cancels the lifetime token. Base: both fail with TimeoutException in under 100 ms — impossible for a real timeout (budgets are 5 s / 15 s), proving the misclassification. Head: both surface OperationCanceledException immediately. Test identities use the repository's disposable OpenClaw.TestSupport.TempDirectory fixture.
  • A third test drives the real client.Dispose() shutdown path during the parked wait and proves it surfaces a cancellation, never a fabricated timeout. It is green on base and head by design: Dispose faults pending completions via ClearPendingRequests before cancelling the lifetime token, which is exactly why a real Dispose cannot deterministically reproduce the racy register-after-clear window — the reflection-modeled pair above pins that window, the Dispose test guards the real entry point.
  • signalkrebs dotnet-conc concurrency gate over the diff: verdict clean, with lane liveness proven (planted sync-over-async and deadlock fixtures caught).
  • Autoreview (local Qwen + OpenRouter cascade) findings dispositioned against source; escalation review by GPT-5.3-Codex-Spark at high effort on the exact patch: NO_DEFECTS_FOUND.

Change Type

  • Bug fix
  • Feature
  • Refactor
  • Docs or instructions
  • Tests or validation
  • Security hardening
  • Chore or infrastructure

Scope

  • Tray or WinUI UX
  • Windows node capability
  • Local MCP or winnode
  • Gateway, connection, or pairing
  • Setup or onboarding
  • Permissions, privacy, or security
  • Tests, CI, or docs

Validation

Windows box at dff33f7 (dotnet restore + builds of OpenClaw.Shared, OpenClaw.Shared.Tests, OpenClaw.Tray.Tests -r win-x64 all succeeded first):

  • dotnet test tests/OpenClaw.Shared.Tests --no-build -c Debug (with OPENCLAW_RUN_INTEGRATION=1) — passed 2,971, failed 0, skipped 0, total 2,971.
  • dotnet test tests/OpenClaw.Tray.Tests --no-build -c Debug -r win-x64 — passed 1,823, failed 0, skipped 0, total 1,823.
  • dotnet test tests/OpenClaw.Shared.Tests --filter "FullyQualifiedName~GatewayRequestShutdownClassificationTests" — passed 3, failed 0 (and repeated stability reruns).

Real Behavior Proof

Interleaving-class defect: the misclassification (a cancelled delay indistinguishable from an elapsed one inside Task.WhenAny) has no deterministically observable live surface, so the deterministic demonstration is the real-behavior proof — with the real shutdown entry point additionally exercised by the Dispose test above.

Before (base 9b5ce4b — shutdown misreported as gateway timeout, in milliseconds; the real-Dispose invariant passes as expected):

Failed OpenClaw.Shared.Tests.GatewayRequestShutdownClassificationTests.SendChatMessage_ShutdownDuringWait_SurfacesCancellationNotTimeout
  ---- System.TimeoutException : Timed out waiting for chat.send response from gateway
Failed OpenClaw.Shared.Tests.GatewayRequestShutdownClassificationTests.ResolveExecApproval_ShutdownDuringWait_SurfacesCancellationNotTimeout
  ---- System.TimeoutException : Timed out waiting for exec.approval.resolve response from gateway

After (head dff33f7 — shutdown classified as cancellation, same scenario, all three tests):

Passed!  - Failed: 0, Passed: 3, Skipped: 0, Total: 3 - OpenClaw.Shared.Tests.dll (net10.0)

A recorded proof manifest (base/head revisions, identical before/after commands, SHA-256-hashed console artifacts) backs this in the local gate ledger.

Review history

https://gist.github.com/anagnorisis2peripeteia/54cb9e32326a9e3bcc8239c3e63fb4a9

… timeouts

A chat.send or exec.approval.resolve response wait races its timeout delay
against the client-lifetime token. A cancelled delay completes Task.WhenAny
exactly like an elapsed one, so client shutdown mid-request surfaced as
'Timed out waiting for ... response from gateway' instead of a cancellation.
Classify the cancelled-token case before throwing TimeoutException at both
sites, mirroring the wizard-request fix in openclaw#1018.

Fixes the two sibling sites of openclaw#1021.
… timeouts

A chat.send or exec.approval.resolve response wait races its timeout delay
against the client-lifetime token. A cancelled delay completes Task.WhenAny
exactly like an elapsed one, so client shutdown mid-request surfaced as
'Timed out waiting for ... response from gateway' instead of a cancellation.
Classify the cancelled-token case before throwing TimeoutException at both
sites, mirroring the wizard-request fix in openclaw#1018.

Fixes the two sibling sites of openclaw#1021.
@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. 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. P2 Normal priority bug or improvement with limited blast radius. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed July 18, 2026, 10:45 PM ET / July 19, 2026, 02:45 UTC.

Summary
The branch centralizes gateway response-wait outcome classification for chat sends and exec-approval resolutions, with three loopback WebSocket regression tests for shutdown cancellation behavior.

Reproducibility: yes. the PR provides a concrete loopback WebSocket path that parks each real client request, cancels the lifetime token, and distinguishes an immediate cancellation from the five- or fifteen-second genuine timeout budget.

Review metrics: 2 noteworthy metrics.

  • Patch scope: 2 files affected; 250 added, 19 removed. Production behavior is confined to one gateway client while most of the change is focused regression coverage.
  • Terminal scenarios: 3 regression tests added. The tests separately cover both affected request types and the normal Dispose shutdown entry point.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #1021
Summary: This PR is the concrete candidate fix for the canonical open gateway request cancellation-classification report.

Members:

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

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Risk before merge

  • [P1] The code intentionally changes shutdown-time exception taxonomy from TimeoutException to OperationCanceledException; CI should complete and maintainers should retain the documented broad caller handling before merge.
  • [P1] The PR body reports project builds and test suites but does not expressly report the repository-prescribed ./build.ps1 command.

Maintainer options:

  1. Preserve the documented cancellation taxonomy (recommended)
    Merge after CI confirms the focused change retains genuine timeout behavior and callers continue to handle shutdown cancellation as required by the pending-request contract.
  2. Pause for caller-contract review
    Hold the PR only if maintainers identify a supported caller that intentionally relies on TimeoutException during client disposal.

Next step before merge

  • [P2] No mechanical repair is indicated; the remaining action is ordinary maintainer acceptance of the intended exception-taxonomy change after CI and required validation coverage complete.

Security
Cleared: The patch changes only request-wait exception classification and tests; it adds no permissions, dependency, secret, artifact, workflow, or code-execution surface.

Review details

Best possible solution:

Merge the narrow shared outcome-classification path once required CI completes and repository-required build coverage is confirmed, preserving TimeoutException only for genuine elapsed gateway deadlines.

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

Yes: the PR provides a concrete loopback WebSocket path that parks each real client request, cancels the lifetime token, and distinguishes an immediate cancellation from the five- or fifteen-second genuine timeout budget.

Is this the best way to solve the issue?

Yes: factoring the already-established gateway response-wait classification into one helper is narrower and less drift-prone than retaining two separate Task.WhenAny implementations, while the tests preserve genuine-timeout behavior as the key invariant.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 93174b274dff.

Label changes

Label changes:

  • add merge-risk: 🚨 compatibility: Merging intentionally changes the exception type visible to callers during gateway shutdown, so existing caller handling must remain compatible.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded diagnostic and cancellation-classification bug in gateway request handling, without evidence of data loss, security exposure, or core-runtime unavailability.
  • merge-risk: 🚨 compatibility: Merging intentionally changes the exception type visible to callers during gateway shutdown, so existing caller handling must remain compatible.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR includes red/green terminal evidence from a real client request path over a loopback WebSocket transport, including the actual Dispose entry point; it directly demonstrates cancellation replacing the phantom timeout.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR includes red/green terminal evidence from a real client request path over a loopback WebSocket transport, including the actual Dispose entry point; it directly demonstrates cancellation replacing the phantom timeout.
Evidence reviewed

What I checked:

Likely related people:

  • shanselman: Authored the merged wizard-request cancellation fix that introduced the directly relevant outcome-classification pattern now extended to the two sibling gateway request paths. (role: adjacent feature contributor; confidence: medium; commits: 9b5ce4bcc4f6; files: src/OpenClaw.Shared/OpenClawGatewayClient.cs)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

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.
  • 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.
Review history (1 earlier review cycle)
  • reviewed 2026-07-18T23:12:11.450Z sha dff33f7 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 19, 2026
@steipete
steipete merged commit bd6c4bf into openclaw:main Jul 19, 2026
12 checks passed
@anagnorisis2peripeteia
anagnorisis2peripeteia deleted the fix/request-timeout-token branch September 9, 2026 00:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. 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.

Concurrency: gateway request timeouts are bound to the client-lifetime token — dispose-during-request can surface as TimeoutException

2 participants