Skip to content

[Bug]: WhatsApp health-monitor re-starts channels stopped by terminal DisconnectReason (loggedOut, connectionReplaced) — 12-channel multi-tenant restart loop, 12.9GB heap, 24s RPC latency on 2026.5.3-1 #78419

Closed

Description

@rutherlesdev

Bug type

Behavior bug (incorrect output/state without crash)

Beta release blocker

No

Summary

On a multi-tenant gateway (12 WhatsApp accounts), all 12 channels enter a perpetual health-monitor: restarting (reason: stopped) loop after their underlying WhatsApp Web sessions are invalidated. The health monitor restarts channels regardless of why they stopped, so channels stopped by terminal DisconnectReasons (loggedOut, connectionReplaced, badSession) get re-started indefinitely with no chance of success — they need a fresh QR pairing, not a restart. Over ~20 hours this drove gateway RSS from <500 MB to 12.9 GB peak, CPU to 16 h of 20 h wall time, and RPC agents.files.get latency from <200 ms to 24-25 s, blocking unrelated tenants on the same gateway.

Steps to reproduce

  1. Run an OpenClaw gateway with multiple WhatsApp Web accounts (channels.whatsapp.accounts.*) on 2026.5.3-1.
  2. Wait for one or more accounts to receive a terminal disconnect from WhatsApp servers — easiest reproductions:
    • User logs out the linked device from the phone (Settings → Linked Devices → unlink) → DisconnectReason.loggedOut (401).
    • User links a new device that replaces the OpenClaw session → DisconnectReason.connectionReplaced (440).
    • Auth state corruption → DisconnectReason.badSession.
  3. Observe that the channel transitions to running=false after the close handler.
  4. Watch ~/.openclaw/logs/gateway.log (or the systemd-user journal) for ~30 min:
    [health-monitor] [whatsapp:cp-tenantN] health-monitor: restarting (reason: stopped)
    
    firing every health-check interval, per channel, with each restart immediately failing the same way.
  5. With 12 stuck channels, observe gateway RSS climb steadily (Baileys WebSocket + Noise handshake state per attempt), event-loop delay rise, and other RPCs degrade.

Expected behavior

  • Channels stopped by terminal DisconnectReasons are marked in a state distinct from "stopped" (e.g. reauth_required) and not restarted by the health-monitor.
  • A channel.reauth_required event (or equivalent) is emitted on the gateway event stream so control planes can surface a re-pairing prompt to the operator.
  • channels.status exposes a reauthRequired: boolean field so downstream consumers can distinguish "needs human action" from "transient outage".
  • Channels that exit for retryable reasons (connectionClosed, connectionLost, restartRequired, timedOut) continue to be restarted as today.
  • A bounded restart budget exists for any restart loop that escapes the DisconnectReason classification (defense-in-depth — see Additional information).

