: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): report why a sandbox agent-server launch timed out (#98043)
Charles Viend63ea6cb5254
diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.pyindex a450842065bd..117cccd6f654 100644--- a/products/tasks/backend/logic/services/agent_server_launcher.py+++ b/products/tasks/backend/logic/services/agent_server_launcher.py@@ -17,7 +17,7 @@ from typing import TYPE_CHECKINGfrom django.conf import settingsfrom products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEX, SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS-from products.tasks.backend.exceptions import ProcessTaskFatalError, SandboxExecutionError+from products.tasks.backend.exceptions import ProcessTaskFatalError, SandboxExecutionError, SandboxTimeoutErrorfrom products.tasks.backend.logic.services.agentsh import (AGENTSH_DAEMON_PORT,BASH_ENV_SCRIPT,@@ -50,6 +50,8 @@ logger = logging.getLogger(__name__)AGENT_SERVER_PORT = 8080 # Modal connect tokens require port 8080AGENT_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 * 1024AGENT_SERVER_HEALTH_DURATION_PREFIX = "__posthog_agent_health_ms="SESSION_INIT_PROBE_HOSTS = (@@ -240,8 +242,13 @@ class AgentServerLaunchMixin(SandboxBase):return diagnosticsdiagnostics["sandbox_terminated"] = "false"- log_result = self.execute("cat /tmp/agent-server.log 2>/dev/null || echo 'No log file'", timeout_seconds=5)+ log_result = self.execute(+ f"tail -c {STARTUP_LOG_MAX_BYTES} /tmp/agent-server.log 2>/dev/null || echo 'No log file'",+ timeout_seconds=5,+ )diagnostics["log"] = log_result.stdout+ if len(log_result.stdout.encode()) >= STARTUP_LOG_MAX_BYTES:+ diagnostics["log_truncated"] = "true"health_result = self.execute(f"curl -s --max-time 3 http://localhost:{AGENT_SERVER_PORT}/health || echo 'no-health-response'",timeout_seconds=5,@@ -396,7 +403,12 @@ class AgentServerLaunchMixin(SandboxBase):execute_command = _start_and_wait_command(command, max_attempts) if wait_for_health else commandtimeout_seconds = 30 + health_check_timeout_seconds(max_attempts) if wait_for_health else 30start_time = time.perf_counter()- launch_result = self.execute(execute_command, timeout_seconds=timeout_seconds)+ try:+ launch_result = self.execute(execute_command, timeout_seconds=timeout_seconds)+ except SandboxTimeoutError as error:+ if not wait_for_health:+ raise+ raise self._startup_timeout_with_diagnostics(allowed_domains, timeout_seconds) from errorstart_and_health_ms = int((time.perf_counter() - start_time) * 1000)if launch_result.exit_code != 0:health_duration_ms = _health_duration_ms(launch_result.stdout)@@ -444,7 +456,13 @@ class AgentServerLaunchMixin(SandboxBase):self, allowed_domains: list[str] | None = None, *, claude_model_access: str | None = None) -> None:max_attempts = 300 if claude_model_access == "own-subscription" else AGENT_SERVER_HEALTH_MAX_ATTEMPTS- if self._wait_for_health_check(max_attempts=max_attempts):+ try:+ healthy = self._wait_for_health_check(max_attempts=max_attempts)+ except SandboxTimeoutError as error:+ raise self._startup_timeout_with_diagnostics(+ allowed_domains, health_check_timeout_seconds(max_attempts)+ ) from error+ if healthy:if allowed_domains is not None and not self._agentsh_daemon_is_healthy():raise SandboxExecutionError("Failed to verify agentsh network enforcement",@@ -460,6 +478,22 @@ class AgentServerLaunchMixin(SandboxBase):cause=RuntimeError(diagnostics.get("failure_reason", "Health check failed after retries")),)+ def _startup_timeout_with_diagnostics(+ self, allowed_domains: list[str] | None, timeout_seconds: int+ ) -> SandboxTimeoutError:+ diagnostics = self._diagnose_startup_failure(allowed_domains)+ logger.warning(+ "Agent-server health poll timed out in sandbox %s after %ss: %s",+ self.id,+ timeout_seconds,+ diagnostics.get("failure_reason"),+ )+ return SandboxTimeoutError(+ "Agent-server failed to start",+ {"sandbox_id": self.id, "timeout_seconds": timeout_seconds, **diagnostics},+ cause=RuntimeError(diagnostics.get("failure_reason", f"health poll exceeded {timeout_seconds}s")),+ )+def mark_repo_ready(self, repo_ready_file: str) -> None:self.execute(f"touch {shlex.quote(repo_ready_file)}", timeout_seconds=10)diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex cd7dad79f819..899dc57394d4 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -105,6 +105,9 @@ STREAMLIT_MODAL_APP_NAME = "posthog-sandbox-streamlit"SELF_DRIVING_MODAL_APP_NAME = "posthog-sandbox-self-driving"+# The Modal SDK reports an exec that outlives its `timeout` as this return code instead of raising.+MODAL_EXEC_TIMEOUT_RETURNCODE = -1+SANDBOX_BASE_IMAGE = "ghcr.io/posthog/posthog-sandbox-base"SANDBOX_NOTEBOOK_IMAGE = "ghcr.io/posthog/posthog-sandbox-notebook"SANDBOX_VM_IMAGE = "ghcr.io/posthog/posthog-sandbox-vm"@@ -1046,8 +1049,21 @@ class ModalSandbox(AgentServerLaunchMixin):error=None,)+ if result.exit_code == MODAL_EXEC_TIMEOUT_RETURNCODE:+ # Not captured: the launcher re-raises this with startup diagnostics and captures that instead.+ raise SandboxTimeoutError(+ f"Execution timed out after {timeout_seconds} seconds",+ {"sandbox_id": self.id, "timeout_seconds": timeout_seconds, "command": redacted_command},+ cause=TimeoutError(+ f"exec returned {MODAL_EXEC_TIMEOUT_RETURNCODE} after {timeout_seconds} seconds"+ ),+ capture=False,+ )+return result+ except SandboxTimeoutError:+ raiseexcept TimeoutError as e:capture_exception(e)raise SandboxTimeoutError(diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex f466ee7b27a5..6e96acb374ec 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -799,6 +799,9 @@ def wait_for_health_check(return False+HEALTH_CURL_MAX_TIME_SECONDS = 2++def build_health_check_command(port: int, max_attempts: int = 60, poll_interval: float = 0.5, pid_file: str | None = None) -> str:@@ -807,10 +810,14 @@ def build_health_check_command(if pid_file is not Noneelse "")+ # The attempt count assumes an instant poll. A poll that waits on curl or python startup+ # would otherwise outrun the exec timeout, and the caller never sees the loop's result.+ budget_seconds = health_check_budget_seconds(max_attempts, poll_interval)return (- f"for i in $(seq 1 {max_attempts}); do "+ "SECONDS=0; i=0; while :; do "+ " i=$((i + 1)); "f"{process_check}"- f" body=$(curl -s --max-time 2 http://localhost:{port}/health); "+ f" body=$(curl -s --max-time {HEALTH_CURL_MAX_TIME_SECONDS} http://localhost:{port}/health); "" status=$?; "' if [ "$status" = "0" ]; then '' case "$body" in *claude_credential_unavailable*) echo "claude_credential_unavailable"; exit 1;; esac; '@@ -820,14 +827,18 @@ def build_health_check_command('sys.exit(0 if payload.get("status") == "ok" and payload.get("hasSession") is True else 1)'f'\' "$body" && echo "ok:$i" && exit 0; '" fi; "+ f' if [ "$i" -ge {max_attempts} ] || [ "$SECONDS" -ge {budget_seconds} ]; then exit 1; fi; 'f" sleep {poll_interval}; "- f"done; "- f"exit 1"+ "done")+def health_check_budget_seconds(max_attempts: int = 60, poll_interval: float = 0.5) -> int:+ return int(max_attempts * poll_interval)++def health_check_timeout_seconds(max_attempts: int = 60, poll_interval: float = 0.5) -> int:- return max(30, int(max_attempts * poll_interval) + 5)+ return max(30, health_check_budget_seconds(max_attempts, poll_interval) + HEALTH_CURL_MAX_TIME_SECONDS + 5)SandboxClass = type[SandboxBase]diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex 2e6290c39356..bbb84d2c5992 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -25,10 +25,15 @@ from products.tasks.backend.exceptions import (SandboxExecutionError,SandboxNetworkPolicyError,SandboxProvisionError,+ SandboxTimeoutError,SnapshotCreationError,SnapshotFileLimitExceededError,SnapshotTimeoutError,)+from products.tasks.backend.logic.services.agent_server_launcher import (+ AGENT_SERVER_HEALTH_MAX_ATTEMPTS,+ STARTUP_LOG_MAX_BYTES,+)from products.tasks.backend.logic.services.local_packages import LocalPackagefrom products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLSfrom products.tasks.backend.logic.services.modal_provision_diagnostics import (@@ -59,6 +64,7 @@ from products.tasks.backend.logic.services.sandbox import (ExecutionResult,SandboxConfig,SandboxTemplate,+ health_check_timeout_seconds,)@@ -490,6 +496,59 @@ class TestModalSandboxAgentServer:assert "--mcpServers <redacted>" in exc.value.context["command"]assert "--mcpServers <redacted>" in exc.value.context["error"]+ def test_execute_raises_timeout_when_modal_reports_minus_one(self, mock_sandbox: Any):+ process = MagicMock(returncode=-1)+ process.wait.return_value = -1+ process.stdout.read.return_value = ""+ process.stderr.read.return_value = ""+ mock_sandbox._sandbox.exec.return_value = process++ with (+ patch("products.tasks.backend.exceptions.capture_exception") as capture_exception,+ pytest.raises(SandboxTimeoutError) as exc,+ ):+ mock_sandbox.execute("sleep 999", timeout_seconds=5)++ assert exc.value.context["timeout_seconds"] == 5+ capture_exception.assert_not_called()++ def test_start_agent_server_launch_timeout_carries_startup_diagnostics(self, mock_sandbox: Any):+ launch_timeout = SandboxTimeoutError(+ "Execution timed out after 155 seconds",+ {"sandbox_id": mock_sandbox.id},+ cause=TimeoutError("exec returned -1"),+ capture=False,+ )++ def _exec(command: str, timeout_seconds: Any = None) -> ExecutionResult:+ if "./node_modules/.bin/agent-server" in command:+ raise launch_timeout+ if command.startswith("SECONDS=0"):+ return ExecutionResult(stdout="", stderr="", exit_code=1, error=None)+ if "agent-server.log" in command:+ return ExecutionResult(stdout="", stderr="", exit_code=0, error=None)+ if "printf" in command:+ return ExecutionResult(+ stdout="gateway.us.posthog.com http_code=200", stderr="", exit_code=0, error=None+ )+ return ExecutionResult(stdout='{"status":"ok","hasSession":false}', stderr="", exit_code=0, error=None)++ mock_sandbox.execute = MagicMock(side_effect=_exec)++ with (+ patch("products.tasks.backend.exceptions.capture_exception") as capture_exception,+ pytest.raises(SandboxTimeoutError) as exc,+ ):+ mock_sandbox.start_agent_server(repository=None, task_id="task-1", run_id="run-1")++ assert exc.value.__cause__ is launch_timeout+ assert "never reported hasSession=true" in exc.value.context["failure_reason"]+ capture_exception.assert_called_once()+ assert "never reported hasSession=true" in str(capture_exception.call_args.args[0])+ assert exc.value.context["timeout_seconds"] == 30 + health_check_timeout_seconds(+ AGENT_SERVER_HEALTH_MAX_ATTEMPTS+ )+def test_start_agent_server_success_without_domains_skips_agentsh(self, mock_sandbox: Any):mock_sandbox.execute = MagicMock(return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),@@ -1374,6 +1433,36 @@ class TestStartupFailureDiagnostics:assert diagnostics["sandbox_terminated"] == "false"assert "never reported hasSession=true" in diagnostics["failure_reason"]+ @pytest.mark.parametrize(+ ("log_bytes", "expected_truncated"),+ [(120, None), (STARTUP_LOG_MAX_BYTES, "true")],+ )+ def test_bounds_the_agent_server_log(self, log_bytes: int, expected_truncated: str | None):+ sandbox = self._sandbox()+ log_commands: list[str] = []++ def _exec(command: str, timeout_seconds: Any = None) -> ExecutionResult:+ if "agent-server.log" in command:+ log_commands.append(command)+ return ExecutionResult(stdout="x" * log_bytes, stderr="", exit_code=0, error=None)+ if "printf" in command:+ return ExecutionResult(+ stdout="gateway.us.posthog.com http_code=200", stderr="", exit_code=0, error=None+ )+ return ExecutionResult(stdout="ok", stderr="", exit_code=0, error=None)++ with (+ patch.object(sandbox, "is_running", return_value=True),+ patch.object(sandbox, "execute", side_effect=_exec),+ ):+ diagnostics = sandbox._diagnose_startup_failure(allowed_domains=None)++ assert log_commands == [+ f"tail -c {STARTUP_LOG_MAX_BYTES} /tmp/agent-server.log 2>/dev/null || echo 'No log file'"+ ]+ assert len(diagnostics["log"]) == log_bytes+ assert diagnostics.get("log_truncated") == expected_truncated+class TestModalSandboxCreateAllowlist:def _create_with_config(self, config: SandboxConfig) -> Any: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.pynew file mode 100644index 000000000000..778a688befef--- /dev/null+++ b/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py@@ -0,0 +1,42 @@+import os+import time+import subprocess+from pathlib import Path++import pytest++from products.tasks.backend.logic.services.sandbox import build_health_check_command, health_check_budget_seconds+++def _path_with_fake_curl(tmp_path: Path, body: str, delay_seconds: float) -> dict[str, str]:+ curl = tmp_path / "curl"+ curl.write_text(f"#!/bin/bash\nsleep {delay_seconds}\nprintf '%s' '{body}'\n")+ curl.chmod(0o755)+ return {**os.environ, "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}"}+++ ("body", "expected_exit_code", "expected_stdout"),+ [+ ('{"status":"ok","hasSession":true}', 0, "ok:1"),+ ('{"status":"ok","hasSession":false}', 1, ""),+ ],+)+def test_health_check_loop_stops_at_wall_clock_budget(tmp_path, body, expected_exit_code, expected_stdout) -> None:+ max_attempts, poll_interval, poll_delay = 100, 0.01, 0.2+ env = _path_with_fake_curl(tmp_path, body, poll_delay)+ budget = health_check_budget_seconds(max_attempts, poll_interval)++ started = time.monotonic()+ completed = subprocess.run(+ ["bash", "-c", build_health_check_command(port=1, max_attempts=max_attempts, poll_interval=poll_interval)],+ env=env,+ capture_output=True,+ text=True,+ timeout=max_attempts * poll_delay,+ )+ elapsed = time.monotonic() - started++ assert completed.returncode == expected_exit_code+ assert completed.stdout.strip() == expected_stdout+ assert elapsed < budget + poll_delay + poll_interval + 2diff --git a/products/tasks/backend/temporal/process_task/README.md b/products/tasks/backend/temporal/process_task/README.mdindex 37664b15f2cd..fd20108c38c6 100644--- a/products/tasks/backend/temporal/process_task/README.md+++ b/products/tasks/backend/temporal/process_task/README.md@@ -168,7 +168,8 @@ If no token arrives within 120 seconds, the run fails with setup instructions.Subscription runs require the `--claudeSubscription` startup option.The launcher checks support before starting the process.-Subscription health checks have a 155-second command limit, leaving time for setup and diagnostics within the five-minute activity.+Health polls stop at a wall-clock budget (120 seconds, or 150 for subscription runs) even when each poll is slow, and the exec limit sits a few seconds above that budget, leaving time for setup and diagnostics within the five-minute activity.+When the exec limit is still hit, the launcher collects the same startup diagnostics as a failed poll and raises `SandboxTimeoutError` with them, because the Modal SDK reports an expired exec as return code -1 rather than raising.The PID check applies only when the PID file exists, so servers launched before deployment can still pass the health check.Continuation inherits the selected billing mode unless the caller explicitly changes it.Subscription runs do not reuse prewarmed sessions, because those processes have already selected their credentials.diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex 13774c6867c8..90661e8468cb 100644--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py@@ -89,6 +89,12 @@ def _emit_agent_server_log_tail(ctx: TaskProcessingContext, sandbox: SandboxBaselog_tail = result.stdout.strip()if log_tail:emit_agent_log(ctx.run_id, "debug", f"agent-server log tail:\n{log_tail}")+ else:+ emit_agent_log(+ ctx.run_id,+ "debug",+ "agent-server log tail: empty. The agent-server wrote nothing to /tmp/agent-server.log.",+ )def _resolve_protected_base_branch(ctx: TaskProcessingContext) -> str | None:diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.pyindex c874a6643740..18a08942d678 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py@@ -18,6 +18,7 @@ from products.tasks.backend.temporal.process_task.activities.start_agent_serverCollectAgentShadowResultInput,StartAgentServerInput,_agentsh_domains_for,+ _emit_agent_server_log_tail,_ensure_repository_on_disk,_include_personal_mcp_for_task,_invoke_start_agent_server,@@ -983,3 +984,21 @@ async def test_start_agent_server_passes_initial_permission_mode(mocker) -> Nonesandbox.start_agent_server.assert_called_once()assert sandbox.start_agent_server.call_args.kwargs["initial_permission_mode"] == "plan"+++ ("stdout", "expected_message"),+ [+ ("line one\nline two\n", "agent-server log tail:\nline one\nline two"),+ ("", "agent-server log tail: empty. The agent-server wrote nothing to /tmp/agent-server.log."),+ ],+)+def test_emit_agent_server_log_tail_reports_empty_log(mocker, stdout, expected_message) -> None:+ context = _context()+ sandbox = mocker.Mock(id="sandbox-id")+ sandbox.execute.return_value = ExecutionResult(stdout=stdout, stderr="", exit_code=0)+ emit = mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.emit_agent_log")++ _emit_agent_server_log_tail(context, sandbox)++ emit.assert_called_once_with(context.run_id, "debug", expected_message)