Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): recover Codex sessions after process exits #12922

Closedmatheustimbo(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/12922/headopened View on GitHub

Summary

Fixes #12904. A Codex App Server killed by SIGKILL left the T3 thread bound to a closed runtime. Every subsequent send failed with ProviderAdapterSessionClosedError until the T3 server was restarted or the session was otherwise replaced.

This PR combines two complementary fixes already proposed upstream:

  • #10874 handles failure of child.exitCode on signal termination, clears the active turn, and emits session/exited.
  • #10799 removes an exited runtime from the Codex adapter's session map and releases its resources, while protecting a replacement session for the same thread.

The original authors and commits are preserved. This branch also closes lifecycle races: observers see the session removed before its terminal event; an explicit stop emits one graceful terminal event; a process exit during startup fails the start; and pending teardown remains covered during adapter shutdown.

A real-process integration regression kills the Codex peer with SIGKILL, checks that hasSession is false and listSessions is empty, then resumes the same native thread and sends a new turn. The interrupted turn is not replayed. A separate test closes the adapter as the terminal event arrives and verifies cleanup.

Related: #10798.

Validation

  • Focused Codex adapter and runtime integration tests: 71 passed.
  • bun run fmt: passed.
  • bun run lint: passed, with existing repository warnings outside these files.
  • bun run typecheck: passed across 15 workspaces.
  • git diff --check: passed.

No live server update is included.

Summary by CodeRabbit

  • Bug Fixes
    • Improved recovery when a Codex session exits unexpectedly, including resuming sessions with saved progress.
    • Prevented stale or duplicate exit notifications during session replacement and cleanup.
    • Ensured replacement sessions can start without being blocked by a previously failed session.
    • Improved exit status reporting for normal closures, unexpected terminations, and non-zero exit codes.
    • Ensured intentional stops report a graceful session exit consistently.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. @@ -2403,4 +2403,11 @@
      24032403 );
      24042404
      24052405 yield* child.exitCode.pipe(
      2406- Effect.flatMap((exitCode) =>
      2406+ Effect.match({
      2407+ onFailure: (cause) => {
      2408+ const diagnostic = cause instanceof Error ? cause.message : String(cause);
      2409+ return {
      2410+ status: "error" as const,
      2411+ message: `Codex App Server exited unexpectedly: ${diagnostic}.`,
      2412+ };
      2413+ },
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      This exposes arbitrary failure text through the provider event, which can leak command output, paths, or other unbounded defect details to downstream UI/RPC consumers. Keep the event message normalized and bounded; the underlying failure remains available in the Effect cause for diagnostics.

      Suggested change
      2407- onFailure: (cause) => {
      2408- const diagnostic = cause instanceof Error ? cause.message : String(cause);
      2409- return {
      2410- status: "error" as const,
      2411- message: `Codex App Server exited unexpectedly: ${diagnostic}.`,
      2412- };
      2413- },
      2407+ onFailure: () => ({
      2408+ status: "error" as const,
      2409+ message: "Codex App Server exited unexpectedly.",
      2410+ }),
      Posted via Macroscope — Effect Service Conventions
    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR adds substantial Codex session recovery and asynchronous lifecycle behavior across production adapter and runtime paths, changing existing start, stop, shutdown, and terminal-event semantics. Its exit handling also forwards unbounded process-failure diagnostics to downstream events, creating a concrete data-exposure concern that requires human review.

      Notes:

      • Diff unchanged. Approvability was decided on eligibility alone.
      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Review Change StackReview Change Stack

      Understand this PR’s impact

      Explore downstream dependencies and potential security impact with Blast Radius.

      View blast radius →

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: Repository: pingdotgg/t3code/.coderabbit.yaml

      Review profile: CHILL

      Plan: Advanced

      Run ID: 0c6df8bb-120f-4759-8957-b0f88065bc13

      📥 Commits

      Reviewing files that changed from the base of the PR and between 1de563c1491c7d82563e4553bf5bf689ce6adbb9 and 67b5747e007235a433b1ba1c4bcd4f6507e1267c.

      📒 Files selected for processing (4)
      • apps/server/src/provider/Layers/CodexAdapter.test.ts
      • apps/server/src/provider/Layers/CodexAdapter.ts
      • apps/server/src/provider/Layers/CodexCollabRuntime.integration.test.ts
      • apps/server/src/provider/Layers/CodexSessionRuntime.ts

      Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


      📝 Walkthrough

      Walkthrough

      The Codex runtime now reports unexpected process exits. The adapter removes exited sessions, separates terminal events from resource teardown, and waits for pending teardown. Tests cover startup exits, process recovery, exit statuses, and intentional closes.

      Changes

      Codex exit recovery

      Layer / File(s)Summary
      Runtime exit status handling
      apps/server/src/provider/Layers/CodexSessionRuntime.ts
      Failed child exits now produce error status and diagnostic messages. Numeric exit codes retain their closed or error mappings.
      Adapter session teardown
      apps/server/src/provider/Layers/CodexAdapter.ts
      The adapter tracks teardown state, filters stale events, removes exited sessions, publishes graceful exits, and releases resources through an idempotent teardown path.
      Lifecycle and recovery validation
      apps/server/src/provider/Layers/CodexAdapter.test.ts, apps/server/src/provider/Layers/CodexCollabRuntime.integration.test.ts
      Tests cover startup exits, replacement sessions, delayed stopAll teardown, SIGKILL recovery, resume requests, numeric exit statuses, and intentional close behavior.

      Priority: ➖ Normal

      Estimated code review effort: 4 (Complex) | ~45 minutes

      Change: Bug fix · Severity of issue fixed: Medium

      Sequence Diagram(s)

      sequenceDiagram
        participant CodexAppServer
        participant CodexSessionRuntime
        participant CodexAdapter
        participant ResumedRuntime
        CodexAppServer->>CodexSessionRuntime: exit unexpectedly
        CodexSessionRuntime->>CodexAdapter: emit session/exited with error status
        CodexAdapter->>CodexAdapter: remove session and release resources
        ResumedRuntime->>CodexAdapter: resume thread with saved cursor
        CodexAdapter->>CodexAppServer: send thread/resume with excludeTurns true

      Suggested reviewers: t3dotgg, juliusmarminge

      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 4 files.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly and concisely describes the primary change: recovering Codex sessions after the App Server process exits.
      Description check✅ PassedThe description is detailed, on-topic, and explains the problem, implementation, validation, and scope. It uses Summary and Validation headings instead of the template's What Changed, Why, and Checkli…
      Linked Issues check✅ PassedThe changes satisfy the coding requirements in issue #12904. CodexSessionRuntime now handles failed exit-status retrieval and emits session/exited for unexpected process termination, including `SI…
      Out of Scope Changes check✅ PassedThe reported changes stay within issue #12904. Runtime exit handling, adapter cleanup, startup-failure handling, teardown ordering, and shutdown behavior directly support reliable recovery and resourc…
      • Fix all pre-merge checks with AI
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR

      Comment `@coderabbitai help` to get the list of available commands.
    5. juliusmarminge added labelsmacroscope-review

    6. Note

      Grok responding on behalf of Julius.

      Closing as superseded — #12904 was completed via #2829, so this fix PR is no longer needed. Thanks for the work.

    7. juliusmarminge closed this

Sign in to join this conversation.