codex icon indicating copy to clipboard operation
codex copied to clipboard

[unified_exec] Interrupting a turn leaves the in-flight shell process running

Open unicorn200066 opened this issue 2 months ago • 8 comments

What version of the Codex App are you using (From “About Codex” dialog)?

26.901.31953

What subscription do you have?

Pro

What platform is your computer?

Darwin 25.5.0 arm64 arm

What issue are you seeing?

When I interrupt an active turn while exec_command or write_stdin is waiting on a long-running command, Codex reports the turn as interrupted, but the shell process continues running in the background.

For example, after starting "sleep 600" and pressing Stop, the turn ends but the sleep process remains alive.

This is misleading because Stop appears to stop the active operation. The remaining process may continue consuming resources, writing files, holding ports or locks, and interfering with later commands.

The issue is limited to interactive Unified Exec commands that can return a process_id. One-shot execution already terminates its process on cancellation.

What steps can reproduce the bug?

  1. Start Codex with Unified Exec enabled.

  2. Ask Codex:

    Use exec_command to run: sh -c 'echo $$ > /tmp/codex-turn-abort-repro.pid; exec sleep 600'

    Set yield_time_ms=30000. If a process_id is returned, keep polling it with write_stdin and wait 30000ms each time.

  3. While exec_command or write_stdin is waiting, press Stop.

  4. In another terminal, run:

    pid="$(cat /tmp/codex-turn-abort-repro.pid)" kill -0 "$pid" && echo "process is still running"

  5. Observe that the process is still running.

Cleanup:

kill "$(cat /tmp/codex-turn-abort-repro.pid)" rm /tmp/codex-turn-abort-repro.pid

What is the expected behavior?

Interrupting a turn should terminate shell processes started by that turn and remove them from the background process store.

If process persistence is intentional, Codex should distinguish Detach from Stop and clearly tell the user that the process is still running.

Additional information

Root-cause analysis The process is stored in the session-level ProcessStore before the initial yield wait. The source comment explicitly states that this is done so interrupting the turn does not terminate the background process:

  1. handle_task_abort cancels the turn token and aborts the task, but it does not terminate Unified Exec processes:
  2. The tool dispatcher aborts the tool handler future:
  3. Aborting the future does not drop the process because ProcessStore still owns an Arc.
  4. ProcessEntry contains no turn identifier, so the process manager cannot determine which processes belong to the aborted turn:
  5. Process termination currently happens only through explicit terminal termination or session-wide cleanup:
    • process_manager.rs lines 1673–1720 The one-shot execution path already handles cancellation by calling terminate_confirmed(), which demonstrates the expected cancellation behavior:
  • oneshot.rs lines 25–74 Possible implementation direction
  • Record the owning turn ID in each ProcessEntry.
  • When a turn is aborted, terminate and remove all processes owned by that turn.
  • Cover both local and ExecServer-backed processes.
  • Add regression tests for interruption:
    • during the initial exec_command yield;
    • during a write_stdin poll;
    • with and without the local sandbox;
    • without affecting normally completed turns or explicitly detached processes.

unicorn200066 avatar Sep 04 '26 10:09 unicorn200066

Thanks for the detailed root-cause analysis — it is very well documented. I dug into the current code and want to flag an important design tension before anyone implements kill-on-abort, because the current behavior is intentional, not an oversight.

In codex-rs/core/src/unified_exec/process_manager.rs (the exec_command_inner path, around lines 567-570), the code persists the live process into the session-level ProcessStore before the initial yield wait, with an explicit comment: "Persist live sessions before the initial yield wait so interrupting the turn cannot drop the last Arc and terminate the background process."

So the reason Stop currently leaves the process alive is that the ProcessStore holds an Arc keyed by call_id. When the turn is aborted, handle_task_abort cancels the turn token and aborts the tool handler future, but that only drops the per-call Arc; the store Arc remains, which keeps the process alive. This matches what I see.

The question is whether killing these processes on turn abort is the desired semantics. There is a real product question here:

  • View A (reporter proposal): Stop should be a hard stop - terminate every process the aborted turn started. This makes Stop symmetric and predictable.
  • View B (current design): Unified Exec background processes are intentionally resilient to interruption - the process outlives the call/turn so a long-running command can keep going and be polled later. Stop cancels the waiting, not the process.

These conflict. The comment explicitly documents View B. So a fix that kills on abort is not a bug fix; it is a behavior change that reverses a documented chosen design.

If maintainers want View A, the implementation is feasible: ProcessEntry already carries call_id (line 186 in unified_exec/mod.rs), and turn_context is available at exec_command_inner, so an owning turn ID can be threaded in, and handle_task_abort can enumerate and terminate the store entries owned by the aborted turn (mirroring the one-shot path in oneshot.rs, which already calls terminate_confirmed on cancellation). The one-shot path demonstrates exactly the kill-on-cancel semantics you expect, which tells me maintainers do support kill-on-cancel in the non-resumable case.

But I would rather ask than assume: is the current persistence-across-interrupt behavior the intended contract for Unified Exec, or is your expectation (processes should die with their turn) the intended contract? If the latter, I would be happy to draft the owning-turn-ID + terminate-on-abort change with regression tests. If the former (View B), then the real fix is a UX/clarity one - making Stop clearly communicate that the background process keeps running, and adding an explicit detach/keep vs terminate affordance.

No change made - just raising the design question before any code is written.

argszero avatar Sep 04 '26 10:09 argszero

Confirmation after explicitly authorized termination

The existing comment correctly distinguishes intentional persistence across Stop from kill-on-abort. This clarification does NOT propose changing Stop semantics.

After a client separately requests termination, which public app-server receipt establishes actual exit/drain completion?

At revision 1bc8fb16ae53512c0c7723a436e4b11be81ad4a8, single-process termination retains identity across its await, but terminate_confirmed locally requests termination then marks internal state exited. The local handle drops rather than awaits its waiter: https://github.com/openai/codex/blob/1bc8fb16ae53512c0c7723a436e4b11be81ad4a8/codex-rs/core/src/unified_exec/process.rs#L227-L255 https://github.com/openai/codex/blob/1bc8fb16ae53512c0c7723a436e4b11be81ad4a8/codex-rs/utils/pty/src/process.rs#L245-L274

The executor termination handler also acknowledges the request without joining the child there: https://github.com/openai/codex/blob/1bc8fb16ae53512c0c7723a436e4b11be81ad4a8/codex-rs/exec-server/src/local_process.rs#L676-L705

Consequently, terminate-then-empty inventory is not itself observed OS wait evidence. This is source analysis, not a newly executed leak reproduction. Internal per-process Exited/Closed events exist; can their retained, incarnation-scoped evidence be exposed or consumed through an existing app-server contract, including remote placement and disconnect uncertainty?

