Skip to content

fix(discord): prevent gateway crash on abort by fixing supervisor teardown ordering - #55000

Closed
openperf wants to merge 1 commit into
openclaw:mainfrom
openperf:fix/discord-gateway-crash-on-abort
Closed

openperf wants to merge 1 commit into
openclaw:mainfrom
openperf:fix/discord-gateway-crash-on-abort

Conversation

@openperf

@openperf openperf commented Mar 26, 2026 •

Copy link
Copy Markdown
Member

Summary

A transient Discord WebSocket disconnection (e.g. close code 1005) or an intentional health-monitor restart can trigger an uncaught Max reconnect attempts (0) exception that crashes the entire gateway process. This kills all channels (Feishu, WhatsApp, Telegram, etc.), not just Discord.

This PR fixes the root cause of these gateway crashes by correcting the supervisor phase transition ordering during an abort.

Fixes #54931
Fixes #54894

Root Cause

The gateway crash happens due to an error routing mismatch during teardown:

  1. onAbort() sets maxAttempts to 0 and calls gateway.disconnect().
  2. disconnect() synchronously triggers @buape/carbon's handleClose → handleReconnectionAttempt, which emits a Max reconnect attempts (0) error on the gateway emitter.
  3. The gateway-supervisor is still in the active phase at this point, so it routes the error to the lifecycle handler instead of suppressing it.
  4. The error surfaces as an uncaught exception, causing the entire gateway process to exit.

The supervisor already has the correct teardown suppression logic (it logs and swallows late errors during the teardown phase). The bug is simply that onAbort() never transitions the supervisor to the teardown phase before disconnecting.

Changes

1. Fix teardown ordering in onAbort()

Call params.gatewaySupervisor.detachLifecycle() before gateway.disconnect(). This ensures the supervisor enters the teardown phase and correctly suppresses the synchronous error emitted during disconnect.

2. Add lifecycleStopping safety net

In the catch block, when lifecycleStopping is already true, we no longer re-throw errors. This acts as a defense-in-depth guard for any edge case where an error might still escape during an intentional shutdown.

Test Results

  • The extension-fast (extension-fast-discord, discord) CI check passes.
  • Verified locally that triggering an abort correctly suppresses the disconnect error and allows the gateway to restart gracefully without crashing the main process.

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord size: XS labels Mar 26, 2026
@greptile-apps

greptile-apps Bot commented Mar 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a gateway crash caused by incorrect supervisor phase transition ordering during abort. When onAbort() was called (e.g., on a WebSocket close code 1005 or health-monitor restart), gateway.disconnect() was invoked while the supervisor was still in the active phase, causing the synchronous Max reconnect attempts (0) error emitted by @buape/carbon to be routed to the lifecycle handler and eventually surface as an uncaught exception — crashing the entire gateway process and killing all channels (Feishu, WhatsApp, Telegram, etc.).\n\nKey changes:\n- Primary fix: params.gatewaySupervisor.detachLifecycle() is now called in onAbort() before gateway.disconnect(), transitioning the supervisor to the teardown phase first so the synchronous error is logged-and-swallowed instead of propagated.\n- Defense-in-depth: The catch block gains a !lifecycleStopping guard so that any error escaping during an intentional shutdown is swallowed rather than re-thrown.\n- The detachLifecycle() call is idempotent (sets phase = "teardown" and clears the handler), so the existing call in the finally block is unaffected.\n- Early-abort edge case (signal already aborted at call time) is safe: onAbort() runs synchronously before attachLifecycle() is ever called, and all downstream guards check lifecycleStopping before proceeding.

Confidence Score: 5/5

Safe to merge — the fix is minimal, correct, and CI is passing.

The two-line root-cause fix (calling detachLifecycle() before disconnect()) directly addresses the described crash by transitioning the supervisor to teardown phase before the synchronous error is emitted. The secondary !lifecycleStopping guard in the catch block is a valid defence-in-depth. The detachLifecycle() implementation is idempotent so the double-call with the finally block is harmless. All edge cases (early abort, null gateway, concurrent teardown) are handled correctly by existing guards. No regressions identified.

