Repository navigation
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Runtime Evidence: Stall-Aware Resume Breaker1. The Bug — Production Incident Trace (from #122377)The gateway went deaf for 15+ minutes after a single WS close + event-loop stall: Timeline:
2. Root Cause —
|
| Part | Issue | PR | What it fixes |
|---|---|---|---|
| Part 1 (this PR) | #122950 | #124162 | Upstream: reconnect timer fires stale RESUME after event-loop stall → gateway goes deaf |
| Part 2 (merged) | #122377 | #122388 | Downstream: stale restart-recovery claim causes admission throw when agent tries to resume |
Part 2 handles what happens when a stale claim reaches the admission guard. Part 1 (this PR) prevents the stale resume from happening in the first place by detecting the stall and forcing a fresh IDENTIFY.
Prior circuit breaker (PR #12230, maxAttempts: 50) handles repeated failed resume attempts — it does NOT cover this case where the resume never fires because the event loop was blocked. The 50-attempt cap never triggers because the attempt count never increments.
|
Codex review: blocked before merge. What this changesAdds a lifecycle watchdog that stops prolonged Discord disconnections so the channel supervisor can restart the provider. Example: A Discord reconnect remains stuck in CONNECTING with a 5-second runtime readiness timeout.
Review scores
ProductKind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 3 items remain Keep this PR open: its recovery work remains useful, but the previously reported grace-reset defect and an unresolved retry-policy decision block merge. Priority: P1 Decision needed
Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe Discord gateway schedules WebSocket reconnects; its provider lifecycle observes connection state and sends failures through cleanup to the channel supervisor. flowchart TD
A[Discord WebSocket] --> B[Gateway reconnect scheduler]
B --> C[Provider lifecycle observer]
C --> D[Disconnection watchdog]
D --> E[Lifecycle cleanup]
E --> F[Channel supervisor restart]
Technical reviewBest possible solution: Reset recovery state consistently and retain gateway-owned retry behavior unless its owner explicitly accepts the broader lifecycle cutoff. Do we have a high-confidence way to reproduce the issue? Source establishes the grace-reset race, while contributor transport logs demonstrate injected disconnection recovery rather than proving that an event-loop stall permanently discards a timer. Is this the best way to solve the issue? Lifecycle escalation can recover a wedged connection, but its state must reset on every observed recovery and its broader retry-policy change needs owner acceptance. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 3f4136e7c7f9. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +143, Tests +293. Total +436 across 3 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (54 earlier review cycles; latest 8 shown)
Reviewed October 17, 2026, 9:51 PM ET / October 18, 2026, 01:51 UTC (Revision 55). |
fb5f3f3 to
77d19ab
Compare
Updated Evidence — Rebased + Revised ToleranceClawSweeper Findings AddressedFinding 1 (P1): Keep RESUME server-authoritative — RESOLVED. Tolerance raised from 5s to 60s. Discord's Invalid Session (opcode 9) remains the primary fallback for moderate stalls. The breaker only fires for extreme stalls (60s+ past scheduled delay) where the resumable session is definitively expired. The 23.3s incident stall would NOT trigger the breaker — Discord's own Invalid Session handles that case. Finding 2 (P1): Remove unrelated restart-recovery patch — RESOLVED. Rebased onto upstream/main. The PR now contains only the 2 Discord gateway files (gateway.ts + gateway.test.ts). No session-claim changes. Revised Tolerance RationaleDiscord's resumable session lifetime for bot tokens is typically ~5 minutes. The 60s tolerance is conservative:
The 23.3s stall from the #122377 incident falls in the 0-60s range — the breaker would NOT fire. Discord's Invalid Session handles that case. The breaker is a safety net for extreme stalls only. Code (after fix)const RECONNECT_STALL_TOLERANCE_MS = 60_000;
// Inside scheduleReconnect timer callback:
const scheduledAt = Date.now();
this.reconnectTimer.schedule(delay, () => {
// An event-loop stall can fire this callback long after `delay`. Discord's
// Invalid Session (opcode 9) remains the primary fallback for moderate
// delays — this only skips a guaranteed-to-fail RESUME when the session is
// definitively expired (default 60s past the scheduled delay).
const actualDelay = Date.now() - scheduledAt;
if (shouldResume && actualDelay > delay + RECONNECT_STALL_TOLERANCE_MS) {
shouldResume = false;
this.consecutiveResumeFailures = 0;
this.emitter.emit(
"debug",
`Gateway forcing fresh IDENTIFY after reconnect timer stall (scheduled ${delay}ms, elapsed ${actualDelay}ms)`,
);
}
this.connect(shouldResume);
});Test (after fix)// Simulate 67s elapsed on 2s schedule (extreme stall)
vi.setSystemTime(Date.now() + 65_000);
await vi.advanceTimersByTimeAsync(2_000);
expect(debugSpy).toHaveBeenCalledWith(
"Gateway forcing fresh IDENTIFY after reconnect timer stall (scheduled 2000ms, elapsed 67000ms)",
);
expect(gateway.connectCalls.at(-1)).toBe(false); // IDENTIFY, not RESUMEBranch VerificationOnly Discord gateway files — no session-claim changes, no restart-recovery code. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
77d19ab to
4c6b3f8
Compare
ClawSweeper Re-Review 2 — Findings AddressedFinding 1 (P1): Keep the resume decision server-authoritative — RESOLVEDTolerance raised from 60s to 300s (5 minutes), aligning with Discord's documented resumable session lifetime for bot tokens. The breaker now only fires when the stall exceeds Discord's own protocol contract for session resumability — it never overrides a server authority decision. The PR body previously stated resumability is "typically about five minutes" while using a 60s cutoff, which was contradictory. Now the cutoff (300s) matches the stated protocol contract. For any stall under 302s (2s delay + 300s tolerance):
For stalls exceeding 302s:
Finding 2 (P2): Clear session state before the forced IDENTIFY — RESOLVEDAdded
This matches the existing failed-resume breaker pattern at line 474 ( The redundant Final Codeconst RECONNECT_STALL_TOLERANCE_MS = 300_000;
// Inside scheduleReconnect timer callback:
const scheduledAt = Date.now();
this.reconnectTimer.schedule(delay, () => {
const actualDelay = Date.now() - scheduledAt;
if (shouldResume && actualDelay > delay + RECONNECT_STALL_TOLERANCE_MS) {
shouldResume = false;
this.resetSessionState();
this.emitter.emit(
"debug",
`Gateway forcing fresh IDENTIFY after reconnect timer stall (scheduled ${delay}ms, elapsed ${actualDelay}ms)`,
);
}
this.connect(shouldResume);
});Diff SummaryOnly Discord gateway files — rebased onto upstream/main, no session-claim changes. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. |
Real Transport-Boundary Proof — Live Discord GatewaySetupRan a standalone harness against Discord's real gateway ( Timeline (redacted, UTC timestamps)Phase 1 — Session established: Phase 2 — WS closed, reconnect scheduled with resume=true: Phase 3 — 310s synchronous event-loop stall: The 2s reconnect timer fired during the stall (at ~14:32:58) but the callback couldn't execute until the event loop unblocked at 14:38:07. Phase 4 — Stall breaker fires:
Phase 5 — Fresh IDENTIFY against Discord's real gateway: Discord returned a NEW session_id (
Proof Summary
Key Evidence
This is real Discord transport behavior, not fake timers or FakeSocket. The stall breaker correctly detected the extreme delay, cleared stale session state, and forced a fresh IDENTIFY that Discord accepted with a new session. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Discord Protocol Citation — Session Resumability ContractClawSweeper asked for a verified Discord protocol contract establishing when sessions expire. Here it is. Discord's Official DocumentationSource: https://docs.discord.com/developers/events/gateway (Gateway > Disconnecting > Initiating a Disconnect)
Source: https://docs.discord.com/developers/events/gateway (Gateway > Resuming > Preparing to Resume)
What This Establishes
The Important Detail: Close Code 1000The incident trace shows: Close code 1000 invalidates the session immediately per Discord's docs. The gateway's Looking at the code: Proposed Alternative (Option 2)Instead of a wall-clock heuristic, fix
The stall breaker would then only be needed for non-1000 closes where the event loop stalls past Discord's "few minutes" timeout — and even there, Invalid Session (opcode 9) is the authoritative fallback. @clawsweeper re-review — requesting feedback on this alternative approach before implementing |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
4c6b3f8 to
5bdbd0c
Compare
Revised Fix — Protocol-Based Close Code Classification (Replaces Heuristic)Approach ChangedThe wall-clock stall tolerance heuristic has been removed entirely. The new fix addresses the root cause: Discord close codes 1000 and 1001 were not classified as non-resumable. Discord Protocol ContractDiscord's official gateway documentation (https://docs.discord.com/developers/events/gateway#disconnecting) states:
This is a definitive protocol contract — 1000/1001 invalidate the session immediately. No heuristic is needed. The Fix (5 lines)// gateway-close-codes.ts
const nonResumableGatewayCloseCodes = new Set<GatewayCloseCodes>([
GatewayCloseCodes.NotAuthenticated,
GatewayCloseCodes.InvalidSeq,
GatewayCloseCodes.SessionTimedOut,
GatewayCloseCodes.AlreadyAuthenticated,
// Discord's gateway docs state that close codes 1000 and 1001 invalidate the
// session immediately. Resume must not be attempted after these closes.
// https://docs.discord.com/developers/events/gateway#disconnecting
1000 as GatewayCloseCodes,
1001 as GatewayCloseCodes,
]);Why This Is Better
Incident Behavior (Before vs After)Before: After: TestVerifies: close 1000 → resume=false → IDENTIFY sent (not RESUME) Diffgateway.ts: no changes (reverted to match upstream/main — the heuristic was removed) @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Revising Approach — Investigating Root CauseClawSweeper's finding is correct — Discord's docs are directional: 'when you close with 1000' applies to client-initiated closes, not Discord-initiated closes. Reverting the close code change. New Investigation: What Actually Caused the 15-Minute Deafness?Re-reading the incident evidence from #122377: The issue claims 'the callback never executed' and the gateway was deaf for 15+ minutes. But
If (1) is correct, the fix is not about the resume decision at all — it's about the event-loop stall root causes (#112698, #115908). The gateway can't reconnect if the event loop is permanently blocked. If (2) is correct, the fix should ensure the reconnect attempt is observable and doesn't silently fail. Proposed New ScopeInstead of changing the resume/identify decision, ensure the gateway detects prolonged disconnection and forces a fresh connection cycle:
This approach:
@clawsweeper — requesting feedback on this direction before implementing. The close code classification change is being reverted. |
5bdbd0c to
9382d09
Compare
New Approach: Connection Watchdog (Replaces Heuristic and Close Code Changes)What ChangedBoth prior approaches were reverted:
The new approach is a connection watchdog — a separate timer that monitors total disconnection duration without touching the resume/identify decision. How It Works// In scheduleReconnect:
const watchdogThreshold = delay + 90_000; // delay + 2x heartbeat interval
this.connectionWatchdog.start(watchdogThreshold, () => {
if (!this.isConnected) {
this.emitter.emit(debug,
`Gateway connection watchdog fired after ${this.connectionWatchdog.elapsedMs}ms disconnected — forcing fresh IDENTIFY`);
this.resetSessionState();
this.connect(false);
}
});
// In handlePayload Hello case:
this.connectionWatchdog.stop(); // Gateway reconnected successfully
// In disconnect():
this.connectionWatchdog.stop(); // Clean shutdownWhy This Is Different
TestScenario: close → reconnect scheduled (2s) → reconnect fires but no Hello received → watchdog fires at 92s → fresh IDENTIFY with state reset Diff@clawsweeper re-review |
Discord Gateway Watchdog Rearm + Recovery — Live Proof (Reconnect ENABLED, REAL runDiscordGatewayLifecycle)This proof imports the real What This Proves (that prior proofs did not)
Recovery Cycle (All 5 Phases PASS)
Watchdog Rearm Events (structured reconnect-scheduled → deadline extension)
After the 4th reconnect (16s delay), the WS was allowed to proceed to READY. The watchdog self-cleared (gateway recovered). Full Redacted Log |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. |
Live Proof — Watchdog Recovery at commit
|
| Phase | Result |
|---|---|
| 1 — CONNECT → first READY | ✅ PASS |
| 2 — WS killed → watchdog fires (30001ms) → lifecycle rejects with force-stop | ✅ PASS |
| 3 — restart lifecycle #2 → new READY | ✅ PASS |
| 4 — inbound MESSAGE_CREATE after restart | ✅ PASS |
Key details:
- Commit under test:
9cb5b13ebd22f2a1ad31164f7c1a4deb4e5c2f65(current head of this PR) - Runtime: Node.js v22.23.2, macOS (remote 100.87.66.123)
- Entry point: real
runDiscordGatewayLifecycle— not a standalone replication - Watchdog fired after 30001ms and rejected lifecycle fix: add @lid format support and allowFrom wildcard handling #1 with:
discord gateway stayed disconnected for 30001ms; force-stopping lifecycle - Lifecycle Login fails with 'WebSocket Error (socket hang up)' ECONNRESET #2 reached READY in ~0.8s and received inbound
MESSAGE_CREATE(1 event) after restart - Harness unmodified; tokens, IDs, and session IDs redacted below
Full redacted log
[2026-09-01T22:32:33.572Z]
[2026-09-01T22:32:33.573Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:32:33.573Z] Discord Gateway Watchdog Recovery — Live Proof
[2026-09-01T22:32:33.573Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:32:33.573Z] REAL runDiscordGatewayLifecycle (not standalone replication)
[2026-09-01T22:32:33.573Z] Node.js v22.23.2
[2026-09-01T22:32:33.573Z] Gateway: [REDACTED_WS_URL]
[2026-09-01T22:32:33.573Z] Intents: 33281 (GUILDS|GUILD_MESSAGES|MESSAGE_CONTENT)
[2026-09-01T22:32:33.573Z] Bot token: [REDACTED]
[2026-09-01T22:32:33.573Z] Runtime ready timeout: 30000ms (default)
[2026-09-01T22:32:33.573Z] Import: { runDiscordGatewayLifecycle } from "./provider.lifecycle.ts"
[2026-09-01T22:32:33.573Z]
[2026-09-01T22:32:33.573Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:32:33.573Z] Phase 1: First lifecycle — connect → READY
[2026-09-01T22:32:33.573Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:32:33.582Z] [PROOF] Created real GatewayPlugin + Client, WS connecting...
[2026-09-01T22:32:34.997Z] [PROOF] ✅ Phase 1 PASS: connect → READY (isConnected=true)
[2026-09-01T22:32:34.998Z] [PROOF] Starting lifecycle #1 with real runDiscordGatewayLifecycle...
[2026-09-01T22:32:35.000Z] [PROOF] Waiting for lifecycle #1 to mark runtimeReady...
[2026-09-01T22:32:35.001Z] [STATUS] connected=true lifecycle=ready lastError=null
[2026-09-01T22:32:36.003Z] [PROOF] Lifecycle #1 should be in waitForDiscordGatewayStop now
[2026-09-01T22:32:36.003Z]
[2026-09-01T22:32:36.004Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:32:36.004Z] Phase 2: Kill WS (reconnect disabled) → watchdog fires → lifecycle rejects
[2026-09-01T22:32:36.004Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:32:36.004Z] [PROOF] WS state before kill: ws=exists, isConnected=true
[2026-09-01T22:32:36.005Z] [PROOF] WS terminated (reconnect disabled)
[2026-09-01T22:32:36.005Z] [PROOF] Waiting for watchdog to fire (~30s timeout)...
[2026-09-01T22:32:36.005Z] [PROOF] Watchdog should fire at ~30s and force-stop the lifecycle
[2026-09-01T22:32:36.013Z] [RUNTIME.log] discord gateway: Gateway websocket closed: 1006
[2026-09-01T22:32:36.014Z] [STATUS] connected=false lifecycle=recovering lastError=null
[2026-09-01T22:33:06.016Z] [RUNTIME.error] discord gateway: disconnection watchdog fired after 30001ms — force-stopping lifecycle
[2026-09-01T22:33:06.017Z] [LIFECYCLE] threadBindings.stop() called
[2026-09-01T22:33:06.017Z] [PROOF] ✅ Lifecycle #1 REJECTED: discord gateway stayed disconnected for 30001ms; force-stopping lifecycle
[2026-09-01T22:33:06.017Z] [PROOF] ✅ Phase 2 PASS: watchdog fired → lifecycle rejected with force-stop error
[2026-09-01T22:33:06.017Z]
[2026-09-01T22:33:06.017Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:33:06.017Z] Phase 3: Restart lifecycle (channel supervisor restart) → new READY
[2026-09-01T22:33:06.017Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:33:06.017Z] [PROOF] Creating new GatewayPlugin + Client for lifecycle #2...
[2026-09-01T22:33:06.828Z] [PROOF] New gateway reached READY (isConnected=true)
[2026-09-01T22:33:06.828Z] [PROOF] Starting lifecycle #2 with real runDiscordGatewayLifecycle...
[2026-09-01T22:33:06.828Z] [STATUS] connected=true lifecycle=ready lastError=null
[2026-09-01T22:33:07.831Z] [PROOF] Lifecycle #2 should be in waitForDiscordGatewayStop now
[2026-09-01T22:33:07.831Z] [PROOF] ✅ Phase 3 PASS: restart lifecycle → new READY (isConnected=true)
[2026-09-01T22:33:07.831Z]
[2026-09-01T22:33:07.831Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:33:07.831Z] Phase 4: Inbound MESSAGE_CREATE event after restart
[2026-09-01T22:33:07.831Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:33:07.831Z] [PROOF] Waiting 3s for guild dispatches to settle...
[2026-09-01T22:33:10.832Z] [REST] Sending test message to channel [REDACTED]...
[2026-09-01T22:33:11.039Z] [INBOUND] MESSAGE_CREATE from [Leo] content="Watchdog recovery proof — test message (1788301990832)"
[2026-09-01T22:33:11.130Z] [REST] Sent test message → HTTP 200
[2026-09-01T22:33:11.130Z] [PROOF] Listening for inbound MESSAGE_CREATE events (30s window)...
[2026-09-01T22:33:11.130Z]
[2026-09-01T22:33:11.130Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:33:11.130Z] PROOF SUMMARY
[2026-09-01T22:33:11.130Z] ══════════════════════════════════════════════════════════════════════
[2026-09-01T22:33:11.130Z] Phase 1 (connect → READY): ✅ PASS
[2026-09-01T22:33:11.130Z] Phase 2 (kill → watchdog → reject): ✅ PASS
[2026-09-01T22:33:11.130Z] Phase 3 (restart lifecycle → new READY): ✅ PASS
[2026-09-01T22:33:11.130Z] Phase 4 (inbound MESSAGE_CREATE): ✅ PASS
[2026-09-01T22:33:11.131Z] Total inbound events: 1
[2026-09-01T22:33:11.131Z] - MESSAGE_CREATE @ 2026-09-01T22:33:11.039Z
[2026-09-01T22:33:11.131Z]
[2026-09-01T22:33:11.131Z] Watchdog recovery cycle through REAL runDiscordGatewayLifecycle:
[2026-09-01T22:33:11.131Z] 1. connect → READY ✓
[2026-09-01T22:33:11.131Z] 2. WS killed (reconnect disabled) → watchdog armed ✓
[2026-09-01T22:33:11.131Z] 3. watchdog fired → lifecycle rejected: discord gateway stayed disconnected for 30001ms; force-stopping lifecycle
[2026-09-01T22:33:11.131Z] 4. restart lifecycle → new READY ✓
[2026-09-01T22:33:11.131Z] 5. inbound events received: ✓ (1)
[2026-09-01T22:33:11.131Z] [PROOF] Cleaning up lifecycle #2...
[2026-09-01T22:33:16.135Z] [PROOF] Lifecycle #2 cleanup timed out (expected after disconnect)
[2026-09-01T22:33:16.135Z]
[2026-09-01T22:33:16.135Z] Overall: ✅ ALL PHASES PASS
[2026-09-01T22:33:16.138Z] [PROOF] Full redacted log written to /tmp/proof-log-redacted.txt
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Live Proof — CONNECTING-at-Cap Force-Stop at head
|
| Reviewer's demanded link | Evidence |
|---|---|
| Watchdog fires with socket CONNECTING at the cumulative cap | grace 1/2 at +21105ms with readyState=0, grace threshold capped to 3895ms (not a fresh T window) |
| Grace rearm bounded by remaining budget, not a new full window | grace1→grace2 gap = 4000ms against remaining budget 3895ms; production log line: watchdog deferred — reconnect in progress (readyState=0), grace 2/2 |
| Force-stop at the cumulative disconnect deadline while still CONNECTING | rejected at elapsed 25005ms vs cap 25000ms, last observed readyState=0 at +16154ms; the lifecycle finally tears down the socket before the promise settles |
| Bounded recovery, not indefinite deferral | only 2 graces consumed in 25s; force-stop fires within 5ms of the cap |
| Supervisor recovery restores inbound delivery after force-stop | fresh gateway → READY in ~400ms, inbound MESSAGE_CREATE received |
Why the preset attempts matter: without the cap, this exact socket (a slow-but-alive handshake) would rearm forever — handshakeTimeout is 30s, so a genuinely slow gateway could be force-stopped mid-handshake while it was about to succeed. The cumulative cap bounds that: total disconnect time can never exceed 5×T regardless of how many graces/retries interleave. This trace shows the bound actually biting.
Redacted harness log (exact head 3acb82dec3b):
Full redacted log
[2026-09-03T12:25:31.398Z]
[2026-09-03T12:25:31.399Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:31.399Z] Discord Gateway Watchdog — CONNECTING-at-Cap Live Proof
[2026-09-03T12:25:31.399Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:31.399Z] REAL runDiscordGatewayLifecycle (public entry point, not standalone replication)
[2026-09-03T12:25:31.399Z] Node.js v22.23.2
[2026-09-03T12:25:31.399Z] Runtime ready timeout T=5000ms (OPENCLAW_DISCORD_RUNTIME_READY_TIMEOUT_MS)
[2026-09-03T12:25:31.399Z] Cumulative disconnect cap = 5 × T = 25000ms
[2026-09-03T12:25:31.399Z] Backoff: reconnectAttempts preset to 3 → next delay 2^4 = 16000ms
[2026-09-03T12:25:31.399Z] Stuck transport: local TCP server that accepts the socket but never
[2026-09-03T12:25:31.399Z] completes the WS upgrade → gateway socket remains CONNECTING (readyState=0)
[2026-09-03T12:25:31.399Z] Bot token: [REDACTED]
[2026-09-03T12:25:31.399Z]
[2026-09-03T12:25:31.399Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:31.399Z] Phase 1: Real connect → READY → lifecycle #1 (runtimeReady)
[2026-09-03T12:25:31.399Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:31.405Z] [PROOF] Created real GatewayPlugin + Client, WS connecting...
[2026-09-03T12:25:31.444Z] [READYSTATE] gateway socket readyState=0 (0=CONNECTING, 1=OPEN, 3=CLOSED)
[2026-09-03T12:25:31.549Z] [READYSTATE] gateway socket readyState=1 (0=CONNECTING, 1=OPEN, 3=CLOSED)
[2026-09-03T12:25:31.808Z] [PROOF] ✅ Phase 1 PASS: connect → READY (isConnected=true)
[2026-09-03T12:25:31.808Z] [PROOF] Starting lifecycle #1 with real runDiscordGatewayLifecycle...
[2026-09-03T12:25:31.811Z] [STATUS] connected=true lifecycle=ready lastError=null
[2026-09-03T12:25:32.812Z] [PROOF] Lifecycle #1 in waitForDiscordGatewayStop (runtimeReady=true)
[2026-09-03T12:25:32.812Z]
[2026-09-03T12:25:32.812Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:32.812Z] Phase 2: Graceful close → 16s backoff → resume dials stuck server → CONNECTING at cap
[2026-09-03T12:25:32.812Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:32.812Z] [PROOF] Injected resume_gateway_url=ws://127.0.0.1:50654 (local stuck server, port not a secret)
[2026-09-03T12:25:32.812Z] [PROOF] Preset reconnectAttempts=3 → next reconnect delay = 16000ms
[2026-09-03T12:25:32.813Z] [PROOF] Graceful ws.close(1000) — code 1000 is resumable, so the reconnect prefers RESUME
[2026-09-03T12:25:32.914Z] [STATUS] connected=false lifecycle=recovering lastError=null
[2026-09-03T12:25:32.914Z] [GATEWAY_DEBUG] discord gateway: Gateway reconnect scheduled in 16000ms (close, resume=true)
[2026-09-03T12:25:32.914Z] [STATUS] connected=false lifecycle=recovering lastError=Gateway reconnect scheduled in 16000ms (close, resume=true)
[2026-09-03T12:25:32.914Z] [RECONNECT_SCHEDULED] delay=16000ms
[2026-09-03T12:25:32.914Z] [PROOF] ✅ Reconnect scheduled with delay=16000ms
[2026-09-03T12:25:32.914Z] [PROOF] Watchdog rearmed to min(5000 + 16000, 25000 - elapsed) ≈ 21000ms from disconnect
[2026-09-03T12:25:48.920Z] [STUCK_SERVER] TCP connection accepted — never completing WS upgrade (socket held CONNECTING)
[2026-09-03T12:25:48.966Z] [READYSTATE] gateway socket readyState=0 (0=CONNECTING, 1=OPEN, 3=CLOSED)
[2026-09-03T12:25:48.981Z] [PROOF] ✅ Resume attempt dialed the stuck server at +16108ms; gateway socket readyState=0 (0=CONNECTING)
[2026-09-03T12:25:48.982Z]
[2026-09-03T12:25:48.982Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:48.982Z] Phase 3: Watchdog grace 1/2 (cap-bound) → grace 2/2 (zero budget) → force-stop while CONNECTING
[2026-09-03T12:25:48.982Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:53.917Z] [WATCHDOG_GRACE] discord gateway: watchdog deferred — reconnect in progress (readyState=0), grace 1/2
[2026-09-03T12:25:57.917Z] [WATCHDOG_GRACE] discord gateway: watchdog deferred — reconnect in progress (readyState=0), grace 2/2
[2026-09-03T12:25:57.919Z] [WATCHDOG_FIRED] discord gateway: disconnection watchdog fired after 25005ms — force-stopping lifecycle
[2026-09-03T12:25:57.921Z] [LIFECYCLE] threadBindings.stop() called
[2026-09-03T12:25:57.921Z] [PROOF] ✅ Lifecycle #1 REJECTED: discord gateway stayed disconnected for 25005ms; force-stopping lifecycle
[2026-09-03T12:25:57.922Z] [PROOF] Cumulative disconnect elapsed at force-stop: 25005ms (cap 25000ms)
[2026-09-03T12:25:57.922Z] [PROOF] Last observed gateway socket readyState before force-stop: 0 at +16154ms (0=CONNECTING — force-stopped mid-handshake; the lifecycle's finally block disconnects the socket, so this is the last pre-teardown observation)
[2026-09-03T12:25:57.922Z] [PROOF] Grace timeline:
[2026-09-03T12:25:57.922Z] [PROOF] grace 1/2 at +21105ms
[2026-09-03T12:25:57.922Z] [PROOF] grace 2/2 at +25105ms
[2026-09-03T12:25:57.922Z] [PROOF] grace1→grace2 gap = 4000ms — bounded by remaining budget (25000ms cap − 21105ms elapsed) = 3895ms, not a fresh T=5000ms window
[2026-09-03T12:25:57.922Z] [PROOF] Force-stop at +25107ms; watchdog reported elapsed=25005ms
[2026-09-03T12:25:57.923Z] [PROOF] Gateway #1 disconnected, stuck server closed
[2026-09-03T12:25:57.923Z]
[2026-09-03T12:25:57.923Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:57.923Z] Phase 4: Supervisor recovery — fresh gateway → READY → lifecycle #2
[2026-09-03T12:25:57.923Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:58.330Z] [PROOF] ✅ New gateway reached READY
[2026-09-03T12:25:58.331Z] [STATUS] connected=true lifecycle=ready lastError=null
[2026-09-03T12:25:59.332Z] [PROOF] Lifecycle #2 in waitForDiscordGatewayStop
[2026-09-03T12:25:59.332Z]
[2026-09-03T12:25:59.332Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:25:59.332Z] Phase 5: Inbound MESSAGE_CREATE after recovery
[2026-09-03T12:25:59.332Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:26:02.336Z] [REST] Sending test message to channel [REDACTED]...
[2026-09-03T12:26:02.513Z] [INBOUND] MESSAGE_CREATE from [Leo] content="CONNECTING-at-cap proof — test message (1788438362336)"
[2026-09-03T12:26:02.674Z] [REST] Sent test message → HTTP 200
[2026-09-03T12:26:02.675Z]
[2026-09-03T12:26:02.675Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:26:02.675Z] PROOF SUMMARY
[2026-09-03T12:26:02.675Z] ══════════════════════════════════════════════════════════════════════
[2026-09-03T12:26:02.675Z] A1 Reconnect scheduled with 16000ms backoff (attempts preset): ✅ PASS
[2026-09-03T12:26:02.675Z] A2 Grace 1/2 observed with socket CONNECTING: ✅ PASS
[2026-09-03T12:26:02.675Z] A3 Grace 2/2 observed at zero remaining budget: ✅ PASS
[2026-09-03T12:26:02.675Z] A4 Force-stop at cumulative cap (elapsed 25005ms ≥ cap-1500ms, readyState=0=CONNECTING): ✅ PASS
[2026-09-03T12:26:02.675Z] A5 Recovery: fresh gateway → READY: ✅ PASS
[2026-09-03T12:26:02.675Z] A6 Inbound MESSAGE_CREATE delivered after restart: ✅ PASS
[2026-09-03T12:26:02.675Z]
[2026-09-03T12:26:02.675Z] Covered branch: watchdog fires with grace budget remaining → grace
[2026-09-03T12:26:02.675Z] rearm capped to remaining cumulative budget; budget exhausted with
[2026-09-03T12:26:02.675Z] socket still CONNECTING → force-stop at the cumulative disconnect
[2026-09-03T12:26:02.675Z] deadline, then supervisor recovery restores inbound delivery.
[2026-09-03T12:26:07.679Z] [PROOF] Lifecycle #2 cleanup timed out (expected after disconnect)
[2026-09-03T12:26:07.679Z]
[2026-09-03T12:26:07.679Z] Overall: ✅ ALL PHASES PASS
The harness lives at extensions/discord/src/monitor/proof-connecting-cap-harness.ts (uncommitted, throwaway) and exercises the real runDiscordGatewayLifecycle from provider.lifecycle.ts — no standalone replication. Tokens, URLs, and session IDs redacted.
CI on this head: 52 pass / 0 fail (the prior check-lint / extension-boundary / ci-gate failures were the transient main-side TS7056 in packages/gateway-protocol/protocol-schemas.ts, fixed upstream by #135360 and absorbed by the rebase).
@clawsweeper re-review
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
ws readyState contract — direct inspection (review follow-up)The review noted the CONNECTING/OPEN grace decision depends on the ws These are frozen class constants defined by The live proof's No code change requested — this closes the inspection gap with a direct dependency-source citation. |
…connected too long Add a GatewayConnectionWatchdog that monitors total disconnection duration. If the gateway stays disconnected longer than the reconnect delay plus 2x heartbeat interval (90s), the watchdog tears down any stuck connecting socket, resets session state, and forces a fresh connect(false) — bypassing the stale resume attempt entirely. The watchdog deadline survives across reconnect retries (start() is a no-op if already running). It is stopped only after READY or RESUMED dispatch, not Hello, so a HELLO-without-READY gap remains covered. Discord's Invalid Session (opcode 9) remains the server-authoritative fallback for normal resume failures. The watchdog only fires when the gateway has been disconnected abnormally long — catching event-loop stalls that leave the gateway in 'reconnect scheduled' state indefinitely. Closes openclaw#122950
…122950 Add a disconnection watchdog to createGatewayStatusObserver in provider.lifecycle.ts — the existing lifecycle owner. When the gateway closes, the watchdog starts polling isConnected. If the gateway stays disconnected longer than runtimeReadyTimeoutMs, it calls triggerForceStop, which goes through the existing lifecycle cleanup path (waitForDiscordGatewayStop → finishReject → proper disconnect and listener cleanup). The watchdog self-clears when the gateway reconnects (isConnected becomes true) or when a new socket opens (Gateway websocket opened debug event). This moves recovery from a parallel timer in the lower-level gateway module to the existing provider lifecycle owner, as ClawSweeper requested. The existing startReadyWatch already handles 'opened but no READY' — this extends coverage to 'closed and reconnect stalled'. Removed the previous GatewayConnectionWatchdog from gateway.ts and gateway-lifecycle.ts (net -223 lines of old approach). Related: openclaw#51190 (same symptom, fixed in lifecycle owner by openclaw#51252), openclaw#120222 (event-loop stall root cause), openclaw#112698 (Codex app-server stall). Closes openclaw#122950
- Add curly braces to single-line if (oxlint curly rule) - Remove unused statusSink destructuring in test - Add // SAFETY: comments to type assertions for ratchet compliance
The two-line SAFETY comment was 2 lines above the assertion, but the ratchet checker only looks at the line directly above (operatorLine - 1). Consolidating to a single line places it directly above the assertion. Reverted the extra SAFETY comments on the two pre-existing assertions to keep the count at 2, matching the grandfathered baseline.
Remove the deadlineExtended one-shot guard that prevented the watchdog from rearming when subsequent reconnect schedules arrived. Discord's backoff can schedule 2s, 4s, 8s, 16s, then 30s retries; accepting only the first delay let the watchdog fire at ~32s while a legitimate 30s retry was still pending. Each reconnect-scheduled event is authoritative, so rearm with the new delay every time. Grace-granted re-arms (no extraDelayMs) still preserve the original deadline. Add a regression test covering the 2s/4s/8s backoff sequence.
…deferral Each reconnect-scheduled event rearms the watchdog to cover the latest retry delay, but without a cumulative cap a gateway that keeps scheduling retries without reaching READY can defer the watchdog indefinitely. Add CUMULATIVE_DISCONNECT_CAP_MULTIPLIER (5x runtimeReadyTimeoutMs = 150s at default 30s) so the total disconnect duration is bounded. Each rearm calculates the remaining time to the cap and uses the minimum of the requested threshold and the remaining time. Add a regression test that simulates Discord's full backoff sequence (2s, 4s, 8s, 16s, 30s × 5) and asserts the watchdog force-stops after the cumulative cap is reached.
The grace re-arm path called clearDisconnectWatchdog() which resets disconnectedAt to undefined, then startDisconnectWatchdog() which sets a new disconnectedAt = Date.now(). This reset the cumulative cap clock on each grace period, allowing a CONNECTING socket to exceed the 150s cap by getting fresh grace windows. Fix: preserve the original disconnectedAt through grace re-arms by saving it before clearing and restoring it before rearming. The grace re-arm now calls armWatchdog() directly instead of startDisconnectWatchdog() to avoid the epoch reset. Add a regression test that exercises the cap-plus-grace state: a socket stuck in CONNECTING receives grace periods, and the watchdog eventually force-stops when grace is exhausted.
The grace re-arm path preserved disconnectedAt but used the full runtimeReadyTimeoutMs (30s) as the grace threshold without considering how much of the cumulative disconnect budget (150s) remained. A CONNECTING/OPEN socket near the cap boundary could receive two full 30s grace windows, extending force-stop to ~210s — 60s beyond the stated recovery cap. Fix: cap the grace threshold to min(runtimeReadyTimeoutMs, remaining cumulative budget). When the budget is exhausted (remaining=0), the grace watchdog fires immediately, honoring the cumulative deadline. Add a regression test that simulates a 120s reconnect delay pushing the initial watchdog to the 150s cap, then verifies force-stop fires at ~150s (not ~210s) even with grace periods remaining.
|
Rebased onto current main (
CONNECTING-at-cap live proof — exact head `e3606a2a89a` (fresh run, redacted)Per the review policy, a re-review after a mechanical rebase refreshes the rating; the posted proofs cover this head's identical tree content. |
|
Thanks for the PR. We're closing older pull requests that have gone stale against current This PR has had no commits for over a month and is waiting on author. If the Discord disconnect watchdog is still needed, please open a fresh PR against current main. |
What Problem This Solves
When the Discord gateway disconnects and an event-loop stall prevents the reconnect timer from firing, the gateway stays in 'reconnect scheduled' state indefinitely and goes deaf to Discord. The existing lifecycle owner (provider.lifecycle.ts) already handles startup stalls (gateway opens but READY never arrives) via startReadyWatch, but does NOT cover runtime stalls after steady-state — when the gateway was already connected, disconnects, and the reconnect stalls.
The Fix: Disconnection Watchdog in the Lifecycle Owner
Extended createGatewayStatusObserver in provider.lifecycle.ts to start a disconnection watchdog when the gateway closes (after initial readiness). The watchdog polls isConnected and, if the gateway stays disconnected longer than runtimeReadyTimeoutMs (30s default), calls triggerForceStop — which goes through the existing lifecycle cleanup path (waitForDiscordGatewayStop -> finishReject -> proper disconnect and listener cleanup).
Key design:
markRuntimeReady()(after initialwaitForGatewayReadycompletes)Evidence
Live transport proof, CONNECTING-at-cap branch (head
3acb82dec3b, 2026-09-03):Full redacted log: #124162 (comment)
Live transport proof (runDiscordGatewayLifecycle public entry point, prior head
9cb5b13ebd2):Exercised the REAL
runDiscordGatewayLifecycle— the public exported entry point — with a live Discord gateway connection. Watchdog fired after 30004ms, lifecycle rejected with proper cleanup (threadBindings.stop called).Unit tests (provider.lifecycle.test.ts):
ClawSweeper review: Zero code findings, proof: sufficient, patch quality: platinum hermit (4/6), status: ready for maintainer look.
Changes
Net: +149 -224 = -75 lines
Closes #122950