Context: https://github.com/openclaw/openclaw/pull/141414 repairs duplicate prompt admission. Separate post-timeout summary recovery must not infer settlement from a boolean or empty inventory. Even genuine per-process exit is distinct from whole-turn or detached-descendant quiescence.

If a stronger operation is needed, it should retain owner-held handles until bounded observed exit/drain completion and report unknown on missing evidence. No automatic kill-on-abort, shared-client shutdown or recovery-policy widening is requested.

This source revision is not asserted to match an installed release. A separate native-driver characterization test has been authored but not compiled or run.

pfrederiksen avatar Sep 08 '26 01:09 pfrederiksen

Additional macOS reproduction: repeated interruption retains 2 → 4 → 6 workers; archive reclaims them

I reproduced this with the core bundled in desktop 26.915.31945 (build 9922), reporting codex-cli 0.155.0-alpha.9.2, on macOS 26.6.2 / 25G83, arm64 (2026-09-21).

In three independent experiments, starting and interrupting a bounded command three times in one thread accumulated live workers as follows:

Experiment After interrupt 1 After interrupt 2 After interrupt 3 After thread/archive
1 2 4 6 0
2 2 4 6 0
3 2 4 6 0

Each execution starts a Python parent and one child in the same process group. These counts include only registered fixture workers. The parents remained children of the live app-server; workers were sleeping processes, not zombies. Observations were taken approximately 3 seconds after interruption and 4 seconds after archive, before the children's 65-second lifetime limit. No app-server crash or kill was involved.

Reproduction method: an independent observer starts the installed core with an isolated application data directory and a deterministic loopback Responses fixture. A temporary skill is discovered and read, then the actual exec_command path runs its script. After exec_command yields a session ID, the fixture holds the next model response while the observer sends turn/interrupt. It repeats this sequence twice in the same thread, then archives the thread. Model responses are scripted; process execution, interruption, and archive are performed by the actual core.

This confirms resource retention across interrupted turns in this build, not unbounded heap leakage or loss of process ownership. It does not test the desktop Stop button, a newer standalone CLI, Windows, or a real model's tool-selection behavior. Normal completion and same-group script-error controls reclaimed workers; separate MCP lifecycle controls also reclaimed their process groups. A deliberately detached script-child case is outside this report.

The nearby rust-v0.155.0-alpha.9 source describes preserving execution across interruption; I cannot assert that tag exactly matches the bundled .2 build. This adds execution evidence to the existing design discussion. Could maintainers clarify the intended interruption contract and whether an explicit “terminate executions owned by this turn” action, with observed-exit confirmation, should be exposed? Intentionally retained services and other threads' executions should remain protected.

Reproduce: save the three unchanged harness modules below in one writable directory and run python3 skill_scenarios.py cancel_churn from an ordinary macOS terminal. Python 3.9+ standard library is sufficient; the tested binary path is /Applications/ChatGPT.app/Contents/Resources/codex (adjust BINARY in probe.py for another installation). The observer needs permission to inspect its own processes and bind a loopback port. No real model credentials/calls are needed. The modules contain other optional control scenarios; the command above runs only the focused three-repeat interruption case. They create disposable test directories and perform PID/start-identity-scoped cleanup. All registered test processes were confirmed gone afterward.

Binary SHA-256: 9280c0754e8f1f6b72f495d30c8c82a006dbc4995bf0492916fa0901f6bfd1f9.

Selected observations (paths and host identifiers omitted)
[
  {
    "repeat": 1,
    "turn_status": "interrupted",
    "observations": [
      {
        "phase": "before_cancel",
        "alive_workers": 2,
        "spawned_workers": 2
      },
      {
        "phase": "after_turn_completed",
        "alive_workers": 2,
        "spawned_workers": 2
      },
      {
        "phase": "after_cancel_2",
        "alive_workers": 4,
        "spawned_workers": 4
      },
      {
        "phase": "after_cancel_3",
        "alive_workers": 6,
        "spawned_workers": 6
      },
      {
        "phase": "after_archive",
        "alive_workers": 0,
        "spawned_workers": 6
      }
    ],
    "harness_cleanup_count": 0,
    "final_alive_count": 0
  },
  {
    "repeat": 2,
    "turn_status": "interrupted",
    "observations": [
      {
        "phase": "before_cancel",
        "alive_workers": 2,
        "spawned_workers": 2
      },
      {
        "phase": "after_turn_completed",
        "alive_workers": 2,
        "spawned_workers": 2
      },
      {
        "phase": "after_cancel_2",
        "alive_workers": 4,
        "spawned_workers": 4
      },
      {
        "phase": "after_cancel_3",
        "alive_workers": 6,
        "spawned_workers": 6
      },
      {
        "phase": "after_archive",
        "alive_workers": 0,
        "spawned_workers": 6
      }
    ],
    "harness_cleanup_count": 0,
    "final_alive_count": 0
  },
  {
    "repeat": 3,
    "turn_status": "interrupted",
    "observations": [
      {
        "phase": "before_cancel",
        "alive_workers": 2,
        "spawned_workers": 2
      },
      {
        "phase": "after_turn_completed",
        "alive_workers": 2,
        "spawned_workers": 2
      },
      {
        "phase": "after_cancel_2",
        "alive_workers": 4,
        "spawned_workers": 4
      },
      {
        "phase": "after_cancel_3",
        "alive_workers": 6,
        "spawned_workers": 6
      },
      {
        "phase": "after_archive",
        "alive_workers": 0,
        "spawned_workers": 6
      }
    ],
    "harness_cleanup_count": 0,
    "final_alive_count": 0
  }
]

Note: the harness phase name after_turn_completed refers to the turn/completed notification; its status in this case is interrupted.

probe.py
"""Bounded local app-server process-lifecycle probe. No model calls or user sessions.

Uses the installed binary with a separate supported CODEX_HOME in the child
environment only. Existing app, settings, credentials and processes are untouched.
Every synthetic worker has a 25-second lifetime; cleanup targets recorded PIDs
only after checking their process-start fingerprint.
"""
import datetime
import json
import os
from pathlib import Path
import queue
import signal
import subprocess
import sys
import tempfile
import threading
import time

ROOT = Path(__file__).resolve().parent
BINARY = '/Applications/ChatGPT.app/Contents/Resources/codex'


def fingerprint(pid):
    p = subprocess.run(['ps', '-p', str(pid), '-o', 'lstart='], capture_output=True, text=True)
    return p.stdout.strip() or None


def table():
    p = subprocess.run(['ps', '-axo', 'pid=,ppid=,pgid=,rss=,stat=,comm='], capture_output=True, text=True, check=True)
    rows = {}
    for line in p.stdout.splitlines():
        a = line.split(None, 5)
        if len(a) == 6:
            rows[int(a[0])] = {'pid': int(a[0]), 'ppid': int(a[1]), 'pgid': int(a[2]), 'rss_kib': int(a[3]), 'stat': a[4], 'exe': a[5]}
    return rows


def worker(ledger, mode, role):
    with open(ledger, 'a') as f:
        f.write(json.dumps({'role': role, 'pid': os.getpid(), 'ppid': os.getppid()}) + '\n')
    if role == 'child':
        time.sleep(.2 if mode == 'normal' else 25)
        return
    child = subprocess.Popen([sys.executable, __file__, 'worker', ledger, mode, 'child'])
    child.wait(timeout=27)


class Server:
    def __init__(self, directory):
        self.events = []
        self.q = queue.Queue()
        self.directory = directory
        self.stderr = open(directory / 'server.stderr', 'w')
        child_env = dict(os.environ)
        # This is the documented application data directory, not a shell variable
        # used for an unrelated purpose. Parent environment remains unchanged.
        child_env['CODEX_HOME'] = str(directory / 'isolated-codex-home')
        Path(child_env['CODEX_HOME']).mkdir()
        self.p = subprocess.Popen([BINARY, '-c', 'analytics.enabled=false', '-c', 'feedback.enabled=false', 'app-server', '--stdio'], cwd=directory, env=child_env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.stderr, text=True, start_new_session=True)
        self.reader = threading.Thread(target=self.read, daemon=True)
        self.reader.start()
        self.send('initialize', {'clientInfo': {'name': 'local_lifecycle_probe', 'version': '1'}, 'capabilities': {'experimentalApi': True}}, 1)
        self.await_id(1, 10)
        self.send('initialized', {})

    def read(self):
        for line in self.p.stdout:
            try:
                obj = json.loads(line)
                self.events.append(obj)
                self.q.put(obj)
            except ValueError:
                pass

    def send(self, method, params, ident=None):
        obj = {'method': method, 'params': params}
        if ident is not None:
            obj['id'] = ident
        self.p.stdin.write(json.dumps(obj) + '\n')
        self.p.stdin.flush()

    def await_id(self, ident, seconds):
        end = time.monotonic() + seconds
        while time.monotonic() < end:
            for event in self.events:
                if event.get('id') == ident:
                    if 'error' in event:
                        raise RuntimeError(json.dumps(event))
                    return event
            time.sleep(.02)
        raise TimeoutError('RPC ' + str(ident))

    def close(self):
        if self.p.poll() is None:
            if not self.p.stdin.closed:
                self.p.stdin.close()
            try:
                self.p.wait(timeout=3)
            except subprocess.TimeoutExpired:
                self.p.terminate()
                try:
                    self.p.wait(timeout=2)
                except subprocess.TimeoutExpired:
                    self.p.kill()
                    self.p.wait(timeout=2)
        self.reader.join(timeout=1)
        self.stderr.close()


def run_case(mode, repeat, run_dir):
    directory = run_dir / (mode + '-' + str(repeat))
    directory.mkdir()
    ledger = directory / 'workers.jsonl'
    server = None
    identities = {}
    result = {'mode': mode, 'repeat': repeat}
    try:
        server = Server(directory)
        result['server_pid'] = server.p.pid
        server.send('command/exec', {
            'command': [sys.executable, __file__, 'worker', str(ledger), mode, 'parent'],
            'cwd': str(directory), 'processId': 'probe',
            'timeoutMs': 1200 if mode == 'timeout' else 28000,
            'sandboxPolicy': {'type': 'workspaceWrite', 'writableRoots': [str(ROOT), str(directory)], 'networkAccess': False},
        }, 2)
        end = time.monotonic() + 5
        workers = []
        while time.monotonic() < end:
            if ledger.exists():
                workers = [json.loads(line) for line in ledger.read_text().splitlines()]
                for w in workers:
                    identities.setdefault(w['pid'], fingerprint(w['pid']))
                if len(workers) >= 2:
                    break
            if any(e.get('id') == 2 and 'error' in e for e in server.events):
                raise RuntimeError(str(server.events))
            time.sleep(.02)
        if len(workers) != 2:
            raise RuntimeError('Synthetic process tree did not start: ' + str(server.events))
        before = table()
        result['workers'] = workers
        result['before'] = [before[w['pid']] for w in workers if w['pid'] in before]
        if mode == 'terminate':
            server.send('command/exec/terminate', {'processId': 'probe'}, 3)
            result['termination_response'] = server.await_id(3, 5)
        elif mode == 'disconnect':
            server.p.stdin.close()
        elif mode == 'server_sigterm':
            server.p.terminate()
        elif mode == 'server_sigkill':
            server.p.kill()
        if mode in ('normal', 'timeout', 'terminate'):
            result['command_response'] = server.await_id(2, 7)
        time.sleep(3)
        after = table()
        result['survivors_after_3s'] = [after[w['pid']] for w in workers if w['pid'] in after and fingerprint(w['pid']) == identities[w['pid']] and not after[w['pid']]['stat'].startswith('Z')]
        result['server_exit_before_harness_cleanup'] = server.p.poll()
        result['outcome'] = 'survivors' if result['survivors_after_3s'] else 'clean'
    except Exception as exc:
        result['outcome'] = 'test_error'
        result['error'] = str(exc)
    finally:
        if server:
            server.close()
            (directory / 'rpc.json').write_text(json.dumps(server.events, indent=2))
        cleaned = []
        for pid, identity in identities.items():
            if identity and fingerprint(pid) == identity:
                try:
                    os.kill(pid, signal.SIGTERM)
                    cleaned.append(pid)
                except ProcessLookupError:
                    pass
        result['harness_cleanup_pids'] = cleaned
        time.sleep(.2)
        rows = table()
        result['remaining_live_workers'] = [pid for pid, identity in identities.items() if identity and fingerprint(pid) == identity and pid in rows and not rows[pid]['stat'].startswith('Z')]
        (directory / 'result.json').write_text(json.dumps(result, indent=2))
    print(json.dumps(result), flush=True)
    return result


if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == 'worker':
        worker(*sys.argv[2:])
    else:
        run_dir = Path(tempfile.mkdtemp(prefix='codex-lifecycle-', dir=str(ROOT)))
        results = []
        modes = sys.argv[1:] or ['normal', 'timeout', 'terminate', 'disconnect', 'server_sigterm', 'server_sigkill']
        for mode in modes:
            for repeat in range(1, 4):
                results.append(run_case(mode, repeat, run_dir))
                if results[-1]['outcome'] == 'test_error':
                    break
        summary = {'time': datetime.datetime.now().astimezone().isoformat(), 'binary': BINARY, 'run_dir': str(run_dir), 'results': results}
        (ROOT / 'probe-results.json').write_text(json.dumps(summary, indent=2))

common_scenarios.py
"""Isolated MCP and skill lifecycle fixtures for the installed Codex core.

No user MCPs, credentials, real model calls, or installed skills are modified.
The observer owns all disposable app servers and checks synthetic PID identities.
"""
import atexit
import json
import os
from pathlib import Path
import queue
import shlex
import signal
import subprocess
import sys
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from probe import BINARY, ROOT, Server, fingerprint, table


class LocalModel:
    """Deterministic loopback Responses fixture, not an external AI model."""
    def __init__(self, directory, script_command=None, hold_after_tool=False):
        self.directory = directory
        self.requests = []
        self.commands = ([script_command] if isinstance(script_command, str) else script_command) or []
        self.command_offset = 0
        self.hold_after_tool = hold_after_tool
        self.release = threading.Event()
        model = self

        class Handler(BaseHTTPRequestHandler):
            def log_message(self, *args):
                pass

            def do_POST(self):
                data = self.rfile.read(int(self.headers.get('Content-Length', 0)))
                try:
                    req = json.loads(data)
                except Exception:
                    req = {'decode_error': True, 'headers': dict(self.headers)}
                model.requests.append(req)
                index = len(model.requests)
                step = index - model.command_offset
                (directory / ('model-request-' + str(index) + '.json')).write_text(json.dumps(req, indent=2))
                if model.hold_after_tool and step > len(model.commands):
                    model.release.wait(timeout=25)
                response_id = 'fixture-' + str(index)
                events = [{'type': 'response.created', 'response': {'id': response_id}}]
                if step <= len(model.commands):
                    events.append({'type': 'response.output_item.done', 'item': {
                        'type': 'function_call', 'call_id': 'fixture-script-' + str(index), 'name': 'exec_command',
                        'arguments': json.dumps({'cmd': model.commands[step - 1], 'yield_time_ms': 1000, 'max_output_tokens': 1800})}})
                else:
                    events.append({'type': 'response.output_item.done', 'item': {'type': 'message',
                        'role': 'assistant', 'id': 'msg-' + str(index), 'content': [{'type': 'output_text', 'text': 'fixture complete'}]}})
                events.append({'type': 'response.completed', 'response': {'id': response_id,
                               'usage': {'input_tokens': 0, 'output_tokens': 0, 'total_tokens': 0}}})
                body = ''.join('data: ' + json.dumps(event) + '\n\n' for event in events).encode()
                self.send_response(200)
                self.send_header('Content-Type', 'text/event-stream')
                self.send_header('Content-Length', str(len(body)))
                self.end_headers()
                try:
                    self.wfile.write(body)
                except BrokenPipeError:
                    pass

        self.http = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
        self.thread = threading.Thread(target=self.http.serve_forever, daemon=True)
        self.thread.start()
        self.port = self.http.server_address[1]

    def close(self):
        self.release.set()
        self.http.shutdown()
        self.http.server_close()
        self.thread.join(timeout=1)


def record(directory, role):
    try:
        identity = fingerprint(os.getpid())
    except PermissionError:
        identity = None  # Filled by the independent observer for sandboxed skills.
    entry = {'pid': os.getpid(), 'ppid': os.getppid(), 'pgid': os.getpgrp(), 'role': role,
             'fingerprint': identity}
    with open(Path(directory) / 'ledger.jsonl', 'a') as f:
        f.write(json.dumps(entry) + '\n')


def child(directory):
    record(directory, 'mcp_descendant')
    time.sleep(80)