No files require special attention.

Important Files Changed

Filename Overview
extensions/discord/src/monitor/provider.lifecycle.ts Adds detachLifecycle() call before gateway.disconnect() in onAbort() to fix supervisor teardown ordering, and adds !lifecycleStopping guard in catch block as a defence-in-depth against errors during intentional shutdown.

Reviews (1): Last reviewed commit: "fix(discord): prevent gateway crash on a..." | Re-trigger Greptile

@steipete

Copy link
Copy Markdown
Contributor

Root cause and fix direction look right.

One gap before merge: please add a targeted regression test for the actual abort crash path.

What I want covered:

  • abort triggers onAbort()
  • supervisor is detached before gateway.disconnect()
  • a synchronous gateway error during that disconnect path no longer rejects the lifecycle or crashes the process

Current abort coverage in extensions/discord/src/monitor/provider.lifecycle.test.ts exercises status behavior, but not the ordering bug this PR fixes.

Optional follow-up: the widened lifecycleStopping catch guard is probably fine as defense in depth, but if you keep it broad I’d either cover it in the same test or narrow it later.

@openperf

Copy link
Copy Markdown
Member Author

Root cause and fix direction look right.

One gap before merge: please add a targeted regression test for the actual abort crash path.

What I want covered:

  • abort triggers onAbort()
  • supervisor is detached before gateway.disconnect()
  • a synchronous gateway error during that disconnect path no longer rejects the lifecycle or crashes the process

Current abort coverage in extensions/discord/src/monitor/provider.lifecycle.test.ts exercises status behavior, but not the ordering bug this PR fixes.

Optional follow-up: the widened lifecycleStopping catch guard is probably fine as defense in depth, but if you keep it broad I’d either cover it in the same test or narrow it later.

Thanks for the clear guidance, @steipete — it made the test much easier to get right.

I've added a dedicated regression test ("detaches the supervisor before disconnecting on abort so synchronous reconnect exhaustion is suppressed") that covers all three points you asked for:

  1. abort triggers onAbort() — the test fires abortController.abort() and asserts that gateway.options.reconnect is set to { maxAttempts: 0 } and gateway.disconnect() is called exactly once.

  2. supervisor is detached before gateway.disconnect() — inside gateway.disconnect.mockImplementation, the very first thing it does is expect(gatewaySupervisor.detachLifecycle).toHaveBeenCalledTimes(1). If the ordering is wrong, the test fails right there.

  3. synchronous gateway error no longer crashes — the disconnect mock synchronously fires a reconnect-exhausted event (mimicking what @buape/carbon does in production), then the test asserts lifecyclePromise resolves cleanly and runtimeError is never called with the reconnect-exhausted message.

I also replaced the fragile await Promise.resolve() with vi.waitFor(() => expect(waitForDiscordGatewayStopMock).toHaveBeenCalledOnce()) — the original single microtick was enough locally but caused a race in CI under load. vi.waitFor polls until the lifecycle has actually reached the abort-listener registration point, which eliminates the timing dependency entirely.

Re the widened lifecycleStopping catch guard — it's indirectly covered here (the error never reaches runtimeError).

…rdown ordering

Transition the gateway supervisor to the teardown phase before calling
gateway.disconnect() during an intentional abort (health-monitor restart,
manual stop, etc.).  This ensures that the synchronous "Max reconnect
attempts (0)" error emitted by @buape/carbon is safely suppressed by the
supervisor instead of being routed to the lifecycle handler and surfacing
as an uncaught exception that crashes the entire gateway process.

As an additional safety net, the catch block now swallows errors when the
lifecycle is already stopping, preventing any edge-case re-throw during
intentional shutdown.

Closes openclaw#54931
Closes openclaw#54894
@openperf
openperf force-pushed the fix/discord-gateway-crash-on-abort branch from ee189bb to e1f87a6 Compare March 27, 2026 08:26
@openperf

Copy link
Copy Markdown
Member Author

Also addressed the CWE-772 flagged by aisle-research-bot — the abort listener previously used an anonymous arrow function and was never cleaned up when the lifecycle completed normally (non-abort path).

Fixed by extracting it into a named reference (earlyDetachOnAbort) and adding a removeEventListener call in the finally block, guarded by !params.abortSignal.aborted so it only runs when the listener wasn't already consumed by an actual abort.

@grp06 grp06 self-assigned this Mar 27, 2026
@Cruel

Cruel commented Mar 27, 2026 •

Copy link
Copy Markdown

Will be glad to have this fixed. Thanks. 👍
Discord is unusable like this, killing running agents constantly.

@openperf

Copy link
Copy Markdown
Member Author

Just wanted to add some context on the scope of this. I spent some time going through the issue tracker and it turns out this race condition has been hitting a lot of people since v2026.3.24 landed.

In short, the Discord gateway supervision refactor in v2026.3.24 changed the error propagation path, so this maxAttempts=0 race condition is no longer contained locally — it bubbles all the way up to the global uncaughtException handler and takes the entire gateway process down, knocking all channels offline at once.

I found 35+ duplicate issues from just the last 48 hours that all trace back to the same root cause:

Open (16):
#56057, #55873, #55618, #55554, #55367, #55350, #55346, #55340, #55301, #55296, #55274, #55260, #54931, #54894, #54851, #54752

Closed (19):
#55421, #55403, #55232, #55165, #55164, #55125, #55116, #55109, #55097, #55026, #54822, #54782, #54729, #54667, #53644, #36055, #32651, #20189, #11836

One small thought: it might be worth adding "max reconnect attempts" to TRANSIENT_NETWORK_MESSAGE_SNIPPETS in src/infra/unhandled-rejections.ts as a safety net, though this PR already stops the error at the source so it's more of a nice-to-have.

Would appreciate it if the maintainers could review this when they have a chance. Happy to make any changes needed — just let me know.

@rzblues

rzblues commented Mar 28, 2026

Copy link
Copy Markdown

This is the most complete fix for the stale-socket restart crash. The other attempts (#55699, #55991) patched the symptom at the lifecycle layer, but the underlying issue is the supervisor phase transition ordering in onAbort().

Root cause summary:

onAbort()
  gateway.options.reconnect = { maxAttempts: 0 }
  gateway.disconnect()           ← Carbon synchronously emits reconnect-exhausted here
                                  ← supervisor is still in active phase
                                  ← error is routed to lifecycleHandler → throws → crash

This PR's fix:

onAbort()
  gatewaySupervisor.detachLifecycle()  ← supervisor enters teardown phase first
  gateway.options.reconnect = { maxAttempts: 0 }
  gateway.disconnect()           ← Carbon emits reconnect-exhausted
                                  ← supervisor is in teardown phase → swallowed, no throw

#55991 (merged) addresses the crash symptom via abortSignal?.aborted in drainPendingGatewayErrors. This PR fixes it at the correct abstraction level. The supervisor already has the right teardown suppression logic — it just wasn't being entered at the right time.

@openperf

Copy link
Copy Markdown
Member Author

Now that #55991 is merged, just wanted to note that this PR remains complementary — #55991 suppresses reconnect-exhausted unconditionally in drainPendingGatewayErrors(), while this PR #55000 scopes the fix to the abort path only by transitioning the supervisor to "teardown" before disconnect(). This avoids masking reconnect failures outside the intentional shutdown window.

@Takhoffman

Copy link
Copy Markdown
Contributor

Thank you for the hard work on this. Your efforts are being noticed. I spoke with the upstream maintainer and this was fixed there. That means I will close this for the time being. If you are still experiencing this issue on the latest release then please drop a note in #clawtributors channel and I will reopen this PR.

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: S

Projects

None yet

6 participants