Skip to content

fix(xai): prevent realtime retries from reviving closed sessions - #117399

Merged
vincentkoc merged 4 commits into
mainfrom
fix-xai-realtime-connect-lifecycle
Aug 1, 2026
Merged

vincentkoc merged 4 commits into
mainfrom
fix-xai-realtime-connect-lifecycle

Conversation

@vincentkoc

Copy link
Copy Markdown
Member

Related: #116201

What Problem This Solves

Fixes an issue where xAI realtime voice users could have late connection events, overlapping connect calls, or retry callbacks mutate a session after it had been replaced, cancelled, or closed.

Why This Change Was Made

Adds a provider-local connection lifecycle with explicit idle, connecting, ready, retry-wait, and terminal states. The xAI adapter now translates socket and provider events into lifecycle facts, fences events by connection and socket identity, owns retry state in one place, and gives failure precedence over later cancel/close events.

The change stays inside the xAI provider. It adds no provider, config, environment-variable, or plugin SDK surface.

User Impact

xAI realtime voice connect, retry, cancel, close, and failure behavior is deterministic and idempotent. Concurrent connects share one attempt, stale events are ignored, explicit reconnects replace pending retry waits, and terminal outcomes are reported once.

Evidence

AI-assisted: yes. The implementation, tests, live results, and known provider-side limitation were reviewed before submission.

* origin/main:
  refactor(doctor): unify legacy auth migration ownership (#117361)
  fix(plugins): surface actionable doctor warnings (#117357)
  fix(ci): use corrected Kova release evaluator (#116920)
  fix(ci): stabilize release validation assertions (#117377)
  refactor(memory): use sqlite transcript identities (#117334)
  fix(plugins): require tracked owners for targeted updates (#117333)
@vincentkoc vincentkoc self-assigned this Aug 1, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review August 1, 2026 12:17
@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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 1, 2026
@clawsweeper

clawsweeper Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 1, 2026, 8:23 AM ET / 12:23 UTC.

ClawSweeper review

What this changes

The PR gives xAI realtime voice connections an explicit provider-local lifecycle so canceled, closed, and replaced sockets cannot revive or mutate the active session during retries.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep this PR open for normal maintainer review, not cleanup: current main still has bridge-wide connection flags and a reused reconnect controller, so late socket callbacks can affect a replacement connection. The branch moves those facts into the xAI provider lifecycle, fences events by connection identity, and adds focused ordering regressions; I found no discrete correctness defect in the patch.

Priority: P1
Reviewed head: f117c2166debfe2b0580fd58b9800fbdf02a9862
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A well-scoped provider repair with source-proven ownership boundaries, focused ordering regressions, and reported live xAI evidence; only normal maintainer and exact-head completion gates remain.
Proof confidence 🐚 platinum hermit (4/6) ✨ media proof bonus Sufficient (linked_artifact): The PR body links credential-hydrated live xAI runs that reached audio, server-VAD, tools, and forced reconnect on the branch, with the remaining resumed-marker backend failure shown to occur on frozen base as well; redaction-sensitive credentials were not copied into the PR.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (linked_artifact): The PR body links credential-hydrated live xAI runs that reached audio, server-VAD, tools, and forced reconnect on the branch, with the remaining resumed-marker backend failure shown to occur on frozen base as well; redaction-sensitive credentials were not copied into the PR.
Evidence reviewed 7 items Current-main defect surface: Current main stores connection readiness and intentional-close state on the bridge, while every socket callback reads and mutates that shared state. Its close handler clears bridge-wide flags and starts retries without proving that the closing socket is still the current one; an older socket can therefore interfere with a newer attempt.
Retry owner on current main: The current retry path keeps a bridge-wide AbortController and calls doConnect() after the delay. A later explicit connect can replace that controller and state, leaving older callbacks without a per-connection ownership fence.
PR owner-boundary repair: The proposed lifecycle records the active connection identity, phase, retry count, abort signal, and terminal notification state together; only the active identity is allowed to accept events or transition lifecycle state.
Findings None None.
Security None None.

How this fits together

The xAI bundled plugin creates a realtime voice bridge that resolves credentials, opens a WebSocket, processes provider events, and forwards audio, transcripts, tool results, and close outcomes to the voice runtime. This change sits between socket callbacks and bridge state, deciding whether each connection event can affect the current voice session.

flowchart LR
  A[Voice runtime calls bridge] --> B[xAI realtime voice bridge]
  B --> C[Connection lifecycle owner]
  C --> D[Credential resolution and WebSocket]
  D --> E[Provider socket events]
  E --> F{Current connection and active phase?}
  F -->|Yes| G[Audio, transcripts, tool results, close outcome]
  F -->|No| H[Ignore stale callback]
  G --> A
Loading

Decision needed

Question Recommendation
Should this provider-local lifecycle repair merge after the remaining exact-head build-artifact and runtime-topology checks complete? Merge after exact-head checks: Accept the provider-local lifecycle model once the remaining checks for head f117c21 complete successfully.

Why: The implementation is a substantive state-transition refactor on a maintainer-labeled realtime provider path; automation can establish the repair shape and evidence, but the final landing decision remains an explicit maintainer responsibility.

Before merge

  • Resolve merge risk (P1) - This refactor intentionally changes xAI reconnect and terminal-close ordering for existing realtime sessions; the remaining exact-head artifact and runtime-topology checks should finish before merge, and any failure should be evaluated against this lifecycle boundary rather than waived as unrelated.
  • Complete next step (P2) - No mechanical repair was found; await protected maintainer review and completion of the remaining exact-head CI jobs before deciding whether to merge.
Agent review details

Security

None.

PR surface

Source +276, Tests +316. Total +592 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 502 226 +276
Tests 2 317 1 +316
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 819 227 +592

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #116201
Summary: This PR is a candidate repair for the terminal-close and post-close-input portion of the broader realtime voice resource and ownership report; the separate resumed-response provider error is distinct.

Members:

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

Merge-risk options

Maintainer options:

  1. Accept the scoped lifecycle change (recommended)
    Merge after the remaining exact-head checks are green, accepting the intentionally stricter rule that only the active xAI connection may update realtime session state.
  2. Pause for lifecycle consolidation
    Pause this PR if maintainers want a shared provider-level lifecycle abstraction before adopting another local implementation.

Technical review

Best possible solution:

Keep lifecycle ownership inside the xAI provider, land it after exact-head validation completes, and keep the separate xAI resumed-response backend failure tracked by #116663 out of this connection-ownership repair.

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

Yes, from source: current main lets any socket callback mutate bridge-wide connection flags and run retry work, while the added focused tests model a deferred stale close after a replacement connects. This read-only review did not execute the live xAI path locally.

Is this the best way to solve the issue?

Yes: a provider-local lifecycle is the narrowest maintainable owner for socket identity, retry state, and terminal outcomes; current xAI state is bridge-wide, while importing the OpenAI extension's private helper would violate extension boundaries.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 142ad75c4336.

Labels

Label changes:

  • add P1: Stale retry and socket callbacks can corrupt the active xAI realtime voice session for affected users.
  • add merge-risk: 🚨 session-state: The PR changes the ownership and terminal ordering of reconnect, pending input, and close state for existing realtime voice sessions.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body links credential-hydrated live xAI runs that reached audio, server-VAD, tools, and forced reconnect on the branch, with the remaining resumed-marker backend failure shown to occur on frozen base as well; redaction-sensitive credentials were not copied into the PR.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The PR body links credential-hydrated live xAI runs that reached audio, server-VAD, tools, and forced reconnect on the branch, with the remaining resumed-marker backend failure shown to occur on frozen base as well; redaction-sensitive credentials were not copied into the PR.

Label justifications:

  • P1: Stale retry and socket callbacks can corrupt the active xAI realtime voice session for affected users.
  • merge-risk: 🚨 session-state: The PR changes the ownership and terminal ordering of reconnect, pending input, and close state for existing realtime voice sessions.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The PR body links credential-hydrated live xAI runs that reached audio, server-VAD, tools, and forced reconnect on the branch, with the remaining resumed-marker backend failure shown to occur on frozen base as well; redaction-sensitive credentials were not copied into the PR.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body links credential-hydrated live xAI runs that reached audio, server-VAD, tools, and forced reconnect on the branch, with the remaining resumed-marker backend failure shown to occur on frozen base as well; redaction-sensitive credentials were not copied into the PR.

Evidence

What I checked:

  • Current-main defect surface: Current main stores connection readiness and intentional-close state on the bridge, while every socket callback reads and mutates that shared state. Its close handler clears bridge-wide flags and starts retries without proving that the closing socket is still the current one; an older socket can therefore interfere with a newer attempt. (extensions/xai/realtime-voice-bridge.ts:239, 142ad75c4336)
  • Retry owner on current main: The current retry path keeps a bridge-wide AbortController and calls doConnect() after the delay. A later explicit connect can replace that controller and state, leaving older callbacks without a per-connection ownership fence. (extensions/xai/realtime-voice-bridge.ts:354, 142ad75c4336)
  • PR owner-boundary repair: The proposed lifecycle records the active connection identity, phase, retry count, abort signal, and terminal notification state together; only the active identity is allowed to accept events or transition lifecycle state. (extensions/xai/realtime-voice-lifecycle.ts:24, f117c2166deb)
  • Stale-socket guard in proposed bridge: The proposed socket handlers reject non-current connections and verify that the socket remains the bridge's current socket before parsing messages, forwarding errors, or acting on close events. (extensions/xai/realtime-voice-bridge.ts:274, f117c2166deb)
  • Regression coverage: The branch adds a provider-level ordering test that defers a canceled socket's close event, starts a replacement connection, then emits stale open/message/error/close callbacks and asserts the replacement remains connected without stale audio or errors. (extensions/xai/realtime-voice-provider.test.ts:317, f117c2166deb)
  • Sibling design and provenance: OpenAI already uses the same connection-identity lifecycle pattern locally, and its recent terminal-preconnect repair was authored by Vincent Koc. The xAI realtime provider was introduced by Peter Steinberger, with a later reconnect-close repair by wahaha1223. (extensions/openai/realtime-voice-lifecycle.ts:29, 42f1e8dd4177)

Likely related people:

  • Peter Steinberger: Introduced the xAI realtime voice provider, including the bridge whose connection lifecycle this PR changes. (role: feature introducer; confidence: high; commits: 6c5084f1adb3; files: extensions/xai/realtime-voice-bridge.ts)
  • wahaha1223: Authored the earlier xAI fix that released reconnect delay on close, directly adjacent to the retry ownership now being refactored. (role: prior reconnect-path contributor; confidence: high; commits: 0903ebe4fa5f; files: extensions/xai/realtime-voice-bridge.ts)
  • Vincent Koc: Authored the prior merged OpenAI terminal-preconnect lifecycle repair and the proposed xAI lifecycle work, establishing relevant ownership beyond this PR alone. (role: recent adjacent lifecycle contributor; confidence: high; commits: 42f1e8dd4177; files: extensions/openai/realtime-voice-lifecycle.ts, extensions/openai/realtime-voice-provider.ts)

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.

@vincentkoc
vincentkoc merged commit b830a65 into main Aug 1, 2026
155 of 163 checks passed
@vincentkoc
vincentkoc deleted the fix-xai-realtime-connect-lifecycle branch August 1, 2026 12:26
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 2, 2026
…nect-lifecycle

* origin/pr-117399-direct:
  fix(xai): preserve immediate restart ownership
  test(xai): cover realtime lifecycle ownership
  fix(xai): own realtime connection lifecycle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: xai maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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.

1 participant