Skip to content

fix(discord): guard gateway cleanup races - #55373

Merged
steipete merged 2 commits into
mainfrom
codex/gateway-supervisor-fix
Mar 26, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/gateway-supervisor-fix

Conversation

@Takhoffman

Copy link
Copy Markdown
Contributor

Summary

  • keep Discord gateway late error handling active through cleanup so reconnect-exhausted close events do not crash the process
  • log post-dispose gateway errors instead of silently dropping them
  • disconnect the Carbon gateway during startup cleanup if lifecycle never started, with regression coverage for both paths

Testing

  • pnpm vitest run extensions/discord/src/monitor/gateway-supervisor.test.ts extensions/discord/src/monitor/provider.test.ts extensions/discord/src/monitor.gateway.test.ts extensions/discord/src/monitor/provider.lifecycle.test.ts

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord size: S maintainer Maintainer-authored PR labels Mar 26, 2026
@greptile-apps

greptile-apps Bot commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes two classes of gateway cleanup races in the Discord monitor: late reconnect-exhausted errors arriving after dispose() no longer crash the process (they are now logged via runtime.error), and the Carbon gateway is explicitly disconnected during startup cleanup when the lifecycle phase was never reached.

Key changes:

  • gateway-supervisor.ts: Removes emitter.removeListener("error", onGatewayError) from dispose() so the handler stays active post-dispose; replaces the silent early-return for disposed with a phase === "disposed" branch that logs the suppressed error via the new logLateDisposedEvent helper.
  • provider.ts: Hoists lifecycleGateway to outer scope so the finally block can call lifecycleGateway?.disconnect() when startup fails before lifecycle begins, guarded by a try/catch that logs any disconnect failure.
  • Tests: Two new regression tests — one verifying post-dispose errors are logged rather than thrown, and one verifying the gateway is disconnected when createDiscordMessageHandler throws before monitorLifecycle is reached.

Confidence Score: 5/5

Safe to merge — the changes are targeted, well-tested, and correct; the only open item is a minor cosmetic redundancy.

All three fixes (post-dispose error logging, listener retention, and startup-path gateway disconnect) are logically sound and directly tested by the new regression cases. The removed removeListener call is intentional and prevents the original crash. No behavioural regression paths were introduced.

No files require special attention; the single P2 comment on gateway-supervisor.ts is cosmetic and non-blocking.

Important Files Changed

Filename Overview
extensions/discord/src/monitor/gateway-supervisor.ts Keeps error listener active after dispose so late reconnect-exhausted errors are logged rather than crashing the process; minor redundant disposed boolean remains.
extensions/discord/src/monitor/provider.ts Hoists lifecycleGateway to outer scope and adds disconnect call in finally block for startup-failure cleanup path.
extensions/discord/src/monitor/gateway-supervisor.test.ts Adds regression test verifying post-dispose errors are logged rather than thrown.
extensions/discord/src/monitor/provider.test.ts Adds regression test verifying gateway disconnect is called when startup fails before lifecycle begins.

Comments Outside Diff (1)

  1. extensions/discord/src/monitor/gateway-supervisor.ts, line 89 (link)

    P2 Redundant disposed boolean after refactor

    After this PR, disposed is only used as an idempotency guard inside dispose() itself. The onGatewayError handler now uses phase === "disposed" for the same check, making disposed and phase carry duplicate state. The guard in dispose() could be written as if (phase === "disposed") { return; } and disposed could be removed entirely to reduce confusion for future maintainers.

    Not a bug — just redundant state that might raise a "why does this exist?" question later.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: extensions/discord/src/monitor/gateway-supervisor.ts
    Line: 89
    
    Comment:
    **Redundant `disposed` boolean after refactor**
    
    After this PR, `disposed` is only used as an idempotency guard inside `dispose()` itself. The `onGatewayError` handler now uses `phase === "disposed"` for the same check, making `disposed` and `phase` carry duplicate state. The guard in `dispose()` could be written as `if (phase === "disposed") { return; }` and `disposed` could be removed entirely to reduce confusion for future maintainers.
    
    Not a bug — just redundant state that might raise a "why does this exist?" question later.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/discord/src/monitor/gateway-supervisor.ts
Line: 89

Comment:
**Redundant `disposed` boolean after refactor**

After this PR, `disposed` is only used as an idempotency guard inside `dispose()` itself. The `onGatewayError` handler now uses `phase === "disposed"` for the same check, making `disposed` and `phase` carry duplicate state. The guard in `dispose()` could be written as `if (phase === "disposed") { return; }` and `disposed` could be removed entirely to reduce confusion for future maintainers.

Not a bug — just redundant state that might raise a "why does this exist?" question later.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(discord): guard gateway cleanup race..." | Re-trigger Greptile

@steipete
steipete force-pushed the codex/gateway-supervisor-fix branch from 9a20e48 to 9423941 Compare March 26, 2026 23:05
@steipete
steipete force-pushed the codex/gateway-supervisor-fix branch from 9423941 to 6815340 Compare March 26, 2026 23:07
@steipete
steipete merged commit 5f28769 into main Mar 26, 2026
1 check passed
@steipete
steipete deleted the codex/gateway-supervisor-fix branch March 26, 2026 23:07
@steipete

Copy link
Copy Markdown
Contributor

Landed via temp rebase onto main.

  • Gate: pnpm check && pnpm build && OPENCLAW_TEST_PROFILE=serial OPENCLAW_TEST_SERIAL_GATEWAY=1 pnpm test
  • Post-rebase check: pnpm check && pnpm test -- extensions/discord/src/monitor/provider.test.ts test/scripts/test-parallel.test.ts
  • Land commit: 6815340
  • Merge commit: 5f28769

Thanks @Takhoffman!

@aisle-research-bot

aisle-research-bot Bot commented Mar 26, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 2 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium EventEmitter 'error' listener not removed on dispose in Discord gateway supervisor (memory/log leak)
2 🔵 Low Terminal/log injection risk from unsanitized Discord gateway error message in late-dispose logging
Vulnerabilities

1. 🟡 EventEmitter 'error' listener not removed on dispose in Discord gateway supervisor (memory/log leak)

Property Value
Severity Medium
CWE CWE-401
Location extensions/discord/src/monitor/gateway-supervisor.ts:104-156

Description

The Discord gateway supervisor attaches an error listener to the gateway EventEmitter but no longer removes it in dispose(). If the gateway emitter outlives the supervisor (e.g., shared plugin instance, reconnect loops, repeated monitor start/stop), each supervisor instance leaves behind a retained listener.

Impact:

  • Memory/resource leak: the retained closure (onGatewayError) keeps params.runtime, pending, and supervisor state referenced, preventing GC.
  • Potential DoS via log spam: after disposal, every emitted gateway error still triggers runtime.error logging (suppressed late gateway ... after dispose), allowing unbounded logging if errors continue.
  • Listener accumulation over time can trigger Node's MaxListenersExceededWarning and degrade performance.

Vulnerable code:

emitter.on("error", onGatewayError);
...
dispose: () => {
  ...
  phase = "disposed";
  pending.length = 0;
  ​// missing: emitter.removeListener("error", onGatewayError)
}

Recommendation

Remove the listener during disposal, while still preventing uncaught error events during disconnect by ensuring the gateway is disconnected before disposing (or by temporarily attaching a no-op error handler only during disconnect).

Example fix:

​// when constructing
emitter.on("error", onGatewayError);

dispose: () => {
  if (disposed) return;
  disposed = true;
  lifecycleHandler = undefined;
  phase = "disposed";
  pending.length = 0;
  emitter.removeListener("error", onGatewayError);
}

If you need to suppress errors that occur during shutdown, consider:

  • calling gateway.disconnect() before dispose() (as you already do in startup cleanup paths), and/or
  • using detachLifecycle() for teardown suppression but still removing the listener once the gateway is known stopped.

2. 🔵 Terminal/log injection risk from unsanitized Discord gateway error message in late-dispose logging

Property Value
Severity Low
CWE CWE-117
Location extensions/discord/src/monitor/gateway-supervisor.ts:97-103

Description

createDiscordGatewaySupervisor() logs suppressed gateway errors after disposal using danger() with an interpolated event.message.

  • event.message is derived from String(err) in classifyDiscordGatewayEvent().
  • Gateway errors may include remote-controlled text (e.g., close reason / error strings), and String(err) can contain newlines or ANSI escape sequences.
  • The message is passed through danger() (chalk colorization) which does not escape control characters; if logs are viewed in a terminal or forwarded to an HTML-capable log viewer, this can enable log forging (newline injection) and terminal escape injection.

Vulnerable code:

params.runtime.error?.(
  danger(
    `discord: suppressed late gateway ${event.type} error after dispose: ${event.message}`,
  ),
);

Recommendation

Sanitize error strings before logging.

  • Strip/escape control characters (at least \r, \n, and ASCII control range) and remove ANSI escape sequences.
  • Prefer structured logging (separate fields) instead of interpolating raw strings.

Example:

import stripAnsi from "strip-ansi";

const sanitizeForLogs = (s: string) =>
  stripAnsi(s).replace(/[\u0000-\u001F\u007F]/g, " ");

params.runtime.error?.(
  danger(
    `discord: suppressed late gateway ${event.type} error after dispose: ${sanitizeForLogs(event.message)}`,
  ),
);

​// Or structured:
runtime.error?.({
  msg: "discord: suppressed late gateway error after dispose",
  type: event.type,
  message: sanitizeForLogs(event.message),
});

Analyzed PR: #55373 at commit 6815340

Last updated on: 2026-03-26T23:14:54Z

steipete added a commit to bugkill3r/openclaw that referenced this pull request Mar 27, 2026
pxnt pushed a commit to pxnt/openclaw that referenced this pull request Mar 27, 2026
godlin-gh pushed a commit to YouMindInc/openclaw that referenced this pull request Mar 27, 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: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants