diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-11-06 11:41:07 -0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-06 11:41:07 -0800 |
| commit | 83b5049e23ad084de27a63ddec2b9af3a52cdc60 (patch) | |
| tree | aac56d2a37d69fec65c9b75c1fb62b4cae4c945d /plugins | |
| parent | a3301039b319e562bb0db6b7245d85f9fd35d44b (diff) | |
| parent | e105e67a9fc3aeef1a0c439c55ee8a83f9159038 (diff) | |
Merge pull request #6985 from anthropics/mhegazy/sg-sdk-install-timeout
security-guidance: a timed-out SDK install leaves no download behind and pauses before retrying
Diffstat (limited to 'plugins')
3 files changed, 349 insertions, 19 deletions
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index 17e61e12..30119f8c 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -77,6 +77,8 @@ SKIP_COOLDOWN = 9 # a recent build was signal-killed (memory pressure) — no # repro confirmed the dominant Linux BUILD_FAILED is a # SIGKILL/SIGSEGV of the memory-heavy venv+pip subprocess # (rc<0, empty streams). See #2154 follow-up. + # Also, for a shorter time, after a pip install ran out + # of time (sdk_timeout_cooldown says which). See #6979. SKIP_REVIEWS_OFF = 10 # the environment turns off every review that would # load the SDK (kill switch included), so nothing is # installed. See #5331. @@ -86,6 +88,14 @@ SKIP_REVIEWS_OFF = 10 # the environment turns off every review that would # session). Keyed by marker mtime. SIGNAL_KILL_COOLDOWN_SEC = 24 * 3600 +# How long to skip rebuilds after a pip install ran out of time. On a +# connection too slow to fetch the SDK wheel inside the limit, every attempt +# downloads most of the wheel and throws it away, and attempts come at every +# SessionStart and every 5 minutes from the tool hooks. Shorter than the +# signal-kill window because a slow or stalled connection is often temporary. +# See #6979. +PIP_TIMEOUT_COOLDOWN_SEC = 3600 + # Phase + err-kind integer encoding for sdk_bootstrap_phase / sdk_bootstrap_err. # @@ -241,23 +251,37 @@ def _is_signal_kill(returncode) -> bool: return returncode < 0 or returncode in (134, 137, 139) -def _cooldown_remaining(state_dir) -> float: - """Seconds left in the signal-kill cooldown (0 if none/expired). Reads the - marker's mtime; a missing/unreadable marker means not in cooldown.""" - marker = Path(state_dir) / "agent-sdk-venv.cooldown" +_SIGNAL_KILL_MARKER = "agent-sdk-venv.cooldown" +_PIP_TIMEOUT_MARKER = "agent-sdk-venv.timeout" + + +def _marker_remaining(state_dir, name, window) -> float: + """Seconds left of the `window` that started at the marker's mtime; a + missing/unreadable marker means not in cooldown.""" try: - age = time.time() - marker.stat().st_mtime + age = time.time() - (Path(state_dir) / name).stat().st_mtime except OSError: return 0.0 - return max(0.0, SIGNAL_KILL_COOLDOWN_SEC - age) + # A marker stamped in the future (clock set back since) counts as fresh. + return min(float(window), max(0.0, window - age)) + + +def _cooldown_remaining(state_dir) -> float: + """Seconds left in the signal-kill cooldown (0 if none/expired).""" + return _marker_remaining(state_dir, _SIGNAL_KILL_MARKER, SIGNAL_KILL_COOLDOWN_SEC) + +def _timeout_cooldown_remaining(state_dir) -> float: + """Seconds left in the pip-timeout cooldown (0 if none/expired).""" + return _marker_remaining(state_dir, _PIP_TIMEOUT_MARKER, PIP_TIMEOUT_COOLDOWN_SEC) -def _write_cooldown(state_dir) -> None: - """Start/refresh the signal-kill cooldown so we stop re-attempting a build - that keeps getting killed every session. Best-effort.""" + +def _write_cooldown(state_dir, name=_SIGNAL_KILL_MARKER) -> None: + """Start/refresh a cooldown (the signal-kill one unless named) so we stop + re-attempting a build that keeps failing the same way. Best-effort.""" try: make_state_dir(str(state_dir)) - (Path(state_dir) / "agent-sdk-venv.cooldown").write_text( + (Path(state_dir) / name).write_text( time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())) except OSError: pass @@ -429,6 +453,8 @@ _SDK_IMPORT_PROBE = ( # Set by main() when the venv's probe exited with _PROBE_EMPTIED. _venv_was_emptied = False +# Set by main() when it skipped the build for the pip-timeout cooldown. +_skipped_for_pip_timeout = False def _target_dir(state_dir) -> Path: @@ -455,6 +481,63 @@ def _target_sdk_importable(state_dir) -> bool: return False +# pip keeps every wheel it downloads in a `pip-unpack-*` folder under the temp +# dir and removes it only when it exits normally. An install killed at the +# timeout (or by the OOM killer) left those folders in the system temp dir, +# one attempt after another. See #6979. So pip gets a temp folder of its own +# under the state dir: removed when the attempt ends, however it ends, and +# swept on a later run when the bootstrap itself was killed first. +_PIP_TIMEOUT_SEC = 120 +# Older than any install can be: the folder of a bootstrap that was killed. +_PIP_TEMP_STALE_SEC = 15 * 60 + + +def _pip_temp_root(state_dir) -> Path: + return Path(state_dir) / "pip-tmp" + + +def _sweep_pip_temp(state_dir) -> None: + """Remove pip temp folders left by a bootstrap that was killed before it + could remove its own. Best-effort; a folder still in use is too young.""" + try: + entries = list(_pip_temp_root(state_dir).iterdir()) + except OSError: + return # the usual case: nothing was ever left + import shutil + now = time.time() + for entry in entries: + try: + if now - entry.stat().st_mtime > _PIP_TEMP_STALE_SEC: + shutil.rmtree(entry, ignore_errors=True) + except OSError: + pass + + +def _run_pip_install(cmd, state_dir): + """Run a `pip install` command under the timeout, with its temp files in + a folder of ours. Raises what subprocess.run(check=True) raises. Falls + back to the inherited temp dir when the folder can't be made.""" + import shutil + import tempfile + tmp = env = None + try: + root = _pip_temp_root(state_dir) + root.mkdir(parents=True, exist_ok=True) + tmp = tempfile.mkdtemp(dir=root) + # tempfile reads TMPDIR, TEMP, TMP in that order on every platform. + env = {**os.environ, "TMPDIR": tmp, "TEMP": tmp, "TMP": tmp} + except OSError: + pass + try: + return subprocess.run( + cmd, capture_output=True, timeout=_PIP_TIMEOUT_SEC, check=True, + cwd=_spawn_cwd(), env=env, + ) + finally: + if tmp is not None: + shutil.rmtree(tmp, ignore_errors=True) + + def _build_via_target(state_dir) -> tuple[int, str, str]: """Fallback install when `python -m venv` can't bootstrap pip (ensurepip missing — Debian python3-venv absent, or a python.org/pyenv build without @@ -468,12 +551,12 @@ def _build_via_target(state_dir) -> tuple[int, str, str]: preference (ARM64 Windows cryptography).""" target = _target_dir(state_dir) try: - subprocess.run( + _run_pip_install( [sys.executable, "-m", "pip", "install", "--target", str(target), "--upgrade", "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir", "claude-agent-sdk"], - capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(), + state_dir, ) return BUILT_TARGET, "", "" except subprocess.CalledProcessError as e: @@ -484,6 +567,7 @@ def _build_via_target(state_dir) -> tuple[int, str, str]: return BUILD_FAILED, "pip_target", f"signal_killed:{e.returncode}" return BUILD_FAILED, "pip_target", _pip_err_from_stderr(e.stderr) except subprocess.TimeoutExpired: + _write_cooldown(state_dir, _PIP_TIMEOUT_MARKER) return BUILD_FAILED, "pip_target", "subprocess_timeout" except Exception as e: errno = getattr(e, "errno", None) @@ -544,10 +628,16 @@ def _install_context_metrics(outcome, state_dir) -> dict: dependencies do not load there. See #5706. sdk_venv_emptied: the venv's SDK package directory had lost its files - and this run went on to rebuild it, whatever the outcome. See #6612.""" + and this run went on to rebuild it, whatever the outcome. See #6612. + + sdk_timeout_cooldown: this run skipped the build (SKIP_COOLDOWN) because + a pip install ran out of time, not because one was signal-killed. See + #6979.""" out = {} if _venv_was_emptied: out["sdk_venv_emptied"] = 1 + if _skipped_for_pip_timeout: + out["sdk_timeout_cooldown"] = 1 if outcome not in (NOOP_VENV, BUILT, BUILT_TARGET, NOOP_TARGET): return out try: @@ -593,8 +683,11 @@ def main() -> tuple[int, str, str]: err_phase / err_kind are non-empty only on BUILD_FAILED — they let telemetry split bootstrap failures by root cause. """ - global _venv_was_emptied + global _venv_was_emptied, _skipped_for_pip_timeout _venv_was_emptied = False + _skipped_for_pip_timeout = False + # Before any early return: nothing else ever clears the state dir. + _sweep_pip_temp(_resolve_state_dir()) # The SDK only serves the LLM reviews. With those switched off, or the # whole plugin (SECURITY_GUIDANCE_DISABLE=1), a venv of a few hundred MB # would be built for code that never runs, and the notice below would @@ -676,6 +769,10 @@ def main() -> tuple[int, str, str]: # system/venv/target still short-circuits above. if _cooldown_remaining(state_dir) > 0: return SKIP_COOLDOWN, "", "" + # Likewise after a pip install that ran out of time, for a shorter while. + if _timeout_cooldown_remaining(state_dir) > 0: + _skipped_for_pip_timeout = True + return SKIP_COOLDOWN, "", "" err_phase = "" err_kind = "" @@ -712,11 +809,11 @@ def main() -> tuple[int, str, str]: # --no-cache-dir trims pip's peak memory (no cache read/write/unpack # buffering) — helps marginal low-memory machines get under the OOM # threshold that kills the dominant Linux builds (CCR repro). - subprocess.run( + _run_pip_install( [str(venv_py), "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir", "claude-agent-sdk"], - capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(), + state_dir, ) return BUILT, "", "" except subprocess.CalledProcessError as e: @@ -814,6 +911,10 @@ def main() -> tuple[int, str, str]: return _build_via_target(state_dir) return BUILD_FAILED, err_phase, err_kind except subprocess.TimeoutExpired: + # Only the download is known to repeat; a slow `python -m venv` is + # more likely a busy machine, and the next attempt may be quicker. + if err_phase == "pip": + _write_cooldown(state_dir, _PIP_TIMEOUT_MARKER) return BUILD_FAILED, err_phase, "subprocess_timeout" except Exception as e: # Embed errno for OSError-family exceptions ("exc:OSError:28") so @@ -847,8 +948,9 @@ def _maybe_emit_user_notice(outcome: int, pv: int) -> str | None: Currently only HOOK_PY_INCOMPATIBLE qualifies. BUILD_FAILED is intentionally excluded — it covers transient causes (network failure, - pip registry hiccup, in-flight rebuild) where the next session may - succeed and a permanent notice would mislead. + pip registry hiccup, in-flight rebuild, a download that ran out of + time) where a later session may succeed and a permanent notice would + mislead. """ if outcome != HOOK_PY_INCOMPATIBLE: return None diff --git a/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py index 2325cd9b..03c35087 100644 --- a/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py +++ b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py @@ -27,7 +27,7 @@ def _spawns(tree): def test_every_spawn_sets_a_plugin_owned_cwd(): tree = ast.parse((HOOKS_DIR / "ensure_agent_sdk.py").read_text()) calls = list(_spawns(tree)) - assert len(calls) >= 6 + assert len(calls) >= 5 for call in calls: cwd = [k for k in call.keywords if k.arg == "cwd"] assert cwd, f"subprocess call on line {call.lineno} inherits the hook's working directory" diff --git a/plugins/security-guidance/tests/test_sdk_install_timeout.py b/plugins/security-guidance/tests/test_sdk_install_timeout.py new file mode 100644 index 00000000..92edde46 --- /dev/null +++ b/plugins/security-guidance/tests/test_sdk_install_timeout.py @@ -0,0 +1,228 @@ +"""A `pip install` that is killed leaves nothing in the system temp dir. + +pip keeps each wheel it downloads in a `pip-unpack-*` folder under the temp +dir and removes it only on a normal exit. The bootstrap kills pip at its +timeout, so on a slow connection every attempt left a download behind, and +attempts repeat while the SDK is missing. See #6979. +""" +import os +import subprocess +import sys +import time + +import pytest + +import ensure_agent_sdk as boot +from test_sdk_bootstrap_switches import SWITCHES + +pytestmark = pytest.mark.skipif(sys.version_info < (3, 10), + reason="bootstrap stops before the install") + +# Stands in for pip: downloads "a wheel" the way pip does, says where, then +# either hangs (a slow connection) or exits without cleaning up. +_STAND_IN_PIP = """ +import sys, tempfile, time +d = tempfile.mkdtemp(prefix="pip-unpack-") +open(d + "/claude_agent_sdk-0.0.0-py3-none-any.whl", "wb").write(b"x" * 4096) +open(sys.argv[2], "a").write(d + "\\n") +if sys.argv[1] == "hang": + time.sleep(120) +""" + + +class Install: + """Empty state dir, no SDK anywhere. `python -m venv` is skipped and + `pip install` is the stand-in above: in "hang" mode it is killed once it + has downloaded, as subprocess.run does at the timeout.""" + + def __init__(self, tmp_path): + self.state = tmp_path / "state" + self.systmp = tmp_path / "systmp" + self.systmp.mkdir() + self.mode = "hang" + self.calls = [] + self._script = tmp_path / "stand_in_pip.py" + self._script.write_text(_STAND_IN_PIP) + self._log = tmp_path / "downloads.txt" + self._real_run = subprocess.run + + def downloads(self): + """The folders the stand-in downloaded into, one per install.""" + return self._log.read_text().split("\n")[:-1] if self._log.exists() else [] + + def run(self, cmd, **kwargs): + cmd = [str(c) for c in cmd] + if cmd[1:3] == ["-m", "venv"]: + return subprocess.CompletedProcess(cmd, 0, b"", b"") + if cmd[1:4] != ["-m", "pip", "install"]: + return self._real_run(cmd, **kwargs) + self.calls.append(cmd) + stand_in = [sys.executable, str(self._script), self.mode, str(self._log)] + if self.mode != "hang": + return self._real_run(stand_in, **kwargs) + before = len(self.downloads()) + proc = subprocess.Popen(stand_in, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + cwd=kwargs.get("cwd"), env=kwargs.get("env")) + deadline = time.time() + 60 + while len(self.downloads()) == before and time.time() < deadline: + time.sleep(0.02) + proc.kill() + proc.wait() + raise subprocess.TimeoutExpired(cmd, kwargs["timeout"]) + + +@pytest.fixture +def install(tmp_path, monkeypatch): + for name in SWITCHES + ("PYTHONPATH",): + monkeypatch.delenv(name, raising=False) + inst = Install(tmp_path) + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(inst.state)) + for name in ("TMPDIR", "TEMP", "TMP"): + monkeypatch.setenv(name, str(inst.systmp)) + monkeypatch.setattr(boot, "_sdk_on_syspath", lambda: False) + monkeypatch.setattr(boot, "_near_git_repo", lambda: True) + monkeypatch.setattr(boot.subprocess, "run", inst.run) + return inst + + +def _left_in(folder): + return sorted(p.name for p in folder.iterdir()) if folder.is_dir() else [] + + +def _downloaded_under(inst, folder): + return [os.path.realpath(d).startswith(os.path.realpath(folder) + os.sep) + for d in inst.downloads()] + + +def test_timed_out_install_leaves_no_download_behind(install): + assert boot.main() == (boot.BUILD_FAILED, "pip", "subprocess_timeout") + assert _downloaded_under(install, install.state / "pip-tmp") == [True] + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def test_repeated_timeouts_do_not_add_up(install): + for _ in range(3): + boot._build_via_target(install.state) + assert len(install.downloads()) == 3 + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def test_fallback_install_is_covered_too(install): + assert boot._build_via_target(install.state) == ( + boot.BUILD_FAILED, "pip_target", "subprocess_timeout") + assert "--target" in install.calls[0] + assert _downloaded_under(install, install.state / "pip-tmp") == [True] + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def test_finished_install_is_cleaned_up_as_well(install): + install.mode = "exit" + assert boot.main()[0] == boot.BUILT + assert len(install.downloads()) == 1 + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def _leave_folder(install, name, age): + folder = install.state / "pip-tmp" / name + (folder / "pip-unpack-abc").mkdir(parents=True) + (folder / "pip-unpack-abc" / "half.whl").write_bytes(b"x" * 4096) + then = time.time() - age + os.utime(folder, (then, then)) + + +def test_folder_of_a_killed_bootstrap_is_removed_by_a_later_run(install): + _leave_folder(install, "tmpkilled", boot._PIP_TEMP_STALE_SEC + 60) + # An attempt that is still running keeps its folder. + _leave_folder(install, "tmprunning", 30) + boot._sweep_pip_temp(install.state) + assert _left_in(install.state / "pip-tmp") == ["tmprunning"] + + +def test_sweep_runs_even_when_nothing_is_installed_this_time(install, monkeypatch): + """Otherwise a folder left just before the SDK got installed stays for good.""" + _leave_folder(install, "tmpkilled", boot._PIP_TEMP_STALE_SEC + 60) + monkeypatch.setattr(boot, "_target_sdk_importable", lambda state_dir: True) + assert boot.main()[0] == boot.NOOP_TARGET + assert install.calls == [] + assert _left_in(install.state / "pip-tmp") == [] + + +@pytest.mark.parametrize("switch", ["SECURITY_GUIDANCE_DISABLE=1", "ENABLE_CODE_SECURITY_REVIEW=0"]) +def test_sweep_runs_with_reviews_switched_off(install, monkeypatch, switch): + _leave_folder(install, "tmpkilled", boot._PIP_TEMP_STALE_SEC + 60) + monkeypatch.setenv(*switch.split("=")) + assert boot.main()[0] == boot.SKIP_REVIEWS_OFF + assert _left_in(install.state / "pip-tmp") == [] + + +def test_install_still_runs_when_the_folder_cannot_be_made(install): + install.mode = "exit" + install.state.mkdir() + (install.state / "pip-tmp").write_text("in the way") + assert boot._build_via_target(install.state)[0] == boot.BUILT_TARGET + assert _downloaded_under(install, install.systmp) == [True] + + +def test_pip_timeout_starts_a_cooldown(install): + assert boot.main()[0] == boot.BUILD_FAILED + # The next attempts (every SessionStart, and every 5 minutes from the + # tool hooks) do not download the SDK again. + outcome = boot.main() + assert outcome == (boot.SKIP_COOLDOWN, "", "") + assert len(install.calls) == 1 + assert boot._install_context_metrics(outcome[0], install.state) == {"sdk_timeout_cooldown": 1} + + +def test_timeout_of_the_fallback_install_starts_it_too(install): + boot._build_via_target(install.state) + assert boot._timeout_cooldown_remaining(install.state) > 0 + + +def test_timeout_cooldown_is_shorter_than_the_signal_kill_one(install): + boot.main() + assert boot._cooldown_remaining(install.state) == 0 + assert 0 < boot._timeout_cooldown_remaining(install.state) <= 3600 + then = time.time() - boot.PIP_TIMEOUT_COOLDOWN_SEC - 60 + os.utime(install.state / "agent-sdk-venv.timeout", (then, then)) + install.mode = "exit" + assert boot.main()[0] == boot.BUILT + assert len(install.calls) == 2 + + +def test_slow_venv_creation_does_not_start_it(install, monkeypatch): + def run(cmd, **kwargs): + if [str(c) for c in cmd][1:3] == ["-m", "venv"]: + raise subprocess.TimeoutExpired(cmd, kwargs["timeout"]) + return install.run(cmd, **kwargs) + monkeypatch.setattr(boot.subprocess, "run", run) + assert boot.main() == (boot.BUILD_FAILED, "venv", "subprocess_timeout") + assert boot._timeout_cooldown_remaining(install.state) == 0 + + +def test_signal_kill_cooldown_is_not_counted_as_a_timeout(install): + boot._write_cooldown(install.state) + boot._write_cooldown(install.state, boot._PIP_TIMEOUT_MARKER) + outcome = boot.main()[0] + assert outcome == boot.SKIP_COOLDOWN + assert "sdk_timeout_cooldown" not in boot._install_context_metrics(outcome, install.state) + + +def test_count_belongs_to_the_run_that_skipped(install): + boot.main() + assert boot.main()[0] == boot.SKIP_COOLDOWN + install.mode = "exit" + (install.state / "agent-sdk-venv.timeout").unlink() + outcome = boot.main()[0] + assert outcome == boot.BUILT + assert "sdk_timeout_cooldown" not in boot._install_context_metrics(outcome, install.state) + + +def test_marker_from_the_future_does_not_stretch_the_cooldown(install): + boot._write_cooldown(install.state, boot._PIP_TIMEOUT_MARKER) + ahead = time.time() + 6 * 3600 + os.utime(install.state / "agent-sdk-venv.timeout", (ahead, ahead)) + assert boot._timeout_cooldown_remaining(install.state) == boot.PIP_TIMEOUT_COOLDOWN_SEC |
