Skip to content

fix(discord): stop queued reconnect exhaustion crash - #55991

Merged
vincentkoc merged 2 commits into
mainfrom
review/issue-batch-55472-55421-55380
Mar 27, 2026
Merged

vincentkoc merged 2 commits into
mainfrom
review/issue-batch-55472-55421-55380

Conversation

@vincentkoc

Copy link
Copy Markdown
Member

Summary

  • Problem: Discord stale-socket restarts could still crash the whole gateway when reconnect-exhausted was buffered before lifecycle teardown flipped lifecycleStopping.
  • Why it matters: a Discord WebSocket close with code 1005 could kill the full gateway process instead of letting the channel health monitor restart Discord cleanly.
  • What changed: drainPendingGatewayErrors() now treats queued reconnect-exhausted the same way as other expected shutdown events, and the lifecycle regression test now locks in graceful completion instead of a thrown crash.
  • What did NOT change (scope boundary): this does not change Carbon reconnect policy, reconnect backoff, or broader Discord supervision behavior outside the queued-before-teardown race.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause / Regression History (if applicable)

  • Root cause: provider.lifecycle.ts only suppressed reconnect-exhausted when lifecycleStopping was already true, but the supervisor can drain a buffered reconnect-exhausted event before teardown flips that flag.
  • Missing detection / guardrail: the regression test encoded the crash path as expected behavior for the queued-before-shutdown window.
  • Prior context (git blame, prior PR, issue, or refactor if known): earlier fixes in fix(discord): suppress expected reconnect-exhausted shutdown errors #55324 and fix(discord): guard gateway cleanup races #55373 covered adjacent shutdown/teardown races, but not the buffered pre-teardown drain path.
  • Why this regressed now: Discord gateway lifecycle handling was split/refined across recent cleanup work, leaving one buffered-event branch still treating the intentional shutdown signal as fatal.
  • If unknown, what was ruled out: N/A

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: extensions/discord/src/monitor/provider.lifecycle.test.ts
  • Scenario the test should lock in: a queued reconnect-exhausted event plus abort should resolve the lifecycle cleanly instead of throwing.
  • Why this is the smallest reliable guardrail: it hits the exact drainPendingGatewayErrors() branch that was still crashing.
  • Existing test that already covers this (if any): the same test existed but asserted the buggy rejection behavior.
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

Discord stale-socket restarts no longer crash the full gateway when the reconnect-exhausted event was buffered just before teardown.

Security Impact (required)

  • New permissions/capabilities? (Yes/No) No
  • Secrets/tokens handling changed? (Yes/No) No
  • New/changed network calls? (Yes/No) No
  • Command/tool execution surface changed? (Yes/No) No
  • Data access scope changed? (Yes/No) No
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: Node 25.5.0 + pnpm 10.32.1
  • Model/provider: N/A
  • Integration/channel (if any): Discord
  • Relevant config (redacted): N/A

Steps

  1. Start the Discord gateway lifecycle.
  2. Queue a reconnect-exhausted gateway event before teardown flips lifecycleStopping.
  3. Abort the lifecycle.

Expected

  • Lifecycle resolves cleanly and the health monitor owns recovery.

Actual

  • Before this patch, the buffered event threw Max reconnect attempts (0) reached after code 1005 and crashed the process.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

  • Verified scenarios: ran pnpm test -- extensions/discord/src/monitor/provider.lifecycle.test.ts extensions/discord/src/monitor/gateway-supervisor.test.ts after the patch.
  • Edge cases checked: kept the existing supervisor lane green; preserved current logging behavior for the queued event while removing the crash.
  • What you did not verify: a live Discord bot against production Discord WS.

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/No) Yes
  • Config/env changes? (Yes/No) No
  • Migration needed? (Yes/No) No
  • If yes, exact upgrade steps:

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: revert this commit.
  • Files/config to restore: extensions/discord/src/monitor/provider.lifecycle.ts
  • Known bad symptoms reviewers should watch for: genuine reconnect exhaustion being swallowed unexpectedly instead of surfacing through the lifecycle.

Risks and Mitigations

  • Risk: treating every queued reconnect-exhausted as a graceful stop could hide a real fatal queued reconnect exhaustion in this narrow pre-teardown path.
  • Mitigation: the change is limited to the buffered drain branch; active lifecycle and supervisor handling remain unchanged, and the health monitor already owns reconnect recovery for this path.

@vincentkoc
vincentkoc merged commit 02e3061 into main Mar 27, 2026
9 checks passed
@vincentkoc
vincentkoc deleted the review/issue-batch-55472-55421-55380 branch March 27, 2026 19:39
@greptile-apps

