diff --git a/adapters/template/driver b/adapters/template/driver index ad0c2884f..7ad587b5e 100755 --- a/adapters/template/driver +++ b/adapters/template/driver @@ -13,6 +13,7 @@ EFFORTS = {'fake-harness': ('--effort', ('low', 'medium', 'high', 'xhigh', 'max' CANT_SET_EFFORT = ("this host can't set effort: remove the effort for this harness in your Models table or Roster to " "run it at the host's default") GRACE = 10 +KILL_GRACE = 2 LSOF_COULD_NOT_CHECK = [] NO_LSOF = ('driver: lsof could not run or failed, so the driver could not check which processes hold this ' "run's output files open; it ended only the turns' process groups and the processes their " @@ -294,11 +295,159 @@ def running(turn, run): return bool(turn) and turn['since'] is not None and since(turn['pid']) == turn['since'] +def legacy_turns(turns): + return isinstance(turns, list) and bool(turns) and all(type(t) is int for t in turns) + + +def format_pids(pids): + ordered = sorted(pids) + shown = ', '.join(str(p) for p in ordered[:10]) + return shown + (' (and %d more)' % (len(ordered) - 10) if len(ordered) > 10 else '') + + +def proc_table(run): + try: + entries = os.listdir('/proc') + except OSError: + raise Refused('run %s could not be checked because /proc is not readable' % run, + 'check and end processes carrying OPENWIZ_RUN=%s by hand' % run) + table, children = {}, {} + for name in entries: + if not name.isdigit(): + continue + pid = int(name) + try: + with open('/proc/%d/stat' % pid) as f: + fields = f.read().rpartition(')')[2].split() + except OSError: + continue + if len(fields) < 20 or fields[0] == 'Z': + continue + ppid, pgid, sid, started = int(fields[1]), int(fields[2]), int(fields[3]), int(fields[19]) + table[pid] = (ppid, pgid, sid, started) + children.setdefault(ppid, []).append(pid) + return table, children + + +# PRIVACY: legacy pre-#1590 records store only turn pids; read /proc//environ only for candidates +# already tied to those turns' pids, process groups or sessions to verify OPENWIZ_RUN, never repeating it. +def scan_legacy(turn_ids, run, mark, tracked, verified_groups, verified_sessions, checked_unmarked): + table, children = proc_table(run) + self_chain, cur = set(), os.getpid() + while cur in table and cur not in self_chain: + self_chain.add(cur) + cur = table[cur][0] + for p in [p for p, st in tracked.items() if p not in table or table[p][3] != st]: + del tracked[p] + live_groups = {pgid for _, pgid, _, _ in table.values()} + live_sessions = {sid for _, _, sid, _ in table.values()} + verified_groups &= live_groups + verified_sessions &= live_sessions + unreadable = set() + for p, (_, pgid, sid, st) in table.items(): + if p in self_chain or p in tracked or (p, st) in checked_unmarked: + continue + if p not in turn_ids and pgid not in turn_ids and sid not in turn_ids: + continue + try: + with open('/proc/%d/environ' % p, 'rb') as f: + raw = f.read() + except (FileNotFoundError, ProcessLookupError): + continue + except PermissionError: + try: + if os.stat('/proc/%d' % p).st_uid != os.geteuid(): + checked_unmarked.add((p, st)) + else: + unreadable.add(p) + except OSError: + pass + continue + except OSError: + if since(p) == st: + unreadable.add(p) + continue + if since(p) != st: + continue + if mark in raw.split(b'\0'): + tracked[p] = st + if pgid in turn_ids: + verified_groups.add(pgid) + if sid in turn_ids: + verified_sessions.add(sid) + else: + checked_unmarked.add((p, st)) + for p, (_, pgid, sid, st) in table.items(): + if p not in self_chain and (pgid in verified_groups or sid in verified_sessions): + tracked[p] = st + todo = list(tracked) + while todo: + for c in children.get(todo.pop(), ()): + if c not in tracked and c not in self_chain and c in table: + tracked[c] = table[c][3] + todo.append(c) + return unreadable - set(tracked) + + +def signal_pinned(targets, sig, sent): + pinned = {} + for p, st in targets.items(): + if (p, st) in sent: + continue + try: + pinned[p] = (os.pidfd_open(p), st) + except OSError: + pass + for p, (fd, st) in pinned.items(): + try: + if since(p) == st: + signal.pidfd_send_signal(fd, sig) + sent.add((p, st)) + except OSError: + pass + finally: + os.close(fd) + + +def end_legacy(turns, run, already_stopped=False): + if not all(type(pid) is int and pid > 0 for pid in turns): + raise Refused('run %s was saved by an older template and a turn is not a pid, so it was not stopped' % run, + 'end its processes by hand') + if not LINUX: + if already_stopped: + return + raise Refused('run %s was saved by an older template and this host cannot confirm its processes ended' % run, + 'stop it on Linux, or end processes carrying OPENWIZ_RUN=%s by hand' % run) + turn_ids, mark = set(turns), ('OPENWIZ_RUN=' + run).encode() + tracked, verified_groups, verified_sessions, checked_unmarked = {}, set(), set(), set() + for sig, wait in ((signal.SIGTERM, GRACE), (signal.SIGKILL, KILL_GRACE)): + sent, deadline = set(), time.monotonic() + wait + while True: + unreadable = scan_legacy(turn_ids, run, mark, tracked, verified_groups, verified_sessions, checked_unmarked) + if not tracked: + if unreadable: + raise Refused('run %s has processes the driver cannot inspect to confirm it stopped' % run, + 'check and end these processes by hand: %s' % format_pids(unreadable)) + return + signal_pinned(tracked, sig, sent) + if time.monotonic() >= deadline: + break + time.sleep(min(0.1, max(0, deadline - time.monotonic()))) + unreadable = scan_legacy(turn_ids, run, mark, tracked, verified_groups, verified_sessions, checked_unmarked) + if not tracked and not unreadable: + return + if not tracked: + raise Refused('run %s has processes the driver cannot inspect to confirm it stopped' % run, + 'check and end these processes by hand: %s' % format_pids(unreadable)) + raise Refused('run %s still has processes after stop' % run, + 'stop it again, or end these processes by hand: %s' % format_pids(tracked)) + + def end(turns, run): kept = [(t['supervisor'], t['supervisor_since']) for t in turns if t and t['supervisor_since'] is not None] if lsof_failed_in(run, kept): LSOF_COULD_NOT_CHECK.append(run) - for sig, wait in ((signal.SIGTERM, GRACE), (signal.SIGKILL, 2)): + for sig, wait in ((signal.SIGTERM, GRACE), (signal.SIGKILL, KILL_GRACE)): sent, deadline = set(), time.monotonic() + wait while time.monotonic() < deadline: kept = [(p, t) for p, t in kept if since(p) == t] @@ -407,6 +556,15 @@ def answer(cmd): lock(run) state = saved(run) if cmd == 'stop': + if legacy_turns(state['turns']): + end_legacy(state['turns'], run, state.get('stopped')) + try: + saved(run, dict(state, stopped=True)) + except OSError: + raise Refused('run %s has ended, but the driver could not save that it is stopped' % run, + 'make OPENWIZ_TEMPLATE_STATE (or ~/.local/state/openwiz-template) a folder you can ' + 'write, then stop it again') + return {'run': run, 'stopped': True} try: saved(run, dict(state, stopped=True)) kept = True @@ -426,6 +584,9 @@ def answer(cmd): return {'run': run, 'stopped': True} if state['stopped']: raise Refused('run %s is stopped' % run, 'start a new run') + if legacy_turns(state['turns']): + raise Refused('run %s was saved by an older template, so it was not woken' % run, + 'stop it, then start a new run') if state.get('starting'): raise Refused('run %s never finished starting' % run, 'stop it, then start a new run') if state['turns'] and running(state['turns'][-1], run): diff --git a/adapters/template/test_driver.py b/adapters/template/test_driver.py index 0a33fe913..32cf39678 100755 --- a/adapters/template/test_driver.py +++ b/adapters/template/test_driver.py @@ -67,6 +67,79 @@ def paused(*args): t.running = paused t.main() ''' +PRE_1590_TEMPLATE = '''import json, os, secrets, subprocess, sys +cmd = sys.argv[1] +req = json.loads(sys.stdin.read()) +state_dir = os.environ['OPENWIZ_TEMPLATE_STATE'] +os.makedirs(state_dir, mode=0o700, exist_ok=True) +def launch(start_req, run, woken): + what = 'You were woken: read the ticket again and carry on' if woken else 'Build the ticket' + prompt = '%s: %s#%d, with the %s skill.' % (what, start_req['repository'], start_req['ticket'], start_req['skill']) + return subprocess.Popen([start_req['harness'], '--model', start_req['model'], '-p', prompt], + env=dict(os.environ, OPENWIZ_RUN=run), start_new_session=True, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).pid +if cmd == 'start': + run = 'run-' + secrets.token_hex(6) + state = {'request': req, 'turns': [launch(req, run, False)], 'stopped': False} + with open(os.path.join(state_dir, run + '.json'), 'w') as f: + json.dump(state, f) + print(json.dumps({'run': run})) +elif cmd == 'wake': + run = req['run'] + path = os.path.join(state_dir, run + '.json') + with open(path) as f: + state = json.load(f) + state['turns'].append(launch(state['request'], run, True)) + with open(path, 'w') as f: + json.dump(state, f) + print(json.dumps({'run': run, 'woke': True})) +''' +CHECKPOINT_HARNESS = '''import os, signal, sys, time +if os.environ.get('IGNORE_TERM'): + signal.signal(signal.SIGTERM, signal.SIG_IGN) +else: + def on_term(*_): + time.sleep(0.25) + with open(os.environ['CHECKPOINT'], 'w') as f: + f.write('saved') + sys.exit(0) + signal.signal(signal.SIGTERM, on_term) +with open(os.environ['READY'], 'w') as f: + f.write(str(os.getpid())) +while True: + time.sleep(0.05) +''' +LEGACY_STOP_WRAPPER = '''import importlib.machinery, importlib.util, os, re, signal, sys +sys.dont_write_bytecode = True +if os.environ.get('AUDIT_ENVIRON') or os.environ.get('DENY_ENVIRON'): + seen, deny = os.environ.get('AUDIT_ENVIRON'), os.environ.get('DENY_ENVIRON') + def audit(event, args): + if event == 'open' and isinstance(args[0], (str, bytes)): + path = os.fsdecode(args[0]) + if re.fullmatch(r'/proc/[0-9]+/environ', path): + if seen: + with open(seen, 'a') as f: + f.write(path + '\\n') + if deny: + raise PermissionError('synthetic environ refusal') + sys.addaudithook(audit) +spec = importlib.util.spec_from_loader('template', importlib.machinery.SourceFileLoader('template', %r)) +t = importlib.util.module_from_spec(spec) +spec.loader.exec_module(t) +if os.environ.get('SHORT_GRACE'): + t.GRACE = float(os.environ['SHORT_GRACE']) + if hasattr(t, 'KILL_GRACE'): + t.KILL_GRACE = float(os.environ['SHORT_GRACE']) +if os.environ.get('DENY_SIGNALS'): + def denied(*_): + raise PermissionError('synthetic signal refusal') + if hasattr(signal, 'pidfd_send_signal'): + signal.pidfd_send_signal = denied + os.killpg = denied + real_kill = os.kill + os.kill = lambda pid, sig: real_kill(pid, sig) if sig == 0 else denied(pid, sig) +t.main() +''' def pinned_path(folder, *fixtures): @@ -162,13 +235,18 @@ def sleeps(self, pid): except OSError: return False - def wrapper(self, name, source): - path = os.path.join(self.folder, name) + def script(self, name, source, folder=None): + folder = folder or self.folder + os.makedirs(folder, exist_ok=True) + path = os.path.join(folder, name) with open(path, 'w') as f: - f.write('#!%s\n' % sys.executable + source % DRIVER) + f.write('#!%s\n' % sys.executable + source) os.chmod(path, 0o700) return path + def wrapper(self, name, source): + return self.script(name, source % DRIVER) + def call(self, cmd, request, driver=DRIVER, **env): env = dict(self.env, **env) no_real_harness(env['PATH'], self.stub_dir) @@ -624,6 +702,107 @@ def test_without_proc_as_on_macos_stop_ends_each_grandchild(self): self.assertEqual(self.asked_ps_for_environments(calls), [], 'the driver asked ps for process environments') + def test_a_run_saved_by_the_older_template_stops_and_does_not_wake(self): + old_driver = self.script('pre-1590-driver', PRE_1590_TEMPLATE) + code, started = self.call('start', START, driver=old_driver, FAKE_SAME_GROUP='1') + self.assertEqual(code, 0, started) + run = started['run'] + [(turn, child, _)] = self.logged(1) + record_path = os.path.join(self.env['OPENWIZ_TEMPLATE_STATE'], run + '.json') + self.assertEqual(json.loads(read(record_path))['turns'], [turn]) + self.assertTrue(self.until(lambda: not alive(turn)), 'the legacy harness did not exit') + self.assertTrue(alive(child)) + code, out = self.call('wake', {'run': run}) + self.assertEqual(code, 1, out) + self.assertIn('older template', out['error']) + self.assertNotIn('TypeError', json.dumps(out)) + self.assertEqual(len(self.logged()), 1, 'wake started a second turn for a legacy run') + self.assertTrue(alive(child)) + outsider = subprocess.Popen(['sleep', '120'], start_new_session=True, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.addCleanup(lambda p=outsider: (p.kill(), p.wait())) + audited = os.path.join(self.folder, 'environ-opens') + driver = self.wrapper('legacy-audit', LEGACY_STOP_WRAPPER) + code, out = self.call('stop', {'run': run}, driver=driver, AUDIT_ENVIRON=audited) + self.assertEqual((code, out), (0, {'run': run, 'stopped': True})) + self.assertFalse(alive(child), 'a worker in the legacy turn group still runs after stop') + self.assertEqual(self.marked(), [], 'a legacy run process still runs after stop') + self.assertTrue(alive(outsider.pid), 'stop affected an unrelated process') + opened = read(audited).splitlines() if os.path.exists(audited) else [] + self.assertNotIn('/proc/%d/environ' % outsider.pid, opened, 'stop read an unrelated process environment') + self.assertEqual(self.call('stop', {'run': run}), (0, {'run': run, 'stopped': True})) + + def test_stop_gives_a_legacy_run_shutdown_grace_before_sigkill(self): + old_driver = self.script('pre-1590-driver', PRE_1590_TEMPLATE) + fixtures = os.path.join(self.folder, 'checkpoint-fixtures') + self.script('fake-harness', CHECKPOINT_HARNESS, folder=fixtures) + path = fixtures + os.pathsep + self.env['PATH'] + ready = os.path.join(self.folder, 'ready-grace') + checkpoint = os.path.join(self.folder, 'checkpoint') + code, started = self.call('start', START, driver=old_driver, PATH=path, READY=ready, CHECKPOINT=checkpoint) + self.assertEqual(code, 0, started) + self.assertTrue(self.until(lambda: os.path.exists(ready) and bool(read(ready).strip()))) + pid = int(read(ready).strip()) + code, out = self.call('stop', started, PATH=path) + self.assertEqual((code, out), (0, dict(started, stopped=True))) + self.assertFalse(alive(pid), 'the legacy harness still runs after stop') + self.assertTrue(os.path.exists(checkpoint) and read(checkpoint) == 'saved', + 'stop killed the legacy harness before it saved its checkpoint') + ready_ign = os.path.join(self.folder, 'ready-ignore') + code, started_ign = self.call('start', START, driver=old_driver, PATH=path, READY=ready_ign, IGNORE_TERM='1') + self.assertEqual(code, 0, started_ign) + self.assertTrue(self.until(lambda: os.path.exists(ready_ign) and bool(read(ready_ign).strip()))) + pid_ign = int(read(ready_ign).strip()) + driver = self.wrapper('legacy-short-grace', LEGACY_STOP_WRAPPER) + t0 = time.monotonic() + code, out = self.call('stop', started_ign, driver=driver, PATH=path, SHORT_GRACE='0.4') + elapsed = time.monotonic() - t0 + self.assertEqual((code, out), (0, dict(started_ign, stopped=True))) + self.assertGreaterEqual(elapsed, 0.35, 'stop did not wait the shutdown grace before SIGKILL') + self.assertFalse(alive(pid_ign), 'a SIGTERM-ignoring legacy harness still runs after stop') + + def test_stop_refuses_a_legacy_run_before_marking_stopped_when_shutdown_is_unconfirmed(self): + old_driver = self.script('pre-1590-driver', PRE_1590_TEMPLATE) + open(self.hold, 'w').close() + code, started = self.call('start', START, driver=old_driver, FAKE_SAME_GROUP='1') + self.assertEqual(code, 0, started) + [(turn, child, _)] = self.logged(1) + record_path = os.path.join(self.env['OPENWIZ_TEMPLATE_STATE'], started['run'] + '.json') + driver = self.wrapper('legacy-deny-signals', LEGACY_STOP_WRAPPER) + code, out = self.call('stop', started, driver=driver, DENY_SIGNALS='1', SHORT_GRACE='0.2') + self.assertEqual(code, 1, out) + self.assertIn('still has processes', out['error']) + self.assertTrue(out.get('next'), out) + self.assertFalse(json.loads(read(record_path))['stopped'], 'stop marked the run stopped despite survivors') + self.assertTrue(alive(turn)) + code, out = self.call('stop', started, driver=driver, DENY_ENVIRON='1') + self.assertEqual(code, 1, out) + self.assertIn('cannot inspect', out['error']) + self.assertTrue(out.get('next'), out) + self.assertFalse(json.loads(read(record_path))['stopped'], 'stop marked the run stopped with unreadable environ') + self.assertTrue(alive(turn)) + macos = {'PATH': NO_PROC + os.pathsep + self.env['PATH'], 'NO_PROC_PYTHON': sys.executable} + code, out = self.call('stop', started, **macos) + self.assertEqual(code, 1, out) + self.assertTrue(out.get('error') and out.get('next'), out) + self.assertFalse(json.loads(read(record_path))['stopped'], 'stop marked the run stopped without /proc') + self.assertTrue(alive(turn)) + self.assertEqual(self.call('stop', started), (0, dict(started, stopped=True))) + self.assertEqual((alive(turn), alive(child)), (False, False)) + self.assertEqual(self.call('stop', started, **macos), (0, dict(started, stopped=True))) + + def test_stop_does_not_signal_an_unrelated_process_that_reused_a_legacy_pid(self): + run = 'run-' + secrets.token_hex(6) + folder = self.env['OPENWIZ_TEMPLATE_STATE'] + os.makedirs(folder, exist_ok=True) + unmarked = subprocess.Popen(['sleep', '120'], start_new_session=True, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.addCleanup(lambda p=unmarked: (p.kill(), p.wait())) + with open(os.path.join(folder, run + '.json'), 'w') as f: + json.dump({'request': START, 'turns': [unmarked.pid], 'stopped': False}, f) + self.assertEqual(self.call('stop', {'run': run}), (0, {'run': run, 'stopped': True})) + self.assertTrue(alive(unmarked.pid), 'stop signaled a process without OPENWIZ_RUN') + def test_a_provider_qualified_model_reaches_the_harness(self): self.env['FAKE_ARGS'] = os.path.join(self.folder, 'args') code, out = self.call('start', dict(START, model='kimi-code/kimi-for-coding')) diff --git a/changes/1694.md b/changes/1694.md new file mode 100644 index 000000000..1546f89dd --- /dev/null +++ b/changes/1694.md @@ -0,0 +1,3 @@ +kind: fixed + +On synthetic fixtures, stopping a run saved by the previous template ends its surviving turns and marked process-group or session workers on Linux after the normal shutdown grace, refuses before recording `stopped` when shutdown cannot be confirmed (including without `/proc`), and refuses `wake` instead of failing with `TypeError`.