Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): make compatible Codex instance switches single-writer #8580

Closedvitaliyhayda(GitHub profile, opens in a new tab)wants to merge 9 commits intomain fromrefs/pull/8580/headopened View on GitHub

Fixes #8259

TLDR

Before this change, the picker could show separately authenticated provider instances, but an existing thread remained bound to its current instance. Switching did not safely transfer that conversation. It could start the target before fully releasing the source or silently create a fresh native thread instead of preserving the same ID.

Now a manual switch between compatible Codex instances stops the old writer, strictly resumes the same native conversation, verifies its identity, and only then commits the new owner. Separate histories remain supported and are still the default for instances with different continuation identities. Only deliberately compatible instances can hand off one history.

Current switching starts the target before stopping the source. Source-stop failures are suppressed, so two app-server instances can compete for one native thread

A simple reorder is insufficient:

  1. Cross-instance start can lose the persisted source cursor
  2. thread/resume can fall back to thread/start
  3. That fallback silently creates a new native thread
  4. Adapter shutdown removes session state before cleanup completes
  5. Runtime-close failures are currently suppressed
  6. Delayed source events can overwrite target-owned state

This change:

  1. Serializes recovery-capable operations with cleanup-safe per-thread locks
  2. Requires compatible continuation identities
  3. Requires an idle source and valid persisted cursor
  4. Persists the cursor before teardown
  5. Stops the source before target startup
  6. Proves child-process release before target resume
  7. Propagates stop and release failures
  8. Uses strict thread/resume whenever a cursor exists
  9. Never falls back to thread/start during handoff
  10. Requires the returned native ID to match
  11. Stops provisional targets after identity or persistence failure
  12. Commits target ownership only after readiness and persistence
  13. Ignores delayed events from stale owners
  14. Keeps turn interruption out of band from a blocked send while ordering it behind handoff
  15. Proves non-owner Codex writers are released before any native resume
  16. Delivers approval and user-input responses outside the long-running turn lock without recovery
  17. Restricts native Codex handoff rules to Codex-to-Codex switches

Failure behavior:

  1. Cursor persistence failure leaves the source running
  2. Release failure prevents target startup
  3. Target failure leaves the source stopped with a recoverable cursor
  4. Identity mismatch stops the target
  5. Binding failure stops the target
  6. Unproven cleanup remains visible and blocks retry
  7. Failed target cleanup blocks source recovery and direct restart

Verification:

  1. 197 focused tests pass
  2. Server typecheck exits 0
  3. git diff --check passes
  4. Tests cover release, cursor, identity, compensation, stale events, lock cleanup, interruption, interactive responses, and cross-provider replacement

Scope:

  1. Existing manual switching only
  2. No UI or schema changes
  3. No automatic routing
  4. No quota logic
  5. No native-history import
  6. No Claude changes
  7. No token handling
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 46734790-fb33-4451-97e4-66a48f3323ea

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. Effect service conventions review of the changed provider service/adapter code. Two error-modeling findings; imports, layer/service structure, thread-lock composition, and test seams otherwise follow the conventions.

      Posted via Macroscope — Effect Service Conventions
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/04beea69852917d7feb86c95299ccc997afa423e/apps/server/src/provider/Layers/CodexAdapter.ts#L2077

      When stopAll() fails during adapter teardown, the Effect.andThen chain stops before Queue.shutdown(runtimeEventQueue) and managedNativeEventLogger.close() run. The final Effect.ignore only suppresses the resulting failure, so buffered native events are not flushed and stream consumers never observe queue shutdown. Run these cleanup actions in an ensuring/independent cleanup path so they execute even when stopping a session fails.

      ✅ Resolved in a266acc84e62c2f08df5844454918df293c371c1

    5. @@ -817,20 +1006 @@
      817- providerTurnMetricAttributes({
      818- provider: metricProvider,
      819- model: metricModel,
      820- extra: {
      821- operation: "send",
      822- },
      823- }),
      824- }),
      825- );
      826- });
      827-
      828- const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(
      829- function* (rawInput) {
      830- const input = yield* decodeInputOrValidationError({
      831- operation: "ProviderService.interruptTurn",
      832- schema: ProviderInterruptTurnInput,
      833- payload: rawInput,
      834- });
      835- let metricProvider = "unknown";
      836- return yield* Effect.gen(function* () {
      1006+ return yield* withThreadLock(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/ProviderService.ts:1006

      sendTurn holds withThreadLock while CursorAdapter.sendTurn awaits ctx.acp.prompt; when Cursor emits request.opened or user-input.requested, the corresponding respondToRequest or respondToUserInput call waits on that same lock, so the turn cannot receive its decision and hangs. Release the thread lock before awaiting the interactive provider turn (while preserving any narrower locking needed for routing/state updates).

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/ProviderService.ts around line 1006:
      
      `sendTurn` holds `withThreadLock` while `CursorAdapter.sendTurn` awaits `ctx.acp.prompt`; when Cursor emits `request.opened` or `user-input.requested`, the corresponding `respondToRequest` or `respondToUserInput` call waits on that same lock, so the turn cannot receive its decision and hangs. Release the thread lock before awaiting the interactive provider turn (while preserving any narrower locking needed for routing/state updates).
    6. Thanks for working on this. We hit the same writer-lock failure twice on T3 0.0.39-nightly.20260903.1262 with Codex CLI 0.153.0.

      One extra detail from our cases: an interrupted turn was not required. One source turn had completed normally, and the other had ended after a usage-limit error. The old, idle app-server still held the writer, so switching from direct Codex to Codex Unified failed on thread/resume.

      After stopping the idle source app-server, Unified resumed the same native threads with their complete 9-turn and 10-turn histories.

      Would you mind adding regression coverage for switching after a normal completion and after a provider error such as a usage limit? The handoff in this PR looks like the right fix for both cases.

    7. Note: GPT-5 on behalf of shivam (@shivamhwp).

      Thanks for the detailed work on safe Codex account switching, especially cleanup failures, conversation identity, and stale events.

      We're closing this because Orchestration V2 in #2829 is replacing the implementation this PR changes. We don't plan to add more lifecycle logic to the retiring path.

      If you'd like to continue this work, contributions against the V2 branch are welcome. Please check which failure cases remain there and target those gaps rather than porting the old implementation wholesale. The scenarios and tests you've developed here would be useful for that.

Sign in to join this conversation.