Skip to content

fix(discord): suppress expected reconnect-exhausted on stale-socket restart - #55699

Closed
rzblues wants to merge 1 commit into
openclaw:mainfrom
rzblues:fix/discord-reconnect-exhausted-stale-socket
Closed

rzblues wants to merge 1 commit into
openclaw:mainfrom
rzblues:fix/discord-reconnect-exhausted-stale-socket

Conversation

@rzblues

@rzblues rzblues commented Mar 27, 2026 •

Copy link
Copy Markdown

Summary

  • Problem: When the health-monitor triggers a stale-socket restart, it sets gateway.options.reconnect.maxAttempts = 0 then calls disconnect(). Carbon immediately emits "Max reconnect attempts (0) reached after code 1005", which lands in the supervisor's pending queue while the lifecycle is still awaiting an early step (e.g. execApprovalsHandler.start()).
  • Why it matters: The previous guard checked lifecycleStopping, which is only set in the finally block — after drainPendingGatewayErrors() has already run. The queued event fell through to throw event.err, crashing the entire gateway process (~54s downtime per occurrence, recurring every ~35 minutes).
  • What changed: Replaced the timing-sensitive lifecycleStopping check with isExpectedReconnectExhausted, which checks gateway.options.reconnect.maxAttempts === 0. This value is set synchronously before disconnect(), so it is reliably true at drain time regardless of async ordering. Added a regression test confirming that reconnect-exhausted with maxAttempts !== 0 (genuine Carbon retry exhaustion) still propagates as a fatal error.
  • What did NOT change: No change to reconnect logic, health-monitor behavior, or any other lifecycle path.

Change Type (select all)

  • Bug fix

Scope (select all touched areas)

  • Gateway / orchestration
  • Integrations

Linked Issue/PR

Root Cause / Regression History (if applicable)

  • Root cause: lifecycleStopping is set in the finally block of runDiscordGatewayLifecycle, but drainPendingGatewayErrors() is called inside the try block — before finally ever runs. On a stale-socket restart, the reconnect-exhausted event is queued synchronously (Carbon emits in the same tick as disconnect()), so it is always drained before lifecycleStopping becomes true.
  • Missing detection / guardrail: No test covered the queued-before-drain timing window.
  • Prior context: The lifecycleStopping guard was added to handle intentional shutdowns, but did not account for the async ordering between drainPendingGatewayErrors and the finally block.
  • Why this regressed now: The health-monitor stale-socket path sets maxAttempts=0 and disconnects — Carbon's error fires faster than the lifecycle flag advances.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
  • Target test: extensions/discord/src/monitor/provider.lifecycle.test.ts
  • Scenario: queue a reconnect-exhausted event before abort fires; verify lifecycle resolves cleanly (not rejects) when maxAttempts=0; verify it still rejects when maxAttempts is not 0.
  • Why this is the smallest reliable guardrail: directly exercises the drain-before-finally timing window without requiring real WebSocket infrastructure.

User-visible / Behavior Changes

Gateway no longer crashes on health-monitor stale-socket restarts. The restart proceeds silently (log at info level instead of an uncaught exception).

Diagram (if applicable)

Before:
[health-monitor abort] -> [maxAttempts=0, disconnect()] -> [Carbon emits error]
  -> [pending queue] -> [drainPendingGatewayErrors]
  -> lifecycleStopping=false -> throw event.err -> CRASH

After:
[health-monitor abort] -> [maxAttempts=0, disconnect()] -> [Carbon emits error]
  -> [pending queue] -> [drainPendingGatewayErrors]
  -> maxAttempts===0 -> log + return "stop" -> lifecycle resolves cleanly

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • OS: macOS (darwin arm64) / Windows 10 x64 (as reported in issue)
  • Runtime: Node 24.14.1
  • Integration/channel: Discord

Steps

  1. Gateway running with Discord channel enabled
  2. Health-monitor detects stale socket and triggers restart
  3. WebSocket closes with code 1005

Expected

Gateway handles reconnect-exhausted gracefully, logs at info level, continues running.

Actual (before fix)

Uncaught exception: Error: Max reconnect attempts (0) reached after code 1005 — gateway process crashes.

Evidence

  • Failing test before + passing after: repurposed existing test "does not suppress reconnect-exhausted already queued before shutdown" → now asserts resolves.toBeUndefined() and confirms the info log. Added "does not suppress reconnect-exhausted when maxAttempts is not 0" as the negative regression guard. All 22 tests pass.

Human Verification (required)

  • Verified scenarios: lifecycle test suite (22/22), full discord extension test suite — all pass.
  • Edge cases checked: maxAttempts undefined (default gateway options) still propagates as fatal; maxAttempts=0 with code 1005 resolves cleanly.
  • What I did not verify: live Discord environment with actual stale-socket trigger (no Discord bot token available).

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Risks and Mitigations

  • Risk: isExpectedReconnectExhausted might suppress a genuine exhaustion if something else sets maxAttempts=0.
    • Mitigation: maxAttempts=0 is only set in one place (provider.lifecycle.reconnect.ts:404, the onAbort handler). The negative regression test guards against over-suppression.

