Skip to content

🩹 Codex app-server leaks MCP process stacks for subagents, causing linear memory growth on Linux #25015

Open

Description

@LostFrxks

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:

https://github.com/LostFrxks/codex-mcp-clean

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

  1. Start Codex app-server with stdio MCP servers enabled.
  2. Take a baseline process/memory snapshot of the codex app-server child tree.
  3. Spawn subagents with trivial tasks that do not use MCP tools.
  4. Wait for the subagents to complete.
  5. Call close_agent for each subagent.
  6. Wait briefly for Codex cleanup.
  7. Check the codex app-server child process tree again.
  8. Optionally repeat with larger subagent batches.

Small Live Repro: 3 Subagents

Before spawning 3 trivial subagents, the selected app-server had:

  • 23 descendants
  • 6 MCP launcher roots
  • RSS around 203 MiB

After spawning 3 subagents:

  • 74 descendants
  • 24 MCP launcher roots
  • RSS around 3.7 GiB
  • Snapshot report showed 18 new MCP launcher roots / 50 new 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:

  • 9 MCP launcher roots
  • 33 processes

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 GiB to about 6.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:

https://github.com/LostFrxks/codex-mcp-clean

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:

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

  1. added
    bug
    mcp
    subagent
    on May 29, 2026
  2. Keesan12 commented on Jun 6, 2026

    @Keesan12
  3. tombelieber commented on Jul 13, 2026

    @tombelieber

    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

    • macOS (Darwin 25.5.0), Apple M5 Max, 128 GB RAM
    • ChatGPT.app Codex build 26.707.62119, running codex -c features.code_mode_host=true app-server
    • 3 stdio MCP servers configured: chrome-devtools-mcp, @upstash/context7-mcp, xcodebuildmcp (via build-ios-apps plugin), all spawned as npx <pkg>@latest

    Observation (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):

    55230  ChatGPT.app → codex app-server            (uptime 47 min)
      ├─ set 1: npm exec xcodebuildmcp@latest + @upstash/context7-mcp + chrome-devtools-mcp@latest   (age 38:38)
      ├─ set 2: same triplet                                                                          (age 38:34)
      ├─ set 3: same triplet                                                                          (age 38:31)
      ├─ set 4: same triplet                                                                          (age 22:08)
      ├─ set 5: same triplet                                                                          (age 17:10)
      └─ set 6: same triplet                                                                          (age 16:07)
    

    Each set = 3 npm exec wrapper 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/codex CLI 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.

  4. dianshili commented on Jul 17, 2026

    @dianshili

    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:

    1. Primary / deterministic: completed or unsubscribed thread sessions remain resident, and every resident session owns an eagerly started full MCP process set. This creates unbounded aggregate process/RSS growth across many root tasks, even if process termination itself never fails.
    2. Secondary / observed: when a real shutdown is finally attempted, macOS killpg(SIGTERM) can return EPERM; 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

    • macOS 26.5.2 (25F84), Apple silicon / arm64
    • ChatGPT/Codex Desktop 26.715.21425, build 5488
    • Embedded codex-cli 0.145.0-alpha.18
    • Exact release source: tag rust-v0.145.0-alpha.18, commit f84f9a6406cc55b210395f71b4c6aed236fc7ebb

    Source-level causal chain

    A. Every thread/session eagerly starts its own MCP stack

    Session owns a session-local MCP manager. The source even contains a TODO to extract session state for sharing between subagents: session.rs L1035-L1100.

    During session construction, Codex calls McpConnectionManager::new(...) before any model turn or MCP tool call: session.rs L1211-L1263. The manager iterates all enabled servers and starts them eagerly: connection_manager.rs L128-L225.

    Therefore the cost is:

    loaded root sessions + resident subagent sessions × all enabled stdio MCP servers

    This 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.rs L431-L518.

    Actual V1 close_agent is a different path and explicitly sends Op::Shutdown, waits, removes the thread, forgets residency, and releases the registry entry: legacy.rs L3-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-scoped VecDeque. 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.rs L79-L149, residency.rs L216-L230.

    The cap is derived from max_concurrent_threads_per_session, not a global Desktop/app-server process or memory budget: config/mod.rs L1462-L1475.

    This behavior was intentionally introduced by PR #26632. PR #26994 then renamed the V2 model-facing close_agent operation to interrupt_agent specifically 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/unsubscribe keeps the thread loaded for 30 minutes after the last subscriber/activity: app-server README L162.

    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_HOME and a separate app-server. I did not touch the user's live app-server or tasks.

    Configuration:

    • plugins, apps, and remote plugins disabled
    • exactly one bundled local stdio MCP server enabled
    • no model turn and no MCP tool invocation
    • five new ephemeral threads

    Observed direct children of the isolated app-server:

    Step Loaded threads MCP child processes MCP RSS
    Baseline 0 0 0
    Start one thread 1 1 ~35 MiB
    Start five threads 5 5 ~170-174 MiB
    Unsubscribe all five; wait and re-list 5 5 ~170 MiB

    All five thread/unsubscribe calls returned status: "unsubscribed". A subsequent thread/loaded/list still 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/delete changed that thread to notLoaded and 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:

    • process termination works when the true session-shutdown boundary is reached;
    • completion/unsubscribe does not reach that boundary, so the heavy runtime remains resident by design.

    The explicit shutdown implementation does call the MCP manager's shutdown path: handlers.rs L597-L615, connection_manager.rs L461-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: EPERM becomes a silent terminal state

    Local stdio servers are launched in their own process group: stdio_server_launcher.rs L263-L280.

    On shutdown, if terminate_process_group() errors, the implementation logs a warning and sets should_escalate = false, so no delayed SIGKILL is attempted: stdio_server_launcher.rs L327-L344. The outer handle has already set its terminated atomic and returns Ok(()) for the local path: stdio_server_launcher.rs L385-L404.

    On this exact build I found four warnings with the exact shape:

    Failed to terminate MCP process group ...: Operation not permitted (os error 1)
    

    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 macOS EPERM is 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:

    • both embed codex-cli 0.145.0-alpha.18 arm64;
    • the 264,898,656-byte codex binaries are byte-for-byte identical through the complete executable payload up to the LC_CODE_SIGNATURE offset (262,827,104); only the signature region differs;
    • the desktop main-process app-server protocol chunk is byte-for-byte identical;
    • the renderer chunk containing thread/loaded/list, thread/unsubscribe, thread/read, and thread/list differs in only 138 bytes, all of which are generated import/source-map filename hashes; the lifecycle logic is identical;
    • main-process JavaScript differs only in an unrelated two-hash allow-list rotation plus generated source-map filenames and build/version metadata.

    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 main commit 315195492c80fdade38e917c18f9584efd599304, the relevant completion, residency, manager-shutdown, and local-process-terminator files retain the same behavior.

    Suggested fix boundary

    1. Decouple logical agent residency from MCP-runtime residency. On final status or last unsubscribe, shut down/detach the MCP runtime while keeping durable agent/thread identity. Recreate it lazily on the next turn/tool use.
    2. Add a global app-server budget/TTL, not only a per-root agent cap: process count, owned RSS, last tool call, owning root/thread, and idle deadline.
    3. Start stdio MCP servers lazily when their catalog/tool is actually needed, rather than in every Session::new().
    4. Do not swallow local termination failure. Preserve a retryable state, validate the recorded PID/PGID identity, and use a safe direct-child or SIGKILL fallback when group termination fails.
    5. Add regression tests that start a blocking PID-reporting mock MCP server and assert:
      • N completed/unsubscribed sessions converge to a bounded MCP baseline;
      • many separate V2 root sessions are bounded globally, not only per root;
      • explicit close/delete reaps every owned process;
      • a forced killpg failure 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 EPERM is the only part I am leaving as an explicitly separate unresolved question; its error-handling defect is confirmed in source.

  5. m13v commented on Jul 17, 2026

    @m13v

    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.

  6. krutftw commented on Jul 30, 2026

    @krutftw

    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

    • Windows 11 Pro x64, 10.0.26100
    • 31.92 GiB physical RAM
    • Codex Desktop AppX package OpenAI.Codex 26.721.11231.0
    • Long-running desktop session with multi-agent use
    • Enabled stdio/local MCP families include Chrome DevTools, Playwright, Context7, Sentry, and Node REPL

    Read-only field snapshot

    Snapshot taken 2026-07-30 10:33 AWST while active tasks were left untouched:

    • System physical memory: 30.80 / 31.92 GiB used
    • Windows committed memory: 73.05 / 73.97 GiB
    • Main desktop codex app-server tree (child of ChatGPT.exe): approximately 345 processes, 17.22 GiB private bytes, and 4.70 GiB working set
    • A nearby process census contained 347 descendants:
      • 175 × node.exe
      • 128 × cmd.exe
      • 16 × node_repl.exe
      • 21 × PowerShell / pwsh
    • The command-line/process shape showed at least 16 repeated session-shaped MCP sets:
      • 16 Context7 instances
      • 16 Playwright instances
      • 16 Sentry MCP instances
      • 16 Node REPL instances
      • 48 Node command lines matching chrome-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

    1. Keep Codex Desktop running for an extended period.
    2. Use multiple root tasks/subagents with several stdio MCP servers enabled.
    3. Completed or inactive agent/session generations leave their full MCP process sets resident under the long-lived app-server.
    4. Repeated use creates additional nearly identical sets.
    5. Node/npm/cmd process count and Windows commit grow until the machine approaches commit exhaustion.

    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.exe wrapper 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.

  7. changed the title [-]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[/+] on Jul 31, 2026
  8. ws404dev commented on Aug 2, 2026

    @ws404dev

    Additional high-scale macOS field confirmation on a newer Desktop build (credential-redacted).

    Environment

    • ChatGPT/Codex Desktop 26.727.51351 (build 6119)
    • Bundled codex-cli 0.146.0-alpha.9.2
    • macOS 26.5.2 (25F84), arm64
    • Long-lived app-server with multi_agent and multi_agent_v2 enabled
    • Multiple local stdio MCP servers

    Observed impact and cleanup

    • Initial operator snapshot: 518 MCP-related OS processes and 27.69 GB aggregate RSS.
    • A saved credential-redacted inventory at 2026-07-31 20:41 MDT contained 451 external MCP processes / 19.63 GiB aggregate RSS; 406 were Codex-owned in that snapshot.
    • After revalidation, 402 stale Codex-owned MCP processes were selected for cleanup. Of those, 399 exited after SIGTERM and 3 exited during the same termination cascade; none survived. They accounted for 17.91 GiB aggregate RSS immediately before termination.
    • After follow-up cleanup, a sample taken three seconds later showed zero Codex-owned external MCP processes. This was a point-in-time result; retained contexts could initialize new stacks again.

    Lifecycle correlation

    • 84 retained node_repl execution contexts were alive in the same Codex app-server process tree.
    • In the sampled process table, 80/80 distinct start-time clusters contained a retained context plus matching configured MCP roots.
    • All 84 context starts were within three seconds of a logged context-creating event: 46 spawn_agent, 31 exec, and 7 wait/message/follow-up events. 71 were also within three seconds of rollout-file creation.
    • Session logs contained 6,941 tool calls across 35 sessions, while there were 84 retained contexts. Matched rollouts contained 3,035 tool calls, with up to 211 calls in one rollout.
    • Together with the process clustering, this is inconsistent with one MCP stack per tool call and instead points to eager MCP initialization per retained rollout/execution context.
    • Matching MCP stacks remained after many associated subagent tasks had completed or been interrupted, indicating that teardown/reaping was not reliably reached or completed.

    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.2 build. 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.

  9. changed the title [-][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[/+] on Aug 3, 2026
  10. Nicolas-nwb commented on Aug 14, 2026

    @Nicolas-nwb

    Current-build reproduction (2026-08-14)

    macOS, Codex Desktop app 26.803.61601 (build 6396), CLI 0.147.0-alpha.6.5. The main app-server had 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 an npm exec wrapper plus its node server 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): 19 npm exec wrappers + 19 node servers, 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_edges joined with threads): 4,555 spawn edges (3,680 open, 875 closed); 5,016 threads with thread_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.

  11. Luzivog commented on Aug 19, 2026

    @Luzivog

    Current stable Linux Desktop confirmation (2026-08-19)

    The same session-shaped MCP multiplication is still observable on a newer Linux Desktop release.

    Environment

    • Ubuntu 24.04.4 LTS, x86_64
    • Kernel 6.14.0-37-generic
    • systemd 255.4-1ubuntu8.17
    • AMD Ryzen 5 PRO 8540U, 6 cores / 12 threads
    • 30.6 GiB RAM, 8 GiB swap
    • ChatGPT/Codex Desktop package 26.814.41957
    • Active app-server: codex-cli 0.147.0 launched as codex -c features.code_mode_host=true app-server --analytics-default-enabled
    • The package also bundles codex-cli 0.148.0-alpha.15, but this app-server was configured to use the local 0.147.0 binary.
    • Exactly two enabled stdio MCP entries from codex mcp list --json: node_repl and claude_collab

    Live process census

    At a fixed capture after approximately 54 minutes of app-server uptime:

    • app-server itself: 1,173,956 KiB RSS, 64 OS threads
    • node_repl: 47 direct children, 375.2 MiB aggregate RSS, 705 OS threads
    • claude_collab stdio server: 37 direct children, 1,845.0 MiB aggregate RSS, 259 OS threads
    • combined configured MCP roots: 84 direct children, ~2.17 GiB aggregate RSS, 964 OS threads
    • app-server plus those MCP roots: ~3.32 GiB RSS and 1,028 OS threads

    The 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 D state 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 default systemd-oomd recorded user-slice pressure at 80.66% > 50% for over 20 seconds, then killed the user's init.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_repl processes.

    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:

    1. loaded/subscribed/executing/idle session counts;
    2. the owner session/thread ID and last-use time for every MCP process root;
    3. global app-server gauges for MCP process count, aggregate RSS, and OS threads;
    4. an invariant/test that completed, unsubscribed, archived, or evicted sessions converge to a globally bounded MCP-runtime baseline.

    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.

  12. Nyukimin commented on Aug 25, 2026

    @Nyukimin

    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: codex-cli 0.149.0
    • Running app-server reported by codex doctor: 0.147.0
    • Linux 5.15.0-187-generic x86_64
    • 8 GiB RAM, 4 GiB swap
    • Long-lived app-server / IDE integration

    Observed behavior:

    • One app-server remained alive for about 8.5 days under one systemd session scope.
    • Its direct children contained at least seven separately-started generations of the same MCP suite, launched at distinct times across multiple days.
    • Repeated launcher roots included Serena MCP, Chrome DevTools MCP, Playwright MCP, a search MCP, and a Node MCP server; Serena generations also retained separate gopls and telemetry descendants.
    • All generations remained children of the live app-server and in the same systemd session scope. There was no per-thread/per-generation cgroup boundary visible.
    • Several older generations showed no CPU-time increase during a five-second observation window but remained alive.

    Resource impact at the snapshot:

    • System swap: approximately 4.0 / 4.0 GiB used.
    • Development-tool process groups collectively retained approximately 2.8 GiB of swap.
    • Approximate swap by group: Chrome DevTools MCP 915 MiB, Codex 660 MiB, gopls 534 MiB, Playwright MCP 430 MiB, Serena MCP 313 MiB.
    • The long-lived app-server process itself retained approximately 413 MiB of swap, almost entirely anonymous memory.
    • Example older individual generations retained about 68 MiB per Serena process, 83 MiB per Chrome DevTools process, and 113-118 MiB per gopls process.
    • Current memory PSI was zero and swap I/O was nearly idle, indicating retained cold pages rather than active thrashing; however, swap capacity was exhausted.

    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.

  13. m13v commented on Sep 2, 2026

    @m13v

    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.

  14. m13v commented on Sep 2, 2026

    @m13v

    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.

  15. m13v commented on Sep 2, 2026

    @m13v

    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.

  16. m13v commented on Sep 2, 2026

    @m13v

    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.

  17. m13v commented on Sep 2, 2026

    @m13v

    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.

  18. simmonspatrick1-cell commented on Oct 13, 2026

    @simmonspatrick1-cell

    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

    • macOS 26.7.1, Apple silicon / arm64 (M5).
    • Codex.app 26.1007.30912, bundle build 20156, bundle ID com.openai.codex.
    • Bundled app-server binary: codex-cli 0.162.0-alpha.17.2.
    • Separately installed PATH CLI: 0.160.0. Its codex doctor --summary successfully 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.
    • Multiple configured and plugin-provided stdio MCP/helper families. No secrets, config files, state databases, rollouts, customer data, or raw log bodies are attached.

    Process evidence

    Historical snapshots from the local incident record (collected earlier the same day):

    • Old desktop app-server PID 1497, uptime approximately 30 hours: 416 Node children, approximately 51 repeated stdio MCP sets and approximately 2.5 GB aggregate memory reported at that capture.
    • The old app-server later reached 513 direct children before relaunch.
    • At approximately 19:04 America/Denver, a full Codex.app quit/relaunch produced a new app-server with 10 direct children. Machine-wide Node processes fell from 604 to 37.

    Fresh read-only snapshots taken in the follow-up chat after that relaunch:

    New desktop app-server PID App-server uptime Direct children Direct Node/helper children Aggregate direct-child RSS
    38312 40m44s 142 not counted at this snapshot not measured
    38312 41m20s 142 127 not measured
    38312 42m35s 144 not counted at this snapshot not measured
    38312 49m20s 142 127 4,947,360 KiB (approximately 4.72 GiB)

    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 stdio referenced 14 distinct thread IDs; 220 rows containing mcp referenced 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.

  19. payam54 commented on Oct 19, 2026

    @payam54

    Same issue. MacOS

  20. keisksw commented on Oct 26, 2026

    @keisksw

    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:

    • On 0.163, an owned stdio MCP fixture remained alive after its owning client unsubscribed (still retained after 4 seconds). Exact-thread archive produced notLoaded and fixture exit. This is consistent with the 1800-second default and is not, by itself, proof of an unconditional leak.
    • On 0.164, a request-scoped thread_unload_delay_secs=0 and removal of the last owned subscription produced notLoaded and actual fixture exit. A second subscribed/protected test thread remained loaded. We then formally archived only our completed test thread and verified all owned fixtures exited. Production MCP configuration was unchanged; fixture isolation was request-local.
    • In Desktop, completed V2 children can retain tool processes. After saving/reviewing completed children, formal owner-initiated archive reclaimed their startup MCP generations. In one maintenance batch, five completed owned children became notLoaded and 65 direct tool-server identities exited. Archive receipt, unloaded state and process exit were recorded separately.
    • V2 interrupt_agent preserves the reusable agent; turn completion is not runtime release. An unrelated client cannot unsubscribe Desktop's existing subscription. mcpServerStatus/list with threadId alone can also start separate discovery; supplying serverName is necessary to reuse the particular existing server connection.

    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.

  21. iMMerSiveTechs commented on Oct 29, 2026

    @iMMerSiveTechs

    Same leak on macOS, in the Codex inside the ChatGPT desktop app.

    Environment

    • macOS 27.0.1 (26A434), Apple silicon, 10 cores, 32 GB
    • ChatGPT desktop 26.1023.51421, Codex Framework 156.0.8078.48, bundled codex-cli 0.165.0-alpha.1.2
    • About 8 to 10 stdio MCP servers configured (plugins plus mcp_servers)

    What we measured

    • Each full set of the configured stdio MCP servers starts as direct children of the one long-lived 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.
    • Right after a reboot: 10 full sets in the first 17 minutes, at about 10 processes per set. Three or four of them came from conversations restored at launch. At 16 minutes the app-server had 109 direct children using 2.9 GB RSS.
    • The day before, the same machine had about 600 leaked processes. Load average reached about 255 on 10 cores, and about 20 GB of swap filled the system disk. Quitting the app or rebooting was the only way to recover.
    • From outside the app, a leaked set can't be reliably tied to its thread. The servers get no thread or session ID in their environment, and start times don't line up cleanly with thread starts. An external cleanup can't safely tell a finished subagent's set from a live conversation's set.

    Possible fixes

    1. Shut down a subagent's or unloaded thread's MCP clients and their process trees when it completes or is closed.
    2. Or pass a thread ID to each stdio server, for example in an environment variable, so leftover sets can be identified and cleaned up safely.
  22. ntsanderc commented on Nov 12, 2026

    @ntsanderc

    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

    • ChatGPT desktop 26.1103.60933, Codex Framework 157.0.8103.39, bundled codex-cli 0.167.0-alpha.3.2 (codex app-server)
    • macOS 27.0.1, Apple silicon
    • features.multi_agent = true; thread_unload_delay_secs not set
    • A local plugin that adds 13 stdio MCP servers (Node). Subagents use custom roles from ~/.codex/agents/*.toml.

    What we measured

    • After about 28 hours of normal use, the app-server had 311 child processes and about 11.2 GB of memory footprint, in 17 per-thread sets. One set is about 18 processes and 600-650 MB.
    • We matched each set to its thread by start time, to the second, using logs_2.sqlite and the rollout session_meta. Every set belonged to a loaded thread. Threads that had logged a shutdown had no live set, so shutdown itself cleans up.
    • 4 sets belonged to subagents that had been idle for 17 to more than 30 hours. Their parent threads had already logged "Shutting down Codex instance" (each parent twice). A parent's shutdown did not shut down its subagents.
    • SIGTERM to those 4 sets freed about 2.5 GB. The app-server stayed up and logged no warnings or errors.

    Role-file MCP settings and a workaround

    • [plugins."<plugin>@<marketplace>"] with enabled = false in 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>] with enabled = false is not applied either. The subagent still tried the initialize handshake with those servers.
    • [mcp_servers.<name>] with only enabled = false makes the role file fail to load (invalid transport), and the spawn then fails with unknown agent_type.
    • This works: [features] plugins = false in 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 in logs_2.sqlite and 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

    1. When a parent thread shuts down, shut down its subagent tree.
    2. Stop a finished subagent's MCP servers after an idle period, and restart them lazily on a follow-up.
    3. Apply a role file's plugins and mcp_servers enable/disable settings when a subagent of that role starts its MCP servers, and accept enabled = false under [mcp_servers.<name>] without a transport.

    Process listings, the matching log rows and the rollout session_meta are available if useful.

    Update, same day: thread_unload_delay_secs = 300
    After the maintainer suggestion in #56937, we set thread_unload_delay_secs = 300 at the top level of config.toml and restarted the desktop app (now bundled codex-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.sqlite has 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.

    • A short background thread with no rollout file started a full set of 13 MCP server processes. Its last log line was at 12:55:05. The set exited between 12:59:56 and 13:00:06, about 5 minutes after the thread went idle. The setting works for that thread.
    • A conversation thread we had reopened in the app started its own set at 12:34. Its rollout was last written at 12:53:07. Its set was still running more than 14 minutes later. A thread that the desktop app still has open does not seem to unload, at least within that time.
    • Finished subagent, tested at 13:20: a new thread spawned one subagent whose role still loads the plugin. The subagent finished at 13:20:49 and the parent at 13:20:54. Neither unloaded after 5 minutes: both were still loaded at 13:32. When we closed the parent thread in the app (which archives it), both threads logged "Shutting down Codex instance" in the same second (13:32:33), and no plugin MCP processes were left under the app-server 8 seconds later. A short background thread from the same run shut down 5 minutes after its last activity, as expected.
    • So on this build, closing the parent did shut down its subagent. That differs from the main report above (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-second thread_unload_delay_secs.
    • The logs don't attribute MCP server processes to threads, and the processes were gone when we looked, so we did not confirm whether this subagent ran its own server set or reused the parent's.
  23. evandrocoan commented on Nov 15, 2026

    @evandrocoan

    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/list returned 190 threads: 8 root threads and 182 spawned subagent threads. All 182 subagents were idle; their latest turns were 181 completed and 1 interrupted.
    • 177 of those 182 subagents had parents absent from the loaded-thread inventory. 169 had not been updated for more than 24 hours.
    • In one inspected example, the desktop had logged successful unsubscribe for a parent days earlier, the parent was notLoaded, but three completed children remained loaded and idle.
    • The app-server process tree contained approximately 1,390 processes and 41.6 GiB of summed per-process 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.

    1. When a thread-created event arrives, the server passes every initialized connection ID to thread-listener attachment, rather than only the client that explicitly opened that child: lib.rs:1327-1345.
    2. Idle unloading is eligible only when both activity and subscribers are absent: thread_lifecycle.rs:60-66. This release already defaults to 60 seconds, and the local configuration did not override it: config/mod.rs:4145-4146. A retained subscription therefore prevents the timer from starting; shortening the delay cannot resolve that case.
    3. thread/unsubscribe removes 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.
    4. The native idle-unload path already invokes try_evict_v2_thread for 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.

  24. dpmedeiros commented on Nov 17, 2026

    @dpmedeiros

    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.51428 and its bundled codex-cli 0.167.0-alpha.4.1 on Linux x86_64. Source references below use the matching release commit d2c035639366e0bf2c316aa2065c24aabc12bcdc.

    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 = 2 and enables multi-agent V2 with max_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/list with that child's threadId and an explicit serverName initializes its own helper connections. There is no explicit thread/resume or subscription request for either child.

    These are the observed results from thread/loaded/list and process inspection:

    Action Loaded core threads Live helper processes
    P and A finish; initialize A's helpers P, A 4: two for P and two for A
    P spawns B; A is evicted; P and B finish; initialize B's helpers P, B 4: P's PIDs unchanged; A's helpers exited and B has two new PIDs
    thread/unsubscribe(A) P, B; response is notLoaded 4
    thread/unsubscribe(P); wait 4 seconds B only 2, both B's
    thread/unsubscribe(B); wait 4 seconds None 0

    The app server exited with status 0. All tracked diagnostic process IDs were absent afterward. Child completion was also present in the recorded turn/completed notifications.

    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 returned notLoaded but still emitted:

    clearing thread listener during thread-state teardown
    listener_generation=1 had_listener=true had_active_turn=false
    

    The listener drops the runtime after ShutdownComplete and keeps a notification relay. Thus, had_listener=true does 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 /tmp and the user's security-server path replaced with /PATH/TO/INSTALLED/.... Replace that placeholder with the installed security MCP server.mjs path. The other executable paths are those of the tested Linux desktop package; adjust them if the package is installed elsewhere.

    Save as reproduce.py and run python3 -u reproduce.py on a host where Python can create a loopback listener and inspect its child processes through /proc. The script creates its own temporary config and leaves results.json, events.json, and stderr.log in the printed diagnostic directory. The published path substitutions have not been rerun; the original harness produced the measurements above.

    import json,os,queue,subprocess,tempfile,threading,time,collections
    from pathlib import Path
    from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
    class Mock(BaseHTTPRequestHandler):
     def log_message(self,*args):pass
     def do_POST(self):
      body=json.loads(self.rfile.read(int(self.headers.get('Content-Length','0'))));items=body.get('input',[]);encoded=json.dumps(items)
      users=[v for v in items if isinstance(v,dict) and v.get('role')=='user'];last=json.dumps(users[-1]) if users else ''
      label=next((v for v in ['alpha','beta'] if 'SPAWN_'+v.upper()+'_DIAGNOSTIC' in last and 'spawn_'+v not in encoded),None)
      if label:item={'type':'function_call','call_id':'spawn_'+label,'namespace':'collaboration','name':'spawn_agent','arguments':json.dumps({'task_name':label,'message':'CHILD_'+label.upper()+'_DIAGNOSTIC. Reply done.','fork_turns':'none'})}
      else:
       if 'CHILD_' in last:time.sleep(.3)
       item={'id':'msg_done','type':'message','role':'assistant','status':'completed','content':[{'type':'output_text','text':'Done.','annotations':[]}]}
      self.send_response(200);self.send_header('Content-Type','text/event-stream');self.send_header('Connection','close');self.end_headers()
      for event in [{'type':'response.created','response':{'id':'resp_test','status':'in_progress'}},{'type':'response.output_item.done','item':item},{'type':'response.completed','response':{'id':'resp_test','status':'completed','usage':{'input_tokens':1,'output_tokens':1,'total_tokens':2}}}]:self.wfile.write(('event: '+event['type']+'\ndata: '+json.dumps(event)+'\n\n').encode())
      self.wfile.flush();self.close_connection=True
    work=Path('/tmp');directory=Path(tempfile.mkdtemp(prefix='subagent-helper-admission-',dir=work))
    http=ThreadingHTTPServer(('127.0.0.1',0),Mock);threading.Thread(target=http.serve_forever,daemon=True).start()
    config=f'''thread_unload_delay_secs = 2
    model_provider = "diagnostic"
    model = "diagnostic"
    [features]
    plugins = false
    apps = false
    [features.multi_agent_v2]
    enabled = true
    max_concurrent_threads_per_session = 2
    [analytics]
    enabled = false
    [model_providers.diagnostic]
    name = "Local simulated responses"
    base_url = "http://127.0.0.1:{http.server_port}/v1"
    wire_api = "responses"
    requires_openai_auth = false
    request_max_retries = 0
    stream_max_retries = 0
    [mcp_servers.cleanup_security]
    command = "/usr/lib/chatgpt/resources/cua_node/bin/node"
    args = ["/PATH/TO/INSTALLED/codex-security/0.1.32/mcp/server.mjs"]
    [mcp_servers.cleanup_node_repl]
    command = "/usr/lib/chatgpt/resources/cua_node/bin/node_repl"
    '''
    (directory/'config.toml').write_text(config)
    env={k:os.environ[k] for k in ['HOME','PATH','LANG','XDG_RUNTIME_DIR'] if k in os.environ};env['CODEX_HOME']=str(directory);env['RUST_LOG']='codex_app_server::thread_state=debug,codex_app_server::request_processors::thread_lifecycle=debug'
    stderr=open(directory/'stderr.log','w');p=subprocess.Popen(['/usr/lib/chatgpt/resources/codex','app-server','--listen','stdio://'],env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=stderr,text=True,bufsize=1)
    q=queue.Queue();events=[];counter=0;results=[]
    def reader():
     for line in p.stdout:
      try:q.put(json.loads(line))
      except ValueError:pass
    threading.Thread(target=reader,daemon=True).start()
    def request(method,params):
     global counter
     counter+=1;p.stdin.write(json.dumps({'jsonrpc':'2.0','id':counter,'method':method,'params':params})+'\n');p.stdin.flush();deadline=time.monotonic()+20
     while time.monotonic()<deadline:
      event=q.get(timeout=max(.01,deadline-time.monotonic()))
      if event.get('id')==counter:
       if 'error' in event:raise RuntimeError(str(event['error']))
       return event.get('result')
      events.append(event)
     raise TimeoutError(method)
    def helpers():
     found=[]
     for path in Path('/proc').iterdir():
      if not path.name.isdigit():continue
      try:
       parent=int((path/'stat').read_text().rsplit(')',1)[1].split()[1]);name=(path/'comm').read_text().strip()
       if parent==p.pid and name in ['node_repl','MainThread']:found.append(int(path.name))
      except (OSError,ValueError):pass
     return sorted(found)
    def record(stage,**values):
     row={'stage':stage,**values};results.append(row);print(json.dumps(row),flush=True)
    def status(stage):record(stage,loaded=request('thread/loaded/list',{})['data'],helpers=helpers())
    def finish_root(root):
     deadline=time.monotonic()+20
     while time.monotonic()<deadline:
      e=q.get(timeout=max(.01,deadline-time.monotonic()));events.append(e)
      if e.get('method')=='turn/completed' and e['params']['threadId']==root:break
     time.sleep(1)
    try:
     print('directory',directory,'server_pid',p.pid)
     request('initialize',{'clientInfo':{'name':'subagent-pipe-trace','version':'1'},'capabilities':{'experimentalApi':True}})
     p.stdin.write(json.dumps({'jsonrpc':'2.0','method':'initialized'})+'\n');p.stdin.flush()
     root=request('thread/start',{'cwd':str(directory),'approvalPolicy':'never','sandbox':'read-only','modelProvider':'diagnostic','model':'diagnostic'})['thread']['id']
     request('turn/start',{'threadId':root,'input':[{'type':'text','text':'SPAWN_ALPHA_DIAGNOSTIC'}]});finish_root(root)
     alpha=next(t for t in request('thread/loaded/list',{})['data'] if t!=root)
     
     for server in ['cleanup_security','cleanup_node_repl']:request('mcpServerStatus/list',{'threadId':alpha,'serverName':server,'limit':10,'detail':'toolsAndAuthOnly'})
     time.sleep(1);status('alpha_completed_helpers_initialized')
     record('root_and_alpha',root=root,alpha=alpha)
     request('turn/start',{'threadId':root,'input':[{'type':'text','text':'SPAWN_BETA_DIAGNOSTIC'}]});finish_root(root)
     beta=next(t for t in request('thread/loaded/list',{})['data'] if t!=root)
     
     for server in ['cleanup_security','cleanup_node_repl']:request('mcpServerStatus/list',{'threadId':beta,'serverName':server,'limit':10,'detail':'toolsAndAuthOnly'})
     time.sleep(1);status('beta_completed_alpha_evicted')
     record('beta',beta=beta)
     record('unsubscribe_alpha',response=request('thread/unsubscribe',{'threadId':alpha}));time.sleep(.2)
     record('unsubscribe_parent',response=request('thread/unsubscribe',{'threadId':root}));time.sleep(4);status('parent_unloaded_beta_still_subscribed')
     record('unsubscribe_beta',response=request('thread/unsubscribe',{'threadId':beta}));time.sleep(4);status('all_unsubscribed')
    finally:
     p.stdin.close()
     try:p.wait(timeout=10)
     except subprocess.TimeoutExpired:p.terminate();p.wait(timeout=5)
     stderr.close();http.shutdown();http.server_close()
     (directory/'results.json').write_text(json.dumps(results,indent=2));(directory/'events.json').write_text(json.dumps(events,indent=2))
     print('exit',p.returncode)
     for line in (directory/'stderr.log').read_text().splitlines():
      if 'clearing thread listener' in line or 'no subscribers and is idle' in line:print('TRACE',line)
  25. evandrocoan commented on Nov 21, 2026

    @evandrocoan

    Follow-up to my November 15 diagnosis. I tested a patched Linux x86_64 build from source revision f273ea856248 with three persisted V2 subagents. The desktop client stayed connected, the parent stayed loaded, and the same app-server process ran throughout.

    • All three children completed and went from idle to notLoaded.
    • Two children ran a small Node REPL MCP call. Four new Node subprocesses appeared under the shared REPL, and all four exited within 54 seconds of the snapshot that showed all three children idle. The shared REPL server itself stayed up.
    • The app-server's open file descriptors went 100 → 112 → 100. Cleanup occurred without restarting the server or explicitly unsubscribing the children.

    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
    diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs
    --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs
    +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs
    @@ -420,6 +420,9 @@ async fn start_listener(
                     conversation_id,
                     &listener_state,
                     connection_ids,
    +                // Passive child notifications must not pin a persisted runtime forever.
    +                // Ephemeral children cannot recover their context after idle eviction.
    +                /*retain_runtime*/ !created || !is_v2_child || config_snapshot.ephemeral,
                     |attached| {
                         let listener_matches = state.listener_matches(&conversation);
                         if !created && conversation.has_shutdown_status() {
    diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs
    --- a/codex-rs/app-server/src/thread_state.rs
    +++ b/codex-rs/app-server/src/thread_state.rs
    @@ -363,7 +363,9 @@ mod tests {
     struct ThreadEntry {
         state: Arc<Mutex<ThreadState>>,
         connection_ids: HashSet<ConnectionId>,
    +    retaining_connection_ids: HashSet<ConnectionId>,
         has_connections_watcher: watch::Sender<bool>,
    +    has_retaining_connections_watcher: watch::Sender<bool>,
     }
     
     impl Default for ThreadEntry {
    @@ -377,7 +379,9 @@ impl ThreadEntry {
             Self {
                 state,
                 connection_ids: HashSet::new(),
    +            retaining_connection_ids: HashSet::new(),
                 has_connections_watcher: watch::channel(false).0,
    +            has_retaining_connections_watcher: watch::channel(false).0,
             }
         }
     
    @@ -387,6 +391,14 @@ impl ThreadEntry {
                 *current = !self.connection_ids.is_empty();
                 prev != *current
             });
    +        let _ = self
    +            .has_retaining_connections_watcher
    +            .send_if_modified(|current| {
    +                let next = !self.retaining_connection_ids.is_empty();
    +                let changed = *current != next;
    +                *current = next;
    +                changed
    +            });
         }
     }
     
    @@ -584,7 +596,7 @@ impl ThreadStateManager {
             }
         }
     
    -    /// Removes an unsubscribed listener's entry without clearing a replacement's state.
    +    /// Removes an unretained listener's entry without clearing a replacement's state.
         #[expect(
             clippy::await_holding_invalid_type,
             reason = "the listener generation must stay fixed while removing its map entry"
    @@ -599,12 +611,16 @@ impl ThreadStateManager {
             let mut state = self.state.lock().await;
             if thread_state.listener_generation != generation
                 || !state.threads.get(&thread_id).is_some_and(|entry| {
    -                Arc::ptr_eq(&entry.state, expected) && entry.connection_ids.is_empty()
    +                Arc::ptr_eq(&entry.state, expected) && entry.retaining_connection_ids.is_empty()
                 })
             {
                 return false;
             }
             state.threads.remove(&thread_id);
    +        state.thread_ids_by_connection.retain(|_, thread_ids| {
    +            thread_ids.remove(&thread_id);
    +            !thread_ids.is_empty()
    +        });
             self.unregister_listener_command_tx(thread_id);
             thread_state.clear_listener();
             true
    @@ -657,6 +673,7 @@ impl ThreadStateManager {
                 }
                 if let Some(thread_entry) = state.threads.get_mut(&thread_id) {
                     thread_entry.connection_ids.remove(&connection_id);
    +                thread_entry.retaining_connection_ids.remove(&connection_id);
                     thread_entry.update_has_connections();
                 }
             };
    @@ -680,6 +697,7 @@ impl ThreadStateManager {
             thread_id: ThreadId,
             candidate: &ListenerStateCandidate,
             connection_ids: &[ConnectionId],
    +        retain_runtime: bool,
             install: impl FnOnce(bool) -> Result<T, E>,
         ) -> Result<Option<(T, watch::Receiver<bool>, bool)>, E> {
             let mut state = self.state.lock().await;
    @@ -706,12 +724,15 @@ impl ThreadStateManager {
                         .or_default()
                         .insert(thread_id);
                     entry.connection_ids.insert(connection_id);
    +                if retain_runtime {
    +                    entry.retaining_connection_ids.insert(connection_id);
    +                }
                 }
             }
             entry.update_has_connections();
             Ok(Some((
                 installed,
    -            entry.has_connections_watcher.subscribe(),
    +            entry.has_retaining_connections_watcher.subscribe(),
                 attached,
             )))
         }
    @@ -732,6 +753,7 @@ impl ThreadStateManager {
                 .insert(thread_id);
             let thread_entry = state.threads.entry(thread_id).or_default();
             thread_entry.connection_ids.insert(connection_id);
    +        thread_entry.retaining_connection_ids.insert(connection_id);
             thread_entry.update_has_connections();
             true
         }
    @@ -747,6 +769,7 @@ impl ThreadStateManager {
                 for thread_id in &thread_ids {
                     if let Some(thread_entry) = state.threads.get_mut(thread_id) {
                         thread_entry.connection_ids.remove(&connection_id);
    +                    thread_entry.retaining_connection_ids.remove(&connection_id);
                         thread_entry.update_has_connections();
                     }
                 }
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

    LinuxPapercuts 2026Papercuts: Source - Supportbugmcpsubagent

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions