Repository navigation
Description
Summary
Codex app-server appears to start additional stdio MCP process stacks when spawning subagents. After the subagents complete and close_agent is called, some MCP child process trees remain alive under the long-lived codex app-server.
This causes process count and memory usage to grow roughly linearly with subagent usage. On my machine this previously caused heavy swap pressure and an OOM/desktop session collapse.
I also created a Linux-only diagnostic/workaround tool that helped confirm the source of the growth:
Environment
- Codex CLI:
codex-cli 0.128.0 - OS: Ubuntu 24.04.4 LTS
- Kernel: Linux 6.17.0-29-generic x86_64
- Machine: 16 GB RAM, 16 GB swap, 8 CPU cores
- Surface: Codex app-server / IDE integration
- Reduced MCP set during repro:
- Serena
- Telegram
- YouTrack via
mcp-remote
Heavy MCP servers such as Playwright, Context7, and Slack were disabled for the reduced repro.
Reproduction Pattern
- Start Codex app-server with stdio MCP servers enabled.
- Take a baseline process/memory snapshot of the
codex app-serverchild tree. - Spawn subagents with trivial tasks that do not use MCP tools.
- Wait for the subagents to complete.
- Call
close_agentfor each subagent. - Wait briefly for Codex cleanup.
- Check the
codex app-serverchild process tree again. - Optionally repeat with larger subagent batches.
Small Live Repro: 3 Subagents
Before spawning 3 trivial subagents, the selected app-server had:
23descendants6MCP launcher roots- RSS around
203 MiB
After spawning 3 subagents:
74descendants24MCP launcher roots- RSS around
3.7 GiB - Snapshot report showed
18new MCP launcher roots /50new processes
After all 3 subagents completed and close_agent was called for each one, Codex cleaned up part of the process tree, but the snapshot still showed:
9MCP launcher roots33processes
A dry-run with codex-mcp-clean cleanup --root-pid <PID> identified those remaining MCP subtrees. Running the same command with --kill terminated them:
TERM sent to 33 processes; SIGKILL fallback attempted for 0
After cleanup:
- snapshot report returned to
launcher_roots=0,processes_total=0 - app-server returned to about the previous baseline MCP footprint
- available memory increased back from about
4.7 GiBto about6.8 GiB
Larger Repro: 10 + 10 Subagents
In an earlier larger run, before the batch:
- app-server descendants:
46 - total RSS under app-server: about
2.9 GiB - total PSS under app-server: about
1.6 GiB - MCP bundles: about
4
After spawning and closing 10 subagents:
- app-server descendants:
156 - total RSS: about
7.9 GiB - total PSS: about
3.6 GiB - MCP bundles: about
14
After spawning and closing another 10 subagents:
- app-server descendants:
266 - total RSS: about
11.7 GiB - swap usage grew to about
6.4 GiB - MCP bundles: about
24
The growth matched the number of spawned subagents.
Expected Behavior
After a subagent finishes and is closed:
- MCP processes created for that subagent should be terminated, or
- subagents should reuse a shared project/app-server MCP process pool, or
- Codex should allow subagents to start without inheriting all parent-session MCP servers.
Repeated subagent usage should return to a bounded baseline instead of accumulating MCP process stacks.
Actual Behavior
Subagent creation starts additional MCP process stacks, even when the subagent task does not call MCP tools.
After subagent completion and close_agent, some MCP child process trees remain alive under the app-server, causing process and memory growth.
Diagnostic / Workaround Tool
I wrote a small Linux-only diagnostic/workaround tool:
It snapshots a selected Codex app-server PID and later reports or kills only MCP launcher subtrees created after that snapshot.
This is not a proposed upstream fix, but it helped confirm that stale MCP child trees are the source of the memory growth. It also avoids touching other Codex app-server PIDs.
Related Issues
This looks related to the same defect class as:
- Subagents leak stdio MCP helper trees in Codex App; xcodebuildmcp and chrome-devtools-mcp accumulate indefinitely #17574
- Regression: Playwright MCP stdio processes still leak after #16895 fix — 213 orphaned pairs, 13.6 GB RSS #17832
- Codex Desktop should use a project-scoped MCP process pool instead of starting MCP per session #20883
- MCP servers eagerly start per session, causing headed browser MCP processes to accumulate #21984
- codex-cli app-server (Linux) leaks chrome-devtools-mcp child trees on JSON-RPC transport close #24347
I am opening this separately because this is a Linux app-server reproduction with a reduced MCP set and controlled before/after measurements.
Happy to help with more testing or open a PR if the Codex team wants an external contribution for this fix.
Activity
Keesan12 commentedon Jun 6, 2026
tombelieber commentedon Jul 13, 2026
Confirming the same leak on macOS — the mechanism described here is not Linux-specific. Evidence below from the ChatGPT desktop app's bundled app-server.
Environment
26.707.62119, runningcodex -c features.code_mode_host=true app-serverchrome-devtools-mcp,@upstash/context7-mcp,xcodebuildmcp(via build-ios-apps plugin), all spawned asnpx <pkg>@latestObservation (app-server pid 55230, uptime ~47 min at capture)
Six complete generations of MCP server sets were alive simultaneously as children of the app-server — apparently one per thread/subagent, never reaped after completion. Three sets were spawned within 7 seconds of each other (parallel subagents):
Each set = 3
npm execwrapper processes + 3 actual server processes ≈ 600–900 MB RSS. At capture the machine had 52 node processes totalling ~5 GB RSS, the majority of them these leaked sets; swap was at 3.2/4 GB.Related datapoint: a standalone
@openai/codexCLI process (npm install, v24.13.1 node) had been orphaned headless (PPID 1, no TTY, idle) for 9.7 days, holding its full MCP server set alive the entire time — consistent with #28794 and the accumulation reported for macOS in #25744.Impact beyond memory: because each set is spawned via
npx <pkg>@latest, every leaked-then-respawned generation also performs a fresh npm registry resolution, adding CPU burst and network churn on every thread start.Workarounds we verified: quitting the ChatGPT app reaps all leaked sets; pinning MCP commands to globally-installed binaries (instead of
npx @latest) reduces per-set cost and spawn time but does not stop the leak itself.dianshili commentedon Jul 17, 2026
Deterministic root-cause closure on current macOS Desktop build
I reproduced and source-traced this on the current macOS Desktop package. The visible symptom contains two separate lifecycle failures:
killpg(SIGTERM)can returnEPERM; the current local-process terminator then suppresses escalation and permanently marks the handle terminated, so that MCP group may survive.This is a resource/lifecycle leak (unbounded retention), not evidence of a single allocator leak inside one Node process.
Environment
26.5.2(25F84), Apple silicon / arm6426.715.21425, build5488codex-cli 0.145.0-alpha.18rust-v0.145.0-alpha.18, commitf84f9a6406cc55b210395f71b4c6aed236fc7ebbSource-level causal chain
A. Every thread/session eagerly starts its own MCP stack
Sessionowns a session-local MCP manager. The source even contains aTODOto extract session state for sharing between subagents:session.rsL1035-L1100.During session construction, Codex calls
McpConnectionManager::new(...)before any model turn or MCP tool call:session.rsL1211-L1263. The manager iterates all enabled servers and starts them eagerly:connection_manager.rsL128-L225.Therefore the cost is:
loaded root sessions + resident subagent sessions×all enabled stdio MCP serversThis happens even when an agent never invokes an MCP tool.
B. V1 completion does not end the child session
The V1 completion watcher waits for a final status and notifies the parent, but it does not call
shutdown_live_agent,remove_thread, or release the registry entry:control.rsL431-L518.Actual V1
close_agentis a different path and explicitly sendsOp::Shutdown, waits, removes the thread, forgets residency, and releases the registry entry:legacy.rsL3-L25.So “agent completed” and “agent session/MCP runtime shut down” are not the same event.
C. V2 intentionally keeps completed agents resident
V2 stores resident subagents in an
AgentControl-scopedVecDeque. It shuts down an unloadable completed/errored/interrupted agent only when a later reservation finds that this root session's residency capacity is full and LRU eviction runs:residency.rsL79-L149,residency.rsL216-L230.The cap is derived from
max_concurrent_threads_per_session, not a global Desktop/app-server process or memory budget:config/mod.rsL1462-L1475.This behavior was intentionally introduced by PR #26632. PR #26994 then renamed the V2 model-facing
close_agentoperation tointerrupt_agentspecifically so the agent remains registered and reusable.The design is coherent for durable logical identity, but it accidentally couples logical durability to a heavyweight live MCP runtime. With many root tasks, each root can remain under its per-session cap while the app-server's global process/RSS total grows without a bound.
D. Desktop unsubscribe also retains the whole session for 30 minutes
The app-server contract explicitly says that
thread/unsubscribekeeps the thread loaded for 30 minutes after the last subscriber/activity:app-server READMEL162.Keeping lightweight thread state resident may be reasonable; keeping every session's eager stdio MCP processes resident for the same window is the expensive coupling.
Isolated black-box reproduction
I used a separate temporary
CODEX_HOMEand a separate app-server. I did not touch the user's live app-server or tasks.Configuration:
Observed direct children of the isolated app-server:
All five
thread/unsubscribecalls returnedstatus: "unsubscribed". A subsequentthread/loaded/liststill returned all five IDs, and all five MCP PIDs remained alive.Control test: I started one additional persisted thread, producing a sixth MCP child.
thread/deletechanged that thread tonotLoadedand immediately reaped exactly its corresponding MCP PID; the five unsubscribed ephemeral sessions and their five MCP children remained. Finally exiting only the isolated app-server reaped all five remaining diagnostic children.This separates the questions cleanly:
The explicit shutdown implementation does call the MCP manager's shutdown path:
handlers.rsL597-L615,connection_manager.rsL461-L472.Field corroboration (sanitized)
In one live app-server snapshot I counted 81 repeated, session-shaped helper bundles. Seventy-six shared one workload cwd. Each complete bundle had the same shape: one Node REPL plus four plugin MCP servers. The local spawn graph contained 7,847 closed and 1,113 open edges; one high-fanout workload had 6,414 closed and 120 open edges across five root parents.
I am not treating an open graph edge as proof that a process is live. The live-process conclusion comes from the OS process tree; the graph counts only corroborate the exposure pattern and show why a per-root cap cannot bound a long-lived desktop globally.
Secondary cleanup defect:
EPERMbecomes a silent terminal stateLocal stdio servers are launched in their own process group:
stdio_server_launcher.rsL263-L280.On shutdown, if
terminate_process_group()errors, the implementation logs a warning and setsshould_escalate = false, so no delayed SIGKILL is attempted:stdio_server_launcher.rsL327-L344. The outer handle has already set itsterminatedatomic and returnsOk(())for the local path:stdio_server_launcher.rsL385-L404.On this exact build I found four warnings with the exact shape:
This is not needed to explain the primary accumulation above, but it can explain survivors after a genuine
close_agent/shutdown attempt. The origin of the intermittent macOSEPERMis not yet isolated; the confirmed bug is that the error is swallowed, prevents fallback, and makes the handle non-retryable.Why PR #19753 did not fully solve this
PR #19753 correctly added explicit MCP shutdown and process handles. The current explicit deletion test proves that path can work. The remaining primary gap is when shutdown is invoked: ordinary agent completion, V2 durable residency, and app-server unsubscribe intentionally retain the session, so the new shutdown method is never reached.
Version attribution
This is not introduced by Desktop build 5488.
I downloaded the official build 5484 package and compared it with the installed 5488 package:
codex-cli 0.145.0-alpha.18arm64;codexbinaries are byte-for-byte identical through the complete executable payload up to theLC_CODE_SIGNATUREoffset (262,827,104); only the signature region differs;thread/loaded/list,thread/unsubscribe,thread/read, andthread/listdiffers in only 138 bytes, all of which are generated import/source-map filename hashes; the lifecycle logic is identical;The same defect family is documented on much older versions in #17832 and this issue. The recent amplification point is the June 8 V2 durable-residency/interrupt design in PRs #26632 and #26994, combined with larger plugin MCP sets and many simultaneously loaded/restored root tasks. It is a long-standing lifecycle defect made more expensive and easier to trigger, not a one-day 5488 regression.
As of current
maincommit315195492c80fdade38e917c18f9584efd599304, the relevant completion, residency, manager-shutdown, and local-process-terminator files retain the same behavior.Suggested fix boundary
Session::new().killpgfailure is surfaced and retried/fallback-cleaned rather than reported as success.Evidence boundary
The primary mechanism is deterministically confirmed by exact release source, a minimal isolated reproduction, version-to-version binary/chunk comparison, and the live process-tree shape. The intermittent cause of macOS
EPERMis the only part I am leaving as an explicitly separate unresolved question; its error-handling defect is confirmed in source.m13v commentedon Jul 17, 2026
this is the fan-out-inherits-everything pattern. each subagent forks the parent's full stdio MCP set at spawn, so process count tracks how wide you fan out, not whether the task ever calls a tool. the leak is a second bug stacked on that: close_agent reaps the agent but the child stdio trees hang off a different lifecycle, so they outlive it. the shared per-project pool in your expected-behavior list kills both, spawn the servers once, hand subagents handles, nothing to reap on close. linear RSS growth is the tell that spawn and teardown aren't symmetric.
krutftw commentedon Jul 30, 2026
Confirming the same failure mode on Windows 11 Codex Desktop. This appears to be cross-platform session/MCP-runtime retention rather than a Linux-only problem.
Environment
10.0.26100OpenAI.Codex 26.721.11231.0Read-only field snapshot
Snapshot taken 2026-07-30 10:33 AWST while active tasks were left untouched:
codex app-servertree (child ofChatGPT.exe): approximately 345 processes, 17.22 GiB private bytes, and 4.70 GiB working set175×node.exe128×cmd.exe16×node_repl.exe21× PowerShell /pwsh16Context7 instances16Playwright instances16Sentry MCP instances16Node REPL instances48Node command lines matchingchrome-devtools-mcp(the npm wrapper/launcher/server layers produce multiple matching processes per set)No processes were killed and the app was not restarted because long-running tasks were active.
Field reproduction pattern
This matches the lifecycle explanation in the macOS evidence above: logical thread/subagent residency remains coupled to an eagerly started heavyweight MCP runtime. On Windows, npm-backed MCPs also add substantial
cmd.exewrapper fan-out.Expected behavior would be for inactive/completed sessions to release or detach their MCP runtimes, for MCPs to start lazily, or for the app-server to enforce a global process/private-byte/idle-time budget. A Windows-safe diagnostic/cleanup mechanism would also help until the lifecycle is fixed.
I can gather a controlled before/after Windows reproduction later, but I did not disturb the live tasks for this field capture.
[-]Codex app-server leaks MCP process stacks for subagents, causing linear memory growth on Linux[/-][+][S] Codex app-server leaks MCP process stacks for subagents, causing linear memory growth on Linux[/+]ws404dev commentedon Aug 2, 2026
Additional high-scale macOS field confirmation on a newer Desktop build (credential-redacted).
Environment
26.727.51351(build6119)codex-cli 0.146.0-alpha.9.226.5.2(25F84), arm64multi_agentandmulti_agent_v2enabledObserved impact and cleanup
Lifecycle correlation
node_replexecution contexts were alive in the same Codex app-server process tree.spawn_agent, 31exec, and 7 wait/message/follow-up events. 71 were also within three seconds of rollout-file creation.Config reload behavior
Disabling one stdio server changed most later context initializations but did not terminate already-running copies. Config disablement therefore is not a cleanup mechanism.
This field dataset matches the session/MCP-runtime retention mechanism already source-traced above and confirms that the defect remains observable in the newer bundled
0.146.0-alpha.9.2build. I have not independently source-traced that exact build's callback path, so the callback-level conclusion here is intentionally limited to the process and timestamp evidence.I can provide credential-redacted PID, PPID, RSS, start-time inventories, and timestamp-correlation tables if useful. No endpoints or credentials are included.
[-][S] Codex app-server leaks MCP process stacks for subagents, causing linear memory growth on Linux[/-][+]🩹 Codex app-server leaks MCP process stacks for subagents, causing linear memory growth on Linux[/+]Nicolas-nwb commentedon Aug 14, 2026
Current-build reproduction (2026-08-14)
macOS, Codex Desktop app
26.803.61601(build6396), CLI0.147.0-alpha.6.5. The mainapp-serverhad been alive ~22.5 h at peak. Parallel workflows / sub-agent threads each spin up their own stdio MCP runtime (opencode-codebase-index-mcp --host codex, launched as annpm execwrapper plus itsnodeserver child). At peak: 218 matching processes (~109 npm+node pairs), all descendants of the live app-server, zero with PPID 1. Live snapshot at time of writing (machine in active use, after the cleanup below): 19npm execwrappers + 19nodeservers, all still direct children of the same long-lived app-server.New causal evidence
Read-only aggregates from the local Codex state database (
thread_spawn_edgesjoined withthreads): 4,555 spawn edges (3,680 open, 875 closed); 5,016 threads withthread_source = 'subagent'(1,785 not archived); 158 child threads created in the last 6 hours; 222 parent threads with 5 or more children. Bursts of child threads are born within the same second/minute during parallel workflows, and each thread carries a full MCP runtime that outlives the sub-agent.Controlled cleanup
Selection based on start-time + cwd correlation with thread metadata (created ±10 min, same cwd, thread not archived, activity <60 min to preserve active ones): 142 stale runtimes stopped, 74 preserved, only 2 respawned afterwards for genuinely active threads. Age alone is a dangerous criterion: one runtime ~14 h 48 old was still serving an active conversation.
Interpretation
This is retention of MCP runtimes per thread/sub-agent under a live app-server, not an EOF-propagation defect of the MCP server and not primarily a watcher storm (see #30408 for the general per-thread angle). Individual processes are mostly idle, but their count and their ~29 OS threads each grow without bound.
Expected invariant
After a sub-agent terminates/closes/is unloaded, the number of MCP runtimes should return toward the number of genuinely active threads; runtimes retained for resume must be detached or lazily recreated.
Evidence availability
Happy to provide a sanitized PID/PPID/start/cwd table (paths hashed) and the aggregation SQL; I won't share the state database or rollouts.
Luzivog commentedon Aug 19, 2026
Current stable Linux Desktop confirmation (2026-08-19)
The same session-shaped MCP multiplication is still observable on a newer Linux Desktop release.
Environment
6.14.0-37-generic255.4-1ubuntu8.1726.814.41957codex-cli 0.147.0launched ascodex -c features.code_mode_host=true app-server --analytics-default-enabledcodex-cli 0.148.0-alpha.15, but this app-server was configured to use the local 0.147.0 binary.codex mcp list --json:node_replandclaude_collabLive process census
At a fixed capture after approximately 54 minutes of app-server uptime:
node_repl: 47 direct children, 375.2 MiB aggregate RSS, 705 OS threadsclaude_collabstdio server: 37 direct children, 1,845.0 MiB aggregate RSS, 259 OS threadsThe tree also contained nine deliberately long-lived project helper servers (~372 MiB RSS); I excluded them from the MCP totals above. There were no direct children in uninterruptible
Dstate at capture.This field snapshot does not prove that every one of the 84 instances was stale. It does show that, on the current stable Linux Desktop build, a long-lived app-server can retain dozens of complete per-session MCP runtimes and more than 1,000 associated OS threads in under an hour, despite having only two configured MCP families. The direct PPID relationship and repeated start-time pairs match the per-loaded-session/session-retention mechanism already source-traced above.
Operational impact observed on this machine
During a separate high-pressure incident,
[email protected]reached 29.0 GiB memory peak and 7.9 GiB swap peak. Ubuntu's defaultsystemd-oomdrecorded user-slice pressure at 80.66% > 50% for over 20 seconds, then killed the user'sinit.scope, collapsing the GNOME session. The candidate report included a 21.6 GiB high-pressure application scope (PSI avg10 79.93) and live Codex/node_replprocesses.There were also multiple concurrent Rust compile/link jobs in that incident, so I am not attributing the entire 21.6 GiB scope or logout solely to MCP retention. The narrower conclusion is that retained per-session MCP runtimes materially consume memory, swap, PID, and thread headroom, amplifying otherwise legitimate parallel workloads.
Diagnostics that would make future reports easier to action
It would help if app-server diagnostics exposed:
The latest OpenAI documentation describes MCP configuration consistently across Codex surfaces, but currently there is no user-visible mapping from a spawned local MCP PID back to the task/session retaining it. That ownership mapping would also make a safe temporary cleanup tool possible without age-based guessing.
Nyukimin commentedon Aug 25, 2026
Additional field report from Linux. This is provided as a diagnostic snapshot only; I am not able to perform additional reproduction work or respond to follow-up QA requests.
Environment:
codex-cli 0.149.0codex doctor:0.147.05.15.0-187-genericx86_64Observed behavior:
goplsand telemetry descendants.Resource impact at the snapshot:
goplsprocess.The process topology is consistent with this issue: new MCP generations are added beneath a live app-server, while previous generations are not reaped. Because all generations share the same long-lived parent and session scope, the OS cannot distinguish completed thread/session ownership and will not reclaim them automatically.
Expected behavior: when a thread/subagent/session is completed, cancelled, disconnected, or reinitialized, Codex should terminate and wait for the owned MCP process tree, with a grace period and descendant-kill fallback. Per-generation ownership metadata or process-group/cgroup isolation would also make cleanup deterministic.
Again, this comment is an evidence contribution only. No additional reproduction or follow-up QA support is available from this reporter.
m13v commentedon Sep 2, 2026
the trap in a Windows-safe cleanup pass is the same swallow the mac terminator hit with EPERM: kill the tree, the cmd/npm wrappers exit, their node children reparent to PID 1 and survive, and it logs 'TERM sent to N' as done. that's a partial reap reported as complete, with no retry on the orphans. verify by committed bytes reclaimed after, not TERM count sent.
m13v commentedon Sep 2, 2026
the SIGTERM sweep is a treadmill, not a fix: those 84 retained node_repl contexts are the thing eagerly initializing a fresh stack, so killing the 402 processes just resets a counter that climbs again on the next spawn_agent. that's also why config disablement didn't help, it gates future inits but leaves the resident context holding its stack. teardown has to evict the retained rollout/execution context, not reap the leaf processes it keeps respawning.
m13v commentedon Sep 2, 2026
the 2 respawns are the tell your correlation sweep can't audit itself: it logged them as clean 'stops' when they were live threads it misfired on, not leaked runtimes. any cwd+start-time heuristic reports its false-positive kills as success, so the count looks done while it silently interrupted active conversations. detach-or-lazily-recreate on resume removes the guess instead of masking it.
m13v commentedon Sep 2, 2026
the global MCP-baseline invariant you floated swaps the leak for cross-session thrash: a global ceiling lets one root's fan-out reap another live root's servers, and each reaped set re-pays the npx @latest resolve on respawn. bound per session with an idle TTL, not by a global cap that evicts across roots.
m13v commentedon Sep 2, 2026
the grace-period + descendant-kill fallback you list is where this goes quiet: if the kill hits EPERM or the tree already reparented to init, the terminator marks the handle reaped and cleanup reports done while the cold pages survive. that's your PSI-zero, swap-full snapshot. teardown has to verify the tree is gone, not fire-and-mark.
simmonspatrick1-cell commentedon Oct 13, 2026
macOS field confirmation on Desktop 26.1007.30912 / app-server 0.162.0-alpha.17.2
Reporting additional evidence on 2026-10-12. The repeated MCP/helper process pools described in this issue still accumulate on this newer macOS Desktop build, including after a full application relaunch. The operational impact included a shell/pre-commit command hanging during the high-process-count incident.
Environment
com.openai.codex.codex-cli 0.162.0-alpha.17.2.codex doctor --summarysuccessfully loads the config, but its desktop/app-server detection does not identify the running bundled app-server; process inspection was used for the measurements below.Process evidence
Historical snapshots from the local incident record (collected earlier the same day):
Fresh read-only snapshots taken in the follow-up chat after that relaunch:
The current app-server itself was 631,520 KiB RSS at the final snapshot. The RSS totals are sums of process RSS, not unique physical memory, and the direct-child total includes non-MCP helpers and transient command processes. Counts fluctuate slightly; these are field snapshots, not a controlled per-subagent experiment.
The selected desktop app-server is the bundled process launched with
-c features.code_mode_host=true app-server --analytics-default-enabled. A separate plugin app-server also exists on the machine and was excluded from these counts.Log evidence and limits
The earlier incident investigation found repeated stdio MCP generations across thread/subagent activity. Its local log coverage began around 05:15 on October 12, so it cannot establish the entire old process lifetime. An observed batch of MCP cancel/restart pairs at 07:59:35-37 coincided with a plugin refresh; no MCP startup timeouts were found in that earlier inspected window. A single-server respawn loop was therefore not supported by that investigation.
For a fresh aggregate-only check, the local SQLite log database was opened read-only. After the new app-server's process start time (2026-10-13 01:04:41 UTC), 69 log rows containing
stdioreferenced 14 distinct thread IDs; 220 rows containingmcpreferenced 12 distinct thread IDs. These are log-row counts, not process or server-start counts, and are only corroborating evidence of activity across multiple thread contexts. Raw messages and thread IDs are withheld.No exact source-level teardown defect has been established for this build. The process topology and repeated growth are consistent with the session/MCP retention pattern already discussed here; the snapshots do not prove every retained child is stale.
Operational impact
During the earlier 416-513-child incident, a pre-commit test hung for approximately 19 minutes. The incident investigation traced the blocked operation to a Homebrew bash heredoc write with 512-byte pipes and attributed the pipe pressure to hundreds of idle helper processes retaining pipes. This is the recorded diagnosis, not a newly repeated kernel-level experiment in this follow-up. The test was stopped, and the local script was changed to avoid that heredoc path.
This makes the issue consequential beyond aggregate RSS: helper/pipe retention can impede unrelated shell work. The application restart sharply reduced the process footprint, but it rebuilt to more than 140 direct children within approximately 43 minutes of normal use.
Mitigation and expected behavior
Before relaunch, two optional stdio servers were disabled and dead config keys were removed. The disabled servers did not start after relaunch, yet the remaining helper pools accumulated again. Reducing the enabled set reduced the baseline but did not prevent growth.
Full application quit/relaunch remains our temporary workaround when the child count reaches the hundreds or shell commands hang. We have not killed arbitrary individual MCP processes or changed trust/approval settings in this follow-up.
Expected behavior: completed/inactive thread and subagent contexts should release their owned MCP/helper runtimes, or resume them lazily, so normal use converges to a bounded active-work footprint. Per-helper owner-thread, last-use, and teardown diagnostics would help distinguish required live runtimes from retained idle generations.
payam54 commentedon Oct 19, 2026
Same issue. MacOS
keisksw commentedon Oct 26, 2026
Adding a bounded macOS reproduction and a supported operational mitigation, rather than claiming that all reports here have the same root cause.
Environment checked on 2026-10-27: macOS arm64; Desktop production 26.1021.31345/build21828 (bundled CLI 0.164.0-alpha.11.1); separate existing CLI/daemon updated normally from 0.163.0 to released 0.164.0. No vendor binary patch/re-signing, blanket MCP disable, or additional app-server was used as the mitigation.
Observed boundaries:
We now use finite owner-scoped cleanup after artifact acceptance, with explicit protection of active/unsaved/approval-waiting work and process-generation verification. Updates preserved provider/auth configuration, and normal/error/timeout/cancel/disconnect/reconnect cases were distinguished. This reduces accumulation operationally, but archiving history is an undesirable side effect when only runtime release is intended.
Related: #21889; per-thread delay #55270; default-delay reduction #57242; V2 close-to-interrupt rationale #26994. We distinguish current main's shorter default from released 0.164.0 and have not treated the source change as a deployed Desktop fix.
Could maintainers confirm the intended supported mitigation and address this in an official update? An explicit owner-scoped V2 runtime release would help: preserve logical agent/history, atomically refuse active/protected/sleeping/pending-mail work, serialize against send/resume, flush the rollout, and return distinct busy/released/alreadyReleased outcomes with observable teardown completion. The existing residency-eviction path appears relevant, but our client-side checks cannot make a read-then-archive sequence atomic.
Please let us know if this workaround is inappropriate or if further narrowly scoped, sanitized evidence would help. We have not run an unconditional background janitor or claimed that #25015/#21889 are resolved.
iMMerSiveTechs commentedon Oct 29, 2026
Same leak on macOS, in the Codex inside the ChatGPT desktop app.
Environment
codex-cli 0.165.0-alpha.1.2mcp_servers)What we measured
codex app-server. New sets appear when conversations are restored at launch and, most of the time, within a few seconds of a subagent starting. No set exits afterwards.Possible fixes
ntsanderc commentedon Nov 12, 2026
Same leak in the Codex inside the ChatGPT desktop app on macOS, on a newer build. This comment adds two things: subagents that outlive their shut-down parents, and a role-file setting that stops the per-subagent MCP set for roles that don't need it.
Environment
codex-cli 0.167.0-alpha.3.2(codex app-server)features.multi_agent = true;thread_unload_delay_secsnot set~/.codex/agents/*.toml.What we measured
logs_2.sqliteand the rolloutsession_meta. Every set belonged to a loaded thread. Threads that had logged a shutdown had no live set, so shutdown itself cleans up.Role-file MCP settings and a workaround
[plugins."<plugin>@<marketplace>"]withenabled = falsein a role file is not applied to a spawned subagent. Subagents of two such roles still ran the plugin's full set of 13 server processes.[plugins."<plugin>@<marketplace>".mcp_servers.<name>]withenabled = falseis not applied either. The subagent still tried the initialize handshake with those servers.[mcp_servers.<name>]with onlyenabled = falsemakes the role file fail to load (invalid transport), and the spawn then fails withunknown agent_type.[features]plugins = falsein the role file. We added it to 4 roles that don't use MCP tools. In the next 14 spawns of those roles (3 of the 4 roles were used), 11 logged a tool catalog inlogs_2.sqliteand none of those listed a plugin MCP server; the other 3 logged no catalog rows. In the 11 spawns of the same roles just before the change, 10 listed all 13. This is log evidence, and the log line is a noisy signal: a role without the flag also listed no plugin server on 3 of its 5 later spawns that logged a catalog. We did not count processes after the change. (Corrected: an earlier version of this comment said 15 spawns.) The flag also turns off every plugin and plugin skill for that role, so it does not help a role that needs some plugin servers (see Per-agent MCP server scoping: allow subagents to opt out of inherited MCP servers #20135).Suggested fixes
pluginsandmcp_serversenable/disable settings when a subagent of that role starts its MCP servers, and acceptenabled = falseunder[mcp_servers.<name>]without a transport.Process listings, the matching log rows and the rollout
session_metaare available if useful.Update, same day:
thread_unload_delay_secs = 300After the maintainer suggestion in #56937, we set
thread_unload_delay_secs = 300at the top level ofconfig.tomland restarted the desktop app (now bundledcodex-cli 0.167.0-alpha.4.1). We watched the MCP processes under the app-server. (Corrected: an earlier version said the app logs nothing at unload.logs_2.sqlitehas a "Shutting down Codex instance" line for the first thread below at 13:00:05, 300 s after its last activity.) Times are US Central.0.167.0-alpha.3.2), where 4 subagents outlived parents that had logged a shutdown by 17 to more than 30 hours. We can't tell from one run whether a newer build fixed that or whether closing a thread works differently from the shutdowns we saw then. While the parent stayed open, the finished subagent stayed loaded well past the 300-secondthread_unload_delay_secs.evandrocoan commentedon Nov 15, 2026
Additional Linux field evidence from 2026-11-15, with a source-level subscription-retention mechanism in released
codex-cli 0.167.0.Environment and observations
A persistent native app-server, independent of the desktop client's lifetime, with multi-agent V2 and several stdio MCP servers enabled. These are read-only observations from a live workload, not a minimal reproduction with the default desktop launch configuration.
thread/loaded/listreturned 190 threads: 8 root threads and 182 spawned subagent threads. All 182 subagents were idle; their latest turns were 181 completed and 1 interrupted.notLoaded, but three completed children remained loaded and idle.VmSwap. This is a whole-tree aggregate, including non-MCP helpers; it does not prove every descendant is stale or represent unique physical memory. The user-visible symptoms included slow typing and conversation switching.Relevant lifecycle mechanism in 0.167.0
All links below refer to release commit
086ccc833bc9cf01024ad2dd6af7dbd421b6bf9a.thread/unsubscriberemoves the subscription for the calling connection and specified thread only: thread_processor.rs:1134-1163. Unsubscribing a parent does not itself cascade to children, and a separate maintenance client cannot remove an existing desktop connection's subscription.try_evict_v2_threadfor V2 children and handles a busy result: thread_lifecycle.rs:631-681.This identifies a subscription-lifetime mechanism consistent with the retained completed children: implicit subscriptions can keep otherwise-idle child runtimes alive after their parent is unloaded. It is not evidence that the native process-termination primitive itself failed. The live API inventory did not expose per-connection subscription ownership, and no controlled unsubscribe/restart experiment was performed, so I am not claiming that this explains every process or every report in this issue.
Suggested fix and regression boundary
Distinguish implicit child subscriptions from explicit client interest, and release implicit subscriptions when they no longer represent needed work, allowing the existing guarded idle-eviction path to run. Preserve active/protected work, durable sleep/mail semantics, history and resumability, and children explicitly followed by a client.
A useful regression would keep a client connected, spawn and complete a child without explicitly opening it, unsubscribe/unload the parent, and verify that the unused child eventually unloads and its owned mock MCP process exits. A second explicitly subscribed or active child should remain usable. This would exercise the missing subscription-lifetime boundary rather than only testing explicit child unsubscribe or killing helper processes.
dpmedeiros commentedon Nov 17, 2026
A controlled reproduction on Linux confirms the subscription-retention mechanism described in the November 15 comment: after a parent unloads, its completed child and the child's MCP processes remain alive. Explicitly unsubscribing the child lets the existing idle cleanup release both.
Tested November 17, 2026, using desktop
26.1106.51428and its bundledcodex-cli 0.167.0-alpha.4.1on Linux x86_64. Source references below use the matching release commitd2c035639366e0bf2c316aa2065c24aabc12bcdc.The reproduction launches a separate app server with a temporary
CODEX_HOME, one persistent stdio client, and a loopback HTTP server that returns synthetic model responses. It uses the installed security MCP server and bundled Node REPL as two real stdio helpers. No external model calls or authentication are needed. Production configuration and processes were left alone.The test configuration sets
thread_unload_delay_secs = 2and enables multi-agent V2 withmax_concurrent_threads_per_session = 2, allowing the parent plus one resident child. It starts parent P, has P spawn child A, then has P spawn child B after A completes. Spawning B forces A's eviction. For each child,mcpServerStatus/listwith that child'sthreadIdand an explicitserverNameinitializes its own helper connections. There is no explicitthread/resumeor subscription request for either child.These are the observed results from
thread/loaded/listand process inspection:thread/unsubscribe(A)notLoadedthread/unsubscribe(P); wait 4 secondsthread/unsubscribe(B); wait 4 secondsThe app server exited with status 0. All tracked diagnostic process IDs were absent afterward. Child completion was also present in the recorded
turn/completednotifications.This confirms that the helper shutdown path works once ownership is released. Parent unsubscribe leaves the child's automatic subscription in place, so waiting beyond the configured idle delay does not unload the child.
The matching source shows why:
There is also a distinction worth preserving when interpreting teardown logs. In this reproduction, A's runtime and helpers were already gone before
thread/unsubscribe(A). That request returnednotLoadedbut still emitted:The listener drops the runtime after ShutdownComplete and keeps a notification relay. Thus,
had_listener=truedoes not establish that the child runtime or its MCP processes were still alive.That distinction corrected our initial reading of the production incident. After heavy remote use of Codex on this desktop, the pre-restart snapshot had 55 security servers, 54 app-tools servers, and 167 Node REPL helpers: 276 total, with 186 older than 24 hours. The kernel later killed a ChatGPT process, followed by transport shutdown and 27 child-listener teardown records. Those 27 children belonged to 13 parents and had last completed about 12.7 to 120.6 hours earlier. We cannot use those records to claim 27 continuously resident runtimes, or map all 276 helpers to individual chats. The controlled test establishes the retention mechanism independently of that historical attribution.
The test uses a single persistent local connection. It does not simulate a remote reconnect or reproduce the desktop's complete subscription state. The source's attachment to every initialized connection explains how a persistent desktop connection can retain a child after another client disconnects.
This supplies a regression case for the behavior discussed in #30985: keep the client connected, complete a child without explicitly opening it, unsubscribe the parent, and check that the unused child and its owned MCP processes eventually leave memory. Active children and children explicitly followed by a client need separate preservation coverage.
Reproduction harness and setup
This is the harness used for the result table. The scratch base has been changed to
/tmpand the user's security-server path replaced with/PATH/TO/INSTALLED/.... Replace that placeholder with the installed security MCPserver.mjspath. The other executable paths are those of the tested Linux desktop package; adjust them if the package is installed elsewhere.Save as
reproduce.pyand runpython3 -u reproduce.pyon a host where Python can create a loopback listener and inspect its child processes through/proc. The script creates its own temporary config and leavesresults.json,events.json, andstderr.login the printed diagnostic directory. The published path substitutions have not been rerun; the original harness produced the measurements above.evandrocoan commentedon Nov 21, 2026
Follow-up to my November 15 diagnosis. I tested a patched Linux x86_64 build from source revision
f273ea856248with three persisted V2 subagents. The desktop client stayed connected, the parent stayed loaded, and the same app-server process ran throughout.idletonotLoaded.My patch separates notification recipients from subscriptions that keep the runtime loaded. Automatic subscriptions to persisted V2 children still receive events and allow the existing guarded idle eviction to run. Explicit subscriptions and ephemeral children retain their prior behavior.
The Linux regression also verified exit of a child-owned stdio MCP fixture. With the old retention behavior restored, that regression failed because the child runtime stayed loaded. With the patch restored, it passed.
Commit: Release idle V2 child runtimes with passive subscribers.
App-server patch