Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): launch the agent server with one preflight exec (#104329)

Alessandro Pogliaghib85f7e90b68e
diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.py
index d0bfa3297956..a8ba45acec54 100644
--- a/products/tasks/backend/logic/services/agent_server_launcher.py
+++ b/products/tasks/backend/logic/services/agent_server_launcher.py
@@ -18,6 +18,8 @@ from typing import TYPE_CHECKING
from django.conf import settings
+from posthog.dataclasses import frozen
+
from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEX, SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS
from products.tasks.backend.exceptions import ProcessTaskFatalError, SandboxExecutionError, SandboxTimeoutError
from products.tasks.backend.logic.services.agentsh import (
@@ -40,6 +42,8 @@ from products.tasks.backend.logic.services.sandbox import (
WORKING_DIR,
SandboxBase,
build_agent_runtime_env_prefix,
+ build_agent_server_capability_probe,
+ build_bundled_skills_clear_command,
build_health_check_command,
health_check_timeout_seconds,
wait_for_health_check,
@@ -51,11 +55,28 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
AGENT_SERVER_PORT = 8080 # Modal connect tokens require port 8080
+AGENT_SERVER_PID_FILE = "/tmp/agent-server.pid"
AGENT_SERVER_HEALTH_MAX_ATTEMPTS = 240
# The whole diagnostics dict rides in the Temporal failure payload, which is capped at about 2 MiB.
STARTUP_LOG_MAX_BYTES = 64 * 1024
AGENT_SERVER_HEALTH_DURATION_PREFIX = "__posthog_agent_health_ms="
+AGENT_SERVER_FREE_PORT_SCRIPT = (
+ "agent_server_pids() { for p in $(pgrep -f '[a]gent-server'); do "
+ 'cmp -s "/proc/$p/cmdline" "/proc/$$/cmdline" 2>/dev/null || echo "$p"; done; }; '
+ 'pids=$(agent_server_pids); [ -n "$pids" ] && echo "$pids" | xargs kill -TERM 2>/dev/null; '
+ 'for _ in $(seq 1 10); do [ -z "$(agent_server_pids)" ] && break; sleep 0.5; done; '
+ 'pids=$(agent_server_pids); [ -n "$pids" ] && echo "$pids" | xargs kill -KILL 2>/dev/null; true'
+)
+
+AGENT_SERVER_LAUNCH_CAPABILITIES = ("pi_runtime", "auto_publish", "exec_permission_regex")
+AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX = "__posthog_agent_preflight_capability="
+AGENT_SERVER_PREFLIGHT_REUSE_MARKER = "__posthog_agent_preflight_reuse=1"
+AGENT_SERVER_PREFLIGHT_SKILLS_EXIT_CODE = 90
+AGENT_SERVER_PREFLIGHT_CHMOD_EXIT_CODE = 91
+AGENT_SERVER_PREFLIGHT_CREDENTIAL_EXIT_CODE = 92
+AGENT_SERVER_PREFLIGHT_TIMEOUT_SECONDS = 60
+
# The read probe wants a large file the agent-server boot never opens, so its first read is cold:
# nothing at boot loads the global TypeScript compiler. Its prefix follows the Node install and its
# largest asset moves between releases, so take the biggest file under either prefix. Nothing above
@@ -159,7 +180,7 @@ def _egress_failure_reason(egress: str) -> str | None:
def _start_and_wait_command(command: str, max_attempts: int = AGENT_SERVER_HEALTH_MAX_ATTEMPTS) -> str:
- health_command = build_health_check_command(AGENT_SERVER_PORT, max_attempts, pid_file="/tmp/agent-server.pid")
+ health_command = build_health_check_command(AGENT_SERVER_PORT, max_attempts, pid_file=AGENT_SERVER_PID_FILE)
return (
f"{command}; launch_status=$?; "
'if [ "$launch_status" -ne 0 ]; then exit "$launch_status"; fi; '
@@ -171,6 +192,46 @@ def _start_and_wait_command(command: str, max_attempts: int = AGENT_SERVER_HEALT
)
+@frozen
+class AgentServerPreflight:
+ reused: bool
+ capabilities: frozenset[str]
+
+ def supports(self, capability: str) -> bool:
+ return capability in self.capabilities
+
+
+def build_agent_server_preflight_script(*, probe_health: bool, executable_paths: tuple[str, ...]) -> str:
+ lines = [
+ f"if ! ( {build_bundled_skills_clear_command()} ); then exit {AGENT_SERVER_PREFLIGHT_SKILLS_EXIT_CODE}; fi"
+ ]
+ lines.extend(
+ f"if ! chmod +x {shlex.quote(path)}; then exit {AGENT_SERVER_PREFLIGHT_CHMOD_EXIT_CODE}; fi"
+ for path in executable_paths
+ )
+ lines.extend(
+ f"if {build_agent_server_capability_probe(capability)}; then "
+ f"echo {shlex.quote(AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX + capability)}; fi"
+ for capability in AGENT_SERVER_LAUNCH_CAPABILITIES
+ )
+ if probe_health:
+ health_command = build_health_check_command(AGENT_SERVER_PORT, 1, 0.0, pid_file=AGENT_SERVER_PID_FILE)
+ lines.extend(
+ [
+ f"health_output=$({health_command})",
+ "health_status=$?",
+ 'printf "%s\\n" "$health_output"',
+ f'case "$health_output" in *claude_credential_unavailable*) '
+ f"exit {AGENT_SERVER_PREFLIGHT_CREDENTIAL_EXIT_CODE};; esac",
+ f'if [ "$health_status" -eq 0 ]; then '
+ f"echo {shlex.quote(AGENT_SERVER_PREFLIGHT_REUSE_MARKER)}; exit 0; fi",
+ AGENT_SERVER_FREE_PORT_SCRIPT,
+ ]
+ )
+ lines.append("exit 0")
+ return "\n".join(lines)
+
+
def _health_duration_ms(stdout: str) -> int | None:
for line in stdout.splitlines():
if line.startswith(AGENT_SERVER_HEALTH_DURATION_PREFIX):
@@ -377,11 +438,12 @@ class AgentServerLaunchMixin(SandboxBase):
)
return self.execute(checks, timeout_seconds=30).stdout.strip()
- def _prepare_agent_server_launch(self, allowed_domains: list[str] | None) -> None:
+ def _install_agent_server_launch_files(self) -> tuple[str, ...]:
self._write_required_file(BASH_ENV_SCRIPT, generate_bash_env_script().encode())
self._write_required_file(GH_GUARD_INSTALL_PATH, read_gh_guard_script())
- self._chmod_required(GH_GUARD_INSTALL_PATH, "+x")
+ return (GH_GUARD_INSTALL_PATH,)
+ def _prepare_agent_server_launch(self, allowed_domains: list[str] | None) -> None:
if allowed_domains is not None:
self._setup_agentsh(WORKING_DIR, allowed_domains)
@@ -398,12 +460,55 @@ class AgentServerLaunchMixin(SandboxBase):
if not self.is_running():
raise RuntimeError("Sandbox not in running state.")
- def _reuse_healthy_agent_server(self, allowed_domains: list[str] | None) -> bool:
- if self._agent_server_is_healthy() and (allowed_domains is None or self._agentsh_daemon_is_healthy()):
- logger.info(f"Agent-server already healthy in sandbox {self.id}; skipping relaunch")
- return True
- self._free_agent_server_port()
- return False
+ def _agent_server_reuse_enabled(self) -> bool:
+ return True
+
+ def _on_agent_server_reused(self) -> None:
+ return None
+
+ def _agent_server_preflight(self, allowed_domains: list[str] | None) -> AgentServerPreflight:
+ executable_paths = self._install_agent_server_launch_files()
+ result = self.execute(
+ build_agent_server_preflight_script(
+ probe_health=self._agent_server_reuse_enabled(), executable_paths=executable_paths
+ ),
+ timeout_seconds=AGENT_SERVER_PREFLIGHT_TIMEOUT_SECONDS,
+ )
+ if result.exit_code == AGENT_SERVER_PREFLIGHT_SKILLS_EXIT_CODE:
+ raise RuntimeError(f"Failed to clear bundled skills in sandbox {self.id}: {result.stderr}")
+ if result.exit_code == AGENT_SERVER_PREFLIGHT_CHMOD_EXIT_CODE:
+ raise SandboxExecutionError(
+ "Failed to set permissions on required sandbox file",
+ {"sandbox_id": self.id, "paths": ",".join(executable_paths), "mode": "+x", "stderr": result.stderr},
+ cause=RuntimeError("agent-server preflight could not make the required files executable"),
+ )
+ if result.exit_code == AGENT_SERVER_PREFLIGHT_CREDENTIAL_EXIT_CODE:
+ raise ProcessTaskFatalError(
+ "The Claude token did not arrive. Open Desktop and check your token in Settings > Harness. Then start the task again.",
+ {"sandbox_id": self.id},
+ RuntimeError("Claude token unavailable"),
+ capture=False,
+ )
+ if result.exit_code != 0:
+ raise SandboxExecutionError(
+ "Agent-server preflight failed",
+ {"sandbox_id": self.id, "exit_code": str(result.exit_code), "stderr": result.stderr},
+ cause=RuntimeError(result.stderr or "agent-server preflight returned a non-zero exit"),
+ )
+
+ lines = result.stdout.splitlines()
+ capabilities = frozenset(
+ line.removeprefix(AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX)
+ for line in lines
+ if line.startswith(AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX)
+ )
+ if AGENT_SERVER_PREFLIGHT_REUSE_MARKER in lines:
+ if allowed_domains is None or self._agentsh_daemon_is_healthy():
+ logger.info(f"Agent-server already healthy in sandbox {self.id}; skipping relaunch")
+ self._on_agent_server_reused()
+ return AgentServerPreflight(reused=True, capabilities=capabilities)
+ self._free_agent_server_port()
+ return AgentServerPreflight(reused=False, capabilities=capabilities)
def _launch_prepared_agent_server(
self,
@@ -513,8 +618,8 @@ class AgentServerLaunchMixin(SandboxBase):
# Before the already-healthy shortcut: images that boot the agent server never relaunch it,
# and the agent reads its skill directories when a session starts, not when the server does.
- self.clear_bundled_skills_if_disabled()
- if self._reuse_healthy_agent_server(allowed_domains):
+ preflight = self._agent_server_preflight(allowed_domains)
+ if preflight.reused:
return 0 if wait_for_health else None
repo_path: str | None = None
@@ -533,15 +638,15 @@ class AgentServerLaunchMixin(SandboxBase):
if relayed_mcp_servers:
relay_mcp_servers_arg = f" --relayMcpServers {shlex.quote(json.dumps(relayed_mcp_servers))}"
- if agent_runtime == "pi" and not self.agent_server_supports_pi_runtime():
+ if agent_runtime == "pi" and not preflight.supports("pi_runtime"):
raise RuntimeError("Installed sandbox agent-server does not support the Pi runtime")
- if auto_publish and not self.agent_server_supports_auto_publish():
+ if auto_publish and not preflight.supports("auto_publish"):
logger.warning(f"Installed agent-server in sandbox {self.id} predates --autoPublish; starting review-first")
auto_publish = False
exec_permission_regex: str | None = POSTHOG_EXEC_PERMISSION_REGEX
- if not self.agent_server_supports_exec_permission_regex():
+ if not preflight.supports("exec_permission_regex"):
logger.warning(
f"Installed agent-server in sandbox {self.id} predates --posthogExecPermissionRegex; "
"connected-project operations will not prompt"
@@ -715,12 +820,9 @@ class AgentServerLaunchMixin(SandboxBase):
) -> bool:
"""Poll health endpoint until server is ready (single remote call)."""
return wait_for_health_check(
- self.execute, self.id, AGENT_SERVER_PORT, max_attempts, poll_interval, pid_file="/tmp/agent-server.pid"
+ self.execute, self.id, AGENT_SERVER_PORT, max_attempts, poll_interval, pid_file=AGENT_SERVER_PID_FILE
)
- def _agent_server_is_healthy(self) -> bool:
- return wait_for_health_check(self.execute, self.id, AGENT_SERVER_PORT, max_attempts=1, poll_interval=0.0)
-
def read_agent_server_session_init_ms(self) -> int | None:
return self._read_health_session_init_ms(AGENT_SERVER_PORT)
@@ -731,9 +833,4 @@ class AgentServerLaunchMixin(SandboxBase):
return self._read_health_boot_metrics(AGENT_SERVER_PORT)
def _free_agent_server_port(self) -> None:
- self.execute(
- "pkill -TERM -f '[a]gent-server' 2>/dev/null || true; "
- "for _ in $(seq 1 10); do pgrep -f '[a]gent-server' >/dev/null || break; sleep 0.5; done; "
- "pkill -KILL -f '[a]gent-server' 2>/dev/null || true",
- timeout_seconds=15,
- )
+ self.execute(AGENT_SERVER_FREE_PORT_SCRIPT, timeout_seconds=15)
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index 0aa72f7a79b1..8fd1839684b4 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -1049,9 +1049,12 @@ class DockerSandbox(AgentServerLaunchMixin):
if self._host_port is None:
raise RuntimeError("Sandbox was not created with port exposure.")
- def _reuse_healthy_agent_server(self, allowed_domains: list[str] | None) -> bool:
+ def _agent_server_reuse_enabled(self) -> bool:
return False
+ def _install_agent_server_launch_files(self) -> tuple[str, ...]:
+ return ()
+
def _prepare_agent_server_launch(self, allowed_domains: list[str] | None) -> None:
# The agent runs each tool command in a fresh shell; BASH_ENV re-sources
# the (backend-refreshed) GitHub token from the env file per command, so
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index e393e60a98e6..0d97f0c39a79 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -768,19 +768,17 @@ class ModalSandbox(AgentServerLaunchMixin):
self.provision_diagnostics = None
self._destroyed = False
- def _reuse_healthy_agent_server(self, allowed_domains: list[str] | None) -> bool:
- if self._agent_server_is_healthy() and (allowed_domains is None or self._agentsh_daemon_is_healthy()):
- # A restored snapshot can carry a healthy agent-server with a stale bash-env
- # or gh shim from the snapshot's epoch. Refresh both before accepting reuse;
- # agentsh setup and session replacement stay on the fresh-launch path so
- # reuse doesn't disrupt the running server or its agentsh session.
- self._write_required_file(BASH_ENV_SCRIPT, generate_bash_env_script().encode())
- self._write_required_file(GH_GUARD_INSTALL_PATH, read_gh_guard_script())
- self._chmod_required(GH_GUARD_INSTALL_PATH, "+x")
- logger.info(f"Agent-server already healthy in sandbox {self.id}; skipping relaunch")
- return True
- self._free_agent_server_port()
- return False
+ def _install_agent_server_launch_files(self) -> tuple[str, ...]:
+ return ()
+
+ def _on_agent_server_reused(self) -> None:
+ # A restored snapshot can carry a healthy agent-server with a stale bash-env
+ # or gh shim from the snapshot's epoch. Refresh both before accepting reuse;
+ # agentsh setup and session replacement stay on the fresh-launch path so
+ # reuse doesn't disrupt the running server or its agentsh session.
+ self._write_required_file(BASH_ENV_SCRIPT, generate_bash_env_script().encode())
+ self._write_required_file(GH_GUARD_INSTALL_PATH, read_gh_guard_script())
+ self._chmod_required(GH_GUARD_INSTALL_PATH, "+x")
def _prepare_agent_server_launch(self, allowed_domains: list[str] | None) -> None:
script_path = f"/tmp/posthog-launch-preparation-{uuid.uuid4().hex}.sh"
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index f919ba848eb3..39230cc330fb 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -371,6 +371,33 @@ def build_agent_runtime_env_prefix(
return f"env {body} " if body else ""
+AGENT_SERVER_BINARY_PATH = "/scripts/node_modules/.bin/agent-server"
+
+AGENT_SERVER_CAPABILITY_TOKENS: dict[str, str] = {
+ "auto_publish": "autoPublish",
+ "exec_permission_regex": "posthogExecPermissionRegex",
+ "pi_runtime": "POSTHOG_AGENT_RUNTIME",
+ "prewarmed_resume_message_driven": "prewarmedResumeMessageDriven",
+}
+
+
+def build_bundled_skills_clear_command() -> str:
+ """Delete the bundled skill folders when the sandbox environment asks for it.
+
+ The check runs inside the sandbox: a sandbox rehydrated by id carries no config env
+ vars, but the container environment still holds the value the launcher set.
+ """
+ paths = " ".join(shlex.quote(path) for path in BUNDLED_SKILLS_PATHS)
+ return f'if [ "${ENV_DISABLE_BUNDLED_SKILLS}" = "1" ]; then rm -rf {paths} && mkdir -p {paths}; fi'
+
+
+def build_agent_server_capability_probe(capability: str) -> str:
+ """Sandboxes restored from old snapshots can carry an agent-server that rejects unknown
+ CLI options, so probe the installed binary before passing a flag such as --autoPublish;
+ unsupported binaries degrade instead of crashing at launch."""
+ return f"grep -q {shlex.quote(AGENT_SERVER_CAPABILITY_TOKENS[capability])} {AGENT_SERVER_BINARY_PATH}"
+
+
class SandboxBase(ABC):
id: str
config: SandboxConfig
@@ -498,42 +525,9 @@ class SandboxBase(ABC):
)
return False
- def clear_bundled_skills_if_disabled(self) -> None:
- """Delete the bundled skill folders when the sandbox environment asks for it.
-
- The check runs inside the sandbox: a sandbox rehydrated by id carries no config env
- vars, but the container environment still holds the value the launcher set.
- """
- paths = " ".join(shlex.quote(path) for path in BUNDLED_SKILLS_PATHS)
- command = f'if [ "${ENV_DISABLE_BUNDLED_SKILLS}" = "1" ]; then rm -rf {paths} && mkdir -p {paths}; fi'
- result = self.execute(command, timeout_seconds=30)
- if result.exit_code != 0:
- raise RuntimeError(f"Failed to clear bundled skills in sandbox {self.id}: {result.stderr}")
-
- def agent_server_supports_auto_publish(self) -> bool:
- """Sandboxes restored from old snapshots can carry an agent-server that rejects unknown
- CLI options, so probe the installed binary before passing --autoPublish; unsupported
- binaries degrade to review-first instead of crashing at launch."""
- result = self.execute("grep -q autoPublish /scripts/node_modules/.bin/agent-server", timeout_seconds=10)
- return result.exit_code == 0
-
- def agent_server_supports_exec_permission_regex(self) -> bool:
- result = self.execute(
- "grep -q posthogExecPermissionRegex /scripts/node_modules/.bin/agent-server", timeout_seconds=10
- )
- return result.exit_code == 0
-
- def agent_server_supports_pi_runtime(self) -> bool:
- result = self.execute(
- "grep -q POSTHOG_AGENT_RUNTIME /scripts/node_modules/.bin/agent-server",
- timeout_seconds=10,
- )
- return result.exit_code == 0
-
def agent_server_supports_prewarmed_resume_message_driven(self) -> bool:
result = self.execute(
- "grep -q prewarmedResumeMessageDriven /scripts/node_modules/.bin/agent-server",
- timeout_seconds=10,
+ build_agent_server_capability_probe("prewarmed_resume_message_driven"), timeout_seconds=10
)
return result.exit_code == 0
diff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.py
index 4de9fff5b264..587914a4c672 100644
--- a/products/tasks/backend/logic/services/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py
@@ -11,6 +11,10 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
from products.tasks.backend.exceptions import ProcessTaskError, SandboxExecutionError, SandboxProvisionError
+from products.tasks.backend.logic.services.agent_server_launcher import (
+ AGENT_SERVER_LAUNCH_CAPABILITIES,
+ AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX,
+)
from products.tasks.backend.logic.services.docker_sandbox import DockerSandbox
from products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLS, ENV_LOCAL_SKILLS_HOST_PATH
from products.tasks.backend.logic.services.sandbox import (
@@ -40,6 +44,10 @@ def _agent_server_launch_command(mock_execute: Any) -> str:
raise AssertionError("agent-server launch command not found among execute calls")
+def _preflight_stdout(capabilities: tuple[str, ...] = AGENT_SERVER_LAUNCH_CAPABILITIES) -> str:
+ return "\n".join(f"{AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX}{capability}" for capability in capabilities)
+
+
def docker_available() -> bool:
try:
result = subprocess.run(["docker", "info"], capture_output=True, timeout=5)
@@ -529,12 +537,10 @@ class TestDockerSandboxUnit:
patch.object(
sandbox, "write_file", return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
),
- patch.object(sandbox, "agent_server_supports_auto_publish", return_value=True),
- patch.object(sandbox, "agent_server_supports_pi_runtime", return_value=True),
patch.object(sandbox, "execute") as mock_execute,
patch.object(sandbox, "_launch_and_check", side_effect=[False, True]) as launch,
):
- mock_execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
+ mock_execute.return_value = ExecutionResult(stdout=_preflight_stdout(), stderr="", exit_code=0, error=None)
sandbox.start_agent_server(
"posthog/posthog",
"task-123",
@@ -566,7 +572,6 @@ class TestDockerSandboxUnit:
patch.object(
sandbox, "execute", return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
),
- patch.object(sandbox, "agent_server_supports_pi_runtime", return_value=False),
pytest.raises(RuntimeError, match="does not support the Pi runtime"),
):
sandbox.start_agent_server(
@@ -679,7 +684,9 @@ class TestDockerSandboxUnit:
clear_index = next(
index for index, command in enumerate(commands) if "rm -rf" in command and "skills" in command
)
- launch_index = next(index for index, command in enumerate(commands) if "agent-server" in command)
+ launch_index = next(
+ index for index, command in enumerate(commands) if "./node_modules/.bin/agent-server" in command
+ )
assert clear_index < launch_index
def test_start_agent_server_without_domains_skips_agentsh(self):
@@ -822,7 +829,9 @@ class TestDockerSandboxUnit:
with patch.object(sandbox, "is_running", return_value=True):
with patch.object(sandbox, "execute") as mock_execute:
- mock_execute.return_value = ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None)
+ mock_execute.return_value = ExecutionResult(
+ stdout=_preflight_stdout(), stderr="", exit_code=0, error=None
+ )
sandbox.start_agent_server(
"posthog/posthog",
"task-123",
diff --git a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
index 5667c797313d..7e847506a430 100644
--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
@@ -9,6 +9,10 @@ from parameterized import parameterized
from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEX
from products.tasks.backend.exceptions import SandboxExecutionError
+from products.tasks.backend.logic.services.agent_server_launcher import (
+ AGENT_SERVER_LAUNCH_CAPABILITIES,
+ AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX,
+)
from products.tasks.backend.logic.services.docker_sandbox import DockerSandbox
from products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLS
from products.tasks.backend.logic.services.sandbox import ExecutionResult, SandboxConfig
@@ -28,6 +32,11 @@ def _ok_result() -> ExecutionResult:
return ExecutionResult(stdout="", stderr="", exit_code=0)
+def _preflight_result(capabilities: tuple[str, ...] = AGENT_SERVER_LAUNCH_CAPABILITIES) -> ExecutionResult:
+ markers = "\n".join(f"{AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX}{capability}" for capability in capabilities)
+ return ExecutionResult(stdout=markers, stderr="", exit_code=0)
+
+
@pytest.mark.parametrize(
("capabilities", "expected"),
[
@@ -142,12 +151,17 @@ def test_build_agent_server_command_gates_connected_project_operations(sandbox:
assert "--posthogExecPermissionRegex" not in without_flag
-def test_start_agent_server_launch_failure_is_captured(sandbox: DockerSandbox):
[email protected]([("supported", AGENT_SERVER_LAUNCH_CAPABILITIES), ("unsupported", ())])
+def test_start_agent_server_launch_failure_is_captured(_name: str, capabilities: tuple[str, ...]):
+ config = SandboxConfig(name="test-sandbox")
+ sandbox = DockerSandbox(container_id="c" * 64, config=config, host_port=8000)
failed = ExecutionResult(stdout="", stderr="boom", exit_code=1)
def execute(command: str, **kwargs) -> ExecutionResult:
# Only the launch fails; the bundled-skills clear and the launch prep that precede it succeed.
- if ENV_DISABLE_BUNDLED_SKILLS in command or command.startswith("chmod "):
+ if ENV_DISABLE_BUNDLED_SKILLS in command:
+ return _preflight_result(capabilities)
+ if command.startswith("chmod "):
return _ok_result()
return failed
@@ -155,7 +169,6 @@ def test_start_agent_server_launch_failure_is_captured(sandbox: DockerSandbox):
patch.object(sandbox, "is_running", return_value=True),
patch.object(sandbox, "write_file", return_value=_ok_result()),
patch.object(sandbox, "_build_agent_server_command", return_value="run-agent-server") as build_command,
- patch.object(sandbox, "agent_server_supports_exec_permission_regex", return_value=True),
patch.object(sandbox, "execute", side_effect=execute),
patch("products.tasks.backend.exceptions.capture_exception") as capture_exception,
pytest.raises(SandboxExecutionError),
@@ -164,7 +177,8 @@ def test_start_agent_server_launch_failure_is_captured(sandbox: DockerSandbox):
# A genuine non-zero launch is a real fault — it still gets captured.
capture_exception.assert_called_once()
- assert build_command.call_args.kwargs["posthog_exec_permission_regex"] == POSTHOG_EXEC_PERMISSION_REGEX
+ expected_regex = POSTHOG_EXEC_PERMISSION_REGEX if capabilities else None
+ assert build_command.call_args.kwargs["posthog_exec_permission_regex"] == expected_regex
@parameterized.expand([("empty", b""), ("with_content", b"GITHUB_TOKEN=ghs_x\x00")])
diff --git a/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.py b/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.py
index 4ed45132b42a..e117ce57c459 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.py
@@ -10,6 +10,7 @@ import pytest
from unittest.mock import MagicMock, patch
from products.tasks.backend.exceptions import SandboxExecutionError
+from products.tasks.backend.logic.services.agent_server_launcher import AgentServerPreflight
from products.tasks.backend.logic.services.agentsh import (
BASH_ENV_SCRIPT,
ENV_WRAPPER_SCRIPT,
@@ -196,8 +197,6 @@ def test_failed_preparation_never_launches_agent_server(failure: str, log_availa
return ExecutionResult(stdout="", stderr="", exit_code=0)
with (
- patch.object(sandbox, "_agent_server_is_healthy", return_value=False),
- patch.object(sandbox, "_free_agent_server_port"),
patch.object(sandbox, "execute", side_effect=execute) as remote_execute,
patch.object(
sandbox,
@@ -261,8 +260,9 @@ def test_preparation_metric_measures_only_upload_and_execution(export_fails: boo
patch("products.tasks.backend.logic.services.modal_sandbox.time") as clock,
patch("products.tasks.backend.logic.services.launch_preparation_metrics.metric_meter") as metric_meter,
patch.object(sandbox, "is_running", return_value=True),
- patch.object(sandbox, "clear_bundled_skills_if_disabled"),
- patch.object(sandbox, "_agent_server_is_healthy", return_value=True),
+ patch.object(
+ sandbox, "_agent_server_preflight", return_value=AgentServerPreflight(reused=True, capabilities=frozenset())
+ ),
):
clock.monotonic.side_effect = [10.0, 10.5, 11.25]
if export_fails:
diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
index f7f0a73bec25..156202b8f794 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -43,6 +43,9 @@ from products.tasks.backend.exceptions import (
)
from products.tasks.backend.logic.services.agent_server_launcher import (
AGENT_SERVER_HEALTH_MAX_ATTEMPTS,
+ AGENT_SERVER_LAUNCH_CAPABILITIES,
+ AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX,
+ AGENT_SERVER_PREFLIGHT_REUSE_MARKER,
HOST_PRESSURE_PROBE_SCRIPT,
STARTUP_LOG_MAX_BYTES,
_egress_failure_reason,
@@ -98,6 +101,17 @@ def _agent_server_launch_command(mock_execute: Any) -> str:
raise AssertionError("agent-server launch command not found among execute calls")
+def _is_preflight_command(command: str) -> bool:
+ return AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX in command
+
+
+def _preflight_stdout(*, reused: bool = False, capabilities: tuple[str, ...] = AGENT_SERVER_LAUNCH_CAPABILITIES) -> str:
+ lines = [f"{AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX}{capability}" for capability in capabilities]
+ if reused:
+ lines.append(AGENT_SERVER_PREFLIGHT_REUSE_MARKER)
+ return "\n".join(lines)
+
+
def _mock_token_response(status_code: int = 200, token: str | None = "test-token"):
resp = MagicMock()
resp.status_code = status_code
@@ -461,14 +475,6 @@ class TestModalSandboxAgentServer:
with patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()):
return ModalSandbox(sandbox=mock_modal_sandbox, config=config)
- @pytest.fixture(autouse=True)
- def _bypass_start_guard(self):
- with (
- patch.object(ModalSandbox, "_agent_server_is_healthy", return_value=False),
- patch.object(ModalSandbox, "_free_agent_server_port"),
- ):
- yield
-
def test_get_connect_credentials_success(self, mock_sandbox: Any):
result = mock_sandbox.get_connect_credentials()
@@ -615,7 +621,9 @@ class TestModalSandboxAgentServer:
clear_index = next(
index for index, command in enumerate(commands) if "rm -rf" in command and "skills" in command
)
- launch_index = next(index for index, command in enumerate(commands) if "agent-server" in command)
+ launch_index = next(
+ index for index, command in enumerate(commands) if "./node_modules/.bin/agent-server" in command
+ )
assert clear_index < launch_index
def test_start_agent_server_clears_bundled_skills_even_when_the_server_is_already_healthy(
@@ -627,20 +635,19 @@ class TestModalSandboxAgentServer:
environment_variables={ENV_DISABLE_BUNDLED_SKILLS: "1"},
)
mock_sandbox.execute = MagicMock(
- return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
+ return_value=ExecutionResult(stdout=_preflight_stdout(reused=True), stderr="", exit_code=0, error=None),
)
- with patch.object(mock_sandbox, "_agent_server_is_healthy", return_value=True):
- mock_sandbox.start_agent_server(
- repository="posthog/posthog",
- task_id="task-123",
- run_id="run-456",
- wait_for_health=False,
- )
+ mock_sandbox.start_agent_server(
+ repository="posthog/posthog",
+ task_id="task-123",
+ run_id="run-456",
+ wait_for_health=False,
+ )
commands = [call.args[0] for call in mock_sandbox.execute.call_args_list]
assert any("rm -rf" in command and "skills" in command for command in commands)
- assert not any("agent-server" in command for command in commands)
+ assert not any("./node_modules/.bin/agent-server" in command for command in commands)
def test_start_agent_server_waits_for_repository_before_launch(self, mock_sandbox: Any):
mock_sandbox.execute = MagicMock(
@@ -732,7 +739,7 @@ class TestModalSandboxAgentServer:
def test_start_agent_server_includes_runtime_environment_variables(self, mock_sandbox: Any):
mock_sandbox.execute = MagicMock(
- return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
+ return_value=ExecutionResult(stdout=_preflight_stdout(), stderr="", exit_code=0, error=None),
)
mock_sandbox.start_agent_server(
@@ -942,10 +949,11 @@ class TestModalSandboxAgentServer:
assert mock_sandbox.execute.call_count == 1
def test_start_agent_server_skips_relaunch_when_already_healthy(self, mock_sandbox: Any):
- mock_sandbox.execute = MagicMock(return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None))
+ mock_sandbox.execute = MagicMock(
+ return_value=ExecutionResult(stdout=_preflight_stdout(reused=True), stderr="", exit_code=0, error=None)
+ )
with (
- patch.object(mock_sandbox, "_agent_server_is_healthy", return_value=True),
patch.object(mock_sandbox, "_agentsh_daemon_is_healthy", return_value=True),
patch.object(mock_sandbox, "wait_for_agent_server_ready") as wait_for_ready,
patch.object(mock_sandbox, "_free_agent_server_port") as mock_free,
@@ -969,12 +977,14 @@ class TestModalSandboxAgentServer:
assert any(command == "chmod +x /opt/posthog/bin/gh" for command in commands[1:])
def test_start_agent_server_relaunches_when_agentsh_is_unhealthy(self, mock_sandbox: Any):
- mock_sandbox.execute = MagicMock(
- return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- )
+ def execute(command: str, timeout_seconds: int | None = None) -> ExecutionResult:
+ if _is_preflight_command(command):
+ return ExecutionResult(stdout=_preflight_stdout(reused=True), stderr="", exit_code=0, error=None)
+ return ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None)
+
+ mock_sandbox.execute = MagicMock(side_effect=execute)
with (
- patch.object(mock_sandbox, "_agent_server_is_healthy", return_value=True),
patch.object(mock_sandbox, "_agentsh_daemon_is_healthy", side_effect=[False, True]),
patch.object(mock_sandbox, "_prepare_agent_server_launch") as mock_setup_agentsh,
patch.object(mock_sandbox, "wait_for_agent_server_ready") as wait_for_ready,
@@ -1016,12 +1026,34 @@ class TestModalSandboxAgentServer:
mode="background",
)
- mock_sandbox._free_agent_server_port.assert_called_once_with()
+ commands = [call.args[0] for call in mock_sandbox.execute.call_args_list]
+ preflight = next(command for command in commands if _is_preflight_command(command))
+ assert "xargs kill -KILL" in preflight
+ assert commands.index(preflight) < commands.index(_agent_server_launch_command(mock_sandbox.execute))
command = _agent_server_launch_command(mock_sandbox.execute)
assert health_ms == 250
assert "nohup" in command
assert "http://localhost:8080/health" in command
+ def test_start_agent_server_runs_one_preflight_exec_before_the_launch(self, mock_sandbox: Any):
+ mock_sandbox.execute = MagicMock(
+ return_value=ExecutionResult(stdout=_preflight_stdout(), stderr="", exit_code=0, error=None)
+ )
+ mock_sandbox.write_file = MagicMock(return_value=ExecutionResult(stdout="", stderr="", exit_code=0))
+
+ mock_sandbox.start_agent_server(
+ repository="posthog/posthog",
+ task_id="task-123",
+ run_id="run-456",
+ wait_for_health=False,
+ )
+
+ commands = [call.args[0] for call in mock_sandbox.execute.call_args_list]
+ launch_index = commands.index(_agent_server_launch_command(mock_sandbox.execute))
+ assert launch_index == 2
+ assert _is_preflight_command(commands[0])
+ assert commands[1].startswith("bash /tmp/posthog-launch-preparation-")
+
def test_create_snapshot_waits_for_container_before_snapshot(self, mock_sandbox: Any) -> None:
events: list[str] = []
exec_process = MagicMock()
@@ -1248,8 +1280,6 @@ class TestModalSandboxCommandEscaping:
with (
patch.object(sandbox, "is_running", return_value=True),
patch.object(sandbox, "_prepare_agent_server_launch"),
- patch.object(sandbox, "_agent_server_is_healthy", return_value=False),
- patch.object(sandbox, "_free_agent_server_port"),
patch.object(sandbox, "execute") as mock_execute,
patch.object(sandbox, "_wait_for_health_check", return_value=True),
):
@@ -1350,22 +1380,6 @@ class TestModalSandboxAgentServerStartupHelpers:
sandbox._sandbox = MagicMock()
return sandbox
- @pytest.mark.parametrize(
- "exit_code,expected",
- [
- (0, True),
- (1, False),
- ],
- )
- def test_agent_server_is_healthy(self, exit_code: int, expected: bool):
- sandbox = self._make_sandbox()
- sandbox.execute = MagicMock(
- return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=exit_code, error=None)
- )
-
- assert sandbox._agent_server_is_healthy() is expected
- assert sandbox.execute.call_count == 1
-
def test_free_agent_server_port_terminates_existing_process(self):
sandbox = self._make_sandbox()
sandbox.execute = MagicMock(return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None))
@@ -1373,8 +1387,8 @@ class TestModalSandboxAgentServerStartupHelpers:
sandbox._free_agent_server_port()
command = sandbox.execute.call_args_list[0][0][0]
- assert "pkill -TERM -f '[a]gent-server'" in command
- assert "pkill -KILL -f '[a]gent-server'" in command
+ assert "xargs kill -TERM" in command
+ assert "xargs kill -KILL" in command
class TestStartupFailureDiagnostics:
diff --git a/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py b/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py
index 778a688befef..142e12418714 100644
--- a/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py
+++ b/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py
@@ -5,7 +5,17 @@ from pathlib import Path
import pytest
-from products.tasks.backend.logic.services.sandbox import build_health_check_command, health_check_budget_seconds
+from products.tasks.backend.logic.services.agent_server_launcher import (
+ AGENT_SERVER_LAUNCH_CAPABILITIES,
+ AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX,
+ AGENT_SERVER_PREFLIGHT_REUSE_MARKER,
+ build_agent_server_preflight_script,
+)
+from products.tasks.backend.logic.services.sandbox import (
+ AGENT_SERVER_CAPABILITY_TOKENS,
+ build_health_check_command,
+ health_check_budget_seconds,
+)
def _path_with_fake_curl(tmp_path: Path, body: str, delay_seconds: float) -> dict[str, str]:
@@ -40,3 +50,78 @@ def test_health_check_loop_stops_at_wall_clock_budget(tmp_path, body, expected_e
assert completed.returncode == expected_exit_code
assert completed.stdout.strip() == expected_stdout
assert elapsed < budget + poll_delay + poll_interval + 2
+
+
+def _run_preflight(tmp_path: Path, health_body: str, capability_tokens: str) -> subprocess.CompletedProcess[str]:
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ fakes = {
+ "curl": f"printf '%s' '{health_body}'",
+ "grep": 'case " $FAKE_CAPABILITIES " in *" $2 "*) exit 0;; esac\nexit 1',
+ "kill": f'echo "$@" >> {tmp_path}/kill.log',
+ "pgrep": f"if [ -e {tmp_path}/pgrep.seen ]; then exit 1; fi; touch {tmp_path}/pgrep.seen; echo 424242",
+ }
+ for name, body in fakes.items():
+ fake = bin_dir / name
+ fake.write_text(f"#!/bin/bash\n{body}\n")
+ fake.chmod(0o755)
+ guard = tmp_path / "gh"
+ guard.write_text("#!/bin/bash\n")
+ script = build_agent_server_preflight_script(probe_health=True, executable_paths=(str(guard),))
+ return subprocess.run(
+ ["bash", "-c", script],
+ env={
+ **os.environ,
+ "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}",
+ "FAKE_CAPABILITIES": capability_tokens,
+ },
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+
+
+def test_preflight_reuses_a_healthy_agent_server_without_freeing_the_port(tmp_path: Path) -> None:
+ completed = _run_preflight(tmp_path, '{"status":"ok","hasSession":true}', "")
+
+ assert completed.returncode == 0
+ assert AGENT_SERVER_PREFLIGHT_REUSE_MARKER in completed.stdout.splitlines()
+ assert not (tmp_path / "kill.log").exists()
+ assert os.access(tmp_path / "gh", os.X_OK)
+
+
+def test_preflight_frees_the_port_when_no_healthy_agent_server_answers(tmp_path: Path) -> None:
+ completed = _run_preflight(tmp_path, '{"status":"ok","hasSession":false}', "")
+
+ assert completed.returncode == 0
+ assert AGENT_SERVER_PREFLIGHT_REUSE_MARKER not in completed.stdout.splitlines()
+ assert (tmp_path / "kill.log").read_text().splitlines() == ["-TERM 424242"]
+
+
+def test_preflight_does_not_kill_its_own_shell_when_freeing_the_port(tmp_path: Path) -> None:
+ env = _path_with_fake_curl(tmp_path, "", 0.0)
+ kill = tmp_path / "kill"
+ kill.write_text(f'#!/bin/bash\necho "$@" >> {tmp_path}/kill.log\n')
+ kill.chmod(0o755)
+ script = build_agent_server_preflight_script(probe_health=True, executable_paths=())
+
+ completed = subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, timeout=60)
+
+ assert completed.returncode == 0, completed.stderr
+ assert not (tmp_path / "kill.log").exists()
+
+
[email protected]("capabilities", [(), ("auto_publish",), AGENT_SERVER_LAUNCH_CAPABILITIES])
+def test_preflight_reports_only_the_capabilities_the_binary_carries(
+ tmp_path: Path, capabilities: tuple[str, ...]
+) -> None:
+ tokens = " ".join(AGENT_SERVER_CAPABILITY_TOKENS[capability] for capability in capabilities)
+
+ completed = _run_preflight(tmp_path, '{"status":"ok","hasSession":false}', tokens)
+
+ reported = [
+ line.removeprefix(AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX)
+ for line in completed.stdout.splitlines()
+ if line.startswith(AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX)
+ ]
+ assert sorted(reported) == sorted(capabilities)
diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.py
index 0106be028483..e3fc7a2af238 100644
--- a/products/tasks/backend/tests/test_agentsh.py
+++ b/products/tasks/backend/tests/test_agentsh.py
@@ -573,6 +573,10 @@ class TestModalSandboxAgentShWrapping(TestCase):
]
)
def test_start_agent_server_drops_auto_publish_when_binary_lacks_support(self, provider, supported):
+ from products.tasks.backend.logic.services.agent_server_launcher import (
+ AGENT_SERVER_LAUNCH_CAPABILITIES,
+ AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX,
+ )
from products.tasks.backend.logic.services.docker_sandbox import DockerSandbox
from products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLS
from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
@@ -581,6 +585,14 @@ class TestModalSandboxAgentShWrapping(TestCase):
# Snapshots restored from old images carry an agent-server that rejects unknown
# options; the launch probe must drop --autoPublish instead of crashing the run.
launched: list[str] = []
+ markers = (
+ "\n".join(
+ f"{AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX}{capability}"
+ for capability in AGENT_SERVER_LAUNCH_CAPABILITIES
+ )
+ if supported
+ else ""
+ )
def execute(command: str, timeout_seconds: int | None = None) -> ExecutionResult:
if "--taskId" in command:
@@ -590,10 +602,9 @@ class TestModalSandboxAgentShWrapping(TestCase):
return ExecutionResult(stdout="", stderr="", exit_code=0)
if command.startswith("bash /tmp/posthog-launch-preparation-"):
return ExecutionResult(stdout="", stderr="", exit_code=0)
- if ENV_DISABLE_BUNDLED_SKILLS in command: # bundled-skills clear
- return ExecutionResult(stdout="", stderr="", exit_code=0)
- self.assertIn("grep", command)
- return ExecutionResult(stdout="", stderr="", exit_code=0 if supported else 1)
+ self.assertIn(ENV_DISABLE_BUNDLED_SKILLS, command)
+ self.assertIn("grep -q autoPublish", command)
+ return ExecutionResult(stdout=markers, stderr="", exit_code=0)
sandbox: ModalSandbox | DockerSandbox
if provider == "modal":
@@ -605,8 +616,6 @@ class TestModalSandboxAgentShWrapping(TestCase):
sandbox.config = SandboxConfig(name="sb-test")
cast_sandbox: Any = sandbox
cast_sandbox.is_running = Mock(return_value=True)
- cast_sandbox._agent_server_is_healthy = Mock(return_value=False)
- cast_sandbox._free_agent_server_port = Mock()
cast_sandbox.write_file = Mock(
return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
)