Skip to content

Commit a5c0485

Browse files
ruiling-smartbearGaoRuilin1haizhongzhengclaude
authored
Stop a CLI session's processes on macOS too (#88)
* Stop a CLI session's processes on macOS too The processes below a session were found through /proc, which macOS lacks, so one in a session of its own was never stopped; they are now found with ps there. On macOS, signalling a group left with only exited, unreaped processes raises PermissionError; it now means the group has ended, in the Base Agent's stop and in the AgentDyn runner's and the Lean swarm launcher's. * Tests: the new stop test cleans up whatever fails; the AgentDyn test reads a process's state on macOS too * Tests: the stop test counts a zombie as stopped, and runs the ps fallback on Linux too - an exited, unreaped grandchild (under a subreaper, or a container's PID 1 that does not reap) is stopped, not a survivor - parametrized proc / ps: CI on Linux now runs the macOS ps fallback; the ps case fails without it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: SmartBea_Linlin_r <80329948+GaoRuilin1@users.noreply.github.com> Co-authored-by: Haizhong Zheng <hzzheng@umich.edu> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d5f0a64 commit a5c0485

6 files changed

Lines changed: 88 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,11 @@ Changes are grouped by software version. Entries under Unreleased describe work
202202
- The AHE Adapter Evolver took a `change_manifest.json` an earlier step left for the current step's: a manifest
203203
naming the next iteration was refused at its own step, then archived as the next step's when that step's session
204204
wrote none. The file (or a directory a session made in its place) is now removed before each Evolve session.
205+
- On macOS a CLI session stopped at its timeout or on cancel could leave processes behind or fail: the processes
206+
below it were found through `/proc`, which macOS lacks, so one in a session of its own (as a sandbox starts its
207+
program) was never stopped; and signalling a process group left with only exited, unreaped processes raises
208+
`PermissionError` there. The processes are now found with `ps` where there is no `/proc`, and that error means the
209+
group has ended. The same holds for the AgentDyn runner's and the Lean swarm launcher's stops.
205210

206211
## 0.2.0 - 2026-11-04
207212

‎examples/agentdyn/utils/experiment_runtime.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,9 @@ def stop_process(proc):
8282
os.killpg(proc.pid, sig)
8383
except ProcessLookupError:
8484
pass
85+
except PermissionError: # macOS: only exited processes, not yet reaped, are left
86+
if proc.poll() is None:
87+
raise
8588
if sig == signal.SIGTERM:
8689
time.sleep(0.3)
8790
proc.wait(timeout=5)

‎examples/lean_swarm/launch.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,9 @@ def killpg(proc: subprocess.Popen | None):
398398
os.killpg(proc.pid, signal.SIGKILL)
399399
except ProcessLookupError:
400400
pass
401+
except PermissionError: # macOS: only exited processes, not yet reaped, are left
402+
if proc.poll() is None:
403+
raise
401404

402405

403406
def cost(ledger: dict, price: dict | None):

‎hermit/agent/base/cli.py‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,9 @@ def _stop(proc) -> None:
448448
os.killpg(proc.pid, sig)
449449
except ProcessLookupError:
450450
return
451+
except PermissionError: # macOS: only exited processes, not yet reaped, are left
452+
if proc.poll() is None:
453+
raise
451454
try:
452455
proc.wait(15)
453456
return
@@ -457,12 +460,8 @@ def _stop(proc) -> None:
457460

458461
def _descendants(pid: int) -> list[int]:
459462
children: dict[int, list[int]] = {}
460-
for entry in Path("/proc").glob("[0-9]*/stat"):
461-
try:
462-
fields = entry.read_text().rsplit(")", 1)[1].split()
463-
except (OSError, IndexError):
464-
continue
465-
children.setdefault(int(fields[1]), []).append(int(entry.parent.name))
463+
for child, parent in _parents():
464+
children.setdefault(parent, []).append(child)
466465
out, todo = [], [pid]
467466
while todo:
468467
for child in children.get(todo.pop(), []):
@@ -471,6 +470,24 @@ def _descendants(pid: int) -> list[int]:
471470
return out
472471

473472

