"""Owned process groups: identify one, probe it, end it, report what happened. The kernel's job supervision and the supervisor's checked signal helper both run this ladder, so the two layers agree on what "terminated" means. A group is live only while it holds a member we can still signal; a reaped leader or a group of non-running (zombie) members is not work. """ from __future__ import annotations from collections.abc import Callable, Sequence from dataclasses import dataclass from typing import Any import asyncio import contextvars import ctypes import os import signal import struct import subprocess import sys import tempfile TERM_GRACE = 0.25 # seconds a group gets to honour TERM KILL_GRACE = 2.0 # seconds a group gets to die after KILL PROBE_INTERVAL = 0.02 LIBC = ctypes.CDLL(None) # True in the tasks that supervise a job; a cell's interrupt is not theirs. SUPERVISING = contextvars.ContextVar("albedo_proc_supervising", default=False) FRAMEWORK_APP = "Resources/Python.app/Contents/MacOS/Python" def named_python(role: str, home: str | None = None) -> str: """Return a role alias for this interpreter, or its path if linking fails.""" executable = sys.executable if os.path.basename(executable).startswith("albedo-"): try: executable = os.path.join( os.path.dirname(executable), os.readlink(executable) ) except OSError: pass executable = framework_app(executable) if home is None: home = os.environ.get("ALBEDO_HOME", os.path.expanduser("~/.albedo")) path = os.path.abspath(os.path.join(home, "bin", "albedo-" + role)) if sys.prefix != sys.base_prefix: # CPython locates pyvenv.cfg relative to the executable it was given. path = os.path.join(sys.prefix, "bin", "albedo-" + role) temporary = None try: if os.path.islink(path) and ( os.readlink(path) == executable or ( sys.prefix != sys.base_prefix and os.path.exists(path) and os.path.samefile(path, executable) ) ): return path os.makedirs(os.path.dirname(path), exist_ok=True) fd, temporary = tempfile.mkstemp(prefix=".albedo-", dir=os.path.dirname(path)) os.close(fd) os.unlink(temporary) os.symlink(executable, temporary) os.replace(temporary, path) return path except OSError: return sys.executable finally: if temporary is not None: try: os.unlink(temporary) except OSError: pass def framework_app(executable: str) -> str: """Return the Python.app executable behind a macOS framework's bin stub. The stub re-execs that executable, which then shows as "Python"; aliasing it directly keeps the role name. A venv keeps its stub, which locates the venv. """ if sys.platform != "darwin" or sys.prefix != sys.base_prefix: return executable target = executable for _ in range(40): try: target = os.path.join(os.path.dirname(target), os.readlink(target)) except OSError: break app = os.path.join(os.path.dirname(os.path.dirname(target)), FRAMEWORK_APP) return app if os.path.isfile(app) else executable def set_name(role: str) -> None: """Rename a Linux fork's main thread without changing its command line.""" if sys.platform == "linux": LIBC.prctl(15, ctypes.c_char_p(("albedo-" + role).encode()), 0, 0, 0) def reap_stopped_safely(loop: asyncio.AbstractEventLoop) -> None: """Let `loop` run children that get paused with SIGSTOP. Python 3.14's threaded child watcher waits with waitid(WEXITED | WNOWAIT), which macOS also answers for a stopped child, and then reaps with a blocking waitpid on the event loop, which can freeze the kernel on a stopped child. The replacement reaps in its thread with a waitpid that ignores stops, as 3.13 did. Linux uses pidfds, which only wake on exit, and needs nothing. """ threaded: Any = getattr( getattr(asyncio, "unix_events", None), "_ThreadedChildWatcher", None ) if ( sys.platform != "darwin" or threaded is None or not isinstance(getattr(loop, "_watcher", None), threaded) ): return class ExitWatcher(threaded): def _do_waitpid( self, loop: asyncio.AbstractEventLoop, expected_pid: int, callback: Callable[..., object], args: tuple[object, ...], ) -> None: try: returncode = os.waitstatus_to_exitcode(os.waitpid(expected_pid, 0)[1]) except ChildProcessError: returncode = 255 try: loop.call_soon_threadsafe(callback, expected_pid, returncode, *args) except RuntimeError: # the loop closed first pass self._threads.pop(expected_pid, None) setattr(loop, "_watcher", ExitWatcher()) @dataclass(frozen=True) class Group: """A target to end: a whole process group, or one process that leads none. `leader` identifies the leader by its start time, so a reused id is refused. """ pgid: int leader: str | None = None whole: bool = True @dataclass(frozen=True) class Termination: """What one termination attempt established about one process group.""" pgid: int | None signals: tuple[str, ...] gone: bool failures: tuple[str, ...] = () note: str = "" def report(self) -> str: where = ( "no process group" if self.pgid is None else f"process group {self.pgid}" ) outcome = "terminated" if self.gone else "SURVIVED" sent = "+".join(self.signals) if self.signals else "no signal" detail = ( "; ".join((*self.failures, self.note)) if self.note else "; ".join(self.failures) ) return f"{where} {outcome} after {sent}" + (f": {detail}" if detail else "") def as_json(self) -> dict[str, object]: return { "pgid": self.pgid, "signals": list(self.signals), "gone": self.gone, "failures": list(self.failures), "note": self.note, } def start_token(stat: bytes) -> str | None: """Start time of one /proc//stat line (field 22, after the command name).""" try: return stat.rsplit(b")", 1)[1].split()[19].decode() except (IndexError, UnicodeDecodeError): return None def leader_token(pid: int) -> str | None: """Identity token for a live pid: its start time, from /proc or, on Darwin, its process table entry. None where neither can tell.""" try: with open(f"/proc/{pid}/stat", "rb") as stat: return start_token(stat.read()) except OSError: return darwin_start(pid) if sys.platform == "darwin" else None def darwin_start(pid: int) -> str | None: """A Darwin process's start time: the timeval that opens its kinfo_proc (sysctl CTL_KERN, KERN_PROC, KERN_PROC_PID). None for a pid not in use.""" mib = (ctypes.c_int * 4)(1, 14, 1, pid) buffer = ctypes.create_string_buffer(1024) size = ctypes.c_size_t(len(buffer)) if LIBC.sysctl(mib, 4, buffer, ctypes.byref(size), None, 0) != 0 or size.value < 12: return None seconds, micros = struct.unpack_from("=qi", buffer.raw) return f"{seconds}.{micros:06d}" KINFO_PROC_SIZE = 648 # sizeof(struct kinfo_proc) on 64-bit Darwin KINFO_P_FLAG = 32 # kp_proc.p_flag KINFO_P_STAT = 36 # kp_proc.p_stat KINFO_P_PID = 40 # kp_proc.p_pid KINFO_E_PPID = 560 # kp_eproc.e_ppid KINFO_E_PGID = 564 # kp_eproc.e_pgid SZOMB = 5 P_WEXIT = 0x2000 PROC_PIDLISTFDS = 1 PROC_PIDFDSOCKETINFO = 3 PROC_PIDFDPIPEINFO = 6 PROX_FDTYPE_SOCKET = 2 PROX_FDTYPE_PIPE = 6 PROC_FDINFO_SIZE = 8 SOCKET_FDINFO_SIZE = 792 PIPE_FDINFO_SIZE = 184 SOCKINFO_UN = 3 AF_UNIX = 1 def _darwin_kinfo_gone(raw: bytes, at: int) -> bool: # Darwin sets P_WEXIT while exit1() tears down memory and fds, before p_stat # becomes SZOMB; killpg already refuses the group with EPERM throughout. flag = struct.unpack_from("=i", raw, at + KINFO_P_FLAG)[0] return raw[at + KINFO_P_STAT] == SZOMB or bool(flag & P_WEXIT) def _darwin_kinfo_start(raw: bytes, at: int) -> str: seconds, micros = struct.unpack_from("=qi", raw, at) return f"{seconds}.{micros:06d}" def _darwin_sysctl_procs(mib: Any) -> bytes | None: for _ in range(3): # the table can grow between the size and the read size = ctypes.c_size_t(0) if LIBC.sysctl(mib, 4, None, ctypes.byref(size), None, 0) != 0: return None buffer = ctypes.create_string_buffer(size.value + 8 * KINFO_PROC_SIZE) size = ctypes.c_size_t(len(buffer)) if LIBC.sysctl(mib, 4, buffer, ctypes.byref(size), None, 0) == 0: return buffer.raw[: size.value] return None def darwin_group(pgid: int) -> list[tuple[int, bool]] | None: """A Darwin group's members as (pid, zombie_or_exiting), from the kernel's own list (sysctl CTL_KERN, KERN_PROC, KERN_PROC_PGRP): one call that no process churn can time out. None where sysctl refuses.""" raw = _darwin_sysctl_procs((ctypes.c_int * 4)(1, 14, 2, pgid)) if raw is None: return None return [ ( struct.unpack_from("=i", raw, at + KINFO_P_PID)[0], _darwin_kinfo_gone(raw, at), ) for at in range(0, len(raw) - KINFO_PROC_SIZE + 1, KINFO_PROC_SIZE) ] def darwin_pid_gone(pid: int) -> bool: """True when a single Darwin pid is absent, zombie, or exiting (P_WEXIT).""" mib = (ctypes.c_int * 4)(1, 14, 1, pid) buffer = ctypes.create_string_buffer(KINFO_PROC_SIZE) size = ctypes.c_size_t(len(buffer)) if LIBC.sysctl(mib, 4, buffer, ctypes.byref(size), None, 0) != 0: return False if size.value < KINFO_PROC_SIZE: return True return _darwin_kinfo_gone(buffer.raw, 0) def pid_gone(pid: int) -> bool: """True when a single pid is reaped, zombie, or tearing down in exit.""" if sys.platform == "darwin": return darwin_pid_gone(pid) try: with open(f"/proc/{pid}/stat", "rb") as stat: fields = stat.read().rsplit(b")", 1)[1].split() return fields[0] == b"Z" except (FileNotFoundError, ProcessLookupError): return True except (OSError, IndexError): return False def table() -> list[tuple[int, int, int, bool]] | None: """Every process as (pid, ppid, pgid, zombie); None where the view is unavailable or incomplete.""" try: entries = os.listdir("/proc") except OSError: if sys.platform != "darwin": return None # Darwin has no /proc. Ask its process table; EPERM alone never means dead. try: result = subprocess.run( [ "/bin/ps", "-A", "-o", "pid=", "-o", "ppid=", "-o", "pgid=", "-o", "stat=", ], capture_output=True, text=True, timeout=0.5, check=True, ) rows = [line.split() for line in result.stdout.splitlines()] return [ ( int(pid), int(ppid), int(pgid), state.startswith("Z") or "E" in state, ) for pid, ppid, pgid, state in rows ] except (OSError, subprocess.SubprocessError, ValueError): return None processes = [] for entry in entries: if not entry.isdigit(): continue try: with open(f"/proc/{entry}/stat", "rb") as stat: fields = stat.read().rsplit(b")", 1)[1].split() processes.append( (int(entry), int(fields[1]), int(fields[2]), fields[0] == b"Z") ) except (FileNotFoundError, ProcessLookupError): # Exited while enumerating: Linux answers ESRCH, not ENOENT, to a # read of a stat file whose process went after the open. continue except (OSError, IndexError, ValueError): return None # an incomplete view cannot prove the group empty return processes def live_members(pgid: int) -> list[int] | None: """Pids in a group that are not zombies; None where the process table is unavailable.""" if sys.platform == "darwin" and (members := darwin_group(pgid)) is not None: return [pid for pid, zombie in members if not zombie] processes = table() if processes is None: return None return [pid for pid, _, group, zombie in processes if group == pgid and not zombie] def _darwin_starts() -> dict[int, str]: raw = _darwin_sysctl_procs((ctypes.c_int * 4)(1, 14, 0, 0)) if raw is None: return {} return { struct.unpack_from("=i", raw, at + KINFO_P_PID)[0]: _darwin_kinfo_start(raw, at) for at in range(0, len(raw) - KINFO_PROC_SIZE + 1, KINFO_PROC_SIZE) } def _darwin_peer_endpoints(pid: int) -> tuple[set[int], set[int]]: """Connected AF_UNIX socket and pipe (local, peer) kernel handles for `pid`.""" locals_set: set[int] = set() peers_set: set[int] = set() needed = LIBC.proc_pidinfo(pid, PROC_PIDLISTFDS, 0, None, 0) if needed <= 0: return locals_set, peers_set buf = ctypes.create_string_buffer(needed + 64 * PROC_FDINFO_SIZE) got = LIBC.proc_pidinfo(pid, PROC_PIDLISTFDS, 0, buf, len(buf)) if got <= 0: return locals_set, peers_set sinfo = ctypes.create_string_buffer(SOCKET_FDINFO_SIZE) pinfo = ctypes.create_string_buffer(PIPE_FDINFO_SIZE) for at in range(0, got - PROC_FDINFO_SIZE + 1, PROC_FDINFO_SIZE): fd, fdtype = struct.unpack_from("=iI", buf.raw, at) if fdtype == PROX_FDTYPE_SOCKET: if ( LIBC.proc_pidfdinfo( pid, fd, PROC_PIDFDSOCKETINFO, sinfo, SOCKET_FDINFO_SIZE ) == SOCKET_FDINFO_SIZE ): family = struct.unpack_from("=i", sinfo.raw, 184)[0] kind = struct.unpack_from("=i", sinfo.raw, 256)[0] if family == AF_UNIX and kind == SOCKINFO_UN: pcb = struct.unpack_from("=Q", sinfo.raw, 168)[0] conn = struct.unpack_from("=Q", sinfo.raw, 272)[0] if pcb and conn: locals_set.add(pcb) peers_set.add(conn) elif fdtype == PROX_FDTYPE_PIPE: if ( LIBC.proc_pidfdinfo( pid, fd, PROC_PIDFDPIPEINFO, pinfo, PIPE_FDINFO_SIZE ) == PIPE_FDINFO_SIZE ): handle, peer = struct.unpack_from("=QQ", pinfo.raw, 160) if handle and peer: locals_set.add(handle) peers_set.add(peer) return locals_set, peers_set def _parse_linux_unix_peers(data: bytes, peers: dict[int, int]) -> bool | None: """Parse one netlink recv buffer; True on DONE, None on ERROR, False to continue.""" offset = 0 while offset + 16 <= len(data): nl_len, nl_type, _, _, _ = struct.unpack_from("=IHHII", data, offset) if nl_len < 16 or offset + nl_len > len(data): return True if nl_type == 2: # NLMSG_ERROR return None if nl_type == 3: # NLMSG_DONE return True if nl_type == 20 and nl_len >= 32: ino = struct.unpack_from("=I", data, offset + 20)[0] attr = offset + 32 end_attr = offset + nl_len while attr + 4 <= end_attr: alen, atype = struct.unpack_from("=HH", data, attr) if alen < 4 or attr + alen > end_attr: break if atype == 2 and alen >= 8: # UNIX_DIAG_PEER peers[ino] = struct.unpack_from("=I", data, attr + 4)[0] attr += (alen + 3) & ~3 offset += (nl_len + 3) & ~3 return False def _query_linux_unix_peers() -> dict[int, int] | None: import socket peers: dict[int, int] = {} try: sock = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, 4) except OSError: return None try: sock.settimeout(0.5) sock.bind((0, 0)) req = struct.pack( "=IHHIIBBHIIIII", 40, 20, 0x301, 1, 0, 1, 0, 0, 0xFFFFFFFF, 0, 0x04, 0, 0 ) sock.sendto(req, (0, 0)) while True: step = _parse_linux_unix_peers(sock.recv(65536), peers) if step is None: return None if step: return peers except OSError: return None finally: sock.close() def _linux_unix_peers() -> dict[int, int]: return _query_linux_unix_peers() or {} def _linux_fds(pid: int) -> tuple[set[int], dict[int, set[int]]]: sockets: set[int] = set() pipes: dict[int, set[int]] = {} fd_dir = f"/proc/{pid}/fd" try: names = os.listdir(fd_dir) except OSError: return sockets, pipes for name in names: try: target = os.readlink(f"{fd_dir}/{name}") except OSError: continue if target.startswith("socket:[") and target.endswith("]"): try: sockets.add(int(target[8:-1])) except ValueError: pass elif target.startswith("pipe:[") and target.endswith("]"): try: ino = int(target[6:-1]) except ValueError: continue mode = 2 try: with open(f"/proc/{pid}/fdinfo/{name}", "r") as info: for line in info: if line.startswith("flags:"): mode = int(line.split()[1], 8) & 3 break except OSError: pass pipes.setdefault(ino, set()).add(mode) return sockets, pipes def _connected_to_movers(unkept: Sequence[int], movers: Sequence[int]) -> set[int]: if not unkept or not movers: return set() if sys.platform == "darwin": mover_locals: set[int] = set() mover_peers: set[int] = set() for pid in movers: locs, rems = _darwin_peer_endpoints(pid) mover_locals |= locs mover_peers |= rems if not mover_locals or not mover_peers: return set() matched: set[int] = set() for pid in unkept: locs, rems = _darwin_peer_endpoints(pid) if (locs & mover_peers) and (rems & mover_locals): matched.add(pid) return matched unix_peers = _linux_unix_peers() mover_socks: set[int] = set() mover_pipes: dict[int, set[int]] = {} for pid in movers: socks, pipes = _linux_fds(pid) mover_socks |= socks for ino, modes in pipes.items(): mover_pipes.setdefault(ino, set()).update(modes) matched = set() for pid in unkept: socks, pipes = _linux_fds(pid) if any(unix_peers.get(ino) in mover_socks for ino in socks): matched.add(pid) continue for ino, modes in pipes.items(): other = mover_pipes.get(ino) if not other: continue if ( (0 in modes and (1 in other or 2 in other)) or (0 in other and (1 in modes or 2 in modes)) or (2 in modes and 2 in other) ): matched.add(pid) break return matched def adopted(group: Group) -> set[int]: """Members of the group that a process which moved out of it still parents or holds an IPC peer to, with their descendants in it. ssh's ControlPersist master forks its ProxyCommand, then daemonizes out of the job's group. When ssh itself led the job, control_persist_detach() forks the [mux] master and exits the original ssh, reparenting the proxy to pid 1 while the new master still holds the other end of its socketpair; plain orphans have no peer among processes that left the job after it began. """ if not group.whole or group.leader is None: return set() processes = table() if processes is None: return set() groups = {pid: pgid for pid, _, pgid, _ in processes} members = { pid: ppid for pid, ppid, pgid, zombie in processes if pgid == group.pgid and not zombie } if not members: return set() begun = float(group.leader) starts = _darwin_starts() if sys.platform == "darwin" else {} def started_at(pid: int) -> str | None: return starts.get(pid) or leader_token(pid) kept = set() for pid, ppid in members.items(): if groups.get(ppid, group.pgid) == group.pgid: continue started = started_at(ppid) if started is not None and float(started) >= begun: kept.add(pid) unkept = [pid for pid in members if pid not in kept] if unkept: movers = [ pid for pid, _, pgid, zombie in processes if pid > 1 and pgid != group.pgid and not zombie and (started := started_at(pid)) is not None and float(started) >= begun ] kept |= _connected_to_movers(unkept, movers) while descendants := { pid for pid, ppid in members.items() if ppid in kept and pid not in kept }: kept |= descendants return kept def deliver(group: Group, sig: int) -> None: """Signal the target: its group, or the single process when it leads none.""" (os.killpg if group.whole else os.kill)(group.pgid, sig) def _darwin_has_exiting(pgid: int) -> bool: raw = _darwin_sysctl_procs((ctypes.c_int * 4)(1, 14, 2, pgid)) if raw is None: return False return any( raw[at + KINFO_P_STAT] != SZOMB and bool(struct.unpack_from("=i", raw, at + KINFO_P_FLAG)[0] & P_WEXIT) for at in range(0, len(raw) - KINFO_PROC_SIZE + 1, KINFO_PROC_SIZE) ) def alive(group: Group) -> bool: """True while the target exists and still looks like the one we created.""" try: deliver(group, 0) except ProcessLookupError: return False except PermissionError: # Darwin answers EPERM for a group of only zombies/exiting processes, # which is not work. Any other EPERM is a cleanup failure, and an # unreadable view is no proof. if group.leader is not None: token = leader_token(group.pgid) if token is not None and token != group.leader: return False zombies_only = ( group.whole and sys.platform == "darwin" and live_members(group.pgid) == [] ) return not zombies_only if not group.whole and pid_gone(group.pgid): return False if group.leader is None: return True token = leader_token(group.pgid) return token is None or token == group.leader def current(group: Group) -> bool: """alive/1 refined by membership: zombies awaiting reaping are not work.""" if not alive(group): return False if not group.whole: return True members = live_members(group.pgid) return True if members is None else bool(members) def send_signal(group: Group, sig: int) -> str | None: """Send one signal to a target; returns the failure text when it did not land.""" try: deliver(group, sig) return None except ProcessLookupError: return None # already gone; the probe decides except OSError as error: return f"{signal.Signals(sig).name} to {group.pgid}: {error.strerror or error}" def _settling(group: Group) -> bool: if alive(group): return True return group.whole and sys.platform == "darwin" and _darwin_has_exiting(group.pgid) async def settled(live: dict[int, Group], window: float) -> dict[int, Group]: """The groups still alive after one shared wait, so batches share a deadline.""" loop = asyncio.get_running_loop() deadline = loop.time() + window while True: remaining = {pgid: group for pgid, group in live.items() if _settling(group)} if not remaining or loop.time() >= deadline: return remaining await asyncio.sleep(PROBE_INTERVAL) async def terminate( groups: Sequence[Group], term: float = TERM_GRACE, kill: float = KILL_GRACE ) -> list[Termination]: """End every group: TERM, then KILL, one shared deadline per step.""" live = {group.pgid: group for group in groups if alive(group)} sent: dict[int, list[str]] = {pgid: [] for pgid in live} failures: dict[int, list[str]] = {pgid: [] for pgid in live} for sig, window in ((signal.SIGTERM, term), (signal.SIGKILL, kill)): for pgid, group in live.items(): failure = send_signal(group, sig) sent[pgid].append(sig.name) if failure is not None: failures[pgid].append(failure) live = await settled(live, window) if not live: break endings = [] for group in groups: pgid, signals = group.pgid, sent.get(group.pgid, []) surviving, note = pgid in live, "" if surviving and not current(group): surviving, note = False, "only non-running members remained" endings.append( Termination( pgid, tuple(signals), not surviving, tuple(failures.get(pgid, [])), note ) ) return endings async def end(group: Group, leave_adopted: bool = False) -> Termination: """End a job's group. Once its command has exited on its own (`leave_adopted`), members a process that left the group still parents are that process's (`adopted`) and stay; the rest are ended one by one.""" if not (leave_adopted and alive(group)): return (await terminate([group]))[0] signals: list[str] = [] failures: list[str] = [] rounds = 0 while True: kept = adopted(group) if not kept: return (await terminate([group]))[0] rest = [pid for pid in live_members(group.pgid) or [] if pid not in kept] if not rest or rounds == 3: # a member may fork while the others end note = f"kept {len(kept)} that a process which left the group parents" return Termination( group.pgid, tuple(signals), not rest, tuple(failures), note ) rounds += 1 targets = [Group(pid, leader_token(pid), whole=False) for pid in rest] for ending in await terminate(targets): signals += [name for name in ending.signals if name not in signals] failures += ending.failures