Repository navigation
Description
What version of the Codex App are you using?
26.1013.40934, build 20770; embedded codex-cli 0.163.0-alpha.10.2.
What subscription do you have?
Account tier was not recorded in the diagnostic package. The isolated reproduction below uses an unauthenticated local model stub and does not require a subscription or API key.
Scope and related reports
This report focuses on safe runtime reclamation for completed V2 subagents, specifically the missing live-background-command guard in eviction. It includes a runnable isolated test showing why explicit archive is not a safe conditional-cleanup substitute, and a proposed maintainer regression test for the background-command risk.
Existing retention reports: #38247 and #55141. This is not intended as another generic MCP-memory report: the additional finding is the background-process eligibility gap and the safety contract needed before making completed-child reclamation automatic. #36095 describes a related but different concurrent-follow-up/residency-accounting race.
Evidence boundary: active-thread archive behavior was reproduced; background-command termination through V2 eviction is a source-supported risk and has not yet been reproduced at runtime. No loss of a user's background command is claimed.
Summary
Completed V2 subagents can retain their runtimes and associated MCP processes after reporting their final result. The existing idle-unload timer only helps after the final subscription is removed; completion alone does not reliably establish that condition.
Please provide a lifecycle operation that releases an eligible completed subagent's runtime without interrupting active work, background commands, its parent, or siblings, and without changing archive state or losing persisted results.
Two findings make an external cleanup workaround unsafe:
- Runtime-reproduced:
thread/archiveaccepts a currently active thread and unloads it. Thusread status -> if idle, archivehas a time-of-check/time-of-use race. Explicit archive may intentionally cancel work; this report does not claim that explicit archive must change semantics. It demonstrates why archive is not a substitute for conditional idle release. - Source-confirmed risk, not a runtime reproduction of background-command loss: the internal V2 eviction guard does not check live background terminals. Successful eviction shuts down the session, whose shutdown path terminates all unified-exec processes. If a child has completed its model turn while a yielded background command is still running, that command appears vulnerable to termination on eviction.
Environment
- Observed and retested: 2026-10-21.
- MacBook Air, Apple Silicon / arm64, 24 GiB RAM.
- macOS 27.0.1, build 26A434.
- Desktop bundle: version 26.1013.40934, build 20770.
- Embedded executable:
codex-cli 0.163.0-alpha.10.2. - Source checkout inspected:
openai/codex, commit4ebc485ca321243727539187169425fcf972f2c4. - V2 collaboration tools available in the affected session: spawn, follow-up, interrupt, send, list, wait; no callable V2
close_agentor conditional unload operation was exposed.
Impact and scope of observations
During prolonged parallel use, the machine accumulated several hundred Node/tool processes and severe memory pressure. This is a system-wide operational observation, not a controlled per-agent memory benchmark, and not a claim that every process was orphaned. Many retained tool processes still had a live app-server parent and pipes.
Completed subagent runtimes remained loaded despite final results being available. Manually unloading individually verified completed runtimes released their associated tool processes. This motivated the request for safe automatic release, rather than a PID-age or process-name killer.
The exact reason every retained child remains resident is not established by the minimal test below. Completion notification, subscription lifetime and V2 residency need investigation together. Do not infer that a completed turn means a task has no remaining background work.
Reproduction A: archive is not a conditional idle-release operation
repro_archive_active.py is embedded in full below (Python standard library only).
Run against the affected executable:
python3 repro_archive_active.py \
--codex-bin /Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex \
--output archive-result.jsonFor another installation, replace --codex-bin with its executable path. If codex is already on PATH, the argument can be omitted.
The script:
- Creates a temporary, isolated
CODEX_HOMEand working directory. It does not connect to the Desktop app-server, copy credentials, or use any existing chat ID. - Starts its own stdio app-server and a loopback HTTP server implementing a minimal Responses stream. No real model inference is requested.
- Initializes the protocol, starts a synthetic thread and starts one turn.
- Keeps the local response stream open and verifies
thread/readreturnsstatus.type = active. - Calls
thread/archiveon only that synthetic thread and thenthread/loaded/list. - Stops its own app-server and HTTP server and removes its temporary state.
The relevant protocol sequence is:
initialize -> initialized
thread/start -> synthetic thread ID
turn/start -> local response stream held open
thread/read -> { "status": { "type": "active", "activeFlags": [] } }
thread/archive -> { "result": {} }
thread/loaded/list -> synthetic thread ID absent
Observed again with the script embedded below:
{
"before_archive_status": {"type": "active", "activeFlags": []},
"archive_response": {"id": 5, "result": {}},
"still_loaded_after_archive": false,
"active_archive_observed": true,
"real_model_inference_used": false,
"isolated_app_server_exited": true
}The full sanitized result is in archive-result.json. A future rejection or changed behavior is reported by active_archive_observed: false; a failed precondition raises an error. Do not use this test to archive a real user thread.
Reproduction B: maintainer regression test for background commands
Proposed integration test; not executed in this report. This case requires access to the internal V2 eviction primitive or a controlled V2 capacity-eviction harness.
- Create a V2 parent and child with an isolated MCP test server.
- In the child, start an owned unified-exec command that yields a session ID and continues updating a temporary heartbeat file. Keep the command alive with an explicit test-controlled release condition.
- Complete the child's model turn while that command remains running. Assert the child is
Completed, has no active model turn, and its background terminal is still live. - Invoke the normal internal conditional-eviction path. For a black-box variant, create sufficient additional children to trigger residency pressure and confirm this child is the selected candidate.
- Assert that eviction returns
Busyor an equivalent structured reason and the heartbeat/process remains alive. Also assert that the parent, siblings and their MCP processes remain unaffected. - Finish the command, retry eviction, and assert that only this child's runtime and owned MCP process are released, with its final result/history preserved.
The inspected implementation appears to admit the child in step 4 and terminate its background process during shutdown. This predicted result still needs the runtime integration test above; no claim is made that a user's background command was actually lost during this investigation.
Source evidence
All links are pinned to the inspected commit, rather than a moving branch.
try_evict_v2_thread, residency gate and exact runtime identity: uses the residency write gate and keeps it through shutdown/persistence/removal. This is a useful basis for a safe operation.is_unloadable: checks terminal-like agent status, no active turn, no outstanding durable sleep and no trigger-turn mailbox items. There is no background-terminal check here.shutdown_session_runtime: callsunified_exec_manager.terminate_all_processes()and shuts down the MCP runtime.- Archive preparation removes/shuts down the runtime without a conditional idle guard. Archive implementation operates on the spawned subtree. The list-state permit does not provide the required turn-admission guard.
- Delayed unloading uses the V2 eviction primitive and retries
Busy; it depends on subscription release. - Completion routing delivers terminal outcomes to the parent, but does not itself provide a public completed-child release operation.
Existing mitigation and its limits
Setting thread_unload_delay_secs = 300 was tested with the installed binary using two isolated synthetic threads, each with its own small MCP test process. After unsubscribing one thread, it and its MCP process remained present at 295 seconds and were gone at 302 seconds. The subscribed control and its MCP process survived. All test processes were subsequently cleaned up.
This verifies the post-unsubscribe delay, not automatic release of retained child subscriptions, background-command safety, or history restoration. Lowering this value alone does not address the reported lifecycle gap.
Requested behavior and acceptance criteria
Provide automatic completed-child release and/or an explicit conditional release operation available to the owning parent/controller. A proposed name such as thread/releaseIfIdle is illustrative; it is not an existing API.
- Trigger a release attempt after a child completes, with a documented retention/grace policy. Do not rely only on last-subscriber removal or later capacity pressure. Completion must not itself be treated as sufficient proof of eligibility.
- Under the same admission/residency synchronization used by turn starts and message delivery, verify the exact current runtime generation and that there are no active or queued turns, pending approval/input waits, durable sleeps, trigger messages, live background commands, or active dependent descendants. Unknown state must fail closed.
- Coordinate background-process creation and completion with that synchronization. Listing processes first and shutting down later is insufficient.
- Return a structured
Busyreason with no shutdown side effects when ineligible. A concurrent follow-up must either prevent eviction or be delivered safely after rehydration; it must never be interrupted or dropped by cleanup. - Persist the terminal result, relevant mailbox state and history before releasing resources. Do not change archive state or cascade shutdown into parents/siblings. Active descendants must prevent release unless ownership can be preserved explicitly.
- Release only resources owned by the selected runtime, including its MCP processes. Shared runtimes/resources need ownership/refcount handling rather than broad termination.
- Preserve the ability to resume the child from persisted state with an explicit contract for which volatile tool state is not retained.
- Cover races, cancellation and partial shutdown/persistence failures with tests. A stale completion event must not evict a newer runtime registered under the same thread ID. Include the background-command regression above, active siblings/parent, pending approval/input, durable sleep, queued follow-up, history read/resume, and process-leak checks.
Embedded files and disclosure
repro_archive_active.py: locally retested reproducer.archive-result.json: fresh synthetic result, without real thread IDs or local account paths.verification-summary.json: sanitized summary of the separate five-minute test and source-evidence status.
No production logs, credentials, real conversation contents or user process listings are included. The reproducer and sanitized results are embedded below so the report is self-contained.
repro_archive_active.py
#!/usr/bin/env python3
"""Probe archive semantics using an isolated Codex app-server and local fake model.
No production CODEX_HOME, chat IDs, credentials, or real inference are used.
The test archives ONLY the synthetic thread created by this script.
"""
import argparse
import http.server
import json
import os
import queue
import shutil
import subprocess
import tempfile
import threading
import time
from pathlib import Path
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--codex-bin", default=shutil.which("codex"))
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if not args.codex_bin:
parser.error("Pass --codex-bin pointing to the Codex executable under test")
binary = str(Path(args.codex_bin).resolve())
version = subprocess.check_output([binary, "--version"], text=True).strip()
ready = threading.Event()
stop = threading.Event()
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *unused: object) -> None:
pass
def do_POST(self) -> None:
self.rfile.read(int(self.headers.get("Content-Length", 0)))
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
event = {
"type": "response.created",
"response": {
"id": "resp_local_probe",
"object": "response",
"created_at": int(time.time()),
"model": "probe",
"status": "in_progress",
"output": [],
},
}
self.wfile.write(("data: " + json.dumps(event) + "\n\n").encode())
self.wfile.flush()
ready.set()
stop.wait(90)
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
process = None
result = None
try:
with tempfile.TemporaryDirectory(prefix="codex-archive-repro-") as temporary:
root = Path(temporary)
home = root / "codex-home"
home.mkdir()
(home / "config.toml").write_text(
'model = "probe"\nmodel_provider = "probe"\n'
'approval_policy = "never"\nsandbox_mode = "read-only"\n'
'[model_providers.probe]\nname = "Local lifecycle test"\n'
f'base_url = "http://127.0.0.1:{server.server_port}/v1"\n'
'wire_api = "responses"\nrequires_openai_auth = false\n',
encoding="utf-8",
)
environment = {
key: os.environ[key]
for key in ("PATH", "HOME", "TMPDIR", "LANG", "SYSTEMROOT")
if key in os.environ
}
environment["CODEX_HOME"] = str(home)
messages = queue.Queue()
with (root / "app-server.log").open("w") as log:
process = subprocess.Popen(
[binary, "app-server"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=log,
text=True,
cwd=root,
env=environment,
)
def reader() -> None:
try:
for line in process.stdout:
messages.put(json.loads(line))
finally:
messages.put(None)
threading.Thread(target=reader, daemon=True).start()
serial = 0
def rpc(method: str, params: dict) -> dict:
nonlocal serial
serial += 1
process.stdin.write(
json.dumps(
{
"id": serial,
"method": method,
"params": params,
}
)
+ "\n"
)
process.stdin.flush()
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
message = messages.get(
timeout=max(0.1, deadline - time.monotonic())
)
if message is None:
raise RuntimeError("app-server exited before replying")
if message.get("id") == serial:
return message
raise TimeoutError(method)
def request(method: str, params: dict) -> dict:
response = rpc(method, params)
if "error" in response:
raise RuntimeError(f"{method}: {response['error']}")
return response["result"]
try:
request(
"initialize",
{
"clientInfo": {
"name": "archive_safety_probe",
"version": "1",
},
"capabilities": {"experimentalApi": True},
},
)
process.stdin.write('{"method":"initialized","params":{}}\n')
process.stdin.flush()
thread_id = request(
"thread/start",
{
"cwd": str(root),
"baseInstructions": "Local synthetic test only.",
},
)["thread"]["id"]
request(
"turn/start",
{
"threadId": thread_id,
"input": [{"type": "text", "text": "Local lifecycle test"}],
},
)
if not ready.wait(20):
raise RuntimeError("Local fake model stream was not reached")
before = request(
"thread/read",
{
"threadId": thread_id,
"includeTurns": True,
},
)["thread"]["status"]
if before.get("type") != "active":
raise RuntimeError(f"Precondition failed: {before}")
archive = rpc("thread/archive", {"threadId": thread_id})
loaded = thread_id in request("thread/loaded/list", {})["data"]
result = {
"codex_version": version,
"before_archive_status": before,
"archive_response": archive,
"still_loaded_after_archive": loaded,
"active_archive_observed": "result" in archive and not loaded,
"real_model_inference_used": False,
}
finally:
stop.set()
process.stdin.close()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
if result is not None:
result["isolated_app_server_exited"] = (
process.poll() is not None
)
finally:
stop.set()
server.shutdown()
server.server_close()
rendered = json.dumps(result, indent=2)
print(rendered)
if args.output:
args.output.write_text(rendered + "\n", encoding="utf-8")
if __name__ == "__main__":
main()archive-result.json
{
"codex_version": "codex-cli 0.163.0-alpha.10.2",
"before_archive_status": {
"type": "active",
"activeFlags": []
},
"archive_response": {
"id": 5,
"result": {}
},
"still_loaded_after_archive": false,
"active_archive_observed": true,
"real_model_inference_used": false,
"isolated_app_server_exited": true
}verification-summary.json
{
"environment": {
"os": "macOS 27.0.1 (26A434)",
"architecture": "arm64",
"hardware": "MacBook Air, 24 GiB RAM",
"desktop_version": "26.1013.40934",
"desktop_build": "20770",
"codex_version": "0.163.0-alpha.10.2"
},
"source_commit": "4ebc485ca321243727539187169425fcf972f2c4",
"archive_probe": {
"evidence_type": "fresh isolated runtime reproduction",
"result_file": "archive-result.json",
"real_model_inference_used": false
},
"idle_unload_probe": {
"evidence_type": "previous isolated runtime test on the same installed version",
"configured_delay_seconds": 300,
"still_loaded_at_seconds": 295,
"unloaded_by_seconds": 302.005188540963,
"released_mcp_exited": true,
"subscribed_control_and_mcp_retained": true,
"all_probe_processes_cleaned_up": true
},
"background_command_risk": {
"evidence_type": "source inspection and proposed integration regression",
"runtime_reproduced": false
},
"limitations": [
"Archive probe does not reproduce V2 child retention itself.",
"Background-command termination during V2 eviction has not been runtime-reproduced.",
"Idle probe did not test history restoration or an active model turn."
]
}
Activity
ariccio commentedon Oct 26, 2026
Disclosure: This comment was generated by Codex, operating fully autonomously in the research and drafting of this comment.
A source recheck against stable 0.164.0 still shows the background-command eligibility gap described here: the unload predicate checks agent status, active turn, durable sleep and mailbox items, while session shutdown terminates the thread's unified-exec processes.
This is a version update to the source-supported risk, not a runtime reproduction of background-command loss. The distinction matters for the completed-child MCP retention in #38247: runtime reclamation needs a conditional eligibility check that also protects background work and concurrent follow-ups.
Version-pinned source paths
is_unloadable, rust-v0.164.0: no live-background-process check in this predicate.shutdown_session_runtime, rust-v0.164.0: terminates unified-exec processes before shutting down the MCP runtime.No eviction or archive was attempted against the live children during this audit.
Prompt that motivated checking the release operation
The account owner selected the scope and controls publication; the measurements, source analysis and wording are Codex's.