def mcp_fixture(directory, behavior):
    record(directory, 'mcp_server')
    subprocess.Popen([sys.executable, __file__, 'child', directory], stdin=subprocess.DEVNULL,
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    if behavior == 'ignore_term':
        signal.signal(signal.SIGTERM, signal.SIG_IGN)
    threading.Timer(85, lambda: os._exit(0)).start()
    lock = threading.Lock()

    def send(obj):
        with lock:
            print(json.dumps(obj), flush=True)

    def handle(req):
        method = req.get('method')
        ident = req.get('id')
        if method == 'initialize':
            if behavior == 'startup_timeout':
                return
            if behavior == 'startup_error':
                time.sleep(.2)  # Ensure the already-spawned descendant has registered.
                send({'jsonrpc': '2.0', 'id': ident, 'error': {'code': -32603, 'message': 'synthetic handshake failure'}})
                return
            result = {'protocolVersion': req['params']['protocolVersion'], 'capabilities': {'tools': {}},
                      'serverInfo': {'name': 'lifecycle-fixture', 'version': '1'}}
        elif method == 'tools/list':
            result = {'tools': [{'name': name, 'description': 'Local bounded lifecycle fixture.',
                                'inputSchema': {'type': 'object', 'properties': {}}}
                               for name in ['echo', 'error', 'slow']]}
        elif method == 'tools/call':
            name = req['params']['name']
            if name == 'slow':
                time.sleep(4)
            result = {'content': [{'type': 'text', 'text': name + '-result'}], 'isError': name == 'error'}
        elif method == 'ping':
            result = {}
        elif ident is not None:
            send({'jsonrpc': '2.0', 'id': ident, 'error': {'code': -32601, 'message': 'method not found'}})
            return
        else:
            return
        send({'jsonrpc': '2.0', 'id': ident, 'result': result})

    for line in sys.stdin:
        try:
            req = json.loads(line)
            threading.Thread(target=handle, args=(req,), daemon=True).start()
        except ValueError:
            pass


class FixtureServer(Server):
    def __init__(self, directory, config):
        self.events = []
        self.q = queue.Queue()
        self.directory = directory
        self.stderr = open(directory / 'server.stderr', 'w')
        child_env = dict(os.environ)
        child_env['CODEX_HOME'] = str(directory / 'isolated-codex-home')
        Path(child_env['CODEX_HOME']).mkdir()
        (Path(child_env['CODEX_HOME']) / 'config.toml').write_text(config)
        self.p = subprocess.Popen([BINARY, 'app-server', '--stdio'], cwd=directory, env=child_env,
                                  stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.stderr,
                                  text=True, start_new_session=True)
        self.reader = threading.Thread(target=self.read, daemon=True)
        self.reader.start()
        self.send('initialize', {'clientInfo': {'name': 'local_common_scenarios', 'version': '1'},
                                'capabilities': {'experimentalApi': True}}, 1)
        self.await_id(1, 10)
        self.send('initialized', {})
        self.next_id = 10

    def rpc(self, method, params, timeout=15, allow_error=False):
        ident = self.next_id
        self.next_id += 1
        self.send(method, params, ident)
        end = time.monotonic() + timeout
        while time.monotonic() < end:
            for event in self.events:
                if event.get('id') == ident:
                    if 'error' in event and not allow_error:
                        raise RuntimeError(method + ': ' + json.dumps(event))
                    return event
            time.sleep(.025)
        raise TimeoutError(method)

    def new_thread(self, ephemeral=False):
        return self.rpc('thread/start', {'cwd': str(self.directory), 'ephemeral': ephemeral,
                        'approvalPolicy': 'never', 'sandbox': 'workspace-write'})['result']['thread']['id']

    def turn(self, tid, inputs=None, wait=True):
        result = self.rpc('turn/start', {'threadId': tid, 'input': inputs or [{'type': 'text', 'text': 'Local fixture, reply done.'}]})
        turn_id = result['result']['turn']['id']
        if wait:
            self.wait_turn(turn_id)
        return turn_id

    def wait_turn(self, turn_id, timeout=20):
        end = time.monotonic() + timeout
        while time.monotonic() < end:
            for e in self.events:
                if e.get('method') == 'turn/completed' and e.get('params', {}).get('turn', {}).get('id') == turn_id:
                    return e
            time.sleep(.03)
        raise TimeoutError('turn completion ' + turn_id)


def config_text(directory, behavior='normal', model_port=9, with_mcp=True):
    text = '''model = "gpt-5.5"
model_provider = "local_fixture"
approval_policy = "never"
sandbox_mode = "workspace-write"
[analytics]
enabled = false
[feedback]
enabled = false
[model_providers.local_fixture]
name = "Local deterministic fixture"
wire_api = "responses"
requires_openai_auth = false
'''
    text += 'base_url = ' + json.dumps('http://127.0.0.1:' + str(model_port) + '/v1') + '\n'
    if with_mcp:
        text += '\n[mcp_servers.lifecycle_fixture]\ncommand = ' + json.dumps(sys.executable) + '\n'
        text += 'args = ' + json.dumps([str(Path(__file__).resolve()), 'wrapper' if behavior == 'wrapper' else 'mcp', str(directory), behavior]) + '\n'
        text += 'startup_timeout_sec = 2\ntool_timeout_sec = 1\n'
    return text


def ledger(directory):
    p = directory / 'ledger.jsonl'
    return [json.loads(l) for l in p.read_text().splitlines()] if p.exists() else []


OBSERVED_IDENTITIES = {}


def alive(directory):
    rows = table()
    result = []
    for r in ledger(directory):
        pid = r['pid']
        if pid not in rows:
            continue
        now = fingerprint(pid)
        identity = r['fingerprint'] or OBSERVED_IDENTITIES.setdefault((str(directory), pid), now)
        if now == identity and not rows[pid]['stat'].startswith('Z'):
            result.append({**r, **rows[pid], 'fingerprint': identity})
    return result


def snapshot(directory, phase):
    result = {'phase': phase, 'time_monotonic': time.monotonic(), 'alive': alive(directory), 'spawned': len(ledger(directory))}
    with open(directory / 'observations.jsonl', 'a') as f:
        f.write(json.dumps(result) + '\n')
    return result


def cleanup(directory):
    cleaned = []
    for row in alive(directory):
        try:
            os.kill(row['pid'], signal.SIGTERM)
            cleaned.append(row['pid'])
        except ProcessLookupError:
            pass
    time.sleep(.2)
    for row in alive(directory):
        try:
            os.kill(row['pid'], signal.SIGKILL)
        except ProcessLookupError:
            pass
    return cleaned


def mcp_case(mode, repeat, run_dir):
    directory = run_dir / (mode + '-' + str(repeat))
    directory.mkdir()
    s = None
    model = None
    result = {'mode': mode, 'repeat': repeat, 'observations': [], 'rpc_checks': []}
    def snap(phase):
        obs = snapshot(directory, phase)
        result['observations'].append(obs)
        return obs
    def call(tid, tool='echo', allow_error=False):
        response = s.rpc('mcpServer/tool/call', {'threadId': tid, 'server': 'lifecycle_fixture', 'tool': tool,
                                                'arguments': {}}, allow_error=allow_error)
        result['rpc_checks'].append(response)
        return response
    try:
        behavior = mode if mode in ['startup_timeout', 'startup_error', 'ignore_term', 'wrapper'] else 'normal'
        model = LocalModel(directory)
        s = FixtureServer(directory, config_text(directory, behavior, model.port))
        result['server_pid'] = s.p.pid
        tid = s.new_thread()
        s.turn(tid)
        call(tid, allow_error=mode.startswith('startup_'))
        time.sleep(.2)
        snap('after_startup')
        if mode.startswith('startup_'):
            time.sleep(3)
            snap('after_failed_startup_grace')
        elif mode == 'reuse':
            for _ in range(5):
                call(tid)
            snap('after_five_calls')
        elif mode == 'tool_error':
            call(tid, 'error')
            call(tid)
            snap('after_error_and_success')
        elif mode == 'tool_timeout':
            call(tid, 'slow', allow_error=True)
            call(tid)
            snap('after_timeout_and_success')
        elif mode in ['refresh', 'refresh_changed']:
            for i in range(3):
                if mode == 'refresh_changed':
                    config = config_text(directory, behavior, model.port)
                    config += '\n[mcp_servers.lifecycle_fixture.env]\nFIXTURE_GENERATION = ' + json.dumps(str(i)) + '\n'
                    (directory / 'isolated-codex-home/config.toml').write_text(config)
                s.rpc('config/mcpServer/reload', None)
                s.turn(tid)
                call(tid)
                time.sleep(3)
                snap('refresh_' + str(i + 1))
        elif mode == 'two_threads':
            tid2 = s.new_thread()
            s.turn(tid2)
            call(tid2)
            snap('two_threads_active')
            s.rpc('thread/archive', {'threadId': tid})
            time.sleep(3)
            snap('first_archived')
            call(tid2)
            tid = tid2
        elif mode == 'unsubscribe':
            result['unsubscribe_response'] = s.rpc('thread/unsubscribe', {'threadId': tid})
            time.sleep(3)
            snap('after_unsubscribe')
        if mode == 'disconnect':
            s.p.stdin.close()
        else:
            result['archive_response'] = s.rpc('thread/archive', {'threadId': tid})
        time.sleep(4)
        result['after_lifecycle_end'] = snap('after_lifecycle_end')
        result['outcome'] = 'survivors' if result['after_lifecycle_end']['alive'] else 'clean'
    except Exception as e:
        result['outcome'] = 'test_error'
        result['error'] = str(e)
    finally:
        if s:
            s.close()
            (directory / 'rpc.json').write_text(json.dumps(s.events, indent=2))
        if model:
            model.close()
        result['after_app_server_close'] = snapshot(directory, 'after_app_server_close')
        result['harness_cleaned'] = cleanup(directory)
        result['final_alive'] = alive(directory)
        (directory / 'result.json').write_text(json.dumps(result, indent=2))
    print(json.dumps({'mode': mode, 'repeat': repeat, 'outcome': result['outcome'], 'error': result.get('error'),
                      'observations': [(o['phase'], len(o['alive']), o['spawned']) for o in result['observations']],
                      'cleanup': result['harness_cleaned'], 'final_alive': len(result['final_alive'])}), flush=True)
    return result


if __name__ == '__main__':
    if sys.argv[1:2] == ['child']:
        child(sys.argv[2])
    elif sys.argv[1:2] == ['mcp']:
        mcp_fixture(sys.argv[2], sys.argv[3])
    elif sys.argv[1:2] == ['wrapper']:
        record(sys.argv[2], 'mcp_wrapper')
        p = subprocess.Popen([sys.executable, __file__, 'mcp', sys.argv[2], 'normal'])
        p.wait(timeout=88)
    else:
        run_dir = Path(tempfile.mkdtemp(prefix='codex-common-'))
        results = []
        modes = sys.argv[1:] or ['reuse', 'tool_error', 'tool_timeout', 'startup_error', 'startup_timeout',
                               'refresh', 'two_threads', 'unsubscribe', 'ignore_term', 'disconnect']
        for mode in modes:
            for repeat in range(1, 4):
                results.append(mcp_case(mode, repeat, run_dir))
                if results[-1]['outcome'] == 'test_error':
                    break
        output = {'run_dir': str(run_dir), 'results': results}
        (ROOT / ('common-results-' + run_dir.name + '.json')).write_text(json.dumps(output, indent=2))

skill_scenarios.py
"""Real Codex skill loading and shell execution with a deterministic local model fixture."""
import json
import os
from pathlib import Path
import shlex
import subprocess
import sys
import tempfile
import time

from common_scenarios import FixtureServer, LocalModel, config_text, record, snapshot, cleanup, alive, ROOT


def script(directory, mode, role):
    record(directory, 'skill_' + role)
    if role == 'child':
        time.sleep(.3 if mode in ['normal', 'error'] else 65)
        return
    p = subprocess.Popen([sys.executable, __file__, 'script', directory, mode, 'child'],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=mode == 'detached_error')
    if mode in ['unjoined_error', 'detached_error']:
        time.sleep(.2)
        raise RuntimeError('Synthetic script failure with an unjoined child')
    try:
        p.wait(timeout=70)
        if mode == 'error':
            raise RuntimeError('Synthetic script failure after normal child completion')
        print('skill script complete', flush=True)
    finally:
        if p.poll() is None:
            p.terminate()
            p.wait(timeout=2)


def run_case(mode, repeat, root):
    directory = root / (mode + '-' + str(repeat))
    directory.mkdir()
    result = {'mode': mode, 'repeat': repeat, 'observations': []}
    s = model = None
    def snap(phase):
        r = snapshot(directory, phase)
        result['observations'].append(r)
        return r
    try:
        skill_dir = directory / '.agents' / 'skills' / 'lifecycle-probe'
        skill_dir.mkdir(parents=True)
        command = shlex.join([sys.executable, str(Path(__file__).resolve()), 'script', str(directory), mode, 'parent'])
        skill_body = ('---\nname: lifecycle-probe\ndescription: Local bounded skill lifecycle test.\n---\n'
                      'SKILL_LIFECYCLE_FIXTURE_20260921\n'
                      + ('Read these instructions and reply fixture complete. Do not launch processes.\n' if mode == 'read_only' else
                         'Run this single local fixture script using exec_command:\n\n```sh\n' + command + '\n```\n'))
        skill_path = skill_dir / 'SKILL.md'
        skill_path.write_text(skill_body)
        commands = [shlex.join(['/bin/cat', str(skill_path)])]
        if mode != 'read_only':
            commands.append(command)
        model = LocalModel(directory, commands, hold_after_tool=mode in ['cancel', 'cancel_churn'])
        s = FixtureServer(directory, config_text(directory, model_port=model.port, with_mcp=False))
        result['server_pid'] = s.p.pid
        discovered = s.rpc('skills/list', {'cwds': [str(directory)], 'forceReload': True})
        result['skill_discovered'] = 'lifecycle-probe' in json.dumps(discovered)
        if not result['skill_discovered']:
            raise RuntimeError('Fixture skill not discovered: ' + json.dumps(discovered))
        tid = s.new_thread()
        inputs = [{'type': 'text', 'text': 'Use $lifecycle-probe for this local test.'},
                  {'type': 'skill', 'name': 'lifecycle-probe', 'path': str(skill_path)}]
        turn = s.turn(tid, inputs, wait=False)
        if mode in ['cancel', 'cancel_churn']:
            end = time.monotonic() + 15
            while time.monotonic() < end and len(alive(directory)) < 2:
                time.sleep(.05)
            if len(alive(directory)) < 2:
                raise RuntimeError('Skill command tree not started before cancellation')
            if mode == 'cancel_churn':
                end = time.monotonic() + 12
                while time.monotonic() < end and len(model.requests) < model.command_offset + 3:
                    time.sleep(.03)
                if len(model.requests) < model.command_offset + 3:
                    raise RuntimeError('Background exec did not yield before cancellation')
            snap('before_cancel')
            result['interrupt_response'] = s.rpc('turn/interrupt', {'threadId': tid, 'turnId': turn})
            model.release.set()
        completed = s.wait_turn(turn)
        result['turn_status'] = completed['params']['turn']['status']
        result['skill_body_in_model_request'] = any('SKILL_LIFECYCLE_FIXTURE_20260921' in json.dumps(x) for x in model.requests)
        if not result['skill_body_in_model_request']:
            raise RuntimeError('Skill body did not reach model fixture')
        command_items = [e.get('params', {}).get('msg', {}) for e in s.events
                         if e.get('method') == 'codex/event/exec_command_end']
        result['tool_outputs'] = [x for req in model.requests for x in req.get('input', [])
                                  if x.get('type') == 'function_call_output']
        result['command_items'] = command_items
        from common_scenarios import ledger
        result['worker_records'] = ledger(directory)
        time.sleep(3)
        snap('after_turn_completed')
        if mode == 'cancel_churn':
            for iteration in [2, 3]:
                model.command_offset = len(model.requests)
                model.release.clear()
                turn = s.turn(tid, inputs, wait=False)
                end = time.monotonic() + 15
                from common_scenarios import ledger
                while time.monotonic() < end and (len(ledger(directory)) < iteration * 2 or len(model.requests) < model.command_offset + 3):
                    time.sleep(.05)
                if len(ledger(directory)) < iteration * 2 or len(model.requests) < model.command_offset + 3:
                    raise RuntimeError('Repeated-cancel tree did not launch')
                s.rpc('turn/interrupt', {'threadId': tid, 'turnId': turn})
                model.release.set()
                s.wait_turn(turn)
                time.sleep(3)
                snap('after_cancel_' + str(iteration))
        s.rpc('thread/archive', {'threadId': tid})
        time.sleep(4)
        r = snap('after_archive')
        result['outcome'] = 'survivors' if r['alive'] else 'clean'
        if mode != 'read_only' and len(result['worker_records']) < 2:
            result['outcome'] = 'test_error'
            result['error'] = 'Script parent/child did not both register; not a valid process lifecycle test'
    except Exception as e:
        result['outcome'] = 'test_error'
        result['error'] = str(e)
    finally:
        if model:
            model.release.set()
        if s:
            s.close()
            (directory / 'rpc.json').write_text(json.dumps(s.events, indent=2))
        if model:
            model.close()
        result['after_server_close'] = snapshot(directory, 'after_server_close')
        result['harness_cleaned'] = cleanup(directory)
        result['final_alive'] = alive(directory)
        (directory / 'result.json').write_text(json.dumps(result, indent=2))
    print(json.dumps({'mode': mode, 'repeat': repeat, 'outcome': result['outcome'], 'error': result.get('error'),
                      'skill_loaded': result.get('skill_body_in_model_request'),
                      'turn_status': result.get('turn_status'),
                      'commands': [(i.get('status'), i.get('exitCode')) for i in result.get('command_items', [])],
                      'observations': [(o['phase'], len(o['alive'])) for o in result['observations']],
                      'cleanup': result['harness_cleaned'], 'final_alive': len(result['final_alive'])}), flush=True)
    return result


if __name__ == '__main__':
    if sys.argv[1:2] == ['script']:
        script(*sys.argv[2:])
    else:
        root = Path(tempfile.mkdtemp(prefix='codex-skill-'))
        results = []
        for mode in sys.argv[1:] or ['read_only', 'normal', 'error', 'unjoined_error', 'background', 'cancel']:
            for repeat in range(1, 4):
                results.append(run_case(mode, repeat, root))
                if results[-1]['outcome'] == 'test_error':
                    break
        (ROOT / ('skill-results-' + root.name + '.json')).write_text(json.dumps({'run_dir': str(root), 'results': results}, indent=2))

AAAholic avatar Sep 21 '26 10:09 AAAholic

We are evaluating a bounded, no-model, one-shot stdio workload launched by an external client on macOS. This is a contract question, not a new reproduction or a request to change interactive Stop semantics. Our last authorized metadata observation recorded Codex package 0.154.0 on Darwin arm64.

The App Server documentation describes command/exec with timeoutMs, processId, command/exec/terminate, and command/exec/outputDelta. Could maintainers clarify whether a supported external entry point provides all of the following?

  1. Which process establishes the effective sandbox before the fixed argv/env/cwd is launched, and what is its scope over descendants?
  2. When does the timeout clock start? If the client or driver fails during creation or execution, which component retains responsibility for termination?
  3. Does explicit termination cover only the direct process or its process group, or also descendants that call setsid() or otherwise leave that group? Please state unsupported cases directly.
  4. Which response or event distinguishes a termination request from observed process exit, and reports stdout/stderr completion or truncation? After a disconnect, is an invocation-specific outcome available, or must the client report it as unknown?

If no current macOS interface supports this complete contract, what one-shot outer-host integration do you recommend? We will not infer these guarantees from a yield interval, a session ID, or one successful exit.

wuhaihu avatar Sep 28 '26 01:09 wuhaihu

Additional reproduction on Linux through the app-server, with one more gap: the surviving process is not listed as a background terminal, so a client has no supported way to stop it.

Environment: codex app-server 0.159.1, Linux x86_64, default sandbox, driven through an ACP adapter (@brokkai/codex-acp 1.13.5) that forwards the client's cancel as turn/interrupt.

Steps

  1. Start a turn with the prompt: Run python3 -c 'import time; time.sleep(77)' and then say done.
  2. About 25 s in, send turn/interrupt for that turn. The turn reports "Interrupted".
  3. Run pgrep -af 'time.sleep' and inspect the tree.

Actual: the whole tree stays alive until the command finishes on its own (43 s and 69 s after the interrupt in two runs on different hosts): bwrap --as-pid-1 --new-session --die-with-parent … (child of the codex process) → codex-linux-sandbox → python3. bwrap and codex-linux-sandbox each lead their own session/process group, so the client process tree does not contain them. thread/backgroundTerminals/list has no entry for the command, and thread/backgroundTerminals/terminate therefore cannot reach it.

Expected: either interrupting the turn terminates the command's process tree, or, if a command is meant to outlive the turn, it appears in thread/backgroundTerminals/list so a client can terminate it. Today it is neither stopped nor listed.

jbellis avatar Oct 01 '26 10:10 jbellis

Proposal: opt-in producer-owned Stop with an observed-exit result

For clients of codex app-server, the not-listed reproduction above means a list-based client cannot always recover a process identity after turn/interrupt. A safe fix needs to live at the command producer, where turn ownership and the launch race can be resolved atomically.

I propose extending the existing turn/interrupt request with an experimental, opt-in owned-work policy rather than changing its default semantics:

// TurnInterruptParams
{
  threadId: string;
  turnId: string;
  ownedWork?: {
    policy: "stop";
    drainTimeoutMs?: number; // default 5000, clamp to 0..30000
  };
}

// TurnInterruptResponse, only when ownedWork was requested
{
  ownedWork?: {
    acceptance: "accepted" | "notApplied";
    notAppliedReason?: "turnCompleted" | "turnNotActive";
    alreadyFenced: boolean;
    rootExit:
      | "allObserved"
      | "noneLaunched"
      | "timedOut"
      | "noRegisteredEvidence"
      | "unavailable";
    counts: {
      leased: number;
      deniedAfterFence: number;
      cancelledBeforeLaunch: number;
      exitedBeforeStop: number;
      rootExitObserved: number;
      rootStillRunning: number;
    };
  };
}

Support should be advertised in the initialize result, for example ownedWorkStop: { version: 1, scope: "unifiedExecRoots" }. Clients should not probe this by interrupting a live thread with a fabricated turn ID.

Required launch linearization

Each owned launch needs a per-turn lease that moves through:

Reserved -> Launching -> Published -> Exited

A per-turn owner lock orders those transitions with turn completion and the Stop fence:

  • If the fence wins while a lease is Reserved, cancel it without spawning. Later reservations are denied.
  • If launch has already entered Launching, Stop waits for handle publication or launch failure, then terminates the published handle.
  • If turn completion wins first, return notApplied/turnCompleted and preserve that completed turn's background work.
  • Repeated Stop requests are idempotent and report the current fenced state.

This avoids the race where a process ID is merely reserved, Stop snapshots the registry, and the process spawns afterward.

Honest completion semantics

rootExitObserved should count only an actual local or exec-server exit event that the producer awaited. Sending a termination request, setting synthetic internal state, or observing an empty inventory is not exit evidence.

The v1 result should explicitly mean root-process exit, not whole-tree quiescence. Descendants that escape the root process group remain outside that claim unless a stronger containment mechanism is added later. No PID, process ID, command, cwd, environment, output, or opaque authority needs to cross the app-server API; counts and status are enough.

Suggested v1 scope

Keep the first version narrow: unified-exec command roots, which already use the producer's process-ID allocation path. Explicitly name these as out of scope for v1 so clients cannot infer coverage:

  • shell-snapshot processes;
  • code-mode cells;
  • MCP-side child processes;
  • sub-agent turns;
  • thread/shellCommand;
  • descendants that escape the root process group.

Plain turn/interrupt without the opt-in policy should retain today's behavior.

Minimum deterministic tests

  1. Stop wins before spawn: the command never starts and reports noneLaunched.
  2. Launch wins just before Stop: Stop awaits publication, terminates the exact root, and observes its exit.
  3. A reservation attempted after the fence is denied.
  4. Multiple current-turn command roots settle independently.
  5. A completed-turn background server survives a later turn's owned Stop.
  6. Commands belonging to another thread/session/generation survive.
  7. Repeated Stop is idempotent.
  8. Timeout, producer loss, unavailable exec-server, or missing evidence never reports allObserved.
  9. Local and exec-server-backed roots both require an observed exit event.
  10. Hidden or unavailable background-terminal listings do not affect producer-owned Stop.

Would maintainers be open to this opt-in extension on turn/interrupt, or would you prefer a separate method with the same producer-side lease and observed-exit semantics? The important boundary is that the producer owns the fence and launch registry; a client-side PID or list-row workaround cannot close this race safely.

jrnichols-dot avatar Oct 07 '26 02:10 jrnichols-dot

Windows reproduction: turn interruption ends the tool wait, but the PowerShell process keeps writing

Adding Windows observations for both the initial exec_command wait and a subsequent write_stdin wait.

Environment and scope

  • Windows, Codex CLI 0.162.0-alpha.2.
  • Codex Desktop package 26.1002.7124.0 was installed, but these were direct stdio app-server tests using turn/interrupt, not tests of the Desktop Stop button or interactive CLI Ctrl+C.
  • A custom model provider was used and left unchanged throughout testing.
  • The tests used bounded PowerShell commands writing timestamped lines to files in an isolated test workspace.
  • Gateway and the messaging relay were not started for these reproductions.

Observed results

Case State when interrupted What stopped What continued
C1 exec_command was waiting The turn became interrupted and the tool wait ended The PowerShell process wrote 5 more lines; the last write was approximately 5.038 seconds after the interrupt request
C2R An execution session had been yielded and write_stdin was waiting on it The turn was interrupted and write_stdin reported being aborted The process associated with that execution session wrote 5 more lines; the last write was approximately 4.222 seconds after the interrupt request

In both cases, an independent cleanup mechanism terminated the exact test process tree. Neither process was demonstrated to terminate because of turn/interrupt. These intervals describe observed post-interrupt writes before cleanup; they are not automatic shutdown latency measurements, and the tests do not establish how long execution would have continued without cleanup.

Test procedure

  1. Start a normal turn on an isolated stdio app-server and have it execute a bounded PowerShell file-writing command through exec_command.
  2. For C1, send turn/interrupt while exec_command is still waiting and the command is running.
  3. For C2R, obtain the execution session, wait on it through write_stdin, and send turn/interrupt while that wait is active and the command is still running.
  4. Observe the turn and tool events separately from OS process liveness and subsequent file writes.
  5. Independently terminate the identified test process tree after the short observation window.

This is a procedure summary rather than a verbatim transcript of the raw requests. No raw session identifiers or private logs are attached.

Interpretation and limits

The runtime observations confirm that cancelling the turn/tool wait did not stop these commands. They are consistent with the process-store persistence mechanism discussed in this issue. However, the installed binary has not been precisely mapped to the referenced source revision, so the exact source-level root cause remains probable, not confirmed for this binary.

These observations concern direct app-server interruption on Windows. They do not establish the behavior of the Desktop Stop button, interactive CLI Ctrl+C, every execution backend, or arbitrary detached descendants. The effective Windows sandbox mode for each run is not specified here because it is not included in the result summary used to prepare this comment.

Question for maintainers

Could you clarify the supported cancellation contract for commands owned by an interrupted turn? If process persistence is intentional, is there a supported way for an app-server client to terminate that turn's execution sessions and receive evidence of actual process exit, rather than only an interruption acknowledgement?

For remote control, reporting interrupted alone cannot establish that file-writing side effects have stopped. This comment adds Windows reproduction evidence; it does not propose a client-side process-name kill workaround or assume that the default interruption semantics should be changed without a maintainer decision.

qq375378013-wq avatar Oct 10 '26 06:10 qq375378013-wq

A data point on what the model is told when this happens, and what that costs. codex-cli 0.171.0's TUI in a Linux container (tmux), models behind an OpenAI-compatible Responses provider.

Pressing Esc while exec_command runs ends the turn, and the command keeps running as a background terminal: the status line shows "1 background terminal running · /ps to view", and the command's effect lands after the key (3 of 3 runs against a scripted model server). After the user types "Continue.", the next request tells the model:

  • for the call: Wall time: 1.1 seconds / aborted by user (composed by stopped_response in core/src/tools/parallel.rs, which does not ask the process manager; the same in 0.172.0);
  • for the turn: <turn_aborted> The user interrupted the previous turn on purpose. Any running unified exec processes may still be running in the background. If any tools/commands were aborted, they may have partially executed.

The model gets no session id for the process, so it cannot reach it with write_stdin and is not told that this command is the one still running.

What models then do (five open-weight families: DeepSeek V4 Pro, Kimi K3.1 Pro, GLM-5.3, MiMo V2.6 Flash, MiniMax M3.1 Flash; three runs each), with the command touch started.flag; (sleep 30; echo one … >> build.log) still to write when the model looks: in 9 of 15 runs the model ran echo one >> build.log itself without having seen the earlier command's line, and that line landed as well, so the work was done twice. In 6 runs the notice led the model to look for the process with ps; 5 of them killed it before it wrote and then did the work once. With a command whose line had landed before Esc (echo one … >> build.log; sleep 30), 9 of 15 wrote the line again.

Whether or not Stop should end the process (the design question above), the result the model gets can say what happened. In the same sessions, with only that call's output rewritten:

  • "still running now in the background … do not start the same work again until it has finished: wait for it, or stop it, then check what is left to do": the work was done twice in 2 of 15 runs;
  • the same, naming the process's real session id and write_stdin: 4 of 15; in all 12 runs of the first four families (GLM-5.3 was run later), the model used write_stdin on it, to stop it or to wait for it;
  • Codex's own words for a command that outlives yield_time_ms ("Process running with session ID N"), with no instruction: 4 of 15;
  • the current "aborted by user": 9 of 15 (the two "still running" texts pooled: 6 of 30, Fisher p = 0.017).

So reporting the call as still running, with its session id, as Codex already does when a command outlives yield_time_ms, would let the model wait for the process or stop it instead of starting the same work again. Related: #15461 (the model is not told about background terminals that are still running).

sha7doww avatar Nov 24 '26 02:11 sha7doww