Actual behavior

  • Channel exits with connection: 'close' and a terminal DisconnectReason from Baileys.
  • Gateway sets the channel to running=false (status: stopped).
  • Health monitor wakes on its interval, sees running=false, and calls startChannel().
  • New connection immediately fails with the same terminal reason (or a connectionReplaced 440 because the previous Noise key is now stale on WhatsApp's side).
  • Loop continues indefinitely. Per-attempt cost (Baileys auth state + protobuf parsing + WebSocket setup) accumulates: in our case 12 channels × ~one attempt every health-check interval × no upper bound on consecutive failures.

Observed metrics (gateway PID, single instance, 20h window):

  • RSS: <500 MB → 12.9 GB peak (~26× growth).
  • CPU: 16 h of 20 h (~80%).
  • agents.files.get RPC p50/p99: ~150 ms / ~24-25 s (normal <200 ms).
  • Other tenants' control-plane RPCs queued behind the saturated event loop.

OpenClaw version

2026.5.3-1

Operating system

Ubuntu 24.04 (Linux 6.8.0-110-generic), VPS

Install method

npm global, gateway as systemd --user unit (openclaw-gateway.service)

Model

Not relevant to this bug — failure is upstream of any model invocation. (Mixed: Anthropic Claude Opus 4.7, Sonnet 4.6 for tenant agents.)

Provider / routing chain

Not relevant — failure is in the WhatsApp transport before any agent runs.

Additional provider/model setup details

Multi-tenant SaaS control plane: ~12 active WhatsApp accounts on a single gateway, each tied to a distinct tenant. This is the relevant difference from prior single-user reports — the blast radius spans tenants.

Logs, screenshots, and evidence

# 12 channels entering health-monitor restart on the same global sweep
[health-monitor] [whatsapp:cp-tenant1]   health-monitor: restarting (reason: stopped)
[health-monitor] [whatsapp:cp-tenant2]   health-monitor: restarting (reason: stopped)
[health-monitor] [whatsapp:cp-tenant3]   health-monitor: restarting (reason: stopped)
... (12 lines, all within the same second) ...

# RPC latency during saturation vs. recovery
[ws] ⇄ res ✓ agents.files.get  24913ms  conn=<redacted>  id=<redacted>
[ws] ⇄ res ✓ agents.files.get  24241ms  conn=<redacted>  id=<redacted>
# After the offending channel was removed from config:
[ws] ⇄ res ✓ agents.files.get     36ms  conn=<redacted>  id=<redacted>

# Gateway RSS over 20h (sampled via systemd-cgtop / RSS column of /proc/<pid>/status)
00:00 RSS=  462 MB
04:00 RSS=  3.1 GB
08:00 RSS=  6.4 GB
12:00 RSS=  9.8 GB
16:00 RSS= 11.7 GB
20:00 RSS= 12.9 GB  ← peak before manual intervention

Impact and severity

  • Affected: any operator running >1 WhatsApp account on a single gateway where one or more accounts is invalidated upstream (logout from phone, account ban, device replaced). Severity scales with channel count.
  • Severity: high — degrades the entire gateway, not just the affected channel. In multi-tenant deployments, one tenant's logout can cause cross-tenant outage.
  • Frequency: 100% reproducible whenever a WhatsApp Web session ends with a terminal DisconnectReason. Frequency in the wild depends on user behavior; in our population we see it weekly.
  • Consequence: gateway memory exhaustion, event-loop saturation, missed cross-channel replies, RPC latency that cascades into agent-side timeouts. Recovery currently requires manual gateway restart + per-channel re-pairing.

Additional information

Relation to prior closed issues

This is the same problem family as #48390, #49305, #51342, #54614, #70463, but the reason logged is now stopped (not stale-socket), and the symptom is observed on 2026.5.3-1 after those fixes shipped. Reading the closed-issue history, the post-fix gateway appears to have moved the health-monitor trigger from "stale event timestamp" to "channel running=false" — which closes the stale-socket false positive, but reintroduces the same loop because the health-monitor still cannot tell why a channel is stopped.

The architectural gap: the health-monitor and the close-reason classifier are decoupled. The close handler knows the channel was logged out; that information does not reach the health-monitor.

Proposed fix #1 — terminal DisconnectReason classification (root cause)

Capture connection.update from Baileys and, when connection === 'close', read lastDisconnect.error.output.statusCode (or lastDisconnect.error.data.reason) and map to DisconnectReason:

DisconnectReason Code Action
loggedOut 401 Mark channel reauth_required; do not restart; clear stored auth state
connectionReplaced 440 Mark channel reauth_required; do not restart
badSession — Mark channel reauth_required; clear auth-profiles.json; do not restart
connectionClosed / connectionLost / restartRequired / timedOut 408 / 428 / 515 / 408 Restart as today (retryable)
multideviceMismatch — Mark reauth_required; do not restart

Additions to public surface:

  • channels.status RPC: add optional reauthRequired: boolean (and ideally reauthReason: 'logged_out' | 'connection_replaced' | 'bad_session' | ...). Optional → does not break existing clients.
  • New gateway event: channel.reauth_required on the event stream, with { channelId, accountId, reason } payload, so control planes can proactively show a re-pair / new-QR prompt.
  • When a fresh QR scan completes successfully, clear reauthRequired and resume normal health-monitor behavior automatically.

Proposed fix #2 — bounded restart budget (defense-in-depth)

For close reasons that fall outside the mapping (new Baileys constants, unmapped 4xx, undocumented disconnects, or close-before-connection.update-fires races):

  • After N consecutive restart attempts (suggested default 5) within a rolling window of X minutes (suggested 10 min), stop restarting.
  • Mark the channel disconnected (max_retries_exceeded); surface the same channel.reauth_required event so operators see the failure.
  • Reset the counter when the channel stays connected for Y minutes (suggested 5 min) without a close.
  • Make N, X, Y configurable under gateway.channelHealthMonitor.{maxConsecutiveRestarts, restartWindowMinutes, healthyResetMinutes}.

Why both fixes, not just one:

Last known good / first known bad

We have not bisected — this is structural rather than a regression. Prior closed issues in the same family suggest the loop has existed across several versions with different surface symptoms (stale-socket → stopped).

Activity

  1. devjotaduo commented on May 6, 2026

    @devjotaduo

    erro

  2. clawsweeper commented on May 6, 2026

    @clawsweeper
    Contributor

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed June 28, 2026, 5:22 PM ET / 21:22 UTC.

    Summary
    Keep open: current main still treats non-manual stopped WhatsApp accounts as restartable, and the open linked pull request remains the active but not-yet-merged fix candidate.

    Reproducibility: yes. from source inspection: current main preserves WhatsApp logged-out/conflict health states, but generic health-monitor and ChannelManager paths still restart non-manual stopped accounts. I did not run a live WhatsApp unlink or replacement-session test.

    Root-cause cluster
    Relationship: canonical
    Canonical: #78419
    Summary: This issue is the canonical report for the WhatsApp terminal-disconnect restart loop; the open linked PR is the candidate fix, while related merged/auth and Telegram health-monitor work only partially overlap.

    Members:

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

    Next step
    No separate ClawSweeper fix job should be queued while #78511 is open as the explicit candidate fix.

    Review details

    Best possible solution:

    Land or replace the linked fix so terminal WhatsApp disconnects suppress both health-monitor and ChannelManager auto-restarts, while deferring new event/config surfaces to explicit maintainer API direction.

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

    Yes, from source inspection: current main preserves WhatsApp logged-out/conflict health states, but generic health-monitor and ChannelManager paths still restart non-manual stopped accounts. I did not run a live WhatsApp unlink or replacement-session test.

    Is this the best way to solve the issue?

    Unclear for the full requested surface: the linked terminal-disconnect guard is the right narrow direction for the bug, but the public event/status/config additions need maintainer product direction and the open PR still needs its review finding resolved.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • The linked pull request still has maintainer-visible compatibility risk and an open review finding, so the issue should not close before that path lands or is replaced.
    • This review confirmed the bug from source and dependency constants, but did not run a live WhatsApp unlink or replacement-session reproduction.
    • The optional new event/status/config surfaces requested in the issue still need maintainer product/API direction beyond the narrow restart-loop fix.

    Codex review notes: model internal, reasoning high; reviewed against 686a2876c7f4.

    Label changes

    Label changes:

    • add maturity:stable: The affected gateway runtime health/restart surface is part of the M4 Stable gateway-runtime taxonomy surface.

    Label justifications:

    • P1: The reported loop can saturate a shared gateway, grow heap sharply, and degrade multi-tenant channel/RPC workflows.
    • impact:crash-loop: The issue is about a health-monitor restart loop that can make the gateway effectively unavailable.
    • impact:message-loss: The report describes missed cross-channel replies and WhatsApp delivery failures while the loop consumes the gateway.
    • impact:session-state: Terminal WhatsApp session states are preserved locally but not carried into restart policy, causing state drift between re-pair-needed and restartable.
    • maturity:stable: The affected gateway runtime health/restart surface is part of the M4 Stable gateway-runtime taxonomy surface.
    Evidence reviewed

    What I checked:

    • Current health policy still collapses stopped accounts to not-running: At the supplied current-main SHA, any managed snapshot with running=false returns not-running without checking WhatsApp terminal states. (src/gateway/channel-health-policy.ts:63, 686a2876c7f4)
    • Current health monitor restarts unhealthy stopped accounts: The monitor resolves a restart reason, logs restarting, resets attempts, and calls startChannel for unhealthy non-manual accounts. (src/gateway/channel-health-monitor.ts:168, 686a2876c7f4)
    • Current ChannelManager task-exit recovery also restarts non-manual exits: The task-exit path schedules restart attempts and calls startChannelInternal without a terminal-disconnect guard. (src/gateway/server-channels.ts:722, 686a2876c7f4)
    • WhatsApp records terminal health state but not a restart-suppression signal: WhatsApp preserves logged-out/conflict/stopped healthState through markStopped, but current channel snapshots only forward healthState and have no terminalDisconnect field. (extensions/whatsapp/src/auto-reply/monitor-state.ts:15, 686a2876c7f4)
    • Current main lacks the linked PR's terminal-disconnect contract: No terminalDisconnect or terminal-disconnect symbol exists in the supplied current-main gateway/channel/WhatsApp paths. (686a2876c7f4)
    • Dependency contract supports the reported terminal/retryable status split: Baileys v7.0.0-rc13 defines loggedOut=401, connectionReplaced=440, badSession=500, multideviceMismatch=411, and retryable connectionClosed/timedOut/restartRequired constants.

    Likely related people:

    • steipete: History shows repeated work on channel health-monitor recovery and WhatsApp monitor-state refactors near the affected paths. (role: recent gateway and WhatsApp lifecycle contributor; confidence: high; commits: 1f850374f6e7, 66743b84fac2; files: src/gateway/channel-health-monitor.ts, src/gateway/server-channels.ts, extensions/whatsapp/src/auto-reply/monitor-state.ts)
    • mcaxtr: Authored the merged related WhatsApp terminal-disconnect preservation work that overlaps this issue but does not replace the generic restart guard. (role: recent WhatsApp terminal-auth contributor; confidence: high; commits: 52d9d16e1be9; files: extensions/whatsapp/src/auto-reply/monitor.ts, extensions/whatsapp/src/connection-controller.ts)
    • rstar327: Authored the health-monitor threshold and max-restart configurability work adjacent to the reported restart-loop behavior. (role: gateway health-monitor configuration contributor; confidence: medium; commits: ba6064cc2256; files: src/gateway/channel-health-monitor.ts, src/gateway/channel-health-policy.ts)
    • openperf: Authored the active linked pull request that directly targets this issue's gateway and WhatsApp terminal-disconnect paths. (role: open fix candidate author; confidence: high; commits: fcd72afb871c; files: src/gateway/channel-health-policy.ts, src/gateway/channel-health-monitor.ts, src/gateway/server-channels.ts)
    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.
  3. rutherlesdev commented on May 6, 2026

    @rutherlesdev
    Author

    Responses to the open API-surface questions from a control-plane perspective:

    Is existing healthState enough?

    Mostly yes — 'conflict' | 'logged-out' | 'disconnected' already carries everything a control plane needs to render a "please re-pair" UI. The only friction today is that healthState appears under lastDisconnect rather than as a top-level field on channels.status (happy to be corrected if I missed it).

    If a new field lands, prefer a discriminated reason over a boolean:

    healthState: 'logged-out' | 'conflict' | 'disconnected' | 'healthy' | ...,
    reauthReason?: 'session_logged_out' | 'session_replaced' | 'bad_session' | 'multidevice_mismatch'

    Lets us show the right operator copy ("phone unlinked" vs. "another device replaced this session" vs. "credentials corrupted — re-pair") without log-string matching.

    Event-stream signal: a channel.status_changed event with the new state would let control planes drop their channels.status polling. Not a blocker — happy to poll.

    Restart budget: flexible on defaults. Our incident would have been contained by max 5 consecutive failed restarts within 10 minutes, reset after 5 minutes connected. Configurability nice-to-have, not a release blocker.

    Scope split, if useful:

    • Ship now (primary fix): channel-health-monitor.ts skips accounts where running=false AND healthState is terminal, with the regression test outlined in the triage.
    • Defer to design: any new field/event surface + restart-budget config.

    Happy with either: keep as one issue, or split.

  4. barnacle-openclaw commented on May 31, 2026

    @barnacle-openclaw

    This issue has been automatically marked as stale due to inactivity.
    Please add updates or it will be closed.

  5. added
    P1High-priority user-facing bug, regression, or broken workflow.
    impact:crash-loopCrash, hang, restart loop, or process-level availability failure.
    impact:message-lossChannel message delivery can be lost, duplicated, or misrouted.
    impact:session-stateSession, memory, transcript, context, or agent state can drift or corrupt.
    issue-rating: 🦞 diamond lobsterVery strong issue quality with high-confidence source-level or clear reproduction.
    clawsweeper:source-reproClawSweeper found a high-confidence source-level issue reproduction.
    clawsweeper:linked-pr-openClawSweeper found an open linked pull request for this issue.
    clawsweeper:no-new-fix-prClawSweeper does not recommend queueing a new automated fix PR for this issue.
    on Jun 14, 2026
  6. added
    clawsweeper:needs-product-decisionClawSweeper marked this issue as needing a product or behavior decision.
    maturity:stableBroken existing behavior primarily owned by an M4/M5 scorecard surface.
    on Jun 26, 2026
  7. added a commit that references this issue on Jul 5, 2026
    e29448d
  8. added a commit that references this issue on Jul 6, 2026
    c39736a
  9. locked as resolved and limited conversation to collaborators on Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1High-priority user-facing bug, regression, or broken workflow.clawsweeper:linked-pr-openClawSweeper found an open linked pull request for this issue.clawsweeper:needs-product-decisionClawSweeper marked this issue as needing a product or behavior decision.clawsweeper:no-new-fix-prClawSweeper does not recommend queueing a new automated fix PR for this issue.clawsweeper:source-reproClawSweeper found a high-confidence source-level issue reproduction.impact:crash-loopCrash, hang, restart loop, or process-level availability failure.impact:message-lossChannel message delivery can be lost, duplicated, or misrouted.impact:session-stateSession, memory, transcript, context, or agent state can drift or corrupt.issue-rating: 🦞 diamond lobsterVery strong issue quality with high-confidence source-level or clear reproduction.maturity:stableBroken existing behavior primarily owned by an M4/M5 scorecard surface.staleMarked as stale due to inactivity

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions