Skip to content

fix(discord): keep voice connect budget monotonic across clock skew - #156979

Merged
altaywtf merged 4 commits into
openclaw:mainfrom
SunnyShu0925:fix/discord-voice-connect-deadline-wall-clock
Oct 1, 2026
Merged

altaywtf merged 4 commits into
openclaw:mainfrom
SunnyShu0925:fix/discord-voice-connect-deadline-wall-clock

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Joining a Discord voice channel can stall or fail spuriously when the system clock moves: the readiness deadline was seeded with Date.now() (wall clock) but consumed through AbortSignal.timeout (a monotonic libuv timer), so a clock rollback enlarged the remaining budget past connectTimeoutMs and a forward jump shrank it toward the Math.max(1, ...) floor, misjudging healthy connections as timed out.

  • Problem: DiscordAudioWorker.connect() computed deadline = Date.now() + connectTimeoutMs, then passed Math.max(1, deadline - Date.now()) to AbortSignal.timeout. Wall-clock skew twisted the budget both ways — connections hung or were rejected twice and surfaced as "cannot join voice channel".
  • Solution: seed and read the deadline with performance.now() (monotonic), flooring the budget so AbortSignal.timeout keeps its integer contract.
  • Scope: audio-worker.ts three sites in connect() — deadline seed (L79), AbortSignal.timeout budget (L115), retry guard (L145). reconnectGraceMs/PLAYBACK_READY_TIMEOUT_MS (L331/L565) already pass integer constants; receivedAt: Date.now() (L487) is an epoch telemetry timestamp and correctly stays wall-clock.

Why This Change Was Made

Matches the canonical pattern already shipped for the same wall-clock-vs-monotonic class: #155603 (codex remote transfer, merged), #155648 (meeting browser), #155323 (provider discovery). Math.floor is required because performance.now() is sub-millisecond and AbortSignal.timeout rejects non-integer delays with ERR_OUT_OF_RANGE (verified below). The fix lands in the single owner of the readiness deadline with no new parser, policy branch, or config surface.

User Impact

Joining a Discord voice channel now respects the configured connectTimeoutMs regardless of system clock adjustments (NTP, DST, manual changes, container drift). Connections no longer hang past the timeout, and healthy connections are no longer rejected as timed out during a forward clock jump.

Evidence

Math.floor is mandatory — AbortSignal.timeout rejects the sub-millisecond float performance.now() produces:

$ node --import tsx -e 'const s=performance.now();const b=Math.max(1,(s+30000)-performance.now());try{AbortSignal.timeout(b)}catch(e){console.log("float threw:",e.code)};try{AbortSignal.timeout(Math.max(1,Math.floor(b)))}catch(e){console.log("floored threw:",e.code)};'
float threw: ERR_OUT_OF_RANGE
floored accepted (no throw)

Without Math.floor the fix throws inside connect() and destroys the attempt before entersState runs.

Pre-fix RED (source reverted, regression test kept) — the 10s wall-clock rollback enlarges the budget to 30000 + 10000 = 40000ms:

$ node scripts/run-vitest.mjs run --config test/vitest/vitest.extension-discord.config.ts \
    extensions/discord/src/voice/audio-worker-deadline-clock.test.ts
 AssertionError: expected 40000 to be less than or equal to 30000

Post-fix GREEN — the budget stays monotonic under the same skew. The regression test asserts AbortSignal.timeout receives [29900, 30000] (monotonic, minus elapsed ms) not [30000, 40000] (wall-clock + rollback):

 ✓ audio-worker-deadline-clock.test.ts > ignores wall-clock skew ... 44ms
 ✓ voice-session.timeouts.test.ts (3 existing timeout tests) — no regression
 Tests  4 passed (4)

CI regression caught and fixed — the existing voice-session.lifecycle.test.ts case "does not retry an aborted voice connection readiness wait after the timeout budget is spent" mocked Date.now() to simulate budget exhaustion. Switching production code to performance.now() made that mock a no-op, so the join spuriously succeeded (expected true to be false). The test mock now spies performance.now() with the same return sequence:

# pre-fix (Date.now spy): expected true to be false  → FAIL
# post-fix (performance.now spy): ✓ 42ms            → PASS

Full voice-session.lifecycle.test.ts (43) + audio-worker-deadline-clock.test.ts + voice-session.timeouts.test.ts = 47/47 green. New test file: 36ms wall, ~15s file-level Duration (vitest overhead), amortized in the existing changed-extensions-config shard.

Production-path transport trace — node --import tsx directly instantiates the production DiscordAudioWorker (real @discordjs/voice SDK, fake credentials, no live gateway). connect() runs the real joinVoiceChannel → entersState path; the connection never reaches Ready and is bounded by the AbortSignal.timeout budget. A Date.now monkey-patch rolls the wall clock back 10s to verify the budget is not inflated:

$ node --import tsx/esm production-budget-proof.mts
[baseline]              connect threw: aborted after 3003ms  budgets: [2998]
[wall-clock-rollback-10s] connect threw: aborted after 3002ms  budgets: [2999]
  events (both): gateway-send, gateway-send, connection, gateway-destroy, stopped
All budgets within (0, connectTimeoutMs=3000]: true
Wall-clock rollback did NOT inflate the budget (performance.now is monotonic): [2999]

The real @discordjs/voice transport sends VoiceStateUpdate (op 4) via gateway-send, confirming the production connect path ran. Under a 10s wall-clock rollback the budget stays at 2999ms (not 12999ms) — the monotonic clock bounds the readiness wait regardless of wall-clock skew.

Not tested: a live Discord voice gateway join (requires bot credentials and a real voice channel). The production transport trace above exercises the real SDK connect path and shows the bounded timeout under clock skew; no stored-data contract changes.

AI Assistance

AI-assisted: Yes. Per review, fixed a CI regression where an existing lifecycle test mocked Date.now() to simulate budget exhaustion; the mock now spies performance.now() to match the monotonic clock domain, reported the new test file's wall time and CI cost, and added a production-path transport trace showing the bounded timeout under wall-clock skew.

@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord size: S labels Sep 24, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 24, 2026
@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 30, 2026, 9:48 PM ET / October 1, 2026, 01:48 UTC (Revision 6).

ClawSweeper review

What this changes

The Discord voice worker measures connection readiness and retry time with a monotonic clock, with tests for clock skew and an exhausted timeout.

Merge readiness

✅ Ready for maintainer review

Current main still gives Discord voice connections a wall-clock-based timeout budget. This PR addresses that distinct defect, and the submitted transport trace and maintainer verification support the fix.

Priority: P2
Reviewed head: 8077fabf0e502ecf6df76b9d4254838ca6cd33fd

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair has meaningful before/after transport evidence and no actionable finding; its proof stops short of an authenticated Discord join.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The changed Discord audio worker was exercised through its production connect path with the real voice SDK and a simulated wall-clock rewind; the recorded after-fix allowance remained bounded and the wait aborted near its configured timeout. The maintainer also reported ordinary, rewind, and forward-jump checks. Live authenticated Discord joining remains outside this evidence. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The changed Discord audio worker was exercised through its production connect path with the real voice SDK and a simulated wall-clock rewind; the recorded after-fix allowance remained bounded and the wait aborted near its configured timeout. The maintainer also reported ordinary, rewind, and forward-jump checks. Live authenticated Discord joining remains outside this evidence. No stored-data contract changes.
Evidence reviewed 7 items Current main remains affected: The fetched main revision still seeds, spends, and checks the connect deadline with Date.now(); the voice SDK wait consumes the resulting delay.
Introduced repair: The pinned PR delta uses performance.now() for deadline creation and retry eligibility and floors the remaining milliseconds passed to AbortSignal.timeout.
Product boundary: The voice session resolves the configured connect timeout and passes it to the audio transport before awaiting readiness; the documentation defines it as the initial Discord voice Ready wait.
Findings None None.
Security None None.

How this fits together

A Discord voice join passes its configured timeout to an audio worker. The worker waits for the Discord voice SDK to become ready, then reports success or failure to the voice session.

flowchart LR
  A[Voice join request] --> B[Configured timeout]
  B --> C[Discord audio worker]
  C --> D[Remaining readiness budget]
  D --> E[Discord voice SDK]
  E --> F[Join result]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +1, Tests +45. Total +46 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 4 3 +1
Tests 2 46 1 +45
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 50 4 +46

Review metrics

None.

Technical review

Best possible solution:

Keep the timeout calculation in the Discord audio worker and preserve the configured allowance across both readiness attempts.

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

Yes, with high confidence from current source and the recorded before/after clock-skew traces. This read-only review did not execute the PR.

Is this the best way to solve the issue?

Yes. The worker already owns the connection deadline; using one monotonic clock for its creation and consumption is a narrow repair.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 80680fb3428a.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Clock corrections can disrupt Discord voice joining, but the affected workflow and trigger are limited.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The changed Discord audio worker was exercised through its production connect path with the real voice SDK and a simulated wall-clock rewind; the recorded after-fix allowance remained bounded and the wait aborted near its configured timeout. The maintainer also reported ordinary, rewind, and forward-jump checks. Live authenticated Discord joining remains outside this evidence. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed Discord audio worker was exercised through its production connect path with the real voice SDK and a simulated wall-clock rewind; the recorded after-fix allowance remained bounded and the wait aborted near its configured timeout. The maintainer also reported ordinary, rewind, and forward-jump checks. Live authenticated Discord joining remains outside this evidence. No stored-data contract changes.

Evidence

What I checked:

  • Current main remains affected: The fetched main revision still seeds, spends, and checks the connect deadline with Date.now(); the voice SDK wait consumes the resulting delay. (extensions/discord/src/voice/audio-worker.ts:79, 80680fb3428a)
  • Introduced repair: The pinned PR delta uses performance.now() for deadline creation and retry eligibility and floors the remaining milliseconds passed to AbortSignal.timeout. (extensions/discord/src/voice/audio-worker.ts:80, 8077fabf0e50)
  • Product boundary: The voice session resolves the configured connect timeout and passes it to the audio transport before awaiting readiness; the documentation defines it as the initial Discord voice Ready wait. (extensions/discord/src/voice/voice-session.ts:204, 8077fabf0e50)
  • Regression coverage: The new test drives the voice manager join under a wall-clock rewind and checks the readiness allowance; an existing lifecycle test now controls the monotonic clock for its exhausted-budget case. (extensions/discord/src/voice/audio-worker-deadline-clock.test.ts:13, 8077fabf0e50)
  • After-fix behavior proof: The captured PR body reports a production-worker trace through the real Discord voice SDK with fake credentials: a 3,000 ms allowance remained 2,999 ms after a ten-second wall-clock rewind and aborted in about 3,002 ms. Maintainer altaywtf independently reported a 500 ms allowance remaining 499 ms and aborting in 500–502 ms across ordinary, rewind, and forward-jump clocks; live authenticated joining was not claimed.
  • Feature history: Local path history ties the existing audio worker to prior merged Discord voice work and later area maintenance. Missing historical objects prevented an exact source-line introduction claim. (extensions/discord/src/voice/audio-worker.ts, 80680fb3428a)

Likely related people:

  • altaywtf: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • 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.

History

Review history (5 earlier review cycles)
  • reviewed 2026-09-24T03:39:20.732Z sha 9d48e136a3613a48b9c5306d5a41579902c47cf9 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-24T04:57:31.080Z sha 365964d :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-24T06:10:27.632Z sha 365964d :: needs maintainer review before merge. :: none
  • reviewed 2026-09-30T08:36:31.563Z sha 8cadf90 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-01T01:03:41.502Z sha e1bf13c :: needs maintainer review before merge. :: none

DiscordAudioWorker.connect() seeded its readiness deadline with Date.now()
(wall clock) but consumed the remaining budget through AbortSignal.timeout,
which is a monotonic libuv timer. A wall-clock rollback enlarged the
remaining budget past connectTimeoutMs (stalling the readiness wait), and a
forward jump shrank it toward the Math.max(1, ...) floor, misjudging healthy
connections as timed out. Seed and read the deadline with performance.now()
instead, flooring the budget so AbortSignal.timeout keeps its integer contract.

Ref: BUG-092-discord-voice-connect-deadline-wall-clock (local finding)
@SunnyShu0925
SunnyShu0925 force-pushed the fix/discord-voice-connect-deadline-wall-clock branch from 9d48e13 to 365964d Compare September 24, 2026 04:49
@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review.

@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 24, 2026
@altaywtf altaywtf self-assigned this Sep 30, 2026
@altaywtf

altaywtf commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

I verified the voice deadline and shortened its comments in 8cadf90d.

  • Before → after: a 500 ms connection budget becomes 10,500 ms on a clock rewind and 1 ms on a forward jump on main. This fix keeps the real Discord SDK's allowance at 499 ms and aborts in 500–502 ms across all three clocks.
  • Tests: pnpm test extensions/discord/src/voice/audio-worker-deadline-clock.test.ts extensions/discord/src/voice/voice-session.lifecycle.test.ts extensions/discord/src/voice/voice-session.timeouts.test.ts --maxWorkers=1 — 47 passed on Linux Crabbox; the comment-only cleanup emits identical executable code.
  • Cost: new regression 7 ms; cold command 116 s; original extension CI 138 s.
  • Review: independent autoreview and final-head ClawSweeper have no actionable P0–P2 findings.
  • Hold: the CI monitor and aggregate gate fail because the trusted base lacks the monitor script; the other executed checks passed. Live authenticated Discord joining is untested. Final merge stays with me.

@altaywtf
altaywtf merged commit d215e92 into openclaw:main Oct 1, 2026
89 checks passed
@altaywtf

altaywtf commented Oct 1, 2026

Copy link
Copy Markdown
Member

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…penclaw#156979)

Keep Discord voice connection waits within the configured elapsed-time budget across wall-clock changes.

- Use one monotonic deadline across readiness attempts and floor the native timeout input.
- Existing Linux Crabbox proof: 47 tests passed; the real SDK keeps a 500 ms allowance across steady, rewound, and advanced wall clocks.
- Current-head CI and ClawSweeper pass with no findings.
- Authenticated Discord joining and audio playback remain untested.

Co-authored-by: Altay <[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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants