Skip to content

fix(discord): keep the gateway READY wait deadline on the monotonic clock - #182064

Closed
mikasa0818 wants to merge 1 commit into
openclaw:mainfrom
mikasa0818:fix/problem-discord-gateway-ready-monotonic-deadline
Closed

mikasa0818 wants to merge 1 commit into
openclaw:mainfrom
mikasa0818:fix/problem-discord-gateway-ready-monotonic-deadline

Conversation

@mikasa0818

@mikasa0818 mikasa0818 commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: the Discord monitor's bounded wait for the gateway READY event keeps polling past its configured timeout when the system wall clock steps backward during the wait, so a Discord account that never reaches READY stalls in "connecting" for the length of the step instead of timing out and reconnecting with backoff.

User Impact

User impact: a Discord channel whose gateway connection never becomes READY now always moves on to the reconnect-with-backoff path after DISCORD_GATEWAY_READY_TIMEOUT_MS (default 15s) of real elapsed time, regardless of NTP corrections or VM/laptop resume. Startup and recovery no longer hang on a wall-clock-inflated wait, and status keeps reporting the recovering lifecycle promptly.

Why This Change Was Made

waitForGatewayReady's inner waitUntilReady seeds deadlineAt = Date.now() + gatewayReadyTimeoutMs and checks Date.now() >= deadlineAt between 250ms polls armed with monotonic setTimeout. A backward wall-clock step during the wait inflates the remaining budget by the step, so the monitor polls for 15s + step before logging the READY timeout and reconnecting; a forward step gives up early.

The deadline now lives on performance.now() — seed and expiry check — which is monotonic and unaffected by wall-clock adjustments. Status timestamps (lastEventAt, transport activity) stay on Date.now() because they are absolute wall-clock facts. This is the same cross-clock-domain pattern already fixed for command process-group teardown in #174151 and the orphaned-process reap grace deadline in #181335; the Discord READY wait is the sibling site left on the wall clock.

Related but separate open PRs touch the same file's outer recovery behavior: #162377 bounds the number of consecutive READY recovery attempts, #124162 adds a runtime disconnection watchdog, and #138441 fixes voice bridge selection. This change only moves the per-attempt wait deadline to the monotonic clock and composes with those.

No configuration, protocol, or status-shape change; the env override semantics (a duration in ms) are untouched, and behavior on a clock that never steps is identical.

Evidence

Pre-fix RED — stock main (97d96e53d22f), regression test only. Fake timers advance 15s of monotonic time past the READY timeout while vi.setSystemTime rewinds the wall clock 60s mid-wait; the timeout never fires, so no error is logged and no reconnect happens:

$ node scripts/run-vitest.mjs run --config test/vitest/vitest.extension-discord.config.ts extensions/discord/src/monitor/provider.lifecycle.test.ts -t monotonic
 × times the READY wait out on the monotonic clock when the wall clock rewinds
   → expected "…" to be called with stringContaining("gateway READY wait timed out after 15000ms")

Post-fix GREEN — the READY wait times out at its 15s monotonic bound, logs the timeout, and reconnects:

$ node scripts/run-vitest.mjs run --config test/vitest/vitest.extension-discord.config.ts extensions/discord/src/monitor/provider.lifecycle.test.ts
      Tests  16 passed (16)

Behavior matrix (gateway never READY, wall clock rewound 60s mid-wait, 15s default timeout):

clock during READY wait     => timeout + reconnect        => result
normal (no step)            => after 15s                  => bounded
wall rewind 60s (pre-fix)   => after 15s + 60s (polling)  => inflated by step
wall rewind 60s (post-fix)  => after 15s                  => bounded

Also verified on the changed tree: pnpm format:check, pnpm lint, and the extensions typecheck entry. The regression drives the real runDiscordGatewayLifecycle through the existing test harness (mocked gateway/supervisor, real lifecycle state machine); the local bundled-gateway proof path is not runnable on this Windows contributor box and was not used as evidence.

Real runtime proof (real timers, lifecycle event trace, in-process wall-clock rewind)

Same scenario executed twice with real timers — no fake clocks: the real runDiscordGatewayLifecycle runs with hand-rolled real collaborator objects (real EventEmitter, real counters) against a gateway that never reaches READY (OPENCLAW_DISCORD_READY_TIMEOUT_MS=5000). One second into the wait, Date.now alone is rewound 120s in-process (NTP-correction analogue); performance.now() keeps reporting real elapsed time. The trace identifies the lifecycle boundary events: the READY-timeout log, gateway disconnect, and the reconnect attempt.

TRACE[discord-ready] t=1003ms wall clock rewound by -120000ms (in-process Date.now injection)
PROOF[discord-ready] variant=old   ready_timeout_env=5000ms wall_rewind=-120000ms -> timeout_fired=false first_timeout_real_ms=none connects=0 disconnects=1 cap_elapsed_ms=13003

TRACE[discord-ready] t=5015ms lifecycle log: discord: gateway READY wait timed out after 5000ms
TRACE[discord-ready] t=5015ms boundary: gateway.disconnect() called
TRACE[discord-ready] t=5015ms boundary: gateway.connect(resume) called (reconnect attempt 1)
PROOF[discord-ready] variant=fixed ready_timeout_env=5000ms wall_rewind=-120000ms -> timeout_fired=true  first_timeout_real_ms=5015 connects=1 disconnects=2 cap_elapsed_ms=5015

Stock main never fires the READY timeout during the observation cap (its budget stretches to ~125s by the rewind); with this PR the timeout fires at 5.02s of real time, the gateway is disconnected, and the monitor moves on to reconnect with backoff.

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord size: XS labels Oct 24, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR measures the Discord gateway READY wait with a monotonic clock so wall-clock adjustments cannot distort its timeout.

Example: Discord never reaches READY, the timeout is 15000ms, and the wall clock moves backward 60000ms during the wait.

  • Before: The wait can stretch to roughly 75 seconds before reconnecting.
  • After: The wait expires after roughly 15 seconds of monotonic elapsed time, subject to polling and event-loop scheduling.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The focused patch is useful and appears correct, but the supplied runtime evidence does not meet the required production-transport proof gate.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A Discord account awaiting READY can remain connecting beyond its configured timeout after a backward wall-clock adjustment.
Reason: The change restores the existing duration contract without adding settings, public APIs, persisted state, or another recovery owner.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this PR repairs a concrete deadline defect still present on current main, with no actionable correctness findings.

Priority: P2
Reviewed head: 9dff666fe1817d715ce39ee1f45e0d9d808ba7af

Before merge

  • Add real behavior proof - The contributor's updated terminal trace exercises runDiscordGatewayLifecycle with real timers and reports timeout at 5015ms after a 120-second Date.now rewind, but hand-built gateway collaborators still replace the production transport, leaving the previous review's transport-proof request unresolved; provide redacted logs or terminal output through the shipped monitor and real transport, removing IPs, API keys, phone numbers, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.

Findings

None.

Tests

  • Missing end-to-end proof: Missing proof exercises a wall-clock rewind during a never-READY connection through the shipped Discord monitor and real transport, showing timeout and reconnect at the configured elapsed-time bound.
Agent review details

How this fits together

The Discord monitor supplies its gateway and supervisor to the lifecycle owner, which observes readiness and errors, publishes channel status, and initiates reconnects after startup READY timeouts.

flowchart LR
  A[Discord monitor] --> B[Gateway lifecycle]
  C[Monotonic clock] --> B
  D[Gateway readiness and errors] --> B
  B --> E[Channel status]
  B --> F[Disconnect and reconnect]
Loading

Technical review

Best possible solution:

Retain the two clock substitutions and focused regression in the existing lifecycle owner.

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

Current-main deadline arithmetic establishes the rewind failure, and the contributor reports matching red/green regression results; no target code was executed during this read-only review.

Is this the best way to solve the issue?

This is the smallest complete repair: elapsed-time deadline arithmetic uses one monotonic clock while status timestamps, timeout settings, retry policy, and cancellation remain unchanged.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 18d7560e2066.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit abd2806 adds extensions/discord/src/monitor/provider.lifecycle.ts:210 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: abd280635bcf; files: extensions/discord/src/monitor/provider.lifecycle.ts)
  • Ayaan Zaidi: Raw commit 095e7b8 adds extensions/discord/src/monitor/provider.lifecycle.ts:14 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 095e7b830a0e; files: extensions/discord/src/monitor/provider.lifecycle.ts)

