Skip to content

[Linux Desktop 0.147.0] Completed v2 subagents retain full stdio MCP runtimes #38247

Open

Description

@qzhqzh

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_agent workflows

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, and codex-security remained.
  • 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

  1. Configure several global stdio MCP servers.
  2. Start Codex Desktop and keep the same app-server alive.
  3. Run a task that creates subagents with spawn_agent; let them finish normally.
  4. Repeat across several tasks and/or use follow-up/resume flows.
  5. After every child reports a terminal status, count the app-server descendants by MCP command.
  6. 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:

  1. Its resident execution runtime (including stdio MCP children) should be unloaded within a bounded period.
  2. Its logical agent id/path and open spawn edge should remain durable so followup_task / send_input can transparently reload it.
  3. Active turns and pending mailbox input must never be unloaded.
  4. 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

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

  1. added
    bug
    app
    mcp
    subagent
    app-server
    on Aug 12, 2026
  2. github-actions commented on Aug 12, 2026

    @github-actions
    Contributor
  3. BranchManager69 commented on Aug 17, 2026

    @BranchManager69

    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 EMFILE failure 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

    • Codex CLI 0.147.0 / tag rust-v0.147.0 (be6e8eac)
    • Linux x86_64
    • Long-lived codex -c features.code_mode_host=true app-server --listen unix://
    • App-server RLIMIT_NOFILE: soft 1024, hard 1048576
    • Subagent-heavy multi-agent workload with configured and plugin-provided stdio MCP servers

    Exhausted-process snapshot

    At 2026-08-17 01:44:05 UTC, the app-server held 990 / 1024 file descriptors:

    Descriptor type Count
    pipes 593
    live pidfds 198
    sockets 57
    remaining files/event handles 142

    All 198 pidfds pointed to live processes; none pointed to an exited target. The live targets were:

    • 98 plugin MCP node processes
    • 49 configured MCP CLI processes
    • 49 npm MCP proxy processes
    • 1 code-mode host
    • 1 diagnostic shell

    The 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 = 784 descriptors, 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 24 occurred at 01:40:46 UTC while app-server tried to load a thread's MCP configuration. In the surrounding four-minute window, the log database contains 114 No 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:

    • five started one or two seconds after a recorded subagent-thread creation;
    • the corresponding five child rollouts had reached a terminal task_complete or turn_aborted event between about 1 hour 45 minutes and 14 hours 22 minutes before the FD snapshot;
    • one sampled pair did not have a matching retained thread row, so I cannot map every live set to an exact durable thread record after the fact.

    The replacement app-server reproduced the same shape: a later read-only snapshot at roughly 2 hours 6 minutes uptime showed 665 / 1024 descriptors 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 main at commit 1f41cc5d. The lifecycle boundary still appears to be:

    1. Every session creates a thread-owned McpRuntime.
    2. App-server passes every initialized connection into listener attachment for each newly created thread (creation path, subscription path).
    3. The generic 30-minute unload clock exists only while a thread is both inactive and has no subscribers; otherwise there is no unloading target (UnloadingState::unloading_target).
    4. The completion watcher delivers the terminal child result and returns without proactively releasing the resident runtime (completion watcher).
    5. V2 residency already knows how to materialize, shut down, and remove a terminal idle child, but invokes that path while reserving a later residency slot under capacity pressure (residency eviction). The residency registry is scoped per root session tree, not globally across the shared app-server (AgentControl scope).

    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:

    1. Spawn a v2 child with a PID-recording stdio MCP fixture and force that child to start/use the fixture.
    2. Wait for the child to reach a terminal state and for its result to be delivered to the parent, without spawning another child to create capacity pressure.
    3. Assert within a bounded interval that the child execution session is unloaded and the MCP PID has exited.
    4. Send a follow-up to the same logical agent and assert that it reloads, starts a new MCP process, and completes successfully.
    5. Repeat across multiple root session trees under one ThreadManager so 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_NOFILE even 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.

  4. mdliss commented on Oct 16, 2026

    @mdliss

    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/archive followed by thread/unarchive unloaded 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.

    Measurement Before After
    Loaded threads 24 15
    Daemon and descendant processes 262 191
    Aggregate physical footprint 9.335 GiB 7.461 GiB

    Footprint was measured using macOS proc_pid_rusage across 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.

  5. Masu135 commented on Oct 25, 2026

    @Masu135

    Same behavior on Windows desktop (Windows 10, codex-cli 0.163.0, long-lived desktop app-server), with measurements that may help quantify this:

    • The parent thread was unsubscribed at 02:08:37 and its agent loop exited at 02:13:38 (~300 s later), as expected.
    • Its 3 spawned subagents (last activity ~31 h earlier) remained loaded the whole time: no "Agent loop exited" in logs, spawn edge still open, and their full stdio MCP process sets (bun, obsidian-mcp, smart-connections, etc.) stayed alive — 83 processes in total.
    • Of 385 processes sampled at baseline, 110 were still alive 31 h later; the survivors' combined private memory grew from 6.25 GiB to 13.66 GiB over that window (three bun.exe instances grew ~2.0–2.4 GiB each).
    • Other subagents of the same parent were evicted only at the exact second a new sibling was spawned (capacity pressure), never from idling.

    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

  6. ariccio commented on Oct 26, 2026

    @ariccio

    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

    I would also be curious if telling a codex session to close old subagent threads that it no longer needs might free up the memory.

    The account owner selected the scope and controls publication; the measurements, source analysis and wording are Codex's.

  7. jmilrc commented on Oct 27, 2026

    @jmilrc

    Adding a CLI reproduction (codex exec and 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

    • Each spawned v2 subagent starts its own copy of the stdio MCP servers it uses. Here that is a small Python server.
    • The start time of each new set matches the child's session_meta thread_spawn timestamp to within a few seconds.
    • After the child's rollout ends with task_complete, the set stays alive under the parent codex process. The parent still holds the stdio pipes, so the server never sees EOF.
    • One census found 77 server processes under 34 codex parents. 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

    • One parent spawned one child. The child called the same MCP tool 6 times, 30 s apart.
    • Between calls 2 and 3, we sent SIGTERM to that child's own server PID only.
    • Calls 1–2 succeeded. Calls 3–6 all failed with tool call failed for <server>/<tool> — Caused by: Transport closed, and no replacement server was ever spawned.
    • The parent's own set was untouched, and a parent call afterwards succeeded.
    • client_for_call (codex-rs/codex-mcp/src/connection_manager.rs L141 @ rust-v0.163.0) reconnects only on StartupOutcomeError::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.rs L27) delivers the child's result but does not release the child.
    • The runtime is torn down in only four places:
      • close_agent → shutdown_agent_tree → shutdown_live_agent (core/src/agent/control/legacy.rs L50, L109, L9). In v2 the model sees interrupt_agent instead (Rename multi-agent v2 close_agent to interrupt_agent #26994), and that preserves the agent. Our parent model reported that no close_agent tool was available.
      • V2 residency eviction (core/src/agent/control/residency.rs L35). It runs only when a new spawn needs a slot. Capacity is max_concurrent_threads_per_session − 1.
      • The app-server idle unload (app-server/src/request_processors/thread_lifecycle.rs L420), which calls try_evict_v2_thread. It runs only after the thread has had no subscribers and no activity for thread_unload_delay_secs.
      • Parent exit.
    • codex exec and 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.
    • Reduce the default thread unload delay to one minute #57242's 60 s default would not change that, and it is not in 0.165.0 anyway: config_toml.rs still says 1800.
    • Role overrides cannot opt a child out of MCP: AgentRoleOverrides (core/src/agent/role.rs L36) has no mcp_servers field (see Per-agent MCP server scoping: allow subagents to opt out of inherited MCP servers #20135).

    What would fix it

    1. When a child's turn reaches a terminal state, release that child's MCP connections, or drop whatever subscription keeps the idle unload from firing. Restart the connections lazily if the child is resumed.
    2. Reconnect a stdio server whose transport closes after startup, instead of failing every later call with Transport closed.

    Our mitigation until then

    • An external reaper runs every 15 minutes and signals exact PIDs only.
    • It never touches a parent's first set or its newest set.
    • It reaps a set only when all of these hold:
      • the set's CPU time is unchanged across two observations;
      • its pid, ppid, start time and argv are unchanged;
      • exactly one child rollout matches its start time, that rollout ends in task_complete, and it has been unmodified for 30 minutes or more.
    • It rechecks all of that before each signal.
    • The residual risk is a later follow-up to a reaped child: that child loses the tool for the rest of its life, as point 2 above describes.

    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.

  8. Masu135 commented on Oct 30, 2026

    @Masu135

    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 = 300 at the config root.

    Observation (2026-10-30, times UTC+8, from logs_2.sqlite + Win32_Process ancestry):

    • Parent thread A logged Agent loop exited at 17:51 and parent thread B at 17:10. Both unloaded normally after their UI subscriptions went away.
    • At 19:13:57, while nobody was at the machine, both were resumed by requests with ids __slingshot_backend_notification_thread_resume__:<thread_id> (thread_lifecycle: "composing running thread resume response").
    • At that same second the app-server spawned 18 new MCP wrapper roots (70 processes, 3.24 GiB private), i.e. one full stdio MCP set per resumed thread.
    • 3.7 h later (22:54) neither thread had logged another 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.
    • Same day: 8 of 13 completed v2 subagents never logged 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).

  9. WingedGuardian commented on Nov 10, 2026

    @WingedGuardian

    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:

    • Daemon path. Threads started from the VS Code extension run on the shared codex app-server daemon. 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.
    • The 60 s default unload delay (0.166+) did not free them. That is consistent with the threads still having a subscriber.
    • Terminal path, for contrast. A terminal codex TUI 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.

  10. pyousefi commented on Nov 11, 2026

    @pyousefi

    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:

    Time Event
    +6.3 s a1 created; its own Serena started at +10.0 s
    +13.4 s a1's Serena gone, 0.1 s before a2 created at +13.5 s
    +20.4 s a2's Serena gone, 0.1 s before a3 created at +20.5 s
    +29.4 s a3's Serena gone, 0.2 s after a4 created at +29.2 s

    At most one finished child's stdio stack was retained, versus all of them with the default setting. list_agents afterwards showed only a4. The cap counts the root thread, so 2 means one child.

    Parallel spawns above the cap (=3): four spawn_agent calls in a row, each child running sleep 25 before calling Serena. p1 and p2 ran to completion and were not evicted. p3 and p4 failed immediately with collab 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_agent is not in the v2 tool schema (#36211). Across about 151 spawn_agent calls in those sessions there were 0 close_agent calls, so the model has no in-session way to release a child. Until finished children release their runtimes, max_concurrent_threads_per_session is 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Linuxappapp-serverbugmcpperformancesubagent

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions