diff --git a/adapters/local/README.md b/adapters/local/README.md index 556310c6b..3d8ef97d7 100644 --- a/adapters/local/README.md +++ b/adapters/local/README.md @@ -23,6 +23,7 @@ adapters/local/driver version # {"driver": "local", ..., "can": [. - **Runs:** `start` saves the run, then runs its first turn. A run whose first turn began but couldn't be saved is ended, and its error says the outcome is unknown and what to check; it never says retry. `wake` runs another turn on the same ticket, in which the agent edits its own status note. While the run's last turn is still running, `wake` answers `woke: true` and starts no second turn, so one ticket never has two agents. On Linux, `stop` ends every process the run's turns started, whatever their session or environment: a polite signal, then a kill after 10 seconds. Each turn runs under a small supervisor (`driver --turn`) that keeps every process it starts (a Linux subreaper), so a worker in its own session or with a clean environment is still stopped. On macOS, `stop` ends every process it can find, within the gap and the `lsof` fallback above. A wake and a stop on one run take turns under its lock. Several runs at once are independent. - **State:** each run's request, its workspace and each turn's output log, owner-only, in `$OPENWIZ_LOCAL_STATE` (default `~/.local/state/openwiz-local`). - **On a VPS:** sign in to the harness and to `gh` there, and run the driver there, for example over `ssh`. +- **Linux process environment:** on Linux, each turn gets an owner-only shell helper (`BASH_ENV`, plus `CLAUDE_ENV_FILE` for `claude`, sourcing any existing file) that raises the shell's `/proc/self/oom_score_adj` to 500 while the harness keeps its default; when the driver's cgroup sets a CPU quota (`cpu.max` or `cpu.cfs_quota_us`/`cpu.cfs_period_us`), the turn also gets `OMP_NUM_THREADS`, `PYTHON_CPU_COUNT` and `CARGO_BUILD_JOBS` set to the ceiling of quota over period unless already set. Nothing changes on macOS or when no quota is set. `schema.json` is byte for byte the kit's `kernel/driver-kit/schema.json`. diff --git a/adapters/local/driver b/adapters/local/driver index 5de276c99..78c871b74 100755 --- a/adapters/local/driver +++ b/adapters/local/driver @@ -1,6 +1,6 @@ #!/usr/bin/env python3 import ctypes, fcntl, importlib.machinery, importlib.util, io, json, os, re, secrets, shutil, signal, subprocess, sys, time, uuid -import tempfile +import math, shlex, tempfile sys.dont_write_bytecode = True @@ -846,9 +846,74 @@ def exited(run, turn): time.sleep(0.05) +CGROUP, PROC_CGROUP = '/sys/fs/cgroup', '/proc/self/cgroup' +OOM_FIRST = 500 +CPU_VARIABLES = ('OMP_NUM_THREADS', 'PYTHON_CPU_COUNT', 'CARGO_BUILD_JOBS') + + +def cpu_quota(): + try: + with open(PROC_CGROUP) as f: + lines = [entry.rstrip('\n').split(':', 2) for entry in f] + except OSError: + return None + found = [] + for _, controllers, path in (entry for entry in lines if len(entry) == 3): + v2 = controllers == '' + if not v2 and 'cpu' not in controllers.split(','): + continue + parts = [p for p in path.split('/') if p and p not in ('.', '..')] + for depth in range(len(parts), -1, -1): + folder = os.path.join(CGROUP, *([] if v2 else [controllers]) + parts[:depth]) + try: + if v2: + with open(os.path.join(folder, 'cpu.max')) as f: + quota, period = f.read().split() + else: + with open(os.path.join(folder, 'cpu.cfs_quota_us')) as f, \ + open(os.path.join(folder, 'cpu.cfs_period_us')) as g: + quota, period = f.read().strip(), g.read().strip() + if quota.isdigit() and period.isdigit() and int(quota) > 0 and int(period) > 0: + found.append(math.ceil(int(quota) / int(period))) + except (OSError, ValueError): + continue + return min(found) if found else None + + +def shells_go_first(path, previous): + lines = ['# OpenWiz local driver: this turn\'s shells go first under memory pressure, never the harness.', + '{ read -r adj < /proc/self/oom_score_adj && [ "$adj" -lt %d ] && echo %d > /proc/self/oom_score_adj; } ' + '2>/dev/null' % (OOM_FIRST, OOM_FIRST)] + lines.append('. %s' % shlex.quote(previous) if previous and previous != path else ':') + new = path + '.new' + with open(os.open(new, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w') as f: + f.write('\n'.join(lines) + '\n') + os.chmod(new, 0o600) + os.replace(new, path) + return path + + +def agent_environment(run, harness, overlay): + if not LINUX: + return {} + owner = dict(os.environ, **overlay) + added = {'BASH_ENV': shells_go_first(os.path.join(STATE, run + '.bash-env'), owner.get('BASH_ENV'))} + if harness == 'claude': + added['CLAUDE_ENV_FILE'] = shells_go_first(os.path.join(STATE, run + '.claude-env'), + owner.get('CLAUDE_ENV_FILE')) + cpus = cpu_quota() + if cpus: + added.update({name: str(cpus) for name in CPU_VARIABLES if name not in owner}) + return added + + def launch(state, run, woken): req = state['request'] cmd, extra = command(state, woken) + try: + extra = dict(extra, **agent_environment(run, req['harness'], extra)) + except OSError as e: + raise Refused('could not write this turn\'s shell helper: %s' % e.strerror, WRITABLE) try: log = open_log(run) output_from = os.fstat(log).st_size diff --git a/adapters/local/fixtures/fake-harness b/adapters/local/fixtures/fake-harness index 69a54d5b1..525660ed9 100755 --- a/adapters/local/fixtures/fake-harness +++ b/adapters/local/fixtures/fake-harness @@ -16,6 +16,23 @@ else: skill = re.search(r'with the ([a-z0-9-]+) skill', prompt).group(1) woken = prompt.startswith('You were woken') +if not worker and os.environ.get('FAKE_PROBE'): + def shell(*argv): + return subprocess.run(argv, stdin=subprocess.DEVNULL, capture_output=True, text=True).stdout.strip() + try: + with open('/proc/self/oom_score_adj') as f: + mine = f.read().strip() + except OSError: + mine = None + probe = {'harness': mine, 'bash': shell('bash', '-c', 'cat /proc/self/oom_score_adj'), + 'owner': shell('bash', '-c', 'echo "$FAKE_OWNER_MARK"'), + 'claude': shell('sh', '-c', '. "$CLAUDE_ENV_FILE"; cat /proc/self/oom_score_adj') + if os.environ.get('CLAUDE_ENV_FILE') else None} + probe.update({k: os.environ.get(k) for k in ('OMP_NUM_THREADS', 'PYTHON_CPU_COUNT', 'CARGO_BUILD_JOBS', + 'BASH_ENV', 'CLAUDE_ENV_FILE')}) + with open(os.environ['FAKE_PROBE'] + '.new', 'w') as f: + json.dump(probe, f) + os.replace(os.environ['FAKE_PROBE'] + '.new', os.environ['FAKE_PROBE']) if not worker: quick = {'refuse': ('Fake harness: permission to use Bash was denied (%s).' % OPAQUE, 0), 'expired': ('Fake harness: OAuth session expired (%s). Please run /login.' % OPAQUE, 0), diff --git a/adapters/local/test_driver.py b/adapters/local/test_driver.py index 293ea2c85..2ca40428d 100755 --- a/adapters/local/test_driver.py +++ b/adapters/local/test_driver.py @@ -46,6 +46,16 @@ def broken(*args): t.launch = broken t.main() ''' +FAKE_CGROUP = '''import importlib.machinery, importlib.util, os, sys +sys.dont_write_bytecode = True +spec = importlib.util.spec_from_loader('local', importlib.machinery.SourceFileLoader('local', %r)) +t = importlib.util.module_from_spec(spec) +spec.loader.exec_module(t) +t.PROC_CGROUP = os.path.join(os.environ['FAKE_CGROUP'], 'proc') +t.CGROUP = os.path.join(os.environ['FAKE_CGROUP'], 'sys') +t.main() +''' +CPU = ('OMP_NUM_THREADS', 'PYTHON_CPU_COUNT', 'CARGO_BUILD_JOBS') def alive(pid): @@ -91,7 +101,8 @@ def setUp(self): json.dump({'record_authors': ['Example-Bot[bot]'], 'comments': []}, f) self.mark = secrets.token_hex(8) self.log = os.path.join(self.folder, 'turns') - self.env = dict(os.environ, KIT_TRACKER=self.tracker, LOCAL_TEST=self.mark, GH_TOKEN=TOKEN, FAKE_TURNS=self.log, + self.env = dict({k: v for k, v in os.environ.items() if k not in CPU + ('BASH_ENV', 'CLAUDE_ENV_FILE')}, + KIT_TRACKER=self.tracker, LOCAL_TEST=self.mark, GH_TOKEN=TOKEN, FAKE_TURNS=self.log, FAKE_REPOS=repos, OPENWIZ_LOCAL_SETTLE='2', OPENWIZ_LOCAL_STATE=os.path.join(self.folder, 'state'), PATH=self.bin + os.pathsep + os.environ.get('PATH', '')) @@ -616,5 +627,91 @@ def test_padded_row_labels_count_as_the_same_row(self): self.until(lambda: len(self.logged()) and self.logged()[-1][4] == mode) self.assertEqual([t[4] for t in self.logged()], ['acceptEdits', 'workspace-write']) + def probed(self, harness='claude', env=None, program=DRIVER): + probe = os.path.join(self.folder, 'probe-%s.json' % secrets.token_hex(4)) + env = dict(env or self.env, FAKE_PROBE=probe) + code, out = self.start(harness, env, program) + self.assertEqual(code, 0, out) + self.until(lambda: os.path.exists(probe) and os.path.getsize(probe)) + self.assertEqual(self.driver('stop', out, env)[0], 0) + with open(probe) as f: + return json.load(f) + + def cgroup(self, proc, files): + folder = tempfile.mkdtemp(dir=self.folder) + with open(os.path.join(folder, 'proc'), 'w') as f: + f.write(proc) + for path, text in files.items(): + os.makedirs(os.path.dirname(os.path.join(folder, 'sys', path)), exist_ok=True) + with open(os.path.join(folder, 'sys', path), 'w') as f: + f.write(text) + program = os.path.join(self.folder, 'fake-cgroup') + with open(program, 'w') as f: + f.write('#!/usr/bin/env python3\n' + FAKE_CGROUP % DRIVER) + os.chmod(program, 0o700) + return dict(self.env, FAKE_CGROUP=folder), program + + def oom_score_adj(self, level): + try: + with open('/proc/self/oom_score_adj', 'w') as f: + f.write(level) + except OSError: + return False + return True + + def test_on_linux_a_turns_shells_go_first_under_memory_pressure_and_the_harness_keeps_its_default(self): + default = read('/proc/self/oom_score_adj').strip() + if int(default) >= 500: + self.addCleanup(self.oom_score_adj, default) + if self.oom_score_adj('0'): + default = '0' + if int(default) >= 500 and not os.environ.get('CI'): + self.skipTest('this host starts processes at oom_score_adj 500 or more and the test cannot go lower') + self.assertLess(int(default), 500, 'this host starts processes at 500 or more and the test cannot go lower') + owner = os.path.join(self.folder, 'owner-bash-env') + with open(owner, 'w') as f: + f.write('export FAKE_OWNER_MARK=owner-kept\n') + for harness in ('claude', 'codex'): + with self.subTest(harness): + probe = self.probed(harness, dict(self.env, BASH_ENV=owner)) + self.assertEqual(probe['harness'], default, "the harness's own oom_score_adj changed") + self.assertEqual(probe['bash'], '500', "a turn's shell does not go first") + self.assertEqual(probe['owner'], 'owner-kept', "the owner's BASH_ENV was lost") + self.assertEqual(probe['claude'], '500' if harness == 'claude' else None) + helper = probe['BASH_ENV'] + self.assertTrue(helper.startswith(self.env['OPENWIZ_LOCAL_STATE'] + os.sep), helper) + self.assertEqual(os.stat(helper).st_mode & 0o777, 0o600) + + def test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins(self): + for name, proc, files in ( + ('v2', '0::/agents/run\n', {'agents/run/cpu.max': '200000 100000\n'}), + ('v2 parent', '0::/agents/run\n', {'agents/cpu.max': '150000 100000\n', + 'agents/run/cpu.max': 'max 100000\n'}), + ('v1', '4:cpu,cpuacct:/agents\n1:name=systemd:/agents\n', + {'cpu,cpuacct/agents/cpu.cfs_quota_us': '200000\n', 'cpu,cpuacct/agents/cpu.cfs_period_us': '100000\n'})): + with self.subTest(name): + env, program = self.cgroup(proc, files) + self.assertEqual({k: self.probed(env=env, program=program)[k] for k in CPU}, dict.fromkeys(CPU, '2')) + env, program = self.cgroup('0::/agents\n', {'agents/cpu.max': '200000 100000\n'}) + probe = self.probed(env=dict(env, OMP_NUM_THREADS='7'), program=program) + self.assertEqual({k: probe[k] for k in CPU}, {'OMP_NUM_THREADS': '7', 'PYTHON_CPU_COUNT': '2', + 'CARGO_BUILD_JOBS': '2'}) + + def test_with_no_cpu_quota_or_without_proc_as_on_macos_the_turn_environment_is_unchanged(self): + for name, proc, files in (('max', '0::/agents\n', {'agents/cpu.max': 'max 100000\n'}), + ('none', '0::/agents\n', {}), + ('v1 unlimited', '4:cpu,cpuacct:/a\n', {'cpu,cpuacct/a/cpu.cfs_quota_us': '-1\n', + 'cpu,cpuacct/a/cpu.cfs_period_us': '100000\n'})): + with self.subTest(name): + env, program = self.cgroup(proc, files) + probe = self.probed(env=env, program=program) + self.assertEqual({k: probe[k] for k in CPU}, dict.fromkeys(CPU)) + env, program = self.cgroup('0::/agents\n', {'agents/cpu.max': '200000 100000\n'}) + macos = dict(env, PATH=NO_PROC + os.pathsep + self.env['PATH'], NO_PROC_PYTHON=sys.executable) + probe = self.probed(env=macos, program=program) + self.assertEqual({k: probe[k] for k in CPU + ('BASH_ENV', 'CLAUDE_ENV_FILE')}, dict.fromkeys(CPU + ('BASH_ENV', 'CLAUDE_ENV_FILE'))) + with open('/proc/self/oom_score_adj') as f: + self.assertEqual(probe['bash'], f.read().strip()) + if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/changes/3120.md b/changes/3120.md new file mode 100644 index 000000000..6c11a303e --- /dev/null +++ b/changes/3120.md @@ -0,0 +1,3 @@ +kind: added + +On Linux, local-driver turns raise their shells' `oom_score_adj` to 500 ahead of the harness and size `OMP_NUM_THREADS`, `PYTHON_CPU_COUNT` and `CARGO_BUILD_JOBS` to the cgroup's CPU quota when one is set. diff --git a/docs/evidence/3120/red.md b/docs/evidence/3120/red.md new file mode 100644 index 000000000..d429d855b --- /dev/null +++ b/docs/evidence/3120/red.md @@ -0,0 +1,74 @@ +# Red run on the base driver + +The three new cases, run with the base `adapters/local/driver` (memory case skipped: that host already starts processes at `oom_score_adj` 500; it runs under `CI`). + +```text +test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins (__main__.Local.test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins) ... + test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins (__main__.Local.test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins) [v2] ... FAIL + test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins (__main__.Local.test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins) [v2 parent] ... FAIL + test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins (__main__.Local.test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins) [v1] ... FAIL +test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins (__main__.Local.test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins) ... FAIL +test_on_linux_a_turns_shells_go_first_under_memory_pressure_and_the_harness_keeps_its_default (__main__.Local.test_on_linux_a_turns_shells_go_first_under_memory_pressure_and_the_harness_keeps_its_default) ... skipped 'this host already starts processes at oom_score_adj 500 or more' +test_with_no_cpu_quota_or_without_proc_as_on_macos_the_turn_environment_is_unchanged (__main__.Local.test_with_no_cpu_quota_or_without_proc_as_on_macos_the_turn_environment_is_unchanged) ... ok + +====================================================================== +FAIL: test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins (__main__.Local.test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins) [v2] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/adapters/local/test_driver.py", line 683, in test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins + self.assertEqual({k: self.probed(env=env, program=program)[k] for k in CPU}, dict.fromkeys(CPU, '2')) +AssertionError: {'OMP_NUM_THREADS': None, 'PYTHON_CPU_COUNT': None, 'CARGO_BUILD_JOBS': None} != {'OMP_NUM_THREADS': '2', 'PYTHON_CPU_COUNT': '2', 'CARGO_BUILD_JOBS': '2'} +- {'CARGO_BUILD_JOBS': None, 'OMP_NUM_THREADS': None, 'PYTHON_CPU_COUNT': None} +? ^^^^ ^^^^ ^^^^ + ++ {'CARGO_BUILD_JOBS': '2', 'OMP_NUM_THREADS': '2', 'PYTHON_CPU_COUNT': '2'} +? ^^^ ^^^ ^^^ + + +====================================================================== +FAIL: test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins (__main__.Local.test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins) [v2 parent] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/adapters/local/test_driver.py", line 683, in test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins + self.assertEqual({k: self.probed(env=env, program=program)[k] for k in CPU}, dict.fromkeys(CPU, '2')) +AssertionError: {'OMP_NUM_THREADS': None, 'PYTHON_CPU_COUNT': None, 'CARGO_BUILD_JOBS': None} != {'OMP_NUM_THREADS': '2', 'PYTHON_CPU_COUNT': '2', 'CARGO_BUILD_JOBS': '2'} +- {'CARGO_BUILD_JOBS': None, 'OMP_NUM_THREADS': None, 'PYTHON_CPU_COUNT': None} +? ^^^^ ^^^^ ^^^^ + ++ {'CARGO_BUILD_JOBS': '2', 'OMP_NUM_THREADS': '2', 'PYTHON_CPU_COUNT': '2'} +? ^^^ ^^^ ^^^ + + +====================================================================== +FAIL: test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins (__main__.Local.test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins) [v1] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/adapters/local/test_driver.py", line 683, in test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins + self.assertEqual({k: self.probed(env=env, program=program)[k] for k in CPU}, dict.fromkeys(CPU, '2')) +AssertionError: {'OMP_NUM_THREADS': None, 'PYTHON_CPU_COUNT': None, 'CARGO_BUILD_JOBS': None} != {'OMP_NUM_THREADS': '2', 'PYTHON_CPU_COUNT': '2', 'CARGO_BUILD_JOBS': '2'} +- {'CARGO_BUILD_JOBS': None, 'OMP_NUM_THREADS': None, 'PYTHON_CPU_COUNT': None} +? ^^^^ ^^^^ ^^^^ + ++ {'CARGO_BUILD_JOBS': '2', 'OMP_NUM_THREADS': '2', 'PYTHON_CPU_COUNT': '2'} +? ^^^ ^^^ ^^^ + + +====================================================================== +FAIL: test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins (__main__.Local.test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/adapters/local/test_driver.py", line 686, in test_a_cpu_quota_sizes_the_turns_workers_and_an_owner_set_value_wins + self.assertEqual({k: probe[k] for k in CPU}, {'OMP_NUM_THREADS': '7', 'PYTHON_CPU_COUNT': '2', +AssertionError: {'OMP_NUM_THREADS': '7', 'PYTHON_CPU_COUNT': None, 'CARGO_BUILD_JOBS': None} != {'OMP_NUM_THREADS': '7', 'PYTHON_CPU_COUNT': '2', 'CARGO_BUILD_JOBS': '2'} +- {'CARGO_BUILD_JOBS': None, 'OMP_NUM_THREADS': '7', 'PYTHON_CPU_COUNT': None} +? ^^^^ ^^^^ + ++ {'CARGO_BUILD_JOBS': '2', 'OMP_NUM_THREADS': '7', 'PYTHON_CPU_COUNT': '2'} +? ^^^ ^^^ + + +---------------------------------------------------------------------- +Ran 3 tests in 32.580s + +FAILED (failures=4, skipped=1) +```