Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

feat(install): add apply flag parity, --env passthrough, and EIO retry (#2152)

Ingmar Krusch896454e97895
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ad9ae9612..53b4e32d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,7 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Unreleased
+### Features
+- **install:** `headroom install apply` now accepts `--code-aware/--no-code-aware`, `--intercept-tool-results`, `--protect-tool-results`, and `--bedrock-profile`, mirroring the equivalent flags already on `headroom proxy`. Previously the only way to run a persistent deployment with these settings was to hand-edit `manifest.json` after the fact, which silently reverts on the next `install apply`.
+- **install:** `headroom install apply --env KEY=VALUE` (repeatable) passes environment variables into supervised runners (macOS launchd, Linux systemd/cron, Windows services/tasks). These runners previously started with a bare environment and did not inherit the interactive shell's exports — e.g. a custom `HEADROOM_WORKSPACE_DIR` never reached the supervised process, so `headroom install agent run` looked for its manifest in the wrong location and failed outright even though `install apply` itself succeeded. `--env` values are merged into `DeploymentManifest.base_env` last, so they can override auto-derived defaults, and are threaded into the generated `run-headroom.sh`/`ensure-headroom.sh` (and Windows equivalents) as `export`/`$env:` lines before the `exec`.
+
### Fixed
+- **install:** `install_supervisor`'s macOS branch did an unconditional `launchctl bootout` followed by a bare `bootstrap` with no retry, unlike `start_supervisor`, which already rides out the ~15s EIO (error 5) window launchd exhibits for several seconds after a bootout. This left `install apply`'s own reinstall path (and anything that re-applies a deployment, e.g. a future `headroom doctor --fix`) exposed to a race that previously required manual recovery (bootout + remove the plist + reapply). Extracted the retry loop already used by `start_supervisor` into a shared `_bootstrap_with_retry()` helper, now used by both call sites.
- **proxy/savings:** `SavingsTracker.record_request()` only appended a history point when `tokens_saved > 0` (headroom's own lossy compression). In `--mode cache`, `tokens_saved` is near-always 0 by design, since the frozen prefix is byte-replayed rather than compressed to keep the provider's prompt cache warm. That silently dropped every history point on a cache-mode deployment even when `cache_read_tokens`/`cache_savings_usd` were large, making `headroom-monthly`-style tooling read as a total savings collapse. The guard now fires on `tokens_saved` OR `cache_read_tokens`, and the appended entry carries `cache_read_tokens`/`cache_savings_usd` so downstream consumers can show them; `_normalize_history_entry` defaults both fields to 0/0.0 for legacy entries that predate this change.
- **litellm:** vendor-specific top-level fields on `/v1/chat/completions`, including vLLM's `chat_template_kwargs` for per-request Qwen3 thinking-mode toggles, now reach OpenAI-compatible backends through LiteLLM `extra_body` instead of being dropped by the standard-parameter allowlist ([#2128](https://github.com/headroomlabs-ai/headroom/issues/2128)).
- **cache aligner:** hash the actual frozen Claude Code prefix instead of only system-message text, so `stable_prefix_hash` / `prefix_changed` now surface prompt-cache churn when a cached tool-result block changes without any system-prompt edit ([#2085](https://github.com/headroomlabs-ai/headroom/issues/2085)).
diff --git a/headroom/cli/install.py b/headroom/cli/install.py
index 77aa18ab3..ad6ed4827 100644
--- a/headroom/cli/install.py
+++ b/headroom/cli/install.py
@@ -238,6 +238,50 @@ def _reject_task_lifecycle(manifest: DeploymentManifest, action: str) -> None:
is_flag=True,
help="Disable HTTP/2 in the persistent runtime (enabled by default).",
)
+ "--code-aware/--no-code-aware",
+ "code_aware",
+ default=None,
+ help=(
+ "Enable/disable AST-based code compression in the persistent runtime. "
+ "Requires the optional tree-sitter dependency: pip install headroom-ai[code]. "
+ "Default: disabled, matching `headroom proxy`."
+ ),
+)
+ "--intercept-tool-results",
+ is_flag=True,
+ help=(
+ "Opt in to tool_result interceptors (ast-grep Read outliner, etc.) in the "
+ "persistent runtime. Off by default while this feature ships."
+ ),
+)
+ "--protect-tool-results",
+ default=None,
+ help=(
+ "Comma-separated tool names whose results are never lossy-compressed in "
+ "the persistent runtime, merged with the built-in defaults (e.g. Bash,WebFetch)."
+ ),
+)
+ "--bedrock-profile",
+ default=None,
+ help="AWS profile name for Bedrock in the persistent runtime (default: use default credentials).",
+)
+ "--env",
+ "extra_env",
+ multiple=True,
+ metavar="KEY=VALUE",
+ help=(
+ "Extra environment variable for the supervised process, e.g. "
+ "--env HEADROOM_WORKSPACE_DIR=/path. Supervisors (launchd, systemd, cron) "
+ "start with a bare environment and do not inherit the interactive shell's "
+ "exports, so anything the runtime needs beyond the flags above must be set "
+ "here. Repeatable."
+ ),
+)
def install_apply(
preset: str,
runtime: str,
@@ -255,6 +299,11 @@ def install_apply(
no_telemetry: bool,
image: str,
no_http2: bool,
+ code_aware: bool | None,
+ intercept_tool_results: bool,
+ protect_tool_results: str | None,
+ bedrock_profile: str | None,
+ extra_env: tuple[str, ...],
) -> None:
"""Install a persistent Headroom deployment."""
@@ -267,6 +316,13 @@ def install_apply(
if preset == InstallPreset.PERSISTENT_DOCKER.value:
runtime = RuntimeKind.DOCKER.value
+ parsed_env: dict[str, str] = {}
+ for item in extra_env:
+ if "=" not in item:
+ raise click.ClickException(f"--env expects KEY=VALUE, got: {item!r}")
+ key, _, value = item.partition("=")
+ parsed_env[key] = value
+
manifest = build_manifest(
profile=profile,
preset=preset,
@@ -283,6 +339,11 @@ def install_apply(
telemetry_enabled=telemetry and not no_telemetry,
image=image,
no_http2=no_http2,
+ code_aware=code_aware,
+ intercept_tool_results=intercept_tool_results,
+ protect_tool_results=protect_tool_results,
+ bedrock_profile=bedrock_profile,
+ extra_env=parsed_env,
)
try:
diff --git a/headroom/install/planner.py b/headroom/install/planner.py
index df5557f8e..c4ac14179 100644
--- a/headroom/install/planner.py
+++ b/headroom/install/planner.py
@@ -125,6 +125,11 @@ def build_manifest(
telemetry_enabled: bool,
image: str,
no_http2: bool = False,
+ code_aware: bool | None = None,
+ intercept_tool_results: bool = False,
+ protect_tool_results: str | None = None,
+ bedrock_profile: str | None = None,
+ extra_env: dict[str, str] | None = None,
) -> DeploymentManifest:
"""Create a normalized deployment manifest."""
@@ -154,6 +159,10 @@ def build_manifest(
base_env["HEADROOM_TELEMETRY"] = "on" if telemetry_enabled else "off"
if memory_enabled:
base_env["HEADROOM_MEMORY_ENABLED"] = "1"
+ # Applied last so explicit --env overrides win over the auto-derived
+ # defaults above (e.g. a custom HEADROOM_WORKSPACE_DIR).
+ if extra_env:
+ base_env.update(extra_env)
proxy_args = [
"--host",
@@ -174,6 +183,14 @@ def build_manifest(
proxy_args.extend(["--region", region])
if no_http2:
proxy_args.append("--no-http2")
+ if code_aware is not None:
+ proxy_args.append("--code-aware" if code_aware else "--no-code-aware")
+ if intercept_tool_results:
+ proxy_args.append("--intercept-tool-results")
+ if protect_tool_results:
+ proxy_args.extend(["--protect-tool-results", protect_tool_results])
+ if bedrock_profile:
+ proxy_args.extend(["--bedrock-profile", bedrock_profile])
container_name = f"headroom-{normalized_profile}"
return DeploymentManifest(
diff --git a/headroom/install/supervisors.py b/headroom/install/supervisors.py
index dad1c2159..7d825fbe7 100644
--- a/headroom/install/supervisors.py
+++ b/headroom/install/supervisors.py
@@ -23,6 +23,7 @@ from .paths import (
windows_run_cmd_path,
windows_run_script_path,
)
+from .providers import _powershell_literal
from .runtime import resolve_headroom_command
# After `launchctl bootout`, a follow-up `bootstrap` of the same label can
@@ -34,20 +35,71 @@ _MACOS_BOOTSTRAP_RETRY_DELAY = 0.5
# `launchctl bootout` of an already-absent job exits with ESRCH ("No such
# process"). That single code is the only failure we treat as already-stopped.
_LAUNCHCTL_ESRCH = 3
+_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
def _is_windows() -> bool:
return sys.platform.startswith("win")
+def _validated_env_items(env: dict[str, str] | None) -> list[tuple[str, str]]:
+ items = list((env or {}).items())
+ for name, _value in items:
+ if not _ENV_NAME_RE.fullmatch(name):
+ raise click.ClickException(
+ f"Invalid environment variable name {name!r}; expected [A-Za-z_][A-Za-z0-9_]*."
+ )
+ return items
+
+
+def _bootstrap_with_retry(domain: str, plist_path: Path, *, action: str = "bootstrap") -> None:
+ """Bootstrap ``plist_path`` into ``domain``, riding out launchd's EIO window.
+
+ After a `launchctl bootout`, a follow-up `bootstrap` of the same label can
+ return EIO (error 5) for several seconds while launchd releases it. Retry
+ for ~15s before giving up. Shared by `install_supervisor` (bootout+bootstrap
+ on every apply) and `start_supervisor` (bootstrap after a failed kickstart)
+ so both self-heal instead of requiring the manual bootout+rm+reapply
+ recovery previously documented for this race.
+ """
+ last: subprocess.CompletedProcess[str] | None = None
+ for _ in range(_MACOS_BOOTSTRAP_RETRIES):
+ boot = run(
+ ["launchctl", "bootstrap", domain, str(plist_path)],
+ capture_output=True,
+ text=True,
+ )
+ if boot.returncode == 0:
+ return
+ last = boot
+ time.sleep(_MACOS_BOOTSTRAP_RETRY_DELAY)
+ detail = (last.stderr or last.stdout or "").strip() if last is not None else ""
+ raise click.ClickException(
+ f"launchctl could not {action} {domain}/{plist_path.stem}: {detail or 'unknown error'}"
+ )
+
+
def _command_for_script(*parts: str) -> list[str]:
return [*resolve_headroom_command(), *parts]
-def _render_unix_runner(path: Path, command: list[str]) -> ArtifactRecord:
+def _render_unix_runner(
+ path: Path, command: list[str], env: dict[str, str] | None = None
+) -> ArtifactRecord:
path.parent.mkdir(parents=True, exist_ok=True)
+ # Supervisors (launchd, systemd, cron) invoke this script with a bare
+ # environment — they do not inherit the interactive shell's exports (e.g.
+ # AWS_PROFILE, a custom HEADROOM_WORKSPACE_DIR). Export base_env here, before
+ # the exec, so `headroom install agent run` itself (which loads the manifest
+ # from HEADROOM_WORKSPACE_DIR) sees the same environment `install apply` was
+ # run under, not just the proxy subprocess it spawns.
+ export_lines = "".join(
+ f"export {name}={shlex.quote(value)}\n" for name, value in _validated_env_items(env)
+ )
path.write_text(
- "#!/usr/bin/env bash\nset -euo pipefail\nexec "
+ "#!/usr/bin/env bash\nset -euo pipefail\n"
+ + export_lines
+ + "exec "
+ " ".join(shlex.quote(x) for x in command)
+ "\n"
)
@@ -56,13 +108,20 @@ def _render_unix_runner(path: Path, command: list[str]) -> ArtifactRecord:
def _render_windows_runner(
- ps1_path: Path, cmd_path: Path, command: list[str]
+ ps1_path: Path, cmd_path: Path, command: list[str], env: dict[str, str] | None = None
) -> list[ArtifactRecord]:
ps1_path.parent.mkdir(parents=True, exist_ok=True)
escaped = " ".join(
[f'"{item}"' if (" " in item or item.endswith(".cmd")) else item for item in command]
)
- ps1_path.write_text(f"$ErrorActionPreference = 'Stop'\n& {escaped}\nexit $LASTEXITCODE\n")
+ # See _render_unix_runner: Windows services/tasks also start with a bare
+ # environment, so base_env must be set explicitly before invoking headroom.
+ env_lines = "".join(
+ f"$env:{name} = {_powershell_literal(value)}\n" for name, value in _validated_env_items(env)
+ )
+ ps1_path.write_text(
+ f"$ErrorActionPreference = 'Stop'\n{env_lines}& {escaped}\nexit $LASTEXITCODE\n"
+ )
cmd_path.write_text(
'@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0'
+ ps1_path.name
@@ -84,6 +143,7 @@ def render_runner_scripts(manifest: DeploymentManifest) -> list[ArtifactRecord]:
windows_run_script_path(manifest.profile),
windows_run_cmd_path(manifest.profile),
_command_for_script("install", "agent", "run", "--profile", manifest.profile),
+ manifest.base_env,
)
)
records.extend(
@@ -91,6 +151,7 @@ def render_runner_scripts(manifest: DeploymentManifest) -> list[ArtifactRecord]:
windows_ensure_script_path(manifest.profile),
windows_ensure_cmd_path(manifest.profile),
_command_for_script("install", "agent", "ensure", "--profile", manifest.profile),
+ manifest.base_env,
)
)
return records
@@ -99,10 +160,12 @@ def render_runner_scripts(manifest: DeploymentManifest) -> list[ArtifactRecord]:
_render_unix_runner(
unix_run_script_path(manifest.profile),
_command_for_script("install", "agent", "run", "--profile", manifest.profile),
+ manifest.base_env,
),
_render_unix_runner(
unix_ensure_script_path(manifest.profile),
_command_for_script("install", "agent", "ensure", "--profile", manifest.profile),
+ manifest.base_env,
),
]
@@ -256,7 +319,7 @@ def install_supervisor(manifest: DeploymentManifest) -> list[ArtifactRecord]:
and manifest.supervisor_kind == SupervisorKind.SERVICE.value
else f"gui/{os.getuid()}"
)
- subprocess.run(["launchctl", "bootstrap", bootstrap_domain, str(plist_path)], check=True)
+ _bootstrap_with_retry(bootstrap_domain, plist_path)
records.append(ArtifactRecord(kind="plist", path=str(plist_path)))
return records
@@ -355,8 +418,6 @@ def start_supervisor(manifest: DeploymentManifest) -> None:
# `stop`/`restart` leave behind, since they `bootout` the job, and
# `kickstart` cannot recover it (launchctl error 113). Bootstrap fresh
# instead — a successful bootstrap also starts the job via RunAtLoad.
- # launchd can return EIO (error 5) from bootstrap for several seconds
- # after a bootout while it releases the label, so retry for ~15s.
plist_dir = (
Path("/Library/LaunchDaemons")
if manifest.scope == "system"
@@ -364,21 +425,8 @@ def start_supervisor(manifest: DeploymentManifest) -> None:
else Path.home() / "Library" / "LaunchAgents"
)
plist_path = plist_dir / f"{label}.plist"
- last = kick
- for _ in range(_MACOS_BOOTSTRAP_RETRIES):
- boot = run(
- ["launchctl", "bootstrap", domain, str(plist_path)],
- capture_output=True,
- text=True,
- )
- if boot.returncode == 0:
- return
- last = boot
- time.sleep(_MACOS_BOOTSTRAP_RETRY_DELAY)
- detail = (last.stderr or last.stdout or "").strip()
- raise click.ClickException(
- f"launchctl could not start {domain}/{label}: {detail or 'unknown error'}"
- )
+ _bootstrap_with_retry(domain, plist_path, action="start")
+ return
if _is_windows() and manifest.supervisor_kind == SupervisorKind.SERVICE.value:
subprocess.run(["sc.exe", "start", manifest.service_name], check=True)
diff --git a/tests/test_install/test_planner.py b/tests/test_install/test_planner.py
index d4ae1561f..ffb559149 100644
--- a/tests/test_install/test_planner.py
+++ b/tests/test_install/test_planner.py
@@ -187,3 +187,84 @@ def test_resolve_targets_provider_scope_manual_rejects_unsupported() -> None:
["cursor"],
scope=ConfigScope.PROVIDER.value,
)
+
+
+def _base_manifest_kwargs(**overrides):
+ kwargs = {
+ "profile": "default",
+ "preset": InstallPreset.PERSISTENT_SERVICE.value,
+ "runtime_kind": "python",
+ "scope": "user",
+ "provider_mode": "manual",
+ "targets": ["claude"],
+ "port": 8787,
+ "backend": "bedrock",
+ "anyllm_provider": None,
+ "region": "eu-west-1",
+ "proxy_mode": "token",
+ "memory_enabled": False,
+ "telemetry_enabled": False,
+ "image": "ghcr.io/chopratejas/headroom:latest",
+ }
+ kwargs.update(overrides)
+ return kwargs
+
+
+def test_build_manifest_omits_new_bedrock_flags_by_default() -> None:
+ manifest = build_manifest(**_base_manifest_kwargs())
+
+ assert "--code-aware" not in manifest.proxy_args
+ assert "--no-code-aware" not in manifest.proxy_args
+ assert "--intercept-tool-results" not in manifest.proxy_args
+ assert "--protect-tool-results" not in manifest.proxy_args
+ assert "--bedrock-profile" not in manifest.proxy_args
+
+
+def test_build_manifest_persists_code_aware_true() -> None:
+ manifest = build_manifest(**_base_manifest_kwargs(code_aware=True))
+
+ assert "--code-aware" in manifest.proxy_args
+ assert "--no-code-aware" not in manifest.proxy_args
+
+
+def test_build_manifest_persists_code_aware_false() -> None:
+ manifest = build_manifest(**_base_manifest_kwargs(code_aware=False))
+
+ assert "--no-code-aware" in manifest.proxy_args
+ assert "--code-aware" not in manifest.proxy_args
+
+
+def test_build_manifest_persists_intercept_tool_results() -> None:
+ manifest = build_manifest(**_base_manifest_kwargs(intercept_tool_results=True))
+
+ assert "--intercept-tool-results" in manifest.proxy_args
+
+
+def test_build_manifest_persists_protect_tool_results() -> None:
+ manifest = build_manifest(**_base_manifest_kwargs(protect_tool_results="Bash,WebFetch"))
+
+ idx = manifest.proxy_args.index("--protect-tool-results")
+ assert manifest.proxy_args[idx + 1] == "Bash,WebFetch"
+
+
+def test_build_manifest_persists_bedrock_profile() -> None:
+ manifest = build_manifest(**_base_manifest_kwargs(bedrock_profile="sso-bedrock"))
+
+ idx = manifest.proxy_args.index("--bedrock-profile")
+ assert manifest.proxy_args[idx + 1] == "sso-bedrock"
+
+
+def test_build_manifest_merges_extra_env_into_base_env() -> None:
+ manifest = build_manifest(
+ **_base_manifest_kwargs(extra_env={"HEADROOM_WORKSPACE_DIR": "/custom/workspace"})
+ )
+
+ assert manifest.base_env["HEADROOM_WORKSPACE_DIR"] == "/custom/workspace"
+
+
+def test_build_manifest_extra_env_overrides_derived_defaults() -> None:
+ manifest = build_manifest(**_base_manifest_kwargs(extra_env={"HEADROOM_TELEMETRY": "on"}))
+
+ # telemetry_enabled=False in _base_manifest_kwargs would normally set "off";
+ # an explicit --env must win.
+ assert manifest.base_env["HEADROOM_TELEMETRY"] == "on"
diff --git a/tests/test_install/test_supervisors.py b/tests/test_install/test_supervisors.py
index c43030341..15a105bea 100644
--- a/tests/test_install/test_supervisors.py
+++ b/tests/test_install/test_supervisors.py
@@ -22,7 +22,11 @@ from headroom.install.supervisors import (
def _manifest(
- *, profile: str = "default", scope: str = "user", supervisor: str = "service"
+ *,
+ profile: str = "default",
+ scope: str = "user",
+ supervisor: str = "service",
+ base_env: dict[str, str] | None = None,
) -> DeploymentManifest:
return DeploymentManifest(
profile=profile,
@@ -36,6 +40,7 @@ def _manifest(
host="127.0.0.1",
backend="anthropic",
service_name=f"headroom-{profile}",
+ base_env=base_env or {},
)
@@ -74,6 +79,36 @@ def test_command_for_script_and_unix_runner(monkeypatch, tmp_path: Path) -> None
assert "exec headroom run --flag" in content
+def test_render_unix_runner_exports_env_before_exec(tmp_path: Path) -> None:
+ record = _render_unix_runner(
+ tmp_path / "run-headroom.sh",
+ ["headroom", "run"],
+ {"HEADROOM_WORKSPACE_DIR": "/Users/x/.headroom-workspace", "AWS_PROFILE": "sso-bedrock"},
+ )
+
+ content = Path(record.path).read_text(encoding="utf-8")
+ export_index = content.index("export HEADROOM_WORKSPACE_DIR=")
+ exec_index = content.index("exec headroom run")
+
+ assert "export HEADROOM_WORKSPACE_DIR=/Users/x/.headroom-workspace" in content
+ assert "export AWS_PROFILE=sso-bedrock" in content
+ assert export_index < exec_index
+
+
+def test_render_unix_runner_rejects_invalid_env_name(tmp_path: Path) -> None:
+ with pytest.raises(click.ClickException, match="Invalid environment variable name"):
+ _render_unix_runner(tmp_path / "run-headroom.sh", ["headroom", "run"], {"BAD-NAME": "x"})
+
+
+def test_render_unix_runner_omits_export_block_without_env(tmp_path: Path) -> None:
+ record = _render_unix_runner(tmp_path / "run-headroom.sh", ["headroom", "run"])
+
+ content = Path(record.path).read_text(encoding="utf-8")
+
+ assert "export" not in content
+ assert content == "#!/usr/bin/env bash\nset -euo pipefail\nexec headroom run\n"
+
+
def test_linux_task_spec_for_user_scope_includes_crontab_markers(tmp_path: Path) -> None:
manifest = _manifest(profile="smoke", supervisor=SupervisorKind.TASK.value)
@@ -128,6 +163,16 @@ def test_render_windows_runner_writes_ps1_and_cmd_wrappers(tmp_path: Path) -> No
)
+def test_render_windows_runner_rejects_invalid_env_name(tmp_path: Path) -> None:
+ with pytest.raises(click.ClickException, match="Invalid environment variable name"):
+ _render_windows_runner(
+ tmp_path / "run-headroom.ps1",
+ tmp_path / "run-headroom.cmd",
+ ["headroom", "run"],
+ {"BAD-NAME": "x"},
+ )
+
+
def test_render_runner_scripts_writes_unix_scripts(monkeypatch, tmp_path: Path) -> None:
monkeypatch.setattr("headroom.install.supervisors.sys.platform", "linux")
monkeypatch.setattr(
@@ -144,6 +189,23 @@ def test_render_runner_scripts_writes_unix_scripts(monkeypatch, tmp_path: Path)
}
+def test_render_runner_scripts_threads_base_env_into_both_scripts(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "linux")
+ monkeypatch.setattr(
+ "headroom.install.supervisors.resolve_headroom_command", lambda: ["headroom"]
+ )
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ manifest = _manifest(base_env={"HEADROOM_WORKSPACE_DIR": "/custom/workspace"})
+
+ records = render_runner_scripts(manifest)
+
+ for record in records:
+ content = Path(record.path).read_text(encoding="utf-8")
+ assert "export HEADROOM_WORKSPACE_DIR=/custom/workspace" in content
+
+
def test_render_runner_scripts_writes_windows_scripts(monkeypatch, tmp_path: Path) -> None:
monkeypatch.setattr("headroom.install.supervisors.sys.platform", "win32")
monkeypatch.setattr(
@@ -276,7 +338,7 @@ def test_install_supervisor_darwin_windows_and_unsupported(monkeypatch, tmp_path
calls: list[list[str]] = []
monkeypatch.setattr(
"headroom.install.supervisors.subprocess.run",
- lambda command, **kwargs: calls.append(command),
+ lambda command, **kwargs: calls.append(command) or _LaunchctlResult(0),
)
monkeypatch.setattr("headroom.install.supervisors.os.getuid", lambda: 123, raising=False)
@@ -335,6 +397,75 @@ def test_install_supervisor_darwin_windows_and_unsupported(monkeypatch, tmp_path
install_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+def test_install_supervisor_retries_bootstrap_until_launchd_settles(
+ monkeypatch, tmp_path: Path
+) -> None:
+ # Same EIO-after-bootout race start_supervisor already rides out, but hit
+ # via install_supervisor's own unconditional bootout+bootstrap sequence on
+ # every apply (issue: this call site had no retry at all before).
+ run_script = tmp_path / "run-headroom.sh"
+ monkeypatch.setattr(
+ "headroom.install.supervisors.render_runner_scripts",
+ lambda manifest: [
+ type("Record", (), {"kind": "script", "path": run_script.as_posix()})(),
+ ],
+ )
+ plist_path = tmp_path / "com.headroom.default.plist"
+ monkeypatch.setattr(
+ "headroom.install.supervisors._macos_launchd_plist",
+ lambda manifest, script, interval=None: (plist_path, "plist"),
+ )
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "darwin")
+ monkeypatch.setattr("headroom.install.supervisors.os.getuid", lambda: 123, raising=False)
+ monkeypatch.setattr("headroom.install.supervisors.time.sleep", lambda _s: None)
+ bootstrap_attempts = 0
+
+ def fake_run(command, **kwargs):
+ nonlocal bootstrap_attempts
+ if command[1] == "bootout":
+ return _LaunchctlResult(0)
+ bootstrap_attempts += 1
+ if bootstrap_attempts < 3:
+ return _LaunchctlResult(5, stderr="Bootstrap failed: 5: Input/output error")
+ return _LaunchctlResult(0)
+
+ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
+
+ install_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ assert bootstrap_attempts == 3
+
+
+def test_install_supervisor_raises_after_bootstrap_keeps_failing(
+ monkeypatch, tmp_path: Path
+) -> None:
+ run_script = tmp_path / "run-headroom.sh"
+ monkeypatch.setattr(
+ "headroom.install.supervisors.render_runner_scripts",
+ lambda manifest: [
+ type("Record", (), {"kind": "script", "path": run_script.as_posix()})(),
+ ],
+ )
+ plist_path = tmp_path / "com.headroom.default.plist"
+ monkeypatch.setattr(
+ "headroom.install.supervisors._macos_launchd_plist",
+ lambda manifest, script, interval=None: (plist_path, "plist"),
+ )
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "darwin")
+ monkeypatch.setattr("headroom.install.supervisors.os.getuid", lambda: 123, raising=False)
+ monkeypatch.setattr("headroom.install.supervisors.time.sleep", lambda _s: None)
+ monkeypatch.setattr("headroom.install.supervisors._MACOS_BOOTSTRAP_RETRIES", 3)
+
+ def fake_run(command, **kwargs):
+ if command[1] == "bootout":
+ return _LaunchctlResult(0)
+ return _LaunchctlResult(5, stderr="Bootstrap failed: 5: Input/output error")
+
+ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
+
+ with pytest.raises(click.ClickException, match="could not bootstrap"):
+ install_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+
+
class _LaunchctlResult:
def __init__(self, returncode: int = 0, stderr: str = "", stdout: str = "") -> None:
self.returncode = returncode