473+
def _parents() -> list[tuple[int, int]]:
474+
"""Every process with its parent: from /proc, else (macOS) from `ps`."""
475+
if Path("/proc/self/stat").is_file():
476+
pairs = []
477+
for entry in Path("/proc").glob("[0-9]*/stat"):
478+
try:
479+
pairs.append((int(entry.parent.name), int(entry.read_text().rsplit(")", 1)[1].split()[1])))
480+
except (OSError, IndexError, ValueError):
481+
continue
482+
return pairs
483+
try:
484+
out = subprocess.run(["ps", "-A", "-o", "pid=", "-o", "ppid="], capture_output=True, text=True,
485+
timeout=10).stdout
486+
except (OSError, subprocess.SubprocessError):
487+
return []
488+
return [(int(p), int(q)) for p, q in (line.split() for line in out.splitlines() if len(line.split()) == 2)]
489+
490+
474491
class CliAgent(BaseAgent):
475492
"""One CLI's session as a Base Agent: the shared run, and the hooks each CLI's subclass fills in."""
476493
backend = "" # the CLI's name (make, CLIS, its stream agent-<backend>.jsonl)

‎tests/core/test_cli_agent.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1178,3 +1178,54 @@ def test_a_session_whose_bwrap_exits_before_the_relay_closes_its_report_listener
11781178
finally:
11791179
box.close()
11801180
assert abandoned
1181+
1182+
1183+
def _alive(pid: int) -> bool:
1184+
"""Running, not an exited process left unreaped (by a subreaper, or a container's PID 1 that does not reap)."""
1185+
import subprocess
1186+
try:
1187+
os.kill(pid, 0)
1188+
except ProcessLookupError:
1189+
return False
1190+
state = subprocess.run(["ps", "-o", "stat=", "-p", str(pid)], capture_output=True, text=True).stdout.strip()
1191+
return bool(state) and not state.startswith("Z")
1192+
1193+
1194+
@pytest.mark.parametrize("proc_fs", [True, False], ids=["proc", "ps"])
1195+
def test_a_stopped_session_takes_a_descendant_in_a_session_of_its_own(tmp_path, monkeypatch, proc_fs):
1196+
"""A session stopped at its timeout or on cancel ends with every process below it, one in a session of its own
1197+
too (as a sandbox starts its program), found through /proc or, as on macOS, through ps."""
1198+
import signal
1199+
import subprocess
1200+
import time
1201+
if not proc_fs:
1202+
monkeypatch.setattr(base_cli, "Path", lambda p: Path("/no-proc") if p == "/proc/self/stat" else Path(p))
1203+
pid_file = tmp_path / "pid"
1204+
proc = subprocess.Popen([sys.executable, "-c", "import subprocess, sys, time; p = subprocess.Popen([sys.executable, "
1205+
"'-c', 'import time; time.sleep(60)'], start_new_session=True); "
1206+
f"open({str(pid_file)!r}, 'w').write(str(p.pid)); time.sleep(60)"],
1207+
start_new_session=True)
1208+
below = None
1209+
try:
1210+
deadline = time.time() + 10
1211+
while not (pid_file.exists() and pid_file.read_text()) and time.time() < deadline:
1212+
time.sleep(0.05)
1213+
below = int(pid_file.read_text())
1214+
assert below in base_cli._descendants(proc.pid)
1215+
base_cli._stop(proc)
1216+
assert proc.poll() is not None
1217+
deadline = time.time() + 10
1218+
while time.time() < deadline:
1219+
if not _alive(below):
1220+
break
1221+
time.sleep(0.05)
1222+
else:
1223+
raise AssertionError("the process in a session of its own outlived the stop")
1224+
finally: # nothing left running, whatever failed
1225+
for group in (proc.pid, below):
1226+
if group is not None:
1227+
try:
1228+
os.killpg(group, signal.SIGKILL)
1229+
except (ProcessLookupError, PermissionError):
1230+
pass
1231+
proc.wait()

‎tests/methods/evosafe/test_agentdyn_experiment_runtime.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,9 @@ def test_formal_entry_check_detects_broken_import_without_model_calls(tmp_path):
8888

8989

9090
def running(pid):
91+
if not Path('/proc').is_dir(): # macOS: the state from ps
92+
state = subprocess.run(['ps', '-o', 'stat=', '-p', str(pid)], capture_output=True, text=True).stdout.strip()
93+
return bool(state) and not state.startswith('Z')
9194
try:
9295
return Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[0] != 'Z'
9396
except FileNotFoundError:

0 commit comments

Comments
 (0)