Skip to content

The agent that grows with you

fix(bot-screen): install timeout kills the package manager's group; atomic slot claim

teknium104f490c17e88
diff --git a/tests/tools/test_bot_desktop_install.py b/tests/tools/test_bot_desktop_install.py
index 5b0912d7e82..a3e5392a66a 100644
--- a/tests/tools/test_bot_desktop_install.py
+++ b/tests/tools/test_bot_desktop_install.py
@@ -45,3 +45,55 @@ def test_second_install_for_same_profile_is_refused(monkeypatch):
gate.set()
worker.join(5)
install.assert_not_running() # slot released once the run finishes
+
+
+def test_claim_is_atomic_and_refuses_a_second_claim():
+ """The gateway claims BEFORE spawning its worker; a second Install click must fail at claim time, not
+ pass a read-only check and race the worker for the slot."""
+ key = install.claim()
+ with pytest.raises(install.InstallBusy):
+ install.claim()
+ with pytest.raises(install.InstallBusy):
+ install.install_packages(ask_password=lambda: "pw", on_line=lambda _l: None)
+ install.release(key)
+ install.claim() # free again
+ install.release(key)
+
+
+def test_timeout_kills_the_package_managers_whole_process_group(monkeypatch):
+ """sudo forks the package manager into the same (new) session; killing sudo alone leaves apt/dnf
+ holding the dpkg lock as root. The timeout must take the group."""
+ import subprocess
+ import time
+
+ monkeypatch.setattr(install, "_sudo_nopasswd", lambda: True)
+ # stand-in for `sudo apt-get ...`: a parent that spawns a child and waits, both in the new session
+ fake = ["sudo"]
+ real_popen = subprocess.Popen
+
+ def popen(argv, **kw):
+ if argv[:1] != fake:
+ return real_popen(argv, **kw)
+ return real_popen(["bash", "-c", "sleep 30 >/dev/null 2>&1 & echo child $!; wait"], **kw)
+
+ monkeypatch.setattr(install.subprocess, "Popen", popen)
+ lines: list[str] = []
+ code = install._run("sudo apt-get install -y x", ask_password=lambda: "", on_line=lines.append, timeout_seconds=0.5)
+ assert code != 0
+ child = next(int(line.split()[1]) for line in lines if line.startswith("child "))
+ from pathlib import Path
+
+ def gone() -> bool: # /proc-based: a reparented orphan sits outside our subtree, where os.kill(pid, 0) is guarded
+ try:
+ return "Z" in (Path(f"/proc/{child}/stat").read_text().rsplit(")", 1)[1].split() or ["Z"])[0]
+ except OSError:
+ return True
+
+ for _ in range(50): # the child must die with the group, not linger reparented to init
+ if gone():
+ break
+ time.sleep(0.1)
+ else:
+ subprocess.run(["kill", "-9", str(child)], check=False)
+ pytest.fail("grandchild survived the install timeout")
diff --git a/tools/bot_desktop/install.py b/tools/bot_desktop/install.py
index ef374a62e3e..ee44b7e06b5 100644
--- a/tools/bot_desktop/install.py
+++ b/tools/bot_desktop/install.py
@@ -12,9 +12,11 @@ One install per profile at a time; a second request while one runs is refused.
from __future__ import annotations
+import contextlib
import logging
import os
import shlex
+import signal
import subprocess
import threading
from typing import Callable, Optional
@@ -38,24 +40,41 @@ def assert_not_running() -> None:
raise InstallBusy("an install is already running for this profile")
-def install_packages(*, ask_password: Callable[[], str], on_line: Callable[[str], None],
- timeout_seconds: float = 900.0) -> int:
- """Run the package install; returns the process exit code (0 = success, ``-1`` = cancelled)."""
- if not runtime.is_supported_host():
- raise RuntimeError("Bot Desktop runs on Linux gateway hosts only")
- cmd = runtime.install_command()
- if cmd is None:
- raise RuntimeError("no supported package manager (apt-get, dnf, pacman) found on this host")
+def claim() -> str:
+ """Atomically take this profile's install slot; raises :class:`InstallBusy` when taken. A caller that
+ claims before handing off to a worker passes ``claimed=True`` to :func:`install_packages`, which then
+ owns releasing it — a check-then-spawn pair (``assert_not_running`` + later claim on the worker) lets
+ two Install clicks both pass the check."""
key = hermes_home_key()
with _install_lock:
if key in _running:
raise InstallBusy("an install is already running for this profile")
_running.add(key)
+ return key
+
+
+def release(key: str) -> None:
+ with _install_lock:
+ _running.discard(key)
+
+
+def install_packages(*, ask_password: Callable[[], str], on_line: Callable[[str], None],
+ timeout_seconds: float = 900.0, claimed: bool = False) -> int:
+ """Run the package install; returns the process exit code (0 = success, ``-1`` = cancelled).
+ ``claimed=True``: the caller already holds the slot via :func:`claim`; it is released here either way."""
+ key = hermes_home_key() if claimed else None
try:
+ if not runtime.is_supported_host():
+ raise RuntimeError("Bot Desktop runs on Linux gateway hosts only")
+ cmd = runtime.install_command()
+ if cmd is None:
+ raise RuntimeError("no supported package manager (apt-get, dnf, pacman) found on this host")
+ if key is None:
+ key = claim()
return _run(cmd, ask_password=ask_password, on_line=on_line, timeout_seconds=timeout_seconds)
finally:
- with _install_lock:
- _running.discard(key)
+ if key is not None:
+ release(key)
def _sudo_nopasswd() -> bool:
@@ -90,7 +109,13 @@ def _run(cmd: str, *, ask_password: Callable[[], str], on_line: Callable[[str],
proc.stdin.close() # type: ignore[union-attr]
except OSError:
pass
- timer = threading.Timer(timeout_seconds, proc.kill)
+ # The package manager runs in its own session (start_new_session); killing only sudo would leave apt/dnf
+ # running as root with the dpkg lock while the slot is released, so the whole group goes.
+ def _kill_group() -> None:
+ with contextlib.suppress(ProcessLookupError):
+ os.killpg(proc.pid, signal.SIGKILL) # windows-footgun: ok — Linux-only (is_supported_host)
+
+ timer = threading.Timer(timeout_seconds, _kill_group)
timer.start()
try:
for line in proc.stdout: # type: ignore[union-attr]