fix(server): recover Codex sessions after process exits #12922
main fromrefs/pull/12922/head·opened View on GitHubSummary#
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.exitCodeon signal termination, clears the active turn, and emitssession/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
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -2403,4 +2403,11 @@24032403 );2404240424052405 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+ },
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 change2407- 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 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.
Understand this PR’s impact
Explore downstream dependencies and potential security impact with 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.tsapps/server/src/provider/Layers/CodexAdapter.tsapps/server/src/provider/Layers/CodexCollabRuntime.integration.test.tsapps/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.tsFailed 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.tsThe 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.tsTests cover startup exits, replacement sessions, delayed stopAllteardown, 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 trueSuggested reviewers:
t3dotgg,juliusmarminge🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring 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 name Status Explanation Title check ✅ Passed The title clearly and concisely describes the primary change: recovering Codex sessions after the App Server process exits. Description check ✅ Passed The 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 ✅ Passed The changes satisfy the coding requirements in issue #12904.CodexSessionRuntimenow handles failed exit-status retrieval and emitssession/exitedfor unexpected process termination, including `SI…Out of Scope Changes check ✅ Passed The 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.juliusmarminge added labelsmacroscope-review
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed