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): record host pressure when a sandbox agent-server fails to start (#98046)

Charles Vien6605e83ebe51
diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.py
index 117cccd6f654..ac4c55309000 100644
--- a/products/tasks/backend/logic/services/agent_server_launcher.py
+++ b/products/tasks/backend/logic/services/agent_server_launcher.py
@@ -54,6 +54,31 @@ AGENT_SERVER_HEALTH_MAX_ATTEMPTS = 240
STARTUP_LOG_MAX_BYTES = 64 * 1024
AGENT_SERVER_HEALTH_DURATION_PREFIX = "__posthog_agent_health_ms="
+# 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
+# the floor means no usable read, because the interpreter boot paged in would time fast, not cold.
+HOST_PRESSURE_COLD_READ_ROOTS = "/usr/lib/node_modules/typescript /usr/local/lib/node_modules/typescript"
+HOST_PRESSURE_COLD_READ_MIN_BYTES = 1024 * 1024
+HOST_PRESSURE_PROBE_SCRIPT = (
+ 'echo "loadavg=$(cat /proc/loadavg 2>/dev/null)"; '
+ 'echo "nproc=$(nproc 2>/dev/null)"; '
+ "for f in /proc/pressure/cpu /proc/pressure/io /proc/pressure/memory /sys/fs/cgroup/cpu.stat; do "
+ ' [ -r "$f" ] && echo "$f: $(tr \'\\n\' \' \' < "$f")"; '
+ "done; "
+ 'cpu_start=$(date +%s%3N); i=0; while [ "$i" -lt 200000 ]; do i=$((i+1)); done; '
+ 'echo "cpu_loop_ms=$(( $(date +%s%3N) - cpu_start ))"; '
+ "spawn_start=$(date +%s%3N); python3 -c pass; "
+ 'echo "python_spawn_ms=$(( $(date +%s%3N) - spawn_start ))"; '
+ f'probe_file="$(timeout 10 find {HOST_PRESSURE_COLD_READ_ROOTS} -type f '
+ '-printf "%s\\t%p\\n" 2>/dev/null | sort -rn | head -1 | cut -f2)"; '
+ 'probe_size="$(stat -c %s "$probe_file" 2>/dev/null || echo 0)"; '
+ f'if [ "$probe_size" -ge {HOST_PRESSURE_COLD_READ_MIN_BYTES} ]; then '
+ ' read_start=$(date +%s%3N); timeout 20 cat "$probe_file" > /dev/null; '
+ ' echo "cold_read_ms=$(( $(date +%s%3N) - read_start )) file=$probe_file size=$probe_size"; '
+ 'else echo "cold_read_ms=unavailable file=${probe_file:-none} size=$probe_size"; fi'
+)
+
SESSION_INIT_PROBE_HOSTS = (
"gateway.us.posthog.com",
"gateway.eu.posthog.com",
@@ -267,8 +292,23 @@ class AgentServerLaunchMixin(SandboxBase):
)
except Exception as e:
diagnostics.setdefault("failure_reason", f"health check failed; diagnostics unavailable: {e}")
+ # Last, and guarded on its own: a starved box can stall this probe too, and that must
+ # not replace the failure reason the checks above already produced.
+ try:
+ diagnostics["host_pressure"] = self._probe_host_pressure()
+ except Exception as e:
+ diagnostics["host_pressure"] = f"unavailable: {e}"
return diagnostics
+ def _probe_host_pressure(self) -> str:
+ """Measure the box, not the agent, so a startup failure can be told apart by cause.
+
+ A slow CPU loop or spawn means CPU starvation. A slow read of a file that boot never
+ touches means the image filesystem is slow to load it, which is what a lazily loaded
+ image looks like on a cold host. Both fast means the agent itself stalled.
+ """
+ return self.execute(HOST_PRESSURE_PROBE_SCRIPT, timeout_seconds=45).stdout.strip()
+
def _probe_session_init_egress(self) -> str:
hosts = _session_init_probe_hosts()
checks = "; ".join(
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 bbb84d2c5992..2f07be3f61d3 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -2,6 +2,7 @@ import json
import shlex
import asyncio
import builtins
+import subprocess
from pathlib import Path
from typing import Any
@@ -32,6 +33,7 @@ from products.tasks.backend.exceptions import (
)
from products.tasks.backend.logic.services.agent_server_launcher import (
AGENT_SERVER_HEALTH_MAX_ATTEMPTS,
+ HOST_PRESSURE_PROBE_SCRIPT,
STARTUP_LOG_MAX_BYTES,
)
from products.tasks.backend.logic.services.local_packages import LocalPackage
@@ -527,7 +529,7 @@ class TestModalSandboxAgentServer:
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:
+ if "http_code=" in command:
return ExecutionResult(
stdout="gateway.us.posthog.com http_code=200", stderr="", exit_code=0, error=None
)
@@ -1393,7 +1395,7 @@ class TestStartupFailureDiagnostics:
sandbox = self._sandbox()
def _exec(command: str, timeout_seconds: Any = None) -> ExecutionResult:
- if "printf" in command:
+ if "http_code=" in command:
return ExecutionResult(
stdout="api.anthropic.com http_code=200\nmcp-eu.posthog.com http_code=000",
stderr="",
@@ -1418,7 +1420,7 @@ class TestStartupFailureDiagnostics:
sandbox = self._sandbox()
def _exec(command: str, timeout_seconds: Any = None) -> ExecutionResult:
- if "printf" in command:
+ if "http_code=" in command:
return ExecutionResult(
stdout="gateway.us.posthog.com http_code=200", stderr="", exit_code=0, error=None
)
@@ -1432,6 +1434,42 @@ class TestStartupFailureDiagnostics:
assert diagnostics["sandbox_terminated"] == "false"
assert "never reported hasSession=true" in diagnostics["failure_reason"]
+ assert diagnostics["host_pressure"] == "ok"
+
+ def test_host_pressure_probe_failure_keeps_the_failure_reason(self):
+ sandbox = self._sandbox()
+
+ def _exec(command: str, timeout_seconds: Any = None) -> ExecutionResult:
+ if "http_code=" in command:
+ return ExecutionResult(
+ stdout="gateway.us.posthog.com http_code=200", stderr="", exit_code=0, error=None
+ )
+ if "cpu_loop_ms" in command:
+ raise SandboxTimeoutError(
+ "Execution timed out after 45 seconds",
+ {"sandbox_id": "sb-diag"},
+ cause=TimeoutError("exec returned -1"),
+ capture=False,
+ )
+ 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 "never reported hasSession=true" in diagnostics["failure_reason"]
+ assert diagnostics["host_pressure"].startswith("unavailable:")
+
+ def test_host_pressure_probe_script_reports_every_measurement(self):
+ completed = subprocess.run(
+ ["bash", "-c", HOST_PRESSURE_PROBE_SCRIPT], capture_output=True, text=True, timeout=60, check=False
+ )
+
+ assert completed.returncode == 0
+ for key in ("loadavg=", "nproc=", "cpu_loop_ms=", "python_spawn_ms=", "cold_read_ms="):
+ assert key in completed.stdout
@pytest.mark.parametrize(
("log_bytes", "expected_truncated"),
@@ -1445,7 +1483,7 @@ class TestStartupFailureDiagnostics:
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:
+ if "http_code=" in command:
return ExecutionResult(
stdout="gateway.us.posthog.com http_code=200", stderr="", exit_code=0, error=None
)