Skip to content

Self-improving AI Employees for everyone

fix(temporal): download + verify binaries at build time; reorder supervisor lifecycle

trohitg0d7ee4f11e8f
diff --git a/cli/commands/build.py b/cli/commands/build.py
index 485c5806..49ffdf04 100644
--- a/cli/commands/build.py
+++ b/cli/commands/build.py
@@ -17,9 +17,10 @@ import sys
import typer
-from cli.run import capture, run
+from cli._common import error_block
+from cli.run import capture, run, uv_run
from cli.colors import console
-from cli.platform_ import project_root
+from cli.platform_ import node_modules_dir, project_root, server_dir
# Source dirs / entry-point modules under ``server/`` that ``machina build``
@@ -83,7 +84,7 @@ def _ensure_uv(python_cmd: str) -> str:
run([python_cmd, "-m", "pip", "install", "uv"])
version = capture(["uv", "--version"])
if not version:
- console.print("[red]Error: failed to install uv. See https://docs.astral.sh/uv/[/]")
+ error_block("failed to install uv.", ["See https://docs.astral.sh/uv/"])
raise typer.Exit(code=1)
console.print(f" uv: {version}")
return version
@@ -106,15 +107,11 @@ def build_command() -> None:
return
# ---- toolchain ---------------------------------------------------
- # Temporal binaries are NOT a build-time dep: the supervised
- # ``TemporalServerRuntime`` (server/services/temporal/_runtime.py)
- # downloads ``temporal`` / ``temporal-server`` / ``temporal-sql-tool``
- # via pooch on first boot. No system install / npm shim required.
console.print("[bold]Checking dependencies...[/]\n")
node_version = capture(["node", "--version"])
console.print(f" Node.js: {node_version or '[red]not found[/]'}")
if not node_version:
- console.print("[red]Error: Node.js is required.[/]")
+ error_block("Node.js is required.", [])
raise typer.Exit(code=1)
npm_version = capture(["npm", "--version"])
@@ -122,9 +119,9 @@ def build_command() -> None:
python_cmd = _which_python()
if not python_cmd or not _check_python(python_cmd):
- console.print(
- "[red]Error: Python 3.12+ is required.[/] "
- "Install from https://python.org/downloads/"
+ error_block(
+ "Python 3.12+ is required.",
+ ["Install from https://python.org/downloads/"],
)
raise typer.Exit(code=1)
@@ -133,7 +130,7 @@ def build_command() -> None:
console.print("\n[green]All dependencies ready.[/]\n")
# ---- build steps -------------------------------------------------
- server_dir = root / "server"
+ server_cwd = server_dir(root)
env_path = root / ".env"
template_path = root / ".env.template"
@@ -162,9 +159,13 @@ def build_command() -> None:
run(["pnpm", "--filter", "machinaos-nodejs-executor", "run", "build"], cwd=root)
console.log("[4/6] Installing Python dependencies...")
- if not (server_dir / ".venv").exists():
- run(["uv", "venv"], cwd=server_dir)
- run(["uv", "sync"], cwd=server_dir)
+ # ``server/`` is its own standalone uv project; ``uv sync`` at that
+ # directory resolves ``server/pyproject.toml`` and materialises
+ # ``server/.venv``. The CLI lives in a separate venv (or system
+ # python via pipx) and never shares this environment -- see
+ # ``cli/platform_.py`` docstring for the rationale. ``uv sync``
+ # is idempotent and creates the venv on first run.
+ run(["uv", "sync"], cwd=server_cwd)
# Pre-compile our Python sources to optimised bytecode (.opt-1.pyc).
# `-O` strips `assert` statements + `__debug__` branches; `-q`
@@ -178,20 +179,22 @@ def build_command() -> None:
# template files inside packages like crawlee that aren't real Python.
console.log("[5/6] Compiling Python bytecode...")
run(
- ["uv", "run", "python", "-O", "-m", "compileall", "-q", "-j", "0", *COMPILEALL_SOURCE_DIRS],
- cwd=server_dir,
+ uv_run("python", "-O", "-m", "compileall", "-q", "-j", "0", *COMPILEALL_SOURCE_DIRS),
+ cwd=server_cwd,
check=False, # missing pyc is non-fatal — runtime regenerates as needed
)
- console.log("[6/6] Verifying edgymeow binary...")
- bin_name = "edgymeow-server.exe" if sys.platform == "win32" else "edgymeow-server"
- edgymeow_bin = root / "node_modules" / "edgymeow" / "bin" / bin_name
- if edgymeow_bin.exists():
- console.print(f" Binary present: {edgymeow_bin}")
- else:
- console.print(
- " [yellow]Warning: edgymeow binary not found. "
- "Set WHATSAPP_RUNTIME_ENABLED=false to disable.[/]"
- )
+ # Temporal is a required runtime dep: fetch + verify the binaries
+ # now so first ``machina start`` is instant instead of paying the
+ # ~90 MB pooch download cost inside ``_pre_spawn``. The ``-m
+ # services.temporal._install`` entry runs ``ensure_temporal_binaries``
+ # then asserts every extracted path exists; non-zero exit aborts
+ # the build via ``run(check=True)``. Idempotent on re-build (pooch
+ # cache hit) so this step is sub-second once the tarball is on disk.
+ console.log("[6/6] Installing Temporal binaries...")
+ run(
+ uv_run("python", "-m", "services.temporal._install"),
+ cwd=server_cwd,
+ )
console.log("[green]Build complete.[/]")
diff --git a/cli/tests/test_build_compile_pipeline.py b/cli/tests/test_build_compile_pipeline.py
index 4d3b0ac2..edbc3bad 100644
--- a/cli/tests/test_build_compile_pipeline.py
+++ b/cli/tests/test_build_compile_pipeline.py
@@ -32,17 +32,6 @@ from cli.commands import build
# Helpers
# ---------------------------------------------------------------------------
-def _seed_edgymeow_binary(tmp_path: Path) -> None:
- """Create a fake edgymeow binary so the [6/6] verify step doesn't warn.
-
- The verify step only stat()s the file; the contents are never read.
- """
- bin_dir = tmp_path / "node_modules" / "edgymeow" / "bin"
- bin_dir.mkdir(parents=True, exist_ok=True)
- bin_name = "edgymeow-server.exe" if build.sys.platform == "win32" else "edgymeow-server"
- (bin_dir / bin_name).write_text("")
-
-
def _run_build_capture_invocations(tmp_path: Path) -> list[dict]:
"""Run ``build_command()`` with all external I/O mocked.
@@ -50,7 +39,6 @@ def _run_build_capture_invocations(tmp_path: Path) -> list[dict]:
to ``cli.run.run`` — in the order the orchestrator emitted them.
Preserving kwargs lets tests assert ``check=False`` and ``cwd=...``.
"""
- _seed_edgymeow_binary(tmp_path)
captured: list[dict] = []
def fake_run(argv, **kwargs):
@@ -63,9 +51,9 @@ def _run_build_capture_invocations(tmp_path: Path) -> list[dict]:
return "Python 3.12.5"
return "v1.0.0"
- # ``_ensure_temporal`` was removed -- the supervised
- # ``TemporalServerRuntime`` downloads the binary via pooch at first
- # boot, so the build command no longer touches Temporal at all.
+ # Step [6/6] invokes ``services.temporal._install`` via ``uv_run`` to
+ # materialise the Temporal binaries at build time. ``fake_run``
+ # captures the argv without actually spawning, so pooch never fires.
with patch.object(build, "run", side_effect=fake_run), \
patch.object(build, "capture", side_effect=fake_capture), \
patch.object(build, "_which_python", return_value="python"), \
@@ -185,15 +173,17 @@ def test_compileall_uses_optimised_flag_quiet_and_parallel(tmp_path: Path):
def test_compileall_runs_via_uv_run_python(tmp_path: Path):
- """Compileall must use ``uv run python`` so the project's pinned
- interpreter is used regardless of what ``python`` is on PATH.
+ """Compileall must go through ``uv run --no-sync python`` (built by
+ :func:`cli.run.uv_run`) so the project's pinned workspace interpreter
+ is used regardless of what ``python`` is on PATH, without re-syncing
+ the lockfile mid-build.
"""
captured = _run_build_capture_invocations(tmp_path)
match = _find_call(captured, lambda c: "compileall" in c)
assert match is not None
argv = match[1]["argv"]
- assert argv[:5] == ["uv", "run", "python", "-O", "-m"], (
- f"expected `uv run python -O -m compileall ...`, got {argv[:6]}"
+ assert argv[:6] == ["uv", "run", "--no-sync", "python", "-O", "-m"], (
+ f"expected `uv run --no-sync python -O -m compileall ...`, got {argv[:7]}"
)
@@ -252,6 +242,90 @@ def test_only_one_compileall_invocation(tmp_path: Path):
assert len(matches) == 1, f"expected exactly 1 compileall call, got {len(matches)}"
+# ---------------------------------------------------------------------------
+# Temporal install step ([6/6])
+# ---------------------------------------------------------------------------
+
+def _find_temporal_install_call(captured: list[dict]) -> tuple[int, dict] | None:
+ return _find_call(
+ captured,
+ lambda c: (
+ c[:3] == ["uv", "run", "--no-sync"]
+ and "services.temporal._install" in c
+ ),
+ )
+
+
+def test_build_invokes_temporal_install_via_uv_run(tmp_path: Path):
+ """[6/6] must invoke ``uv run --no-sync python -m
+ services.temporal._install`` so pooch downloads the Temporal
+ tarball at build time (idempotent on re-build via the pooch cache).
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ match = _find_temporal_install_call(captured)
+ assert match is not None, (
+ "expected temporal install step in "
+ f"{[c['argv'] for c in captured]}"
+ )
+ argv = match[1]["argv"]
+ assert argv[:6] == ["uv", "run", "--no-sync", "python", "-m",
+ "services.temporal._install"], (
+ f"expected `uv run --no-sync python -m services.temporal._install`, got {argv[:7]}"
+ )
+
+
+def test_temporal_install_runs_in_server_dir(tmp_path: Path):
+ """Temporal install runs under ``server/`` so ``uv run`` resolves the
+ workspace venv with ``services.temporal._install`` on sys.path.
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ match = _find_temporal_install_call(captured)
+ assert match is not None
+ call = match[1]
+ assert call.get("cwd") == tmp_path / "server", (
+ f"temporal install must cwd into server/, got {call.get('cwd')}"
+ )
+
+
+def test_temporal_install_is_fatal_on_failure(tmp_path: Path):
+ """Temporal is a required runtime dep, so the install step must NOT
+ pass ``check=False`` — a pooch failure (network, SHA mismatch,
+ missing asset) has to abort the build cleanly rather than silently
+ deferring the failure to ``machina start``.
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ match = _find_temporal_install_call(captured)
+ assert match is not None
+ call = match[1]
+ # ``check`` defaults to True in ``cli.run.run`` — assert no override.
+ assert call.get("check", True) is True, (
+ "temporal install must keep check=True so build aborts on fetch failure"
+ )
+
+
+def test_temporal_install_runs_after_uv_sync(tmp_path: Path):
+ """Temporal install MUST follow ``uv sync`` because it invokes
+ ``uv run python -m services.temporal._install``, which requires the
+ workspace venv (and pooch + the install module) to be materialised.
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ uv_sync = _find_call(captured, lambda c: c[:2] == ["uv", "sync"])
+ temporal = _find_temporal_install_call(captured)
+ assert uv_sync is not None and temporal is not None
+ assert uv_sync[0] < temporal[0], (
+ f"uv_sync idx {uv_sync[0]} must precede temporal install idx {temporal[0]}"
+ )
+
+
+def test_only_one_temporal_install_invocation(tmp_path: Path):
+ """Temporal install must fire exactly once per build."""
+ captured = _run_build_capture_invocations(tmp_path)
+ matches = [c for c in captured if "services.temporal._install" in c["argv"]]
+ assert len(matches) == 1, (
+ f"expected exactly 1 temporal install call, got {len(matches)}"
+ )
+
+
# ---------------------------------------------------------------------------
# Step ordering invariants
# ---------------------------------------------------------------------------
diff --git a/server/services/_supervisor/process.py b/server/services/_supervisor/process.py
index 44304a79..942b1dc0 100644
--- a/server/services/_supervisor/process.py
+++ b/server/services/_supervisor/process.py
@@ -70,12 +70,16 @@ class BaseProcessSupervisor(BaseSupervisor):
return self._proc is not None and self._proc.returncode is None
async def _do_start(self) -> None:
+ # Subclasses that download or otherwise materialise their binary
+ # do so in ``_pre_spawn`` (e.g. Temporal's pooch fetch populates
+ # ``self._binaries``). Run that first so ``binary_path`` can
+ # return the real on-disk location before the existence check.
+ await self._pre_spawn()
+
binary = self.binary_path()
if not binary.exists():
raise FileNotFoundError(f"{self.label} binary not found at {binary}")
- await self._pre_spawn()
-
argv = self.argv()
kwargs: dict[str, Any] = {
"cwd": str(self.cwd()) if self.cwd() else None,
diff --git a/server/services/temporal/_install.py b/server/services/temporal/_install.py
index 7b65376f..07a436cc 100644
--- a/server/services/temporal/_install.py
+++ b/server/services/temporal/_install.py
@@ -71,17 +71,33 @@ _CHECKSUMS_BY_VERSION: dict[str, dict[str, str]] = {
}
# Names of the binaries we extract from each release tarball. The
-# Temporal release ships several; we extract the three MachinaOS
-# actually invokes:
-# - ``temporal`` — standalone CLI. Powers the sqlite-backend dev
-# server (``temporal server start-dev``) and any
-# ad-hoc workflow / operator commands.
+# ``temporalio/temporal`` server release contains the cluster binaries
+# only — the user-facing ``temporal`` CLI is a separate distribution
+# fetched from the official URL documented at
+# https://docs.temporal.io/develop/python/set-up-your-local-python:
# - ``temporal-server`` — full cluster binary used by the postgres
-# backend with a YAML config.
+# backend with a YAML config
+# (``temporal-server start --config <yaml>``).
# - ``temporal-sql-tool`` — schema migrator invoked once at boot to
# create + update the Postgres databases.
-# Adding ``tctl`` here would also extract it.
-_BINARY_NAMES: tuple[str, ...] = ("temporal", "temporal-server", "temporal-sql-tool")
+_BINARY_NAMES: tuple[str, ...] = ("temporal-server", "temporal-sql-tool")
+
+# Official Temporal CLI download URL. Per the docs at
+# https://docs.temporal.io/develop/python/set-up-your-local-python the
+# CLI archive lives at ``temporal.download/cli/archive/latest`` with
+# ``platform`` and ``arch`` query parameters. Contains a single
+# ``temporal`` binary; powers ``temporal server start-dev`` (the
+# sqlite/in-memory dev server) and ad-hoc workflow / operator commands.
+_CLI_BASE_URL = "https://temporal.download/cli/archive/latest"
+_CLI_PLATFORM_MAP: dict[tuple[str, str], tuple[str, str]] = {
+ # platform.system, platform.machine -> (URL platform, URL arch)
+ ("Linux", "x86_64"): ("linux", "amd64"),
+ ("Linux", "aarch64"): ("linux", "arm64"),
+ ("Darwin", "x86_64"): ("darwin", "amd64"),
+ ("Darwin", "arm64"): ("darwin", "arm64"),
+ ("Windows", "AMD64"): ("windows", "amd64"),
+ ("Windows", "ARM64"): ("windows", "arm64"),
+}
# pooch cache namespace. Re-used across versions; pooch's own cache
# layout includes the asset URL so versions don't collide.
@@ -124,7 +140,15 @@ def _resolver(version: str) -> pooch.Pooch:
async def ensure_temporal_binaries(
settings: Settings | None = None,
) -> dict[str, Path]:
- """Return ``{"temporal-server": Path, "temporal-sql-tool": Path}``.
+ """Return ``{"temporal": Path, "temporal-server": Path, "temporal-sql-tool": Path}``.
+
+ Two fetches, merged into one dict:
+ - ``temporal-server`` + ``temporal-sql-tool`` from the pinned
+ ``temporalio/temporal`` GitHub release (SHA-verified).
+ - ``temporal`` CLI from the official URL at
+ https://docs.temporal.io/develop/python/set-up-your-local-python
+ (``temporal.download/cli/archive/latest``). No SHA pin — the
+ ``latest`` URL rotates and is served over TLS.
Idempotent — first call downloads, subsequent calls hit the pooch
cache (XDG / OS-conventional dir). Async-locked so concurrent
@@ -140,14 +164,59 @@ async def ensure_temporal_binaries(
async with _lock:
if _cached is not None:
return _cached
- _cached = await asyncio.to_thread(_fetch_sync, version)
+ cluster_paths = await asyncio.to_thread(_fetch_sync, version)
+ cli_path = await asyncio.to_thread(_fetch_cli_sync)
+ _cached = {**cluster_paths, "temporal": cli_path}
logger.info(
- "[Temporal install] binaries ready (v=%s): %s",
+ "[Temporal install] binaries ready (cluster v=%s + official CLI): %s",
version, {k: str(v) for k, v in _cached.items()},
)
return _cached
+def _fetch_cli_sync() -> Path:
+ """Download the official ``temporal`` CLI archive and return the binary path.
+
+ Uses ``pooch.retrieve`` with ``known_hash=None`` because the
+ ``temporal.download/cli/archive/latest`` URL rotates as new CLI
+ versions ship — pinning a SHA would defeat the "latest" semantics
+ the official docs document. TLS gives us transport integrity.
+ """
+ key = (platform.system(), platform.machine())
+ if key not in _CLI_PLATFORM_MAP:
+ raise RuntimeError(
+ f"[Temporal install] Unsupported platform for CLI: {key}. "
+ f"Supported: {sorted(_CLI_PLATFORM_MAP.keys())}"
+ )
+ url_platform, url_arch = _CLI_PLATFORM_MAP[key]
+ url = f"{_CLI_BASE_URL}?platform={url_platform}&arch={url_arch}"
+
+ is_windows = platform.system() == "Windows"
+ fname = f"temporal_cli_latest_{url_platform}_{url_arch}.{'zip' if is_windows else 'tar.gz'}"
+ processor = pooch.Unzip() if is_windows else pooch.Untar()
+
+ extracted = pooch.retrieve(
+ url=url,
+ known_hash=None,
+ path=pooch.os_cache(_CACHE_NAMESPACE),
+ fname=fname,
+ processor=processor,
+ progressbar=True,
+ )
+
+ target = "temporal.exe" if is_windows else "temporal"
+ match = next((Path(p) for p in extracted if Path(p).name == target), None)
+ if match is None:
+ raise RuntimeError(
+ f"[Temporal install] CLI binary {target!r} not found in archive. "
+ f"Extracted files: {[Path(p).name for p in extracted]}"
+ )
+ if not is_windows:
+ mode = match.stat().st_mode
+ match.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+ return match
+
+
def _fetch_sync(version: str) -> dict[str, Path]:
"""Synchronous pooch fetch + post-extraction binary location.
@@ -181,3 +250,39 @@ def _fetch_sync(version: str) -> dict[str, Path]:
__all__ = ["ensure_temporal_binaries"]
+
+
+def _main() -> int:
+ """Standalone entry: ``python -m services.temporal._install``.
+
+ Used by ``machina build`` step [6/6] to materialise the Temporal
+ binaries at build time instead of paying the ~90 MB download cost
+ on first ``machina start``. Fetches, verifies every extracted path
+ exists on disk, prints the resolved locations. Non-zero exit on
+ any failure (pooch raises on SHA mismatch / network errors / asset
+ missing from tarball; we add an explicit post-fetch existence pass
+ so partial extractions also fail loudly).
+ """
+ import sys as _sys
+
+ try:
+ paths = asyncio.run(ensure_temporal_binaries())
+ except Exception as exc: # noqa: BLE001 — propagate to non-zero exit
+ print(f"[Temporal install] {exc}", file=_sys.stderr)
+ return 1
+
+ missing = [name for name, path in paths.items() if not path.exists()]
+ if missing:
+ print(
+ f"[Temporal install] binaries missing after fetch: {missing}",
+ file=_sys.stderr,
+ )
+ return 1
+
+ for name, path in paths.items():
+ print(f" {name}: {path}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(_main())
diff --git a/server/services/temporal/_runtime.py b/server/services/temporal/_runtime.py
index 1d5d5a94..49724cb8 100644
--- a/server/services/temporal/_runtime.py
+++ b/server/services/temporal/_runtime.py
@@ -266,12 +266,14 @@ class TemporalServerRuntime(BaseProcessSupervisor):
self._sqlite_path.parent.mkdir(parents=True, exist_ok=True)
def binary_path(self) -> Path:
- # Pre-``_pre_spawn`` placeholders for any existence check
- # BaseProcessSupervisor may run; the real paths are populated
- # once pooch resolves the cache.
+ # ``_pre_spawn`` (called by ``BaseProcessSupervisor._do_start``
+ # before this method) populates ``self._binaries`` via the
+ # pooch downloader. Loud failure if that contract regresses.
binary = "temporal-server" if self.backend == "postgres" else "temporal"
- if self._binaries is None:
- return Path(binary)
+ assert self._binaries is not None, (
+ f"[{self.label}] binary_path() called before _pre_spawn() "
+ "populated self._binaries"
+ )
return self._binaries[binary]
def argv(self) -> list[str]:
diff --git a/server/tests/services/test_process_lifecycle.py b/server/tests/services/test_process_lifecycle.py
new file mode 100644
index 00000000..86ca2103
--- /dev/null
+++ b/server/tests/services/test_process_lifecycle.py
@@ -0,0 +1,126 @@
+"""Lock the ordering of ``BaseProcessSupervisor._do_start``.
+
+The contract: ``_pre_spawn`` must run before ``binary_path``'s existence
+check. Subclasses that download or materialise their binary inside
+``_pre_spawn`` (notably ``TemporalServerRuntime``, which pooch-fetches
+its binary on first call) depend on this — checking existence first
+fails against an unresolved placeholder and the subprocess never starts.
+
+Locking the order via test makes a future regression of this lifecycle
+contract a loud test failure instead of a silent
+``FileNotFoundError: <bin> not found`` at runtime.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+# Ensure server/ on sys.path (mirrors conftest.py)
+SERVER_DIR = Path(__file__).resolve().parents[2]
+if str(SERVER_DIR) not in sys.path:
+ sys.path.insert(0, str(SERVER_DIR))
+
+from services._supervisor import BaseProcessSupervisor # noqa: E402
+
+
+class _DownloadOnPreSpawn(BaseProcessSupervisor):
+ """Models the Temporal pattern: binary is materialised by _pre_spawn."""
+
+ name = "fake-download"
+
+ def __init__(self, tmp_path: Path) -> None:
+ super().__init__()
+ self._tmp = tmp_path
+ self._binary: Path | None = None
+ self.pre_spawn_calls = 0
+
+ async def _pre_spawn(self) -> None:
+ self.pre_spawn_calls += 1
+ # Materialise the binary on disk — mirrors pooch fetching the
+ # Temporal release tarball into the cache.
+ target = self._tmp / "fake_binary"
+ target.write_text("#!/bin/sh\nexit 0\n")
+ target.chmod(0o755)
+ self._binary = target
+
+ def binary_path(self) -> Path:
+ # Pre-``_pre_spawn`` placeholder; real path appears after.
+ return self._binary if self._binary is not None else Path("/nonexistent")
+
+ def argv(self) -> list[str]:
+ return [str(self.binary_path())]
+
+
+class _NoMaterialise(BaseProcessSupervisor):
+ """Models a misconfigured subclass: binary missing, _pre_spawn is no-op."""
+
+ name = "fake-broken"
+
+ def binary_path(self) -> Path:
+ return Path("/definitely/not/a/real/binary")
+
+ def argv(self) -> list[str]:
+ return [str(self.binary_path())]
+
+
[email protected](autouse=True)
+def _reset_singletons():
+ """Per-class singleton storage on ``BaseSupervisor`` leaks across tests."""
+ for klass in (BaseProcessSupervisor, _DownloadOnPreSpawn, _NoMaterialise):
+ klass._instance = None
+ yield
+ for klass in (BaseProcessSupervisor, _DownloadOnPreSpawn, _NoMaterialise):
+ klass._instance = None
+
+
+async def test_pre_spawn_runs_before_binary_existence_check(tmp_path):
+ """The Temporal-failure scenario: binary materialised inside _pre_spawn.
+
+ With the correct ordering, _do_start should:
+ 1. call _pre_spawn (which writes the binary to disk)
+ 2. then check binary_path().exists() — finds the freshly written file
+ 3. then spawn the subprocess (we mock anyio.open_process to avoid
+ actually executing the shell stub).
+ """
+ sub = _DownloadOnPreSpawn(tmp_path)
+
+ fake_proc = AsyncMock()
+ fake_proc.pid = 4242
+ fake_proc.returncode = None
+ # ``_do_stop`` tree-kills the pid via psutil; bypass that for the
+ # fake pid so test teardown doesn't reach the real OS process table.
+ with patch(
+ "services._supervisor.process.anyio.open_process",
+ new=AsyncMock(return_value=fake_proc),
+ ), patch(
+ "services._supervisor.util.kill_tree",
+ ):
+ await sub.start()
+
+ assert sub.pre_spawn_calls == 1, "_pre_spawn must run before existence check"
+ assert sub._binary is not None and sub._binary.exists()
+ assert sub.is_running()
+
+ # Mark the proc as exited so ``is_running`` flips false and the
+ # supervisor's stop path short-circuits cleanly.
+ fake_proc.returncode = 0
+ await sub.stop()
+
+
+async def test_existence_check_still_raises_when_pre_spawn_doesnt_provide_binary():
+ """Safety net: a misconfigured subclass still gets a clear error.
+
+ Reordering _pre_spawn before the existence check must not remove the
+ check itself — when nothing materialises the binary, the supervisor
+ should still raise FileNotFoundError pointing at the missing path.
+ """
+ sub = _NoMaterialise()
+ with pytest.raises(FileNotFoundError, match="fake-broken"):
+ await sub.start()
+ assert not sub.is_running()