🤖 Generated with Claude Code

…estart

When the health-monitor triggers a stale-socket restart it sets
gateway.options.reconnect.maxAttempts = 0 before disconnecting.
Carbon immediately emits "Max reconnect attempts (0) reached after
code 1005", which arrives in the supervisor pending queue while the
lifecycle is still inside an early await (e.g. execApprovalsHandler).

The previous guard checked lifecycleStopping, which is only set in
the finally block — after drainPendingGatewayErrors has already run.
So the queued event fell through to throw event.err, crashing the
gateway process.

Fix: replace the timing-sensitive lifecycleStopping check with
isExpectedReconnectExhausted, which checks
gateway.options.reconnect.maxAttempts === 0. This value is set
before the disconnect, so it is true at drain time regardless of
async ordering.

Also add a regression test confirming that reconnect-exhausted with
maxAttempts !== 0 (genuine Carbon retry exhaustion) still propagates
as a fatal error.

Closes openclaw#55554

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord size: XS labels Mar 27, 2026
@greptile-apps

greptile-apps Bot commented Mar 27, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a gateway crash that occurred during health-monitor stale-socket restarts on Discord. The root cause was a timing race: drainPendingGatewayErrors() runs inside the try block, but the lifecycleStopping = true flag (previously used to suppress expected reconnect-exhausted errors) is only set in the finally block — so the queued error always fell through to throw event.err.\n\nThe fix replaces the timing-sensitive lifecycleStopping guard with isExpectedReconnectExhausted, which checks gateway?.options.reconnect?.maxAttempts === 0. This value is set synchronously in the onAbort handler (provider.lifecycle.reconnect.ts:404) before disconnect() is called, so it is reliably observable at drain time regardless of async ordering. A new negative regression test ensures that genuine Carbon retry exhaustion (non-zero maxAttempts) still propagates as a fatal error.\n\nKey changes:\n- provider.lifecycle.ts: Replaced two lifecycleStopping && event.type === \"reconnect-exhausted\" guards with isExpectedReconnectExhausted(event) (checks maxAttempts === 0).\n- provider.lifecycle.test.ts: Repurposed the existing queued-before-drain test to assert clean resolution when maxAttempts=0; added a new negative test confirming the error still throws when maxAttempts is non-zero.

Confidence Score: 5/5

Safe to merge — the fix is narrowly scoped, well-tested with both positive and negative regression cases, and the synchronous ordering invariant it relies on is sound.

No P0 or P1 issues found. The approach is correct: maxAttempts=0 is set synchronously in the abort handler before any async drain occurs, making the check reliably true at the right time. Both the positive-suppression and negative-propagation paths are exercised by tests.

No files require special attention.

Important Files Changed

Filename Overview
extensions/discord/src/monitor/provider.lifecycle.ts Replaced timing-sensitive lifecycleStopping guard with isExpectedReconnectExhausted (checks maxAttempts===0), eliminating the race condition between drainPendingGatewayErrors (try block) and lifecycleStopping=true (finally block).
extensions/discord/src/monitor/provider.lifecycle.test.ts Repurposed existing queued-before-drain test to assert clean resolution when maxAttempts=0; added negative regression test confirming fatal propagation when maxAttempts is non-zero.

Reviews (1): Last reviewed commit: "fix(discord): suppress expected reconnec..." | Re-trigger Greptile

@rzblues

rzblues commented Mar 28, 2026

Copy link
Copy Markdown
Author

Closing in favour of #55991, which has already been merged into main and covers the same race condition.

Quick comparison of the three approaches that tackled this bug:

PR Fix location Approach
#55699 (this PR) handleGatewayEvent Replace lifecycleStopping check with maxAttempts === 0 — state set before disconnect, so timing-safe
#55991 (merged) drainPendingGatewayErrors Add abortSignal?.aborted as extra guard — abort fires before disconnect, so also timing-safe
#55000 (open) onAbort() Call detachLifecycle() before disconnect() — supervisor enters teardown phase first and suppresses the error before it reaches the lifecycle layer

#55991 fixes the crash. #55000 fixes the root cause (wrong supervisor phase transition ordering) and is worth tracking.

@rzblues rzblues closed this Mar 28, 2026
@rzblues
rzblues deleted the fix/discord-reconnect-exhausted-stale-socket branch March 28, 2026 04:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: discord Channel integration: discord size: XS

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] SafeGatewayPlugin: Unhandled exception on WebSocket close code 1005 crashes gateway (triggered by health-monitor stale-socket restart)

1 participant