File size: 15,368 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
870b85a
 
3f15e9f
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""Bounded execution and cleanup of observed descendants, across sessions.

``execute_command(command, cwd, log_path, timeout)`` returns a JSON-compatible
dict with command, cwd, pid, exit_code (the launcher's actual return code),
timed_out, elapsed_s (including cleanup), cleanup_passed, and cleanup. The latter
records each owned PID and immutable birth identity, signals sent, errors, and
remaining live processes. ``cleanup['complete']`` concerns observed ownership.
Logs are created exclusively and retained on failure/timeout. Invalid arguments
and launch failures raise. Tracking failures stop execution, trigger cleanup,
and return cleanup_passed=False with error evidence. Any launched job is cleaned
in finally. No shell, process-wide signal handlers, or subreaper settings are used.

Linux requires /proc and Python/kernel pidfd support (Python 3.9+, Linux 5.3+).
macOS uses libproc's BSD/unique-ID snapshot and audit-token signal API. Both
validate immutable birth identity before signaling and bind the signal to the
kernel process identity, avoiding a check-then-kill PID-reuse race. Unsupported
identity/signal facilities fail before launch rather than using an unsafe kill.

Containment limit: polling can miss a double-fork that reparents between samples,
including a child created immediately before its parent exits. This is NOT a
sandbox. There is no adoption of arbitrary caller children, process-name search,
or process-group signaling. Observed descendants remain owned after reparenting.
Zombies are not running; only the direct Popen child is reaped. Cleanup grants
0.5s for TERM and 1s for KILL/reaping, in addition to timeout and snapshot/OS-call
overhead. Unkillable processes are reported, never waited on indefinitely.
"""
from __future__ import annotations

import ctypes
from dataclasses import asdict, dataclass
import errno
import math
import os
from pathlib import Path
import signal
import subprocess
import sys
import time


_POLL_S = .02
_TERM_GRACE_S = .5
_KILL_GRACE_S = 1.
_CONTAINMENT_LIMIT = (
    'Polling can miss a double-fork or child that reparents between samples; '
    'complete covers observed identities only, not full sandbox containment.'
)


@dataclass(frozen=True)
class _Process:
    pid: int
    ppid: int
    birth: tuple[int, ...]
    state: str
    version: int = 0


class _BSDInfo(ctypes.Structure):
    _fields_ = [(name, ctypes.c_uint32) for name in (
        'flags', 'status', 'xstatus', 'pid', 'ppid', 'uid', 'gid', 'ruid',
        'rgid', 'svuid', 'svgid', 'reserved')]
    _fields_ += [('comm', ctypes.c_char * 16), ('name', ctypes.c_char * 32)]
    _fields_ += [(name, ctypes.c_uint32) for name in (
        'nfiles', 'pgid', 'jobc', 'tdev', 'tpgid')]
    _fields_ += [('nice', ctypes.c_int32), ('seconds', ctypes.c_uint64),
                 ('microseconds', ctypes.c_uint64)]


class _UniqueInfo(ctypes.Structure):
    _fields_ = [('uuid', ctypes.c_uint8 * 16), ('uniqueid', ctypes.c_uint64),
                ('parent_uniqueid', ctypes.c_uint64), ('version', ctypes.c_int32),
                ('parent_version', ctypes.c_int32), ('reserved2', ctypes.c_uint64),
                ('reserved3', ctypes.c_uint64)]


class _DarwinInfo(ctypes.Structure):
    _fields_ = [('bsd', _BSDInfo), ('unique', _UniqueInfo)]


class _ProcessTable:
    def __init__(self):
        self.backend = sys.platform
        if self.backend == 'darwin':
            self.lib = ctypes.CDLL('/usr/lib/libproc.dylib', use_errno=True)
            self.lib.proc_listpids.argtypes = [ctypes.c_uint32, ctypes.c_uint32,
                                              ctypes.c_void_p, ctypes.c_int]
            self.lib.proc_listpids.restype = ctypes.c_int
            self.lib.proc_pidinfo.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
                                             ctypes.c_void_p, ctypes.c_int]
            self.lib.proc_pidinfo.restype = ctypes.c_int
            self.lib.proc_signal_with_audittoken.argtypes = [ctypes.c_void_p, ctypes.c_int]
            self.lib.proc_signal_with_audittoken.restype = ctypes.c_int
        elif self.backend.startswith('linux'):
            if not (hasattr(os, 'pidfd_open') and hasattr(signal, 'pidfd_send_signal')):
                raise RuntimeError('Safe Linux ownership cleanup requires pidfd support')
        else:
            raise RuntimeError('Ownership tracking supports Linux and macOS only')
        own = self.read(os.getpid())
        if own is None:
            raise RuntimeError('Cannot read native process birth identity')
        if self.backend.startswith('linux'):
            self.send_signal(own, 0)

    def read(self, pid):
        if self.backend == 'darwin':
            info = _DarwinInfo()
            # XNU PROC_PIDT_BSDINFOWITHUNIQID=18 returns both in one call.
            size = self.lib.proc_pidinfo(pid, 18, 0, ctypes.byref(info), ctypes.sizeof(info))
            if size != ctypes.sizeof(info):
                error = ctypes.get_errno()
                if size == 0 and error in (errno.ESRCH, errno.ENOENT):
                    return None
                raise OSError(error or errno.EIO, 'proc_pidinfo failed', str(pid))
            bsd = info.bsd
            return _Process(pid, bsd.ppid,
                            (bsd.seconds, bsd.microseconds, info.unique.uniqueid),
                            'Z' if bsd.status == 5 else 'S', info.unique.version)
        try:
            with open('/proc/'+str(pid)+'/stat', 'rb') as source:
                data = source.read()
        except (FileNotFoundError, ProcessLookupError):
            return None
        # comm can contain opaque bytes, spaces and right parentheses. Split
        # after its final delimiter; only the state token needs ASCII decoding.
        fields = data.rsplit(b')', 1)[1].split()
        return _Process(pid, int(fields[1]), (int(fields[19]),), fields[0].decode('ascii'))

    def snapshot(self):
        if self.backend == 'darwin':
            size = self.lib.proc_listpids(1, 0, None, 0)
            if size <= 0:
                raise OSError(ctypes.get_errno() or errno.EIO, 'proc_listpids failed')
            # Spare capacity covers forks between sizing and fetching the table.
            pids = (ctypes.c_int * (size // ctypes.sizeof(ctypes.c_int) + 256))()
            size = self.lib.proc_listpids(1, 0, pids, ctypes.sizeof(pids))
            if size <= 0 or size >= ctypes.sizeof(pids):
                raise OSError(ctypes.get_errno() or errno.EOVERFLOW, 'Incomplete process table')
            ids = pids[:size // ctypes.sizeof(ctypes.c_int)]
        else:
            ids = [int(name) for name in os.listdir('/proc') if name.isdigit()]
        result = {}
        for pid in ids:
            if pid <= 0:
                continue
            try:
                row = self.read(pid)
            except PermissionError:
                # Other users' processes need not be inspectable; owned reads still fail.
                continue
            if row is not None:
                result[pid] = row
        return result

    def send_signal(self, owned, sig):
        if self.backend == 'darwin':
            current = self.read(owned.pid)
            if current is None or current.birth != owned.birth:
                raise ProcessLookupError(errno.ESRCH, 'Process identity no longer exists')
            # XNU checks PID + pidversion atomically, even if exit/reuse races this call.
            # pidversion can change across exec; immutable birth/uniqueid cannot.
            token = (ctypes.c_uint32 * 8)()
            token[5], token[7] = owned.pid, current.version
            error = self.lib.proc_signal_with_audittoken(token, sig)
            if error:
                raise OSError(error, os.strerror(error), str(owned.pid))
            return
        fd = os.pidfd_open(owned.pid, 0)
        try:
            current = self.read(owned.pid)
            if current is None or current.birth != owned.birth:
                raise ProcessLookupError(errno.ESRCH, 'Process identity no longer exists')
            signal.pidfd_send_signal(fd, sig, None, 0)
        finally:
            os.close(fd)


class _Ownership:
    def __init__(self, table, root):
        self.table = table
        self.owned = {} if root is None else {root.pid: root}
        self.term_sent = []
        self.kill_sent = []
        self.errors = []
        self.samples = 0

    def collect(self):
        table = self.table.snapshot()
        self.samples += 1
        for pid, owned in self.owned.items():
            if pid not in table:
                current = self.table.read(pid)
                if current and current.birth == owned.birth and current.state != 'Z':
                    self._error('sample', pid, 'Known live identity missing from process snapshot')
                    table[pid] = current
        parents = {pid for pid, row in self.owned.items()
                   if pid in table and table[pid].birth == row.birth}
        pending = list(parents)
        children = {}
        for row in table.values():
            children.setdefault(row.ppid, []).append(row)
        while pending:
            parent = pending.pop()
            current = self.table.read(parent)
            if current is None or current.birth != self.owned[parent].birth:
                continue
            for row in children.get(parent, ()):
                if row.pid in self.owned or row.birth[-1] < current.birth[-1]:
                    continue
                # Never replace a first-seen identity with a recycled PID's birth.
                self.owned[row.pid] = row
                pending.append(row.pid)

    def live(self):
        result = []
        for row in self.owned.values():
            try:
                current = self.table.read(row.pid)
            except Exception as error:
                self._error('inspect', row.pid, error)
                result.append(row)  # Unknown is not proof of successful cleanup.
                continue
            if current and current.birth == row.birth and current.state != 'Z':
                result.append(row)
        return result

    def _error(self, action, pid, error):
        record = dict(action=action, pid=pid, error=str(error))
        if record not in self.errors:
            self.errors.append(record)

    def signal(self, sig):
        sent = self.term_sent if sig == signal.SIGTERM else self.kill_sent
        for row in reversed(self.live()):
            if row.pid in sent:
                continue
            try:
                self.table.send_signal(row, sig)
                sent.append(row.pid)
            except ProcessLookupError:
                pass
            except Exception as error:
                self._error('signal', row.pid, error)

    def cleanup(self, process):
        # Final pretermination sample, then keep discovering during both grace periods.
        for sig, grace in ((signal.SIGTERM, _TERM_GRACE_S),
                           (signal.SIGKILL, _KILL_GRACE_S)):
            deadline = time.monotonic() + grace
            while True:
                try:
                    self.collect()
                except Exception as error:
                    self._error('sample', None, error)
                self.signal(sig)
                # Popen exclusively owns this direct child; unreaped children cannot reuse PID.
                if process.pid not in self.owned and process.poll() is None:
                    try:
                        process.send_signal(sig)
                    except ProcessLookupError:
                        pass
                    except Exception as error:
                        self._error('signal', process.pid, error)
                process.poll()
                if not self.live() and process.returncode is not None:
                    break
                if time.monotonic() >= deadline:
                    break
                time.sleep(min(_POLL_S, max(0., deadline - time.monotonic())))
        remaining = self.live()
        return dict(
            strategy='birth-identity-tracked-descendants', backend=self.table.backend,
            owned_processes=[asdict(row) for row in self.owned.values()],
            term_sent=self.term_sent, kill_sent=self.kill_sent,
            remaining=[asdict(row) for row in remaining], errors=self.errors,
            complete=not remaining and not self.errors and process.returncode is not None,
            samples=self.samples, full_containment=False, containment_limit=_CONTAINMENT_LIMIT,
        )


def execute_command(command: list[str], cwd: Path, log_path: Path, timeout: float) -> dict:
    """Run a command with a retained combined log and bounded ownership cleanup.

    Always inspect cleanup_passed as well as exit_code/timed_out. A zero launcher
    exit does not imply successful cleanup. See module docstring for containment
    and platform requirements. No output directories are created implicitly.
    """
    if (not isinstance(command, list) or not command
            or any(not isinstance(arg, str) for arg in command)):
        raise ValueError('command must be a nonempty list of strings')
    if (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
            or not math.isfinite(timeout) or timeout <= 0):
        raise ValueError('timeout must be a finite positive number')
    cwd, log_path = Path(cwd), Path(log_path)
    table = _ProcessTable()
    started = time.monotonic()
    timed_out = False
    with log_path.open('xb') as log:
        process = subprocess.Popen(command, cwd=cwd, stdout=log,
                                   stderr=subprocess.STDOUT, start_new_session=True)
        tracker = _Ownership(table, None)
        try:
            try:
                root = table.read(process.pid)
            except Exception as error:
                root = None
                tracker._error('identify', process.pid, error)
            if root is not None:
                tracker.owned[root.pid] = root
            else:
                tracker._error('identify', process.pid, 'Launcher birth identity unavailable')
            deadline = started + timeout
            while not tracker.errors:
                # Collect before poll reaps a just-exited launcher and loses its ancestry.
                try:
                    tracker.collect()
                except Exception as error:
                    tracker._error('sample', None, error)
                    break
                if tracker.errors:
                    break
                if process.poll() is not None:
                    break
                if time.monotonic() >= deadline:
                    timed_out = True
                    break
                time.sleep(min(_POLL_S, max(0., deadline - time.monotonic())))
        finally:
            cleanup = tracker.cleanup(process)
    receipt = dict(command=list(command), cwd=str(cwd), pid=process.pid,
                   exit_code=process.returncode, timed_out=timed_out,
                   elapsed_s=round(time.monotonic() - started, 3),
                   cleanup_passed=cleanup['complete'], cleanup=cleanup)
    # asdict preserves tuples; normalize them to JSON arrays for receipt consumers.
    for key in ('owned_processes', 'remaining'):
        for row in cleanup[key]:
            row['birth'] = list(row['birth'])
    return receipt