greptile-apps Bot commented Mar 27, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a narrow race condition in the Discord gateway lifecycle: a reconnect-exhausted event buffered before teardown sets lifecycleStopping = true would bypass the existing lifecycleStopping && event.type === \"reconnect-exhausted\" guard in drainPendingGatewayErrors, fall through to throw event.err, and crash the whole gateway process instead of allowing the health monitor to manage reconnect recovery.\n\nThe fix is minimal and well-scoped:\n- provider.lifecycle.ts: In the drainPendingGatewayErrors callback, drops the lifecycleStopping guard for reconnect-exhausted so any buffered instance of that event type is always treated as a graceful stop rather than a thrown crash. The live event handling path (through waitForDiscordGatewayStop → handleGatewayEvent) is unaffected.\n- provider.lifecycle.test.ts: Flips the regression test from rejects.toThrow(...) (asserting the buggy crash) to resolves.toBeUndefined() (asserting the clean resolution). The test also retains expect(runtimeError).toHaveBeenCalledWith(...) to confirm the event is still surfaced as an error-level log entry — it is not silently swallowed.\n- CHANGELOG.md: Entry added correctly noting the fix.\n\nNo P0 or P1 issues were identified.

Confidence Score: 5/5

This PR is safe to merge; it fixes a real crash path with a minimal, targeted change and correct regression coverage.

No P0 or P1 findings. The fix is correctly scoped to the buffered-drain branch only — live event handling is untouched, runtime.error logging is preserved (confirmed by the updated test assertion), and the test correctly flips from asserting the crash to asserting a clean resolution.

No files require special attention.

Important Files Changed

Filename Overview
extensions/discord/src/monitor/provider.lifecycle.ts Removes the lifecycleStopping guard from the drainPendingGatewayErrors callback so buffered reconnect-exhausted events are always treated as graceful stops rather than thrown crashes.
extensions/discord/src/monitor/provider.lifecycle.test.ts Flips the regression test from asserting a crash (rejects.toThrow) to asserting a clean resolution (resolves.toBeUndefined), and retains the runtimeError assertion to confirm the error is still logged.
CHANGELOG.md Adds a changelog entry for the buffered reconnect-exhausted crash fix.

Reviews (1): Last reviewed commit: "Merge branch 'main' into review/issue-ba..." | Re-trigger Greptile

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9ee491c80f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// Don't throw for expected shutdown events. `reconnect-exhausted` can be
// queued before teardown flips `lifecycleStopping`, so treat it as a
// graceful stop here and let the health monitor own reconnect behavior.
if (event.type === "disallowed-intents" || event.type === "reconnect-exhausted") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restrict queued reconnect-exhausted suppression to shutdown path

This change makes drainPendingGatewayErrors() treat every buffered reconnect-exhausted event as a graceful stop, even when the lifecycle is still starting and no shutdown/abort is in progress. In that startup-buffering scenario, runDiscordGatewayLifecycle() now returns instead of rejecting, so the channel restart loop in src/gateway/server-channels.ts does not run its .catch(...) path that records lastError, which hides a real reconnect exhaustion failure from runtime status and diagnostics while the account keeps restarting. Please gate this suppression to an explicit stop condition (e.g., abort/lifecycle teardown) rather than all buffered reconnect exhaustion events.

Useful? React with 👍 / 👎.

@rzblues

rzblues commented Mar 28, 2026

Copy link
Copy Markdown

Nice fix — the abortSignal?.aborted guard covers the timing window cleanly.

Worth flagging: #55000 addresses the same crash at the root cause level by calling gatewaySupervisor.detachLifecycle() before gateway.disconnect() in onAbort(). That way the supervisor enters teardown phase first and the error never reaches the lifecycle handler at all, so no lifecycle-layer guard is needed. Might be worth a look before closing the chapter on this one.

johnkhagler pushed a commit to johnkhagler/openclaw that referenced this pull request Mar 29, 2026
alexcode-cc pushed a commit to alexcode-cc/clawdbot that referenced this pull request Mar 30, 2026
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
Nachx639 pushed a commit to Nachx639/clawdbot that referenced this pull request Jun 17, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request Sep 29, 2026
lhfer pushed a commit to lhfer/openclaw that referenced this pull request Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: discord Channel integration: discord maintainer Maintainer-authored PR size: XS

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Discord WebSocket close (1005) crashes entire gateway — maxReconnectAttempts=0

2 participants