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): reduce agent startup command overhead (#92425)

Alessandro Pogliaghi59df8967d6f3
diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.py
index d1bfdabf2e93..1df8b5f8e9e1 100644
--- a/products/tasks/backend/logic/services/agent_server_launcher.py
+++ b/products/tasks/backend/logic/services/agent_server_launcher.py
@@ -9,6 +9,7 @@ inherit it unchanged.
from __future__ import annotations
import json
+import time
import shlex
import logging
from typing import TYPE_CHECKING
@@ -37,6 +38,8 @@ from products.tasks.backend.logic.services.sandbox import (
WORKING_DIR,
SandboxBase,
build_agent_runtime_env_prefix,
+ build_health_check_command,
+ health_check_timeout_seconds,
wait_for_health_check,
)
@@ -47,6 +50,7 @@ logger = logging.getLogger(__name__)
AGENT_SERVER_PORT = 8080 # Modal connect tokens require port 8080
AGENT_SERVER_HEALTH_MAX_ATTEMPTS = 240
+AGENT_SERVER_HEALTH_DURATION_PREFIX = "__posthog_agent_health_ms="
SESSION_INIT_PROBE_HOSTS = (
"gateway.us.posthog.com",
@@ -72,9 +76,35 @@ def _session_init_probe_hosts() -> list[str]:
return hosts
+def _start_and_wait_command(command: str) -> str:
+ health_command = build_health_check_command(AGENT_SERVER_PORT, AGENT_SERVER_HEALTH_MAX_ATTEMPTS)
+ return (
+ f"{command}; launch_status=$?; "
+ 'if [ "$launch_status" -ne 0 ]; then exit "$launch_status"; fi; '
+ "health_started=$(date +%s%3N); "
+ f"({health_command}); health_status=$?; "
+ "health_finished=$(date +%s%3N); "
+ f'echo "{AGENT_SERVER_HEALTH_DURATION_PREFIX}$((health_finished - health_started))"; '
+ 'exit "$health_status"'
+ )
+
+
+def _health_duration_ms(stdout: str) -> int | None:
+ for line in stdout.splitlines():
+ if line.startswith(AGENT_SERVER_HEALTH_DURATION_PREFIX):
+ try:
+ return max(0, int(line.removeprefix(AGENT_SERVER_HEALTH_DURATION_PREFIX)))
+ except ValueError:
+ return None
+ return None
+
+
class AgentServerLaunchMixin(SandboxBase):
"""Launches and supervises the in-sandbox agent-server over ``execute``."""
+ def supports_combined_agent_server_start_and_health(self) -> bool:
+ return True
+
def _build_agent_server_command(
self,
repo_path: str | None,
@@ -245,7 +275,7 @@ class AgentServerLaunchMixin(SandboxBase):
rtk_enabled: bool = True,
benjamin_enabled: bool = False,
peer_messaging: bool = False,
- ) -> None:
+ ) -> int | None:
"""Start the agent-server HTTP server in the sandbox.
The sandbox URL and token should be obtained via get_connect_credentials()
@@ -256,10 +286,8 @@ class AgentServerLaunchMixin(SandboxBase):
raise RuntimeError("Sandbox not in running state.")
if self._agent_server_is_healthy() and (allowed_domains is None or self._agentsh_daemon_is_healthy()):
- if wait_for_health:
- self.wait_for_agent_server_ready(allowed_domains)
logger.info(f"Agent-server already healthy in sandbox {self.id}; skipping relaunch")
- return
+ return 0 if wait_for_health else None
self._free_agent_server_port()
repo_path: str | None = None
@@ -333,8 +361,25 @@ class AgentServerLaunchMixin(SandboxBase):
)
logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")
- launch_result = self.execute(command, timeout_seconds=30)
+ execute_command = _start_and_wait_command(command) if wait_for_health else command
+ timeout_seconds = 30 + health_check_timeout_seconds(AGENT_SERVER_HEALTH_MAX_ATTEMPTS) if wait_for_health else 30
+ start_time = time.perf_counter()
+ launch_result = self.execute(execute_command, timeout_seconds=timeout_seconds)
+ start_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)
+ if wait_for_health and health_duration_ms is not None:
+ diagnostics = self._diagnose_startup_failure(allowed_domains)
+ raise SandboxExecutionError(
+ "Agent-server failed to start",
+ {
+ "sandbox_id": self.id,
+ **diagnostics,
+ "health_poll_ms": health_duration_ms,
+ "start_and_health_ms": start_and_health_ms,
+ },
+ cause=RuntimeError(diagnostics.get("failure_reason", "Health check failed after retries")),
+ )
logger.warning(f"Agent-server process failed to launch in sandbox {self.id}: {launch_result.stderr}")
raise SandboxExecutionError(
"Agent-server failed to start",
@@ -343,7 +388,15 @@ class AgentServerLaunchMixin(SandboxBase):
)
if wait_for_health:
- self.wait_for_agent_server_ready(allowed_domains)
+ if allowed_domains is not None and not self._agentsh_daemon_is_healthy():
+ raise SandboxExecutionError(
+ "Failed to verify agentsh network enforcement",
+ {"sandbox_id": self.id},
+ cause=RuntimeError("agentsh daemon health check failed"),
+ )
+ logger.info(f"Agent-server ready in sandbox {self.id}")
+ return _health_duration_ms(launch_result.stdout)
+ return None
def wait_for_agent_server_ready(self, allowed_domains: list[str] | None = None) -> None:
if self._wait_for_health_check():
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index c0068bc9e0b1..8090f734c629 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -233,9 +233,13 @@ PUBLIC_SANDBOX_REPOS: frozenset[str] = frozenset({"posthog/hedgebox", "posthog/.
SENSITIVE_AGENT_RUNTIME_ENV_NAMES: frozenset[str] = frozenset(
{"POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN", "POSTHOG_TASK_RUN_SESSION_TOKEN"}
)
+SHELL_ARGUMENT_VALUE_PATTERN = r"'(?:[^']|'\"'\"')*'|\"(?:\\.|[^\"])*\"|\S+"
SENSITIVE_AGENT_RUNTIME_ENV_PATTERN = re.compile(
r"(?P<name>" + "|".join(re.escape(name) for name in SENSITIVE_AGENT_RUNTIME_ENV_NAMES) + r")="
- r"(?P<value>'(?:[^']|'\"'\"')*'|\"(?:\\.|[^\"])*\"|\S+)"
+ rf"(?P<value>{SHELL_ARGUMENT_VALUE_PATTERN})"
+)
+SENSITIVE_AGENT_RUNTIME_ARGUMENT_PATTERN = re.compile(
+ rf"(?P<name>--mcpServers)\s+(?P<value>{SHELL_ARGUMENT_VALUE_PATTERN})"
)
@@ -250,7 +254,8 @@ def sandbox_repo_path(repository: str) -> str:
def redact_sandbox_command(command: str) -> str:
- return SENSITIVE_AGENT_RUNTIME_ENV_PATTERN.sub(r"\g<name>=<redacted>", command)
+ redacted = SENSITIVE_AGENT_RUNTIME_ENV_PATTERN.sub(r"\g<name>=<redacted>", command)
+ return SENSITIVE_AGENT_RUNTIME_ARGUMENT_PATTERN.sub(r"\g<name> <redacted>", redacted)
def build_agent_runtime_env_prefix(
@@ -550,7 +555,7 @@ class SandboxBase(ABC):
rtk_enabled: bool = True,
benjamin_enabled: bool = False,
peer_messaging: bool = False,
- ) -> None:
+ ) -> int | None:
"""Start the agent-server HTTP server in the sandbox.
The sandbox URL and token should be obtained via get_connect_credentials()
@@ -558,6 +563,9 @@ class SandboxBase(ABC):
"""
...
+ def supports_combined_agent_server_start_and_health(self) -> bool:
+ return False
+
@abstractmethod
def wait_for_agent_server_ready(self, allowed_domains: list[str] | None = None) -> None: ...
@@ -722,7 +730,16 @@ def wait_for_health_check(
Runs a bash polling loop inside the sandbox so only one round-trip is
needed regardless of how many attempts are required.
"""
- health_script = (
+ health_script = build_health_check_command(port, max_attempts, poll_interval)
+ result = execute(health_script, timeout_seconds=health_check_timeout_seconds(max_attempts, poll_interval))
+ if result.exit_code == 0:
+ _logger.info(f"Agent-server health check passed in sandbox {sandbox_id} ({result.stdout.strip()})")
+ return True
+ return False
+
+
+def build_health_check_command(port: int, max_attempts: int = 60, poll_interval: float = 0.5) -> str:
+ return (
f"for i in $(seq 1 {max_attempts}); do "
f" body=$(curl -s http://localhost:{port}/health); "
" status=$?; "
@@ -737,11 +754,10 @@ def wait_for_health_check(
f"done; "
f"exit 1"
)
- result = execute(health_script, timeout_seconds=max(30, int(max_attempts * poll_interval) + 5))
- if result.exit_code == 0:
- _logger.info(f"Agent-server health check passed in sandbox {sandbox_id} ({result.stdout.strip()})")
- return True
- return False
+
+
+def health_check_timeout_seconds(max_attempts: int = 60, poll_interval: float = 0.5) -> int:
+ return max(30, int(max_attempts * poll_interval) + 5)
SandboxClass = type[SandboxBase]
diff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.py
index 9487764f340e..72c4b97b7a87 100644
--- a/products/tasks/backend/logic/services/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py
@@ -126,6 +126,13 @@ class TestDockerSandboxUnit:
assert "secret token" not in redacted
assert "POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=<redacted>" in redacted
+ def test_redact_sandbox_command_hides_mcp_credentials(self):
+ command = 'agent-server --mcpServers \'[{"headers":{"Authorization":"Bearer secret-token"}}]\' --port 8080'
+
+ redacted = redact_sandbox_command(command)
+
+ assert redacted == "agent-server --mcpServers <redacted> --port 8080"
+
@pytest.mark.parametrize(
"input_url,expected_url",
[
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 a01fa8abbbf5..6531bb2d8477 100644
--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
@@ -52,6 +52,10 @@ def test_start_agent_server_health_check_timeout_is_retryable_and_not_captured(s
capture_exception.assert_not_called()
+def test_docker_sandbox_does_not_combine_agent_server_start_and_health(sandbox: DockerSandbox):
+ assert sandbox.supports_combined_agent_server_start_and_health() is False
+
+
def test_read_agent_server_boot_metrics_includes_process_milestones(sandbox: DockerSandbox):
response = ExecutionResult(
stdout='{"sessionInitMs":90,"boot":{"totalMs":140,"httpReadyMs":12,"phasesMs":{"context_fetch":40,"secret":1}}}',
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 34cbb56bca68..8581fe1153b4 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -477,6 +477,18 @@ class TestModalSandboxAgentServer:
assert "secret-token" not in exc.value.context["error"]
capture_exception.assert_not_called()
+ def test_execution_redacts_mcp_credentials_from_error_context(self, mock_sandbox: Any):
+ command = 'agent-server --mcpServers \'[{"headers":{"Authorization":"Bearer secret-token"}}]\''
+ mock_sandbox._sandbox.exec.side_effect = RuntimeError(f"failed {command}")
+
+ with pytest.raises(SandboxExecutionError) as exc:
+ mock_sandbox.execute(command)
+
+ assert "secret-token" not in exc.value.context["command"]
+ assert "secret-token" not in exc.value.context["error"]
+ assert "--mcpServers <redacted>" in exc.value.context["command"]
+ assert "--mcpServers <redacted>" in exc.value.context["error"]
+
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),
@@ -736,19 +748,24 @@ class TestModalSandboxAgentServer:
ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # gh shim write (mv)
ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # gh shim chmod
ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # --posthogExecPermissionRegex probe
- ExecutionResult(stdout="", stderr="", exit_code=1, error=None),
- ExecutionResult(stdout="some log output", stderr="", exit_code=0, error=None),
+ ExecutionResult(stdout="__posthog_agent_health_ms=120000", stderr="", exit_code=1, error=None),
]
)
- with patch.object(mock_sandbox, "_setup_agentsh"):
- with pytest.raises(SandboxExecutionError, match="Agent-server failed to start"):
+ with (
+ patch.object(mock_sandbox, "_setup_agentsh"),
+ patch.object(mock_sandbox, "_diagnose_startup_failure", return_value={"failure_reason": "not ready"}),
+ ):
+ with pytest.raises(SandboxExecutionError, match="Agent-server failed to start") as error:
mock_sandbox.start_agent_server(
repository="posthog/posthog",
task_id="task-123",
run_id="run-456",
)
+ assert error.value.context["health_poll_ms"] == 120000
+ assert mock_sandbox.supports_combined_agent_server_start_and_health() is True
+
def test_wait_for_health_check_passes(self, mock_sandbox: Any):
mock_sandbox.execute = MagicMock(
return_value=ExecutionResult(stdout="ok:3", stderr="", exit_code=0, error=None),
@@ -778,7 +795,7 @@ class TestModalSandboxAgentServer:
patch.object(mock_sandbox, "wait_for_agent_server_ready") as wait_for_ready,
patch.object(mock_sandbox, "_free_agent_server_port") as mock_free,
):
- mock_sandbox.start_agent_server(
+ health_ms = mock_sandbox.start_agent_server(
repository="posthog/posthog",
task_id="task-123",
run_id="run-456",
@@ -786,7 +803,8 @@ class TestModalSandboxAgentServer:
allowed_domains=["example.com"],
)
- wait_for_ready.assert_called_once_with(["example.com"])
+ assert health_ms == 0
+ wait_for_ready.assert_not_called()
mock_free.assert_not_called()
mock_sandbox.execute.assert_not_called()
@@ -797,7 +815,7 @@ class TestModalSandboxAgentServer:
with (
patch.object(mock_sandbox, "_agent_server_is_healthy", return_value=True),
- patch.object(mock_sandbox, "_agentsh_daemon_is_healthy", return_value=False),
+ patch.object(mock_sandbox, "_agentsh_daemon_is_healthy", side_effect=[False, True]),
patch.object(mock_sandbox, "_setup_agentsh") as mock_setup_agentsh,
patch.object(mock_sandbox, "wait_for_agent_server_ready") as wait_for_ready,
patch.object(mock_sandbox, "_free_agent_server_port") as mock_free,
@@ -812,7 +830,7 @@ class TestModalSandboxAgentServer:
mock_free.assert_called_once_with()
mock_setup_agentsh.assert_called_once_with("/tmp/workspace", ["example.com"])
- wait_for_ready.assert_called_once_with(["example.com"])
+ wait_for_ready.assert_not_called()
assert "./node_modules/.bin/agent-server" in _agent_server_launch_command(mock_sandbox.execute)
def test_wait_for_agent_server_ready_rejects_unhealthy_agentsh(self, mock_sandbox: Any):
@@ -830,12 +848,11 @@ class TestModalSandboxAgentServer:
ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # gh shim write (mv)
ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # gh shim chmod
ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # --posthogExecPermissionRegex probe
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
+ ExecutionResult(stdout="ok:1\n__posthog_agent_health_ms=250", stderr="", exit_code=0, error=None),
]
)
- mock_sandbox.start_agent_server(
+ health_ms = mock_sandbox.start_agent_server(
repository="posthog/posthog",
task_id="task-123",
run_id="run-456",
@@ -843,7 +860,10 @@ class TestModalSandboxAgentServer:
)
mock_sandbox._free_agent_server_port.assert_called_once_with()
- assert "nohup" in _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_create_snapshot_waits_for_container_before_snapshot(self, mock_sandbox: Any) -> None:
events: list[str] = []
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index 10dd11428d09..d66c8d541684 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -355,6 +355,36 @@ def record_agent_server_session_init_ms(
pass
+def record_agent_server_step_ms(
+ step: str,
+ duration_ms: int,
+ boot_path: str,
+ *,
+ status: str = "COMPLETED",
+ used_snapshot: bool | None = None,
+ origin_product: str | None = None,
+ runtime: str | None = None,
+) -> None:
+ try:
+ attributes: Attributes = {
+ "step": step,
+ "used_snapshot": _bool_label(used_snapshot),
+ "status": status,
+ "boot_path": boot_path,
+ }
+ if origin_product is not None:
+ attributes["origin_product"] = origin_product
+ if runtime is not None:
+ attributes["runtime"] = runtime
+ _metric_meter(attributes).create_histogram_timedelta(
+ "tasks_process_sandbox_step_latency",
+ "Latency for get_sandbox_for_repository sub-steps",
+ unit="ms",
+ ).record(dt.timedelta(milliseconds=duration_ms))
+ except Exception:
+ pass
+
+
def increment_agent_server_readiness_retry(
attempt: int,
outcome: str,
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.py
index d632a41a9b5e..e81ca6cecc8e 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
@@ -1,4 +1,5 @@
import json
+import time
import shlex
import threading
from dataclasses import dataclass, field
@@ -20,7 +21,12 @@ from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import asyncify, retry_on_db_connection_drop
from posthog.temporal.oauth import PosthogMcpScopes
-from products.tasks.backend.exceptions import OAuthTokenError, SandboxExecutionError, SandboxMissingRepositoryError
+from products.tasks.backend.exceptions import (
+ OAuthTokenError,
+ ProcessTaskError,
+ SandboxExecutionError,
+ SandboxMissingRepositoryError,
+)
from products.tasks.backend.logic.services.connection_token import create_sandbox_event_ingest_token
from products.tasks.backend.logic.services.sandbox import (
REPO_READY_FILE,
@@ -34,6 +40,7 @@ from products.tasks.backend.temporal.metrics import (
StepTimer,
increment_agent_server_readiness_retry,
record_agent_server_session_init_ms,
+ record_agent_server_step_ms,
record_boot_total_ms,
record_network_enforcement,
sandbox_runtime_label,
@@ -517,9 +524,10 @@ def _invoke_start_agent_server(
params: _LaunchParams,
*,
repo_ready_file: str | None,
-) -> None:
+ wait_for_health: bool = False,
+) -> int | None:
try:
- sandbox.start_agent_server(
+ health_duration_ms = sandbox.start_agent_server(
repository=ctx.repository if len(ctx.repositories) <= 1 else None,
task_id=ctx.task_id,
run_id=ctx.run_id,
@@ -544,12 +552,18 @@ def _invoke_start_agent_server(
event_ingest_url=params.event_ingest_url,
event_ingest_keep_stream_open=params.event_ingest_keep_stream_open,
repo_ready_file=repo_ready_file,
- wait_for_health=False,
+ wait_for_health=wait_for_health,
rtk_enabled=ctx.rtk_enabled,
benjamin_enabled=ctx.benjamin_enabled,
peer_messaging=ctx.peer_messaging_enabled,
)
+ return health_duration_ms if isinstance(health_duration_ms, int) else None
+ except ProcessTaskError:
+ if params.agentsh_domains is not None:
+ _emit_agentsh_log_tail(ctx, sandbox)
+ _emit_agent_server_log_tail(ctx, sandbox)
+ raise
except Exception as e:
if params.agentsh_domains is not None:
_emit_agentsh_log_tail(ctx, sandbox)
@@ -655,14 +669,74 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
"agent_server_ready", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
) as ready_timer:
shadow_launched = _launch_agent_shadow(ctx, sandbox)
- with StepTimer(
- "agent_server_invoke", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
- ) as invoke_timer:
- _invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=None)
- with StepTimer(
- "agent_server_health", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
- ) as health_timer:
- sandbox.wait_for_agent_server_ready(params.agentsh_domains)
+ invoke_ms: int | None
+ health_poll_ms: int | None
+ if sandbox.supports_combined_agent_server_start_and_health():
+ start_time = time.perf_counter()
+ health_poll_ms = None
+ invoke_status = "COMPLETED"
+ health_status = "COMPLETED"
+ start_and_health_ms = None
+ try:
+ health_poll_ms = _invoke_start_agent_server(
+ sandbox, ctx, params, repo_ready_file=None, wait_for_health=True
+ )
+ except ProcessTaskError as error:
+ failed_health_ms = error.context.get("health_poll_ms")
+ health_poll_ms = failed_health_ms if isinstance(failed_health_ms, int) else None
+ failed_start_and_health_ms = error.context.get("start_and_health_ms")
+ start_and_health_ms = (
+ failed_start_and_health_ms if isinstance(failed_start_and_health_ms, int) else None
+ )
+ invoke_status = "COMPLETED" if health_poll_ms is not None else "FAILED"
+ health_status = "FAILED"
+ raise
+ finally:
+ if start_and_health_ms is None:
+ start_and_health_ms = int((time.perf_counter() - start_time) * 1000)
+ invoke_ms = (
+ max(0, start_and_health_ms - health_poll_ms)
+ if health_poll_ms is not None
+ else start_and_health_ms
+ )
+ record_agent_server_step_ms(
+ "agent_server_invoke",
+ invoke_ms,
+ input.boot_path,
+ status=invoke_status,
+ used_snapshot=input.used_snapshot,
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ )
+ if health_poll_ms is not None:
+ record_agent_server_step_ms(
+ "agent_server_health",
+ health_poll_ms,
+ input.boot_path,
+ status=health_status,
+ used_snapshot=input.used_snapshot,
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ )
+ else:
+ with StepTimer(
+ "agent_server_invoke",
+ used_snapshot=input.used_snapshot,
+ boot_path=input.boot_path,
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ ) as invoke_timer:
+ _invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=None)
+ with StepTimer(
+ "agent_server_health",
+ used_snapshot=input.used_snapshot,
+ boot_path=input.boot_path,
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ ) as health_timer:
+ sandbox.wait_for_agent_server_ready(params.agentsh_domains)
+ invoke_ms = invoke_timer.elapsed_ms
+ health_poll_ms = health_timer.elapsed_ms
_record_agent_server_launch(sandbox, ctx, params)
_record_network_enforcement_observation(ctx)
@@ -684,8 +758,8 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
sandbox_url=input.sandbox_url,
connect_token=input.sandbox_connect_token,
prepare_ms=prepare_timer.elapsed_ms,
- invoke_ms=invoke_timer.elapsed_ms,
- health_poll_ms=health_timer.elapsed_ms,
+ invoke_ms=invoke_ms,
+ health_poll_ms=health_poll_ms,
ready_wait_ms=ready_timer.elapsed_ms,
session_init_ms=session_init_ms,
boot_phases_ms=boot_phases_ms,
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.py
index 00437a1e21da..e684595635ed 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
@@ -3,7 +3,12 @@ from freezegun import freeze_time
from django.db import OperationalError
-from products.tasks.backend.exceptions import OAuthTokenError, SandboxExecutionError, SandboxMissingRepositoryError
+from products.tasks.backend.exceptions import (
+ OAuthTokenError,
+ SandboxExecutionError,
+ SandboxMissingRepositoryError,
+ SandboxTimeoutError,
+)
from products.tasks.backend.logic.services.sandbox import ExecutionResult, sandbox_repo_path
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.activities.start_agent_server import (
@@ -12,6 +17,7 @@ from products.tasks.backend.temporal.process_task.activities.start_agent_server
_agentsh_domains_for,
_ensure_repository_on_disk,
_include_personal_mcp_for_task,
+ _invoke_start_agent_server,
_is_agent_shadow_enabled,
_launch_agent_shadow,
_LaunchParams,
@@ -135,9 +141,12 @@ async def test_start_failure_does_not_report_network_enforcement_observation(moc
use_modal_network_allowlist=True,
network_policy_fingerprint="policy-hash",
)
+ sandbox = mocker.Mock()
+ sandbox.supports_combined_agent_server_start_and_health.return_value = False
+ sandbox.wait_for_agent_server_ready.side_effect = RuntimeError("health check failed")
mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server.get_sandbox_class_for_sandbox_id",
- **{"return_value.get_by_id.return_value": mocker.Mock()},
+ **{"return_value.get_by_id.return_value": sandbox},
)
mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server._prepare_launch",
@@ -145,7 +154,7 @@ async def test_start_failure_does_not_report_network_enforcement_observation(moc
)
mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server._invoke_start_agent_server",
- side_effect=RuntimeError("health check failed"),
+ return_value=None,
)
record_observation = mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server._record_network_enforcement_observation"
@@ -161,6 +170,94 @@ async def test_start_failure_does_not_report_network_enforcement_observation(moc
)
record_observation.assert_not_called()
+ sandbox.wait_for_agent_server_ready.assert_called_once()
+
+
[email protected]("error_type", [SandboxExecutionError, SandboxTimeoutError])
+def test_invoke_start_agent_server_preserves_process_task_error(mocker, error_type) -> None:
+ context = _context()
+ error = error_type(
+ "Agent-server failed to start",
+ {"sandbox_id": "sandbox-id", "failure_reason": "not ready"},
+ cause=RuntimeError("not ready"),
+ capture=False,
+ )
+ sandbox = mocker.Mock(id="sandbox-id")
+ sandbox.start_agent_server.side_effect = error
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._emit_agent_server_log_tail"
+ )
+
+ with pytest.raises(error_type) as raised:
+ _invoke_start_agent_server(sandbox, context, mocker.Mock(agentsh_domains=None), repo_ready_file=None)
+
+ assert raised.value is error
+
+
+ ("error", "expected_statuses"),
+ [
+ (
+ SandboxExecutionError(
+ "Agent-server failed to start",
+ {"health_poll_ms": 120, "start_and_health_ms": 150},
+ cause=RuntimeError("not ready"),
+ capture=False,
+ ),
+ ["COMPLETED", "FAILED"],
+ ),
+ (
+ SandboxTimeoutError(
+ "Execution timed out",
+ {"timeout_seconds": 155},
+ cause=RuntimeError("timed out"),
+ capture=False,
+ ),
+ ["FAILED"],
+ ),
+ ],
+)
+async def test_combined_start_failure_records_step_statuses(mocker, error, expected_statuses) -> None:
+ context = _context()
+ sandbox = mocker.Mock(id="sandbox-id")
+ sandbox.supports_combined_agent_server_start_and_health.return_value = True
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.get_sandbox_class_for_sandbox_id",
+ **{"return_value.get_by_id.return_value": sandbox},
+ )
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._prepare_launch",
+ return_value=mocker.Mock(agentsh_domains=None),
+ )
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._invoke_start_agent_server",
+ side_effect=error,
+ )
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._launch_agent_shadow",
+ return_value=False,
+ )
+ mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.emit_agent_log")
+ record_step = mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.record_agent_server_step_ms"
+ )
+
+ with pytest.raises(type(error)) as raised:
+ await start_agent_server(
+ StartAgentServerInput(
+ context=context,
+ sandbox_id="sandbox-id",
+ sandbox_url="https://sandbox.example",
+ used_snapshot=True,
+ )
+ )
+
+ assert raised.value is error
+ assert [record.kwargs["status"] for record in record_step.call_args_list] == expected_statuses
+ assert all(record.kwargs["used_snapshot"] is True for record in record_step.call_args_list)
+ if len(record_step.call_args_list) == 2:
+ assert record_step.call_args_list[0].args[:2] == ("agent_server_invoke", 30)
+ assert record_step.call_args_list[1].args[:2] == ("agent_server_health", 120)
@pytest.mark.parametrize(("attempt", "expects_relaunch"), [(1, False), (2, True), (3, True)])
@@ -668,6 +765,7 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mocker
sandbox = mocker.Mock()
sandbox.execute.return_value.stdout = ""
sandbox.execute.return_value.stderr = ""
+ sandbox.start_agent_server.return_value = 125
sandbox.read_agent_server_boot_metrics.return_value = (None, {})
mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server.get_sandbox_class_for_sandbox_id",
@@ -743,8 +841,9 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mocker
allowed_gateway_server_ids=["srv-1"],
)
sandbox.start_agent_server.assert_called_once()
- sandbox.wait_for_agent_server_ready.assert_called_once_with(None)
- assert sandbox.start_agent_server.call_args.kwargs["wait_for_health"] is False
+ sandbox.wait_for_agent_server_ready.assert_not_called()
+ assert sandbox.start_agent_server.call_args.kwargs["wait_for_health"] is True
+ assert result.health_poll_ms == 125
assert sandbox.start_agent_server.call_args.kwargs["event_ingest_token"] == "event-ingest-token"