PR surface

Source +3, Tests +18. Total +21 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 5 2 +3
Tests 1 18 0 +18
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 23 2 +21

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Wall-clock adjustments can delay Discord startup recovery, with a concrete but limited trigger and no evidence of widespread urgent impact.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-24T01:11:40.049Z sha 9dff666 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-24T08:16:32.183Z sha 9dff666 :: needs real behavior proof before merge. :: none

Reviewed October 24, 2026, 5:37 AM ET / 09:37 UTC (Revision 3).

@mikasa0818

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 24, 2026
@mikasa0818

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 24, 2026
obviyus added a commit that referenced this pull request Oct 28, 2026
fix: measure deadlines and budgets on one monotonic clock owner

Many deadline, budget and timeout calculations used Date.now(), so a wall-clock step (NTP correction, VM resume, manual change) made them expire early or run long. Contributors had been fixing these one call site at a time. Core now has one owner, src/shared/monotonic-time.ts, for process-local deadlines and elapsed time, replacing the supervisor-local helper and the per-site variants. Bundled extensions use performance.now() directly. Wall-clock values stay where they are persisted, shown to users or exchanged between processes: the public provider deadline stays epoch-valued, with monotonic enforcement kept privately, and the plugin SDK facade is unchanged.

This absorbs the per-site fixes from @SunnyShu0925 (#186039, #186134, #186412, #184716, #184613) and @mikasa0818 (#184576, #184525, #182064), whose original commits are kept. Update, Doctor, Windows-only and security-held sites are listed under "Not fixed here" in the PR.

Evidence: built CLI suspend wait, browser Gateway CDP waits, Discord READY wait and node host-stats checkpoint, each with Date.now stepped inside the process only. On main each misbehaved under the clock step (early expiry or a stretched wait); with this change each matched the no-step control. Media generation's guard blocks local fixtures, so that family relies on the shared owner's regression. Production 479 changed lines, tests net 0.

Co-authored-by: SunnyShu <0668000539@local>
Co-authored-by: mikasa0818 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator

Thanks @mikasa0818. This is now fixed at the root in #186484 (bf10fbe): process-local deadlines and budgets go through one monotonic clock owner, src/shared/monotonic-time.ts (bundled extensions use performance.now()). Your commit from this PR is kept in that merge and you're credited as co-author, so I'm closing this one as covered. For new deadline code, please use that owner rather than a per-site change.

@obviyus obviyus closed this Oct 28, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 29, 2026
…86484)

fix: measure deadlines and budgets on one monotonic clock owner

Many deadline, budget and timeout calculations used Date.now(), so a wall-clock step (NTP correction, VM resume, manual change) made them expire early or run long. Contributors had been fixing these one call site at a time. Core now has one owner, src/shared/monotonic-time.ts, for process-local deadlines and elapsed time, replacing the supervisor-local helper and the per-site variants. Bundled extensions use performance.now() directly. Wall-clock values stay where they are persisted, shown to users or exchanged between processes: the public provider deadline stays epoch-valued, with monotonic enforcement kept privately, and the plugin SDK facade is unchanged.

This absorbs the per-site fixes from @SunnyShu0925 (openclaw#186039, openclaw#186134, openclaw#186412, openclaw#184716, openclaw#184613) and @mikasa0818 (openclaw#184576, openclaw#184525, openclaw#182064), whose original commits are kept. Update, Doctor, Windows-only and security-held sites are listed under "Not fixed here" in the PR.

Evidence: built CLI suspend wait, browser Gateway CDP waits, Discord READY wait and node host-stats checkpoint, each with Date.now stepped inside the process only. On main each misbehaved under the clock step (early expiry or a stretched wait); with this change each matched the no-step control. Media generation's guard blocks local fixtures, so that family relies on the shared owner's regression. Production 479 changed lines, tests net 0.

Co-authored-by: SunnyShu <0668000539@local>
Co-authored-by: mikasa0818 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: discord Channel integration: discord P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XS status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants