Repository navigation
Description
Environment
- Codex Desktop on Linux
- Bundled / local CLI:
codex-cli 0.147.0 - Platform:
Linux 6.8.0-137-generic x86_64(Ubuntu 24.04) - Authentication: ChatGPT subscription
- MCP configuration at the time of reproduction: 8 enabled stdio servers plus 4 Streamable HTTP servers
- Long-lived Desktop
app-server - Multi-agent v2 /
spawn_agentworkflows
What issue are you seeing?
Completed subagents can leave their entire stdio MCP runtime resident under the live Desktop app-server. The processes are not zombies and are not reparented to PID 1: every retained MCP launcher/server is still a direct descendant of the same healthy app-server.
On one real workload, after a subagent-heavy task:
- 15 instances each of
context7,github,gitee,playwright, andcodex-securityremained. - The 15 start clusters aligned across unrelated servers, so the growth unit was one complete MCP stack, not one crashing third-party server.
- A sixth stdio MCP was unusually expensive because of its own development logging, amplifying the Codex lifecycle bug but not causing the stack duplication.
- System used memory grew to about 29 GiB; the Desktop cgroup accounted for about 23.9 GiB RSS.
- Sending SIGTERM only to the stale MCP descendants reduced system used memory to about 11 GiB and the Desktop cgroup to about 5.4 GiB. The live task then recreated one healthy current stack, demonstrating that the old stacks were not required for the current task.
Local logs correlate each new process batch with:
spawn_agent / followup_task
-> thread_spawn
-> session_init
-> session_init.mcp_manager_init
-> mcp.runtime.refresh
-> start_server_task
This is related to #12491 and #17832, but the narrower failure mode here is completed v2 subagents retaining live runtimes while their logical agent identity remains resumable. It is not a request to mark the spawn edge closed, and it is not only the already-fixed manager-replacement leak from #18881.
Steps to reproduce
- Configure several global stdio MCP servers.
- Start Codex Desktop and keep the same
app-serveralive. - Run a task that creates subagents with
spawn_agent; let them finish normally. - Repeat across several tasks and/or use follow-up/resume flows.
- After every child reports a terminal status, count the
app-serverdescendants by MCP command. - Observe complete, timestamp-aligned MCP stacks remaining after the child work has completed and memory increasing monotonically.
The problem becomes especially visible with a high-memory stdio server, but it also reproduces as equal instance counts across small, unrelated servers.
Current-main code observation
The current v2 residency path can unload Completed, Errored, or Interrupted threads, preserving their durable logical identity so they can be reloaded on later delivery. However, that unload path is currently driven by a later residency-slot reservation under capacity pressure. The completion watcher delivers the child result to the parent and returns without proactively releasing the now-idle resident thread/runtime.
This can leave completed children holding stdio MCP processes indefinitely when no later spawn forces eviction. Across multiple Desktop tasks, those resident stacks accumulate under the same long-lived app-server.
Recent lazy startup work reduces how many MCPs a child starts, but any MCP actually started by the child still needs an idle release path.
Expected behavior
After a v2 subagent reaches a terminal status, its result has been delivered, its active turn is cleared, and its mailbox is empty:
- Its resident execution runtime (including stdio MCP children) should be unloaded within a bounded period.
- Its logical agent id/path and open spawn edge should remain durable so
followup_task/send_inputcan transparently reload it. - Active turns and pending mailbox input must never be unloaded.
- Repeating completed subagent runs should return MCP process counts and RSS near the idle baseline instead of growing monotonically.
A regression test should use a PID-recording stdio MCP fixture, verify that the process exits after terminal idle, then send a follow-up and verify that the same logical agent reloads and can start/use MCP again.
Related issues / changes
- Codex.app GUI: MCP child processes not reaped after task completion — 1300+ zombies, 37GB memory leak #12491 — broad Desktop MCP child cleanup tracking; latest maintainer guidance asks distinct bugs to be filed separately
- Regression: Playwright MCP stdio processes still leak after #16895 fix — 213 orphaned pairs, 13.6 GB RSS #17832 — Playwright stdio processes retained after subagents
- Subagents leak stdio MCP helper trees in Codex App; xcodebuildmcp and chrome-devtools-mcp accumulate indefinitely #17574 — subagent MCP helper process trees
- MCP server processes leak: per-thread processes never cleaned up (9+ GB RSS) #30408 — closed/archived threads retaining MCP processes
- [macOS App] Completed subagents stay open in thread_spawn_edges and restore stale MCP stacks #33700 — persisted subagent state / rehydration observations (logical edge lifetime is related but should not be conflated with runtime residency)
- MCP child processes leak when McpConnectionManager is replaced #18881 / Terminate stdio MCP servers on shutdown to avoid process leaks #19753 — explicit manager/client shutdown fixes
- feat: add v2 agent residency lru #26632 and Avoid reopening v2 descendants on resume #26997 — durable v2 unload/reload behavior
- Start required cached MCP servers lazily for subagents #38217 — lazy startup of required cached MCP servers for subagents
I am preparing a minimal patch with tests. I understand external contributions are invitation-only; if maintainers agree that proactively releasing terminal-idle v2 runtimes is the right layer, please explicitly invite the PR and I will open it against main.
Activity
github-actions commentedon Aug 12, 2026
Potential duplicates detected. Please review them and close your issue if it is a duplicate.
Powered by Codex Action
BranchManager69 commentedon Aug 17, 2026
Additional Linux 0.147.0 reproduction: retained v2 MCP runtimes exhausted the app-server FD table
I independently reproduced this on Linux and traced the resulting
EMFILEfailure down to the app-server's retained per-thread MCP process sets. This connects the terminal-subagent residency problem in this issue to the descriptor-exhaustion symptom in #26984.Environment
0.147.0/ tagrust-v0.147.0(be6e8eac)codex -c features.code_mode_host=true app-server --listen unix://RLIMIT_NOFILE: soft1024, hard1048576Exhausted-process snapshot
At
2026-08-17 01:44:05 UTC, the app-server held990 / 1024file descriptors:All 198 pidfds pointed to live processes; none pointed to an exited target. The live targets were:
nodeprocessesnpmMCP proxy processesThe 196 MCP children formed 49 copies of the same four direct-child roots. The parent held approximately three stdio pipe ends plus one pidfd per MCP child:
196 × 4 = 784descriptors, about 79% of its entire FD table. This was not 990 programs, zombie handles, or machine-wide file-table exhaustion. The system file table was healthy at 30,418 allocated handles with a practically unbounded configured maximum.The first recorded
os error 24occurred at01:40:46 UTCwhile app-server tried to load a thread's MCP configuration. In the surrounding four-minute window, the log database contains 114No file descriptors available (os error 24)records across MCP refresh, skill/plugin reads, thread-store writing, and session handling.Thread/process correlation
During this app-server's approximately 27-hour lifetime, the local thread database recorded 232 new threads, 224 of them spawned child threads. This is not a claim that all 224 still had a runtime at the final snapshot; the live process census showed 49 retained MCP sets.
For six retained MCP process pairs sampled by start time:
task_completeorturn_abortedevent between about 1 hour 45 minutes and 14 hours 22 minutes before the FD snapshot;The replacement app-server reproduced the same shape: a later read-only snapshot at roughly 2 hours 6 minutes uptime showed
665 / 1024descriptors and 127 direct children. That later rate should not be treated as an ordinary-user baseline because this investigation and other concurrent chats themselves loaded additional sessions; it only shows that the per-session multiplication is repeatable.Source trace
I traced the running tag and rechecked current
mainat commit1f41cc5d. The lifecycle boundary still appears to be:McpRuntime.UnloadingState::unloading_target).AgentControlscope).Actual session shutdown explicitly shuts down the MCP runtime (shutdown path). I also found successful process-shutdown events elsewhere in the same app-server lifetime. My read is therefore that the primary failure here is missing global eviction/proactive terminal-idle release, not evidence that every individual stdio teardown is broken.
The newer cached-tool lazy-start work reduces how many servers a subagent starts, but it does not release a runtime after that child actually starts an MCP server.
Proposed acceptance test
A regression test should:
ThreadManagerso the per-root residency cap cannot hide unbounded app-server-wide growth.The smallest behavior-preserving fix appears to be proactive terminal-idle unloading using the existing residency teardown path while retaining the durable agent identity for reload. A short bounded grace period could avoid racing an immediate follow-up. Separately, a global app-server MCP/session resource budget would keep one process from approaching
RLIMIT_NOFILEeven when many roots remain open.Would maintainers prefer the first change in the v2 completion/residency path, or should terminal subagent listener subscriptions be detached in app-server instead? I am happy to prepare a targeted PR and tests if invited under the repository's contribution policy.
Related: #30408, #26984, #37870.
mdliss commentedon Oct 16, 2026
Adding macOS / shared-daemon evidence on Codex CLI and app-server 0.163.0, collected 2026-10-16.
Five regular conversations were open, but 24 threads were loaded, including 19 subagents. Nine were completed, persisted leaf subagents that had been inactive for at least 60 minutes, with unloaded parents and no queued work or background terminals.
Targeted native
thread/archivefollowed bythread/unarchiveunloaded those nine while leaving their saved conversations unarchived. Hashes of their indexed persisted history were unchanged, and all five active regular conversations remained on their same in-progress turns. No daemon restart or installed-binary patch was used.Footprint was measured using macOS
proc_pid_rusageacross the daemon and its descendants. Seventy-three original PIDs exited and two new processes appeared during the interval. Other work continued concurrently, so this is an aggregate before/after comparison, not exact per-agent memory attribution.The 0.163.0 source still passes every initialized connection into new-thread listener attachment, attaches each connection, discards unrelated TUI notifications, and requires zero subscribers for idle unloading. This matches the earlier source analysis here. Live per-client subscriber ownership was not exposed, so these observations do not prove which client retained each runtime.
A useful regression would keep unrelated client B connected after client A's child completes and A disconnects, verify that the child runtime and owned MCP processes unload, then verify a follow-up can reload the same saved agent with its history intact. Active turns and queued work must remain protected.
Masu135 commentedon Oct 25, 2026
Same behavior on Windows desktop (Windows 10, codex-cli 0.163.0, long-lived desktop app-server), with measurements that may help quantify this:
open, and their full stdio MCP process sets (bun, obsidian-mcp, smart-connections, etc.) stayed alive — 83 processes in total.This matches the reading earlier in this thread that idle unload only counts down after the last subscriber unsubscribes, and that resident subagents are otherwise evicted only under capacity pressure: the subagents' spawn edges never get unsubscribed, so they never unload.
Expected: terminal-idle subagents released after a grace period or when the parent unloads, or a documented non-archiving release operation.
Related: #55787
ariccio commentedon Oct 26, 2026
Disclosure: This comment was generated by Codex, operating fully autonomously in the research and drafting of this comment.
On macOS 27.0.1 / Apple Silicon, a long-running parent conversation using CLI and managed app-server 0.164.0 retained 17 sets of four stdio MCP servers: 136 processes, with 9.25 GiB aggregate reported footprint.
Fifteen process cohorts were associated by timestamps with children whose latest model turns had completed. Those cohorts accounted for 8.14 GiB of that footprint. Twelve of the fifteen belonged to children with no recorded tool calls to any of the four server families.
The practical missing control is a supported, conditional way to release eligible child runtimes while preserving their logical identity for follow-up. #55787 covers why a completed model turn alone is insufficient to decide eligibility. The two-client subscription mechanism has already been reproduced on this version in #30408.
Measurements and the limits of the process-to-child associations
The four families were MongoDB MCP, Google Cloud Observability MCP, MobileBuildMCP, and Apple Docs MCP. Each set contained four npm launchers and four server processes.
Process counters were captured on October 26 at 16:29 UTC; child-turn status at 16:33 UTC. The fleet's 9.25 GiB footprint included 7.79 GiB of logical compressed-or-swapped accounting. Summed RSS was 1.51 GiB. These counters overlap; they are not exact per-process SSD swap or immediately recoverable physical RAM.
Captured histories for all 18 ordinary children contained no MongoDB or Google Cloud MCP tool calls. The twelve-of-fifteen figure excludes children with recorded calls to any of the four families. Initialization and discovery traffic are outside that call count.
The PID-to-child associations use startup timing and recorded child activity, rather than authoritative owner telemetry. No live subscriber census or release experiment was performed, so this does not establish each runtime's retention cause or full release eligibility.
Prompt that motivated the investigation
The account owner selected the scope and controls publication; the measurements, source analysis and wording are Codex's.
jmilrc commentedon Oct 27, 2026
Adding a CLI reproduction (
codex execand the interactive TUI, not Desktop) on codex-cli 0.163.0, macOS arm64. It includes one kill experiment that the thread does not have yet, plus source pointers.Observed
session_metathread_spawntimestamp to within a few seconds.task_complete, the set stays alive under the parentcodexprocess. The parent still holds the stdio pipes, so the server never sees EOF.codexparents. 24 of those parents held 2–6 sets each, and the oldest child sets were about 16 h old. The 1800 s default unload delay should have released them long before that.Kill experiment: an external reaper cannot touch a child that is mid-turn
tool call failed for <server>/<tool> — Caused by: Transport closed, and no replacement server was ever spawned.client_for_call(codex-rs/codex-mcp/src/connection_manager.rsL141 @ rust-v0.163.0) reconnects only onStartupOutcomeError::Failed. A transport that closes after startup stays closed for the life of the thread, which looks like CLI session loses stdio MCP connections after initial successful calls; fresh codex exec still works #16899.Release paths at rust-v0.163.0
notify_parent_of_terminal_turn(core/src/agent/control/completion.rsL27) delivers the child's result but does not release the child.close_agent→shutdown_agent_tree→shutdown_live_agent(core/src/agent/control/legacy.rsL50, L109, L9). In v2 the model seesinterrupt_agentinstead (Rename multi-agent v2 close_agent to interrupt_agent #26994), and that preserves the agent. Our parent model reported that noclose_agenttool was available.core/src/agent/control/residency.rsL35). It runs only when a new spawn needs a slot. Capacity ismax_concurrent_threads_per_session − 1.app-server/src/request_processors/thread_lifecycle.rsL420), which callstry_evict_v2_thread. It runs only after the thread has had no subscribers and no activity forthread_unload_delay_secs.codex execand the TUI embed the app-server in process (app-server-client), so the idle-unload path should apply here too. These children outlive it by hours, so something is evidently still subscribed to them.config_toml.rsstill says 1800.AgentRoleOverrides(core/src/agent/role.rsL36) has nomcp_serversfield (see Per-agent MCP server scoping: allow subagents to opt out of inherited MCP servers #20135).What would fix it
Transport closed.Our mitigation until then
task_complete, and it has been unmodified for 30 minutes or more.Related: #25015, #34658, #42000.
Disclosure: an AI coding agent drafted this comment from our process census, rollout files and the 0.163.0 source; a second reviewer checked it against the source before posting.
Masu135 commentedon Oct 30, 2026
Follow-up from Windows desktop, now on codex-cli 0.164.0 (my earlier comment was on 0.163.0). The completed-subagent retention is unchanged, and I found a second path that bypasses the idle-unload timer: backend-notification resumes of already-unloaded parent threads.
Setup: Win10, long-lived desktop app-server,
thread_unload_delay_secs = 300at the config root.Observation (2026-10-30, times UTC+8, from
logs_2.sqlite+ Win32_Process ancestry):Agent loop exitedat 17:51 and parent thread B at 17:10. Both unloaded normally after their UI subscriptions went away.__slingshot_backend_notification_thread_resume__:<thread_id>(thread_lifecycle: "composing running thread resume response").Agent loop exited, and all 70 processes were still alive. No window ever showed these threads, so no client subscribes and later unsubscribes. As described in this issue, the unload countdown only starts after the last subscriber is removed, so the 300 s delay never begins for them.Agent loop exited. Total app-server descendants: 302 processes / 12.5 GiB private on a 32 GiB machine (3.3 GiB physical free).Expected: a thread resumed by a backend notification with no UI subscriber should be eligible for the idle unload delay, or the notification path should release its runtime after handling.
Mitigation on my side: archiving the idle threads, and disabling a rarely used MCP server that was the heaviest part of each per-thread set (one Bun process, 0.5–0.9 GiB each, growing over time).
Related: #55141 (desktop per-thread tool server accumulation), #55787 (safe completed-child release).
WingedGuardian commentedon Nov 10, 2026
Same retention on Linux, through the VS Code extension and the shared daemon (0.167.0). One data point that may help narrow it down:
codex app-serverdaemon. There, each subagent thread starts its own full set of stdio MCP servers. Finished subagents kept those sets alive for hours while the parent chat stayed open: one parent spawned about 50 subagents in 5.5 h, and about 47 MCP processes (~8 GB RSS) built up before we stopped the app-server.codexTUI on the same machine, both the 0.166 CLI and the managed 0.167 binary, ran embedded. Its subagents shared the parent's MCP servers, nothing built up, and exiting the TUI freed everything.So the per-subagent sets and their retention look specific to the daemon/app-server path that editor clients use.
pyousefi commentedon Nov 11, 2026
Measurements on codex-cli 0.167.1 (Linux x86_64) for the capacity-pressure eviction mentioned above. It currently works as a bounded mitigation, and it is safe for running agents.
Sequential spawns with
-c features.multi_agent_v2.max_concurrent_threads_per_session=2. The root spawns a1 through a4 in sequence. Each child calls Serena once and finishes before the next is spawned:At most one finished child's stdio stack was retained, versus all of them with the default setting.
list_agentsafterwards showed only a4. The cap counts the root thread, so 2 means one child.Parallel spawns above the cap (
=3): fourspawn_agentcalls in a row, each child runningsleep 25before calling Serena. p1 and p2 ran to completion and were not evicted. p3 and p4 failed immediately withcollab spawn failed: agent thread limit reached. Eviction therefore only takes finished children, and running ones are protected.Why this matters for the shared daemon: in VS Code extension sessions on the shared daemon,
close_agentis not in the v2 tool schema (#36211). Across about 151spawn_agentcalls in those sessions there were 0close_agentcalls, so the model has no in-session way to release a child. Until finished children release their runtimes,max_concurrent_threads_per_sessionis the only control I found that bounds the retained stacks. The cost is parallel fan-out width.Also observed: the root thread starts configured stdio servers eagerly. A child starts its own copy lazily, on its first call to that server. Children that never call a server never start it.
feat(sentinel): deterministic stop for a Codex daemon's MCP servers (#…