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.

feat(tasks): batch cloud sandbox launch preparation (#100247)

Alessandro Pogliaghi07dd2946be36
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index f2ba8f4220af..77a42b3ce01d 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -84,8 +84,16 @@ orchestrates these activities:
2. **get_sandbox_for_repository** — Creates an OAuth access token, provisions a
Docker sandbox (reusing a snapshot if one exists), clones the repository, and
stores the sandbox URL in `TaskRun.state`
-3. **start_agent_server** — Runs `npx agent-server` inside the sandbox and polls
- `/health` until it responds
+3. **start_agent_server** — Prepares and starts the agent server inside the sandbox, then polls `/health` until it responds.
+ Modal uploads one preparation script to install the shell environment hook and GitHub CLI shim.
+ When network enforcement is enabled, that script also installs the agentsh configuration, policy, and environment wrapper, then starts the daemon and creates its session.
+ Files are staged with their required permissions before atomic replacement, and any preparation failure stops the launch.
+ Failed preparation terminates and reaps its agentsh daemon, and captured errors include a bounded daemon log tail when available.
+ The `Modal launch preparation finished` worker log records upload, installation, daemon/session, and total preparation times in milliseconds.
+ This preparation runs inside the `agent_server_invoke` latency metric; `agent_server_prepare` measures credentials and MCP configuration before the sandbox call.
+ The `tasks_modal_launch_preparation_latency` histogram measures the preparation upload and execution in milliseconds, excluding later launch work and failure diagnostics.
+ Labels identify runtime, boot path, origin product, snapshot use, and `COMPLETED` or `FAILED` status; healthy-server reuse emits no preparation sample.
+ Its `_count`, `_sum`, and `_bucket` series support attempt counts, mean duration, and percentiles, with finer buckets between 1 and 10 seconds.
4. **wait_condition** — The workflow blocks with a 30-minute inactivity timeout,
extended by `heartbeat` signals from the agent. Exits on a `complete_task`
signal or when no heartbeat arrives within 30 minutes
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.py
index 2a5e4ac8ddcd..f89e3e2dd058 100644
--- a/posthog/temporal/common/worker.py
+++ b/posthog/temporal/common/worker.py
@@ -80,6 +80,8 @@ from products.logs.backend.facade.temporal import (
from products.tasks.backend.facade.temporal import (
TASKS_LATENCY_HISTOGRAM_BUCKETS,
TASKS_LATENCY_HISTOGRAM_METRICS,
+ TASKS_LAUNCH_PREPARATION_HISTOGRAM_BUCKETS,
+ TASKS_LAUNCH_PREPARATION_HISTOGRAM_METRICS,
TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS,
TASKS_RUN_TOKENS_HISTOGRAM_METRICS,
TASKS_RUN_TURNS_HISTOGRAM_BUCKETS,
@@ -297,6 +299,11 @@ async def create_worker(
)
)
| dict(zip(TASKS_LATENCY_HISTOGRAM_METRICS, itertools.repeat(TASKS_LATENCY_HISTOGRAM_BUCKETS)))
+ | dict(
+ zip(
+ TASKS_LAUNCH_PREPARATION_HISTOGRAM_METRICS, itertools.repeat(TASKS_LAUNCH_PREPARATION_HISTOGRAM_BUCKETS)
+ )
+ )
| dict(zip(TASKS_RUN_TOKENS_HISTOGRAM_METRICS, itertools.repeat(TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS)))
| dict(zip(TASKS_RUN_TURNS_HISTOGRAM_METRICS, itertools.repeat(TASKS_RUN_TURNS_HISTOGRAM_BUCKETS)))
| dict(
diff --git a/products/tasks/backend/facade/temporal.py b/products/tasks/backend/facade/temporal.py
index 5902769c1507..aa4bef0d5406 100644
--- a/products/tasks/backend/facade/temporal.py
+++ b/products/tasks/backend/facade/temporal.py
@@ -19,6 +19,8 @@ from products.tasks.backend.temporal.client import (
from products.tasks.backend.temporal.metrics import (
TASKS_LATENCY_HISTOGRAM_BUCKETS,
TASKS_LATENCY_HISTOGRAM_METRICS,
+ TASKS_LAUNCH_PREPARATION_HISTOGRAM_BUCKETS,
+ TASKS_LAUNCH_PREPARATION_HISTOGRAM_METRICS,
TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS,
TASKS_RUN_TOKENS_HISTOGRAM_METRICS,
TASKS_RUN_TURNS_HISTOGRAM_BUCKETS,
@@ -34,6 +36,8 @@ __all__ = [
"ACTIVITIES",
"TASKS_LATENCY_HISTOGRAM_BUCKETS",
"TASKS_LATENCY_HISTOGRAM_METRICS",
+ "TASKS_LAUNCH_PREPARATION_HISTOGRAM_BUCKETS",
+ "TASKS_LAUNCH_PREPARATION_HISTOGRAM_METRICS",
"TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS",
"TASKS_RUN_TOKENS_HISTOGRAM_METRICS",
"TASKS_RUN_TURNS_HISTOGRAM_BUCKETS",
diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.py
index 9744a9123eec..d0bfa3297956 100644
--- a/products/tasks/backend/logic/services/agent_server_launcher.py
+++ b/products/tasks/backend/logic/services/agent_server_launcher.py
@@ -13,6 +13,7 @@ import json
import time
import shlex
import logging
+from collections.abc import Callable
from typing import TYPE_CHECKING
from django.conf import settings
@@ -376,6 +377,99 @@ class AgentServerLaunchMixin(SandboxBase):
)
return self.execute(checks, timeout_seconds=30).stdout.strip()
+ def _prepare_agent_server_launch(self, allowed_domains: list[str] | None) -> None:
+ 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")
+
+ if allowed_domains is not None:
+ self._setup_agentsh(WORKING_DIR, allowed_domains)
+
+ def _chmod_required(self, path: str, mode: str) -> None:
+ result = self.execute(f"chmod {mode} {shlex.quote(path)}", timeout_seconds=30)
+ if result.exit_code != 0:
+ raise SandboxExecutionError(
+ "Failed to set permissions on required sandbox file",
+ {"sandbox_id": self.id, "path": path, "mode": mode, "stderr": result.stderr},
+ cause=RuntimeError(f"chmod {mode} {path} exited {result.exit_code}"),
+ )
+
+ def _validate_agent_server_launch(self) -> None:
+ 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 _launch_prepared_agent_server(
+ self,
+ build_command: Callable[[str | None], str],
+ *,
+ branch: str | None,
+ task_id: str,
+ run_id: str,
+ wait_for_health: bool,
+ allowed_domains: list[str] | None,
+ claude_model_access: str | None,
+ ) -> int | None:
+ command = build_command(branch)
+ max_attempts = 300 if claude_model_access == "own-subscription" else AGENT_SERVER_HEALTH_MAX_ATTEMPTS
+ execute_command = _start_and_wait_command(command, max_attempts) if wait_for_health else command
+ timeout_seconds = 30 + health_check_timeout_seconds(max_attempts) if wait_for_health else 30
+ start_time = time.perf_counter()
+ 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 error
+ 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)
+ if (
+ "claude_credential_unavailable" in launch_result.stdout
+ or "claude_credential_unavailable" in diagnostics.get("log", "")
+ ):
+ raise ProcessTaskFatalError(
+ "The Claude token did not arrive. Open Desktop and check your token in Settings > Harness. Then start the task again.",
+ {"task_id": task_id, "run_id": run_id},
+ RuntimeError("Claude token unavailable"),
+ capture=False,
+ )
+ 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",
+ {"sandbox_id": self.id, "stderr": launch_result.stderr, "exit_code": str(launch_result.exit_code)},
+ cause=RuntimeError(launch_result.stderr or "launch command returned non-zero exit"),
+ )
+
+ if wait_for_health:
+ 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 start_agent_server(
self,
repository: str | None,
@@ -415,31 +509,20 @@ class AgentServerLaunchMixin(SandboxBase):
before calling this method. The agent-server runs on port 8080 which is
exposed via the provider's tunnel/proxy mechanism.
"""
- if not self.is_running():
- raise RuntimeError("Sandbox not in running state.")
+ self._validate_agent_server_launch()
# 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._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")
+ if self._reuse_healthy_agent_server(allowed_domains):
return 0 if wait_for_health else None
- self._free_agent_server_port()
repo_path: str | None = None
if repository:
org, repo = repository.lower().split("/")
repo_path = f"/tmp/workspace/repos/{org}/{repo}"
- self._write_required_file(BASH_ENV_SCRIPT, generate_bash_env_script().encode())
- # Install the gh shim at runtime too (see agentsh.GH_GUARD_INSTALL_PATH): a resume from a
- # pre-shim filesystem snapshot — or any window where the base image lags this backend —
- # would otherwise leave gh with no token once the frozen launch-env token is unset.
- self._write_required_file(GH_GUARD_INSTALL_PATH, read_gh_guard_script())
- self.execute(f"chmod +x {shlex.quote(GH_GUARD_INSTALL_PATH)}", timeout_seconds=30)
-
- if allowed_domains is not None:
- self._setup_agentsh(WORKING_DIR, allowed_domains)
+ self._prepare_agent_server_launch(allowed_domains)
mcp_servers_arg = ""
if mcp_configs:
@@ -465,93 +548,51 @@ class AgentServerLaunchMixin(SandboxBase):
)
exec_permission_regex = None
- command = self._build_agent_server_command(
- repo_path,
- task_id,
- run_id,
- mode,
- create_pr,
- auto_publish,
- interaction_origin,
- branch,
- agent_runtime,
- runtime_adapter,
- provider,
- model,
- reasoning_effort,
- service_tier=service_tier,
- context_window=context_window,
- fast_mode=fast_mode,
- initial_permission_mode=initial_permission_mode,
- mcp_servers_arg=mcp_servers_arg,
- relay_mcp_servers_arg=relay_mcp_servers_arg,
+ def build_command(base_branch: str | None) -> str:
+ return self._build_agent_server_command(
+ repo_path,
+ task_id,
+ run_id,
+ mode,
+ create_pr,
+ auto_publish,
+ interaction_origin,
+ base_branch,
+ agent_runtime,
+ runtime_adapter,
+ provider,
+ model,
+ reasoning_effort,
+ service_tier=service_tier,
+ context_window=context_window,
+ fast_mode=fast_mode,
+ initial_permission_mode=initial_permission_mode,
+ mcp_servers_arg=mcp_servers_arg,
+ relay_mcp_servers_arg=relay_mcp_servers_arg,
+ allowed_domains=allowed_domains,
+ event_ingest_token=event_ingest_token,
+ task_run_session_token=task_run_session_token,
+ event_ingest_url=event_ingest_url,
+ event_ingest_keep_stream_open=event_ingest_keep_stream_open,
+ repo_ready_file=repo_ready_file,
+ rtk_enabled=rtk_enabled,
+ benjamin_enabled=benjamin_enabled,
+ peer_messaging=peer_messaging,
+ posthog_exec_permission_regex=exec_permission_regex,
+ claude_model_access=claude_model_access,
+ )
+
+ logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")
+ return self._launch_prepared_agent_server(
+ build_command,
+ branch=branch,
+ task_id=task_id,
+ run_id=run_id,
+ wait_for_health=wait_for_health,
allowed_domains=allowed_domains,
- event_ingest_token=event_ingest_token,
- task_run_session_token=task_run_session_token,
- event_ingest_url=event_ingest_url,
- event_ingest_keep_stream_open=event_ingest_keep_stream_open,
- repo_ready_file=repo_ready_file,
- rtk_enabled=rtk_enabled,
- benjamin_enabled=benjamin_enabled,
- peer_messaging=peer_messaging,
- posthog_exec_permission_regex=exec_permission_regex,
claude_model_access=claude_model_access,
)
- logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")
- max_attempts = 300 if claude_model_access == "own-subscription" else AGENT_SERVER_HEALTH_MAX_ATTEMPTS
- execute_command = _start_and_wait_command(command, max_attempts) if wait_for_health else command
- timeout_seconds = 30 + health_check_timeout_seconds(max_attempts) if wait_for_health else 30
- start_time = time.perf_counter()
- 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 error
- 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)
- if (
- "claude_credential_unavailable" in launch_result.stdout
- or "claude_credential_unavailable" in diagnostics.get("log", "")
- ):
- raise ProcessTaskFatalError(
- "The Claude token did not arrive. Open Desktop and check your token in Settings > Harness. Then start the task again.",
- {"task_id": task_id, "run_id": run_id},
- RuntimeError("Claude token unavailable"),
- capture=False,
- )
- 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",
- {"sandbox_id": self.id, "stderr": launch_result.stderr, "exit_code": str(launch_result.exit_code)},
- cause=RuntimeError(launch_result.stderr or "launch command returned non-zero exit"),
- )
-
- if wait_for_health:
- 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, *, claude_model_access: str | None = None
) -> None:
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index 7b69b872da6c..0aa72f7a79b1 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -14,18 +14,15 @@ import logging
import tempfile
import threading
import subprocess
-from collections.abc import Iterable, Iterator
+from collections.abc import Callable, Iterable, Iterator
from contextlib import contextmanager
from contextvars import ContextVar
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Optional
+from typing import Any, Optional
from django.conf import settings
-if TYPE_CHECKING:
- from products.tasks.backend.temporal.process_task.utils import McpServerConfig
-
-from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEX, SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS
+from products.tasks.backend.constants import SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS
from products.tasks.backend.exceptions import (
ProcessTaskError,
ProcessTaskFatalError,
@@ -38,6 +35,7 @@ from products.tasks.backend.exceptions import (
)
from products.tasks.backend.models import SandboxSnapshot
+from .agent_server_launcher import AgentServerLaunchMixin
from .agentsh import (
BASH_ENV_SCRIPT,
ENV_WRAPPER_SCRIPT,
@@ -62,7 +60,6 @@ from .sandbox import (
AgentServerResult,
ExecutionResult,
ExecutionStream,
- SandboxBase,
SandboxConfig,
SandboxStatus,
SandboxTemplate,
@@ -177,7 +174,7 @@ def _run_cancellable_subprocess(
continue
-class DockerSandbox(SandboxBase):
+class DockerSandbox(AgentServerLaunchMixin):
"""
Docker-based sandbox for local development and testing.
Implements the same interface as the Modal-based Sandbox.
@@ -1041,129 +1038,43 @@ class DockerSandbox(SandboxBase):
New base images bake it in, but a resume from a pre-shim filesystem snapshot (or any window
where the image lags this backend) would otherwise lack it, leaving gh with no token once the
frozen launch-env token is unset."""
- self.write_file(GH_GUARD_INSTALL_PATH, read_gh_guard_script())
- self.execute(f"chmod +x {shlex.quote(GH_GUARD_INSTALL_PATH)}", timeout_seconds=30)
+ self._write_required_file(GH_GUARD_INSTALL_PATH, read_gh_guard_script())
+ self._chmod_required(GH_GUARD_INSTALL_PATH, "+x")
- def start_agent_server(
- self,
- repository: str | None,
- task_id: str,
- run_id: str,
- mode: str = "background",
- create_pr: bool = True,
- auto_publish: bool = False,
- interaction_origin: str | None = None,
- branch: str | None = None,
- agent_runtime: str | None = None,
- runtime_adapter: str | None = None,
- provider: str | None = None,
- model: str | None = None,
- reasoning_effort: str | None = None,
- service_tier: str | None = None,
- context_window: str | None = None,
- fast_mode: bool | None = None,
- initial_permission_mode: str | None = None,
- mcp_configs: list[McpServerConfig] | None = None,
- relayed_mcp_servers: list[str] | None = None,
- allowed_domains: list[str] | None = None,
- event_ingest_token: str | None = None,
- task_run_session_token: str | None = None,
- event_ingest_url: str | None = None,
- event_ingest_keep_stream_open: bool = False,
- repo_ready_file: str | None = None,
- wait_for_health: bool = True,
- rtk_enabled: bool = True,
- benjamin_enabled: bool = False,
- peer_messaging: bool = False,
- claude_model_access: str | None = None,
- ) -> None:
- """Start the agent-server HTTP server in the sandbox.
-
- The sandbox URL should be obtained via get_connect_credentials()
- before calling this method.
- """
- if not self.is_running():
- raise RuntimeError("Sandbox not in running state.")
+ def supports_combined_agent_server_start_and_health(self) -> bool:
+ return False
+ def _validate_agent_server_launch(self) -> None:
+ super()._validate_agent_server_launch()
if self._host_port is None:
raise RuntimeError("Sandbox was not created with port exposure.")
- self.clear_bundled_skills_if_disabled()
-
- repo_path: str | None = None
- if repository:
- org, repo = repository.lower().split("/")
- repo_path = f"/tmp/workspace/repos/{org}/{repo}"
+ def _reuse_healthy_agent_server(self, allowed_domains: list[str] | None) -> bool:
+ return False
+ 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
# mid-session credential refreshes reach git/gh. Needed for both agentsh
# and non-agentsh runs.
- self.write_file(BASH_ENV_SCRIPT, generate_bash_env_script().encode())
+ self._write_required_file(BASH_ENV_SCRIPT, generate_bash_env_script().encode())
self._install_gh_guard()
if allowed_domains is not None:
self._setup_agentsh(WORKING_DIR, allowed_domains)
- mcp_servers_arg = ""
- if mcp_configs:
- mcp_json = json.dumps([c.to_dict() for c in mcp_configs])
- mcp_servers_arg = f" --mcpServers {shlex.quote(mcp_json)}"
-
- relay_mcp_servers_arg = ""
- 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():
- raise RuntimeError("Installed sandbox agent-server does not support the Pi runtime")
-
- if auto_publish and not self.agent_server_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():
- logger.warning(
- f"Installed agent-server in sandbox {self.id} predates --posthogExecPermissionRegex; "
- "connected-project operations will not prompt"
- )
- exec_permission_regex = None
-
- command = self._build_agent_server_command(
- repo_path,
- task_id,
- run_id,
- mode,
- create_pr,
- auto_publish,
- interaction_origin,
- branch,
- agent_runtime,
- runtime_adapter,
- provider,
- model,
- reasoning_effort,
- service_tier=service_tier,
- context_window=context_window,
- fast_mode=fast_mode,
- initial_permission_mode=initial_permission_mode,
- mcp_servers_arg=mcp_servers_arg,
- relay_mcp_servers_arg=relay_mcp_servers_arg,
- allowed_domains=allowed_domains,
- event_ingest_token=event_ingest_token,
- task_run_session_token=task_run_session_token,
- event_ingest_url=event_ingest_url,
- event_ingest_keep_stream_open=event_ingest_keep_stream_open,
- repo_ready_file=repo_ready_file,
- rtk_enabled=rtk_enabled,
- benjamin_enabled=benjamin_enabled,
- peer_messaging=peer_messaging,
- posthog_exec_permission_regex=exec_permission_regex,
- claude_model_access=claude_model_access,
- )
-
- logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")
-
+ def _launch_prepared_agent_server(
+ self,
+ build_command: Callable[[str | None], str],
+ *,
+ branch: str | None,
+ task_id: str,
+ run_id: str,
+ wait_for_health: bool,
+ allowed_domains: list[str] | None,
+ claude_model_access: str | None,
+ ) -> int | None:
+ command = build_command(branch)
if not wait_for_health:
result = self.execute(command, timeout_seconds=30)
if result.exit_code != 0:
@@ -1172,12 +1083,12 @@ class DockerSandbox(SandboxBase):
{"sandbox_id": self.id, "stderr": result.stderr, "exit_code": str(result.exit_code)},
cause=RuntimeError(result.stderr or "launch command returned non-zero exit"),
)
- return
+ return None
max_attempts = 300 if claude_model_access == "own-subscription" else 20
if self._launch_and_check(command, max_attempts=max_attempts):
logger.info(f"Agent-server started on port {self._host_port}")
- return
+ return None
# If branch flag was used, the installed agent-server version may not support --baseBranch.
# Kill the failed process and retry without it.
@@ -1189,41 +1100,10 @@ class DockerSandbox(SandboxBase):
)
self.execute("pkill -f agent-server || true", timeout_seconds=5)
- command = self._build_agent_server_command(
- repo_path,
- task_id,
- run_id,
- mode,
- create_pr,
- auto_publish,
- interaction_origin,
- branch=None,
- agent_runtime=agent_runtime,
- runtime_adapter=runtime_adapter,
- provider=provider,
- model=model,
- reasoning_effort=reasoning_effort,
- service_tier=service_tier,
- context_window=context_window,
- fast_mode=fast_mode,
- initial_permission_mode=initial_permission_mode,
- mcp_servers_arg=mcp_servers_arg,
- relay_mcp_servers_arg=relay_mcp_servers_arg,
- allowed_domains=allowed_domains,
- event_ingest_token=event_ingest_token,
- task_run_session_token=task_run_session_token,
- event_ingest_url=event_ingest_url,
- event_ingest_keep_stream_open=event_ingest_keep_stream_open,
- repo_ready_file=repo_ready_file,
- rtk_enabled=rtk_enabled,
- benjamin_enabled=benjamin_enabled,
- peer_messaging=peer_messaging,
- posthog_exec_permission_regex=exec_permission_regex,
- claude_model_access=claude_model_access,
- )
+ command = build_command(None)
if self._launch_and_check(command, max_attempts=max_attempts):
logger.info(f"Agent-server started on port {self._host_port} (without --baseBranch)")
- return
+ return None
log_result = self.execute("cat /tmp/agent-server.log 2>/dev/null || echo 'No log file'", timeout_seconds=5)
logger.warning(f"Agent-server health check failed for sandbox {self.id}. Log output:\n{log_result.stdout}")
diff --git a/products/tasks/backend/logic/services/launch_preparation_metrics.py b/products/tasks/backend/logic/services/launch_preparation_metrics.py
new file mode 100644
index 000000000000..ae8d3883e7c0
--- /dev/null
+++ b/products/tasks/backend/logic/services/launch_preparation_metrics.py
@@ -0,0 +1,43 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+from contextvars import ContextVar
+from datetime import timedelta
+from typing import Literal
+
+from temporalio.activity import metric_meter
+
+_launch_preparation_attributes: ContextVar[dict[str, str] | None] = ContextVar(
+ "launch_preparation_attributes", default=None
+)
+
+
+@contextmanager
+def launch_preparation_metric_context(
+ *, boot_path: str, runtime: str, origin_product: str | None, used_snapshot: bool | None
+) -> Iterator[None]:
+ token = _launch_preparation_attributes.set(
+ {
+ "boot_path": boot_path,
+ "runtime": runtime,
+ "origin_product": origin_product or "unknown",
+ "used_snapshot": "unknown" if used_snapshot is None else str(used_snapshot).lower(),
+ }
+ )
+ try:
+ yield
+ finally:
+ _launch_preparation_attributes.reset(token)
+
+
+def record_launch_preparation_ms(duration_ms: int, status: Literal["COMPLETED", "FAILED"]) -> None:
+ attributes = _launch_preparation_attributes.get()
+ if attributes is None:
+ return
+ try:
+ metric_meter().with_additional_attributes({**attributes, "status": status}).create_histogram_timedelta(
+ "tasks_modal_launch_preparation_latency",
+ "Modal launch file installation and agentsh preparation, including upload",
+ unit="ms",
+ ).record(timedelta(milliseconds=duration_ms))
+ except Exception:
+ pass
diff --git a/products/tasks/backend/logic/services/modal_launch_preparation.py b/products/tasks/backend/logic/services/modal_launch_preparation.py
new file mode 100644
index 000000000000..1a034ecfdcde
--- /dev/null
+++ b/products/tasks/backend/logic/services/modal_launch_preparation.py
@@ -0,0 +1,115 @@
+import shlex
+import base64
+
+from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR
+
+from .agentsh import (
+ AGENTSH_DAEMON_PORT,
+ BASH_ENV_SCRIPT,
+ ENV_WRAPPER_SCRIPT,
+ GH_GUARD_INSTALL_PATH,
+ SESSION_ID_FILE,
+ generate_bash_env_script,
+ generate_config_yaml,
+ generate_env_wrapper,
+ generate_policy_yaml,
+ read_gh_guard_script,
+)
+
+
+def build_modal_launch_preparation_script(allowed_domains: list[str] | None) -> str:
+ files = [
+ (BASH_ENV_SCRIPT, generate_bash_env_script().encode(), "644"),
+ (GH_GUARD_INSTALL_PATH, read_gh_guard_script(), "755"),
+ ]
+ if allowed_domains is not None:
+ files.extend(
+ [
+ ("/etc/agentsh/config.yaml", generate_config_yaml(enable_ptrace=True, full_trace=True).encode(), "644"),
+ ("/etc/agentsh/policies/default.yaml", generate_policy_yaml(allowed_domains).encode(), "644"),
+ (ENV_WRAPPER_SCRIPT, generate_env_wrapper().encode(), "755"),
+ ]
+ )
+
+ script = [
+ "#!/bin/bash",
+ "set -euo pipefail",
+ "umask 077",
+ "stage=install",
+ "staged_files=()",
+ 'daemon_pid=""',
+ "started_at=$(date +%s%3N)",
+ "cleanup() {",
+ " result=$?",
+ " trap - EXIT",
+ ' if [ "$result" -ne 0 ] && [ -n "$daemon_pid" ]; then',
+ ' kill "$daemon_pid" 2>/dev/null || true',
+ " for i in $(seq 1 20); do",
+ ' if ! kill -0 "$daemon_pid" 2>/dev/null; then break; fi',
+ " sleep 0.1",
+ " done",
+ ' kill -KILL "$daemon_pid" 2>/dev/null || true',
+ ' wait "$daemon_pid" 2>/dev/null || true',
+ " fi",
+ ' if [ "$result" -ne 0 ]; then printf "__posthog_launch_preparation_failed=%s\\n" "$stage" >&2; fi',
+ ' rm -f -- "${staged_files[@]}" "$0" || true',
+ ' exit "$result"',
+ "}",
+ "trap cleanup EXIT",
+ ]
+ for path, payload, mode in files:
+ destination = shlex.quote(path)
+ encoded = shlex.quote(base64.b64encode(payload).decode())
+ script.extend(
+ [
+ f'mkdir -p -- "$(dirname -- {destination})"',
+ f"temporary=$(mktemp {shlex.quote(path + '.tmp.XXXXXX')})",
+ 'staged_files+=("$temporary")',
+ f'printf %s {encoded} | base64 -d > "$temporary"',
+ f'chmod {mode} "$temporary"',
+ ]
+ )
+ for index, (path, _, _) in enumerate(files):
+ script.append(f"test ! -d {shlex.quote(path)}")
+ script.append(f'mv -f -- "${{staged_files[{index}]}}" {shlex.quote(path)}')
+ script.extend(
+ [
+ "installed_at=$(date +%s%3N)",
+ 'printf "__posthog_launch_preparation_install_ms=%s\\n" "$((installed_at - started_at))"',
+ ]
+ )
+
+ if allowed_domains is not None:
+ script.extend(
+ [
+ "stage=daemon_session",
+ "pkill -f '[a]gentsh server' || [ $? -eq 1 ]",
+ "for i in $(seq 1 50); do",
+ " if ! pgrep -f '[a]gentsh server' > /dev/null; then break; fi",
+ " sleep 0.1",
+ "done",
+ "if pgrep -f '[a]gentsh server' > /dev/null; then exit 1; fi",
+ "mkdir -p /var/log/agentsh /var/lib/agentsh/sessions",
+ f"rm -f -- {shlex.quote(SESSION_ID_FILE)}",
+ "nohup agentsh server --config /etc/agentsh/config.yaml > /var/log/agentsh/agentsh.log 2>&1 &",
+ "daemon_pid=$!",
+ "healthy=0",
+ "for i in $(seq 1 30); do",
+ f" if [ \"$(curl -s --max-time 1 -o /dev/null -w '%{{http_code}}' http://127.0.0.1:{AGENTSH_DAEMON_PORT}/health || true)\" = 200 ]; then",
+ " healthy=1",
+ " break",
+ " fi",
+ " sleep 0.5",
+ "done",
+ '[ "$healthy" -eq 1 ]',
+ 'kill -0 "$daemon_pid"',
+ f"session_id=$(timeout 60s agentsh session create --workspace {shlex.quote(DEFAULT_SANDBOX_WORKING_DIR)} --policy default --json | jq -er '.id | select(type == \"string\" and length > 0)')",
+ f"temporary=$(mktemp {shlex.quote(SESSION_ID_FILE + '.tmp.XXXXXX')})",
+ 'staged_files+=("$temporary")',
+ 'printf %s "$session_id" > "$temporary"',
+ f'mv -f -- "$temporary" {shlex.quote(SESSION_ID_FILE)}',
+ f"test -s {shlex.quote(SESSION_ID_FILE)}",
+ 'printf "__posthog_launch_preparation_daemon_session_ms=%s\\n" "$(($(date +%s%3N) - installed_at))"',
+ ]
+ )
+ return "\n".join(script) + "\n"
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index fee2483aa626..073d422bf73e 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -59,6 +59,12 @@ from products.tasks.backend.exceptions import (
SnapshotFileLimitExceededError,
SnapshotTimeoutError,
)
+from products.tasks.backend.logic.services.agentsh import (
+ BASH_ENV_SCRIPT,
+ GH_GUARD_INSTALL_PATH,
+ generate_bash_env_script,
+ read_gh_guard_script,
+)
from products.tasks.backend.logic.services.cpu_billing import (
CPU_BILLING_SAMPLER_PATH as CPU_BILLING_SAMPLER_PATH,
CPU_BILLING_STATE_PATH,
@@ -66,6 +72,7 @@ from products.tasks.backend.logic.services.cpu_billing import (
compute_billed_cpu_usage_usec,
parse_cpu_stat_usage_usec,
)
+from products.tasks.backend.logic.services.launch_preparation_metrics import record_launch_preparation_ms
from products.tasks.backend.logic.services.local_packages import (
LocalPackage,
get_local_package_runtime_dependencies,
@@ -76,6 +83,7 @@ from products.tasks.backend.logic.services.local_skills import (
LocalSkillsCache,
populate_skills_directory,
)
+from products.tasks.backend.logic.services.modal_launch_preparation import build_modal_launch_preparation_script
from products.tasks.backend.logic.services.modal_provision_diagnostics import (
SandboxProvisionDiagnostics,
capture_modal_output_if_debug,
@@ -753,6 +761,80 @@ 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 _prepare_agent_server_launch(self, allowed_domains: list[str] | None) -> None:
+ script_path = f"/tmp/posthog-launch-preparation-{uuid.uuid4().hex}.sh"
+ started_at = time.monotonic()
+ result: ExecutionResult | None = None
+ try:
+ self._write_required_file(script_path, build_modal_launch_preparation_script(allowed_domains).encode())
+ uploaded_at = time.monotonic()
+ result = self.execute(f"bash {shlex.quote(script_path)}", timeout_seconds=120)
+ finally:
+ total_ms = round((time.monotonic() - started_at) * 1000)
+ record_launch_preparation_ms(
+ total_ms, "COMPLETED" if result is not None and result.exit_code == 0 else "FAILED"
+ )
+ timings = {
+ stage: int(duration)
+ for stage, duration in re.findall(
+ r"^__posthog_launch_preparation_(install_ms|daemon_session_ms)=(\d+)$", result.stdout, re.MULTILINE
+ )
+ }
+ logger.info(
+ "Modal launch preparation finished in sandbox %s: upload_ms=%d install_ms=%s "
+ "daemon_session_ms=%s total_ms=%d exit_code=%d",
+ self.id,
+ round((uploaded_at - started_at) * 1000),
+ timings.get("install_ms"),
+ timings.get("daemon_session_ms"),
+ total_ms,
+ result.exit_code,
+ )
+ if result.exit_code != 0:
+ stage = re.search(
+ r"^__posthog_launch_preparation_failed=(install|daemon_session)$", result.stderr, re.MULTILINE
+ )
+ preparation_stage = stage.group(1) if stage else "unknown"
+ agentsh_log = ""
+ if preparation_stage == "daemon_session":
+ try:
+ agentsh_log = self.execute(
+ "tail -c 2000 /var/log/agentsh/agentsh.log 2>/dev/null || true", timeout_seconds=5
+ ).stdout[-2000:]
+ except Exception:
+ logger.warning("Failed to read agentsh diagnostics in sandbox %s", self.id, exc_info=True)
+ logger.error(
+ "Modal launch preparation failed in sandbox %s; stderr=%r agentsh_log=%r",
+ self.id,
+ result.stderr[-1000:],
+ agentsh_log,
+ )
+ raise SandboxExecutionError(
+ "Failed to prepare agent-server launch",
+ {
+ "sandbox_id": self.id,
+ "preparation_stage": preparation_stage,
+ "exit_code": result.exit_code,
+ "stderr": result.stderr[-1000:],
+ "agentsh_log": agentsh_log,
+ },
+ cause=RuntimeError("Modal launch preparation failed"),
+ )
+
@property
def sandbox_url(self) -> str | None:
"""Return the URL for connecting to the agent server, or None if not available."""
diff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.py
index 85e658d41139..4de9fff5b264 100644
--- a/products/tasks/backend/logic/services/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py
@@ -517,7 +517,7 @@ class TestDockerSandboxUnit:
assert shlex.quote(mode) in command
assert "--createPr true" in command
- def test_start_agent_server_preserves_pi_protocol_without_branch_retry(self) -> None:
+ def test_start_agent_server_preserves_pi_protocol_on_branch_retry(self) -> None:
sandbox = DockerSandbox.__new__(DockerSandbox)
sandbox._container_id = "abc123"
sandbox.id = "abc123"
@@ -526,14 +526,13 @@ class TestDockerSandboxUnit:
with (
patch.object(sandbox, "is_running", return_value=True),
- patch.object(sandbox, "write_file"),
+ 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]),
- patch.object(
- sandbox, "_build_agent_server_command", wraps=sandbox._build_agent_server_command
- ) as mock_build,
+ patch.object(sandbox, "_launch_and_check", side_effect=[False, True]) as launch,
):
mock_execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
sandbox.start_agent_server(
@@ -544,8 +543,13 @@ class TestDockerSandboxUnit:
agent_runtime="pi",
)
- assert mock_build.call_count == 2
- assert mock_build.call_args_list[1].kwargs["agent_runtime"] == "pi"
+ assert launch.call_count == 2
+ first_command = launch.call_args_list[0].args[0]
+ retry_command = launch.call_args_list[1].args[0]
+ assert "--baseBranch main" in first_command
+ assert "--baseBranch" not in retry_command
+ assert "POSTHOG_AGENT_RUNTIME=pi" in first_command
+ assert "POSTHOG_AGENT_RUNTIME=pi" in retry_command
def test_start_agent_server_rejects_an_image_without_pi_support(self) -> None:
sandbox = DockerSandbox.__new__(DockerSandbox)
@@ -556,7 +560,9 @@ class TestDockerSandboxUnit:
with (
patch.object(sandbox, "is_running", return_value=True),
- patch.object(sandbox, "write_file"),
+ patch.object(
+ sandbox, "write_file", return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
+ ),
patch.object(
sandbox, "execute", return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
),
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 6e4893a39930..d41ab47f5e8f 100644
--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
@@ -24,6 +24,10 @@ def _log_result() -> ExecutionResult:
return ExecutionResult(stdout="agent-server log", stderr="", exit_code=0)
+def _ok_result() -> ExecutionResult:
+ return ExecutionResult(stdout="", stderr="", exit_code=0)
+
+
@pytest.mark.parametrize(
("capabilities", "expected"),
[
@@ -66,7 +70,7 @@ def test_wait_for_agent_server_ready_timeout_is_retryable_and_not_captured(sandb
def test_start_agent_server_health_check_timeout_is_retryable_and_not_captured(sandbox: DockerSandbox):
with (
patch.object(sandbox, "is_running", return_value=True),
- patch.object(sandbox, "write_file"),
+ patch.object(sandbox, "write_file", return_value=_ok_result()),
patch.object(sandbox, "_build_agent_server_command", return_value="run-agent-server"),
patch.object(sandbox, "_launch_and_check", return_value=False),
patch.object(sandbox, "execute", return_value=_log_result()),
@@ -116,14 +120,14 @@ def test_start_agent_server_launch_failure_is_captured(sandbox: DockerSandbox):
failed = ExecutionResult(stdout="", stderr="boom", exit_code=1)
def execute(command: str, **kwargs) -> ExecutionResult:
- # Only the launch fails; the bundled-skills clear that precedes it succeeds.
- if ENV_DISABLE_BUNDLED_SKILLS in command:
- return ExecutionResult(stdout="", stderr="", exit_code=0)
+ # 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 "):
+ return _ok_result()
return failed
with (
patch.object(sandbox, "is_running", return_value=True),
- patch.object(sandbox, "write_file"),
+ 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),
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
new file mode 100644
index 000000000000..4ed45132b42a
--- /dev/null
+++ b/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.py
@@ -0,0 +1,295 @@
+import os
+import re
+import shlex
+import signal
+import subprocess
+from datetime import timedelta
+from pathlib import Path
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.tasks.backend.exceptions import SandboxExecutionError
+from products.tasks.backend.logic.services.agentsh import (
+ BASH_ENV_SCRIPT,
+ ENV_WRAPPER_SCRIPT,
+ GH_GUARD_INSTALL_PATH,
+ SESSION_ID_FILE,
+ generate_bash_env_script,
+ generate_config_yaml,
+ generate_env_wrapper,
+ generate_policy_yaml,
+ read_gh_guard_script,
+)
+from products.tasks.backend.logic.services.launch_preparation_metrics import (
+ launch_preparation_metric_context,
+ record_launch_preparation_ms,
+)
+from products.tasks.backend.logic.services.modal_launch_preparation import build_modal_launch_preparation_script
+from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
+from products.tasks.backend.logic.services.sandbox import ExecutionResult, SandboxConfig
+
+
+def shell_environment(tmp_path: Path) -> dict[str, str]:
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ commands = {
+ "date": "echo 1000",
+ "sleep": "true",
+ "pkill": "exit 1",
+ "pgrep": '[ "${PREPARATION_FAULT:-}" = daemon_stop ]',
+ "curl": 'if [ "${PREPARATION_FAULT:-}" = health ]; then echo 000; exit 7; fi; echo 200',
+ "agentsh": """
+if [ "$1" = server ]; then exit 0; fi
+case "${PREPARATION_FAULT:-}" in
+ session) echo '{"id":"partial-session"}'; exit 23 ;;
+ empty_session) echo '{"id":""}' ;;
+ null_session) echo '{"id":null}' ;;
+ *) echo '{"id":"ready-session"}' ;;
+esac
+""",
+ }
+ for name, command in commands.items():
+ path = bin_dir / name
+ path.write_text(f"#!/bin/bash\n{command}\n")
+ path.chmod(0o755)
+ return {"PATH": f"{bin_dir}:{os.environ['PATH']}"}
+
+
+def run_preparation(
+ root: Path, allowed_domains: list[str] | None, environment: dict[str, str]
+) -> subprocess.CompletedProcess[str]:
+ script = build_modal_launch_preparation_script(allowed_domains)
+ script = re.sub(r"/(?:tmp|etc|opt|var)/", lambda match: f"{root}{match.group()}", script)
+ if environment.get("PREPARATION_REAL_DAEMON") != "1":
+ script = 'kill() { [ "${PREPARATION_FAULT:-}" != daemon_start ]; }\n' + script
+ script_path = root / "preparation.sh"
+ script_path.write_text(script)
+ return subprocess.run(
+ ["bash", str(script_path)], cwd=root, env=environment, capture_output=True, text=True, timeout=10
+ )
+
+
[email protected]("allowed_domains", [None, [], ["example.com", "$(touch injected);'example.com"]])
+def test_preparation_installs_complete_files_and_can_be_reapplied(
+ tmp_path: Path, shell_environment: dict[str, str], allowed_domains: list[str] | None
+) -> None:
+ expected_files = {
+ BASH_ENV_SCRIPT: (generate_bash_env_script().encode(), 0o644),
+ GH_GUARD_INSTALL_PATH: (read_gh_guard_script(), 0o755),
+ }
+ if allowed_domains is not None:
+ expected_files.update(
+ {
+ "/etc/agentsh/config.yaml": (generate_config_yaml(enable_ptrace=True, full_trace=True).encode(), 0o644),
+ "/etc/agentsh/policies/default.yaml": (generate_policy_yaml(allowed_domains).encode(), 0o644),
+ ENV_WRAPPER_SCRIPT: (generate_env_wrapper().encode(), 0o755),
+ SESSION_ID_FILE: (b"ready-session", 0o600),
+ }
+ )
+ for _ in range(2):
+ result = run_preparation(tmp_path, allowed_domains, shell_environment)
+ assert result.returncode == 0, result.stderr
+ for path, (payload, mode) in expected_files.items():
+ installed = tmp_path / path.lstrip("/")
+ assert installed.read_bytes() == payload
+ assert installed.stat().st_mode & 0o777 == mode
+ assert not list(tmp_path.rglob("*.tmp.*"))
+ assert not (tmp_path / "preparation.sh").exists()
+ assert not (tmp_path / "injected").exists()
+ if allowed_domains is None:
+ assert not (tmp_path / "etc/agentsh").exists()
+ assert not (tmp_path / SESSION_ID_FILE.lstrip("/")).exists()
+
+
+ "fault", ["install", "rename", "daemon_stop", "daemon_start", "health", "session", "empty_session", "null_session"]
+)
+def test_preparation_stops_on_failure_and_cleans_staged_files(
+ tmp_path: Path, shell_environment: dict[str, str], fault: str
+) -> None:
+ bash_env = tmp_path / BASH_ENV_SCRIPT.lstrip("/")
+ bash_env.parent.mkdir(parents=True)
+ bash_env.write_bytes(b"previous-complete-file")
+ if fault == "install":
+ chmod = tmp_path / "bin/chmod"
+ chmod.write_text("#!/bin/bash\nexit 19\n")
+ chmod.chmod(0o755)
+ elif fault == "rename":
+ destination = tmp_path / GH_GUARD_INSTALL_PATH.lstrip("/")
+ destination.mkdir(parents=True)
+
+ result = run_preparation(tmp_path, [], {**shell_environment, "PREPARATION_FAULT": fault})
+
+ assert result.returncode != 0
+ stage = "install" if fault in ("install", "rename") else "daemon_session"
+ assert f"__posthog_launch_preparation_failed={stage}" in result.stderr
+ assert not list(tmp_path.rglob("*.tmp.*"))
+ assert not (tmp_path / "preparation.sh").exists()
+ assert not (tmp_path / SESSION_ID_FILE.lstrip("/")).exists()
+ if fault == "install":
+ assert bash_env.read_bytes() == b"previous-complete-file"
+
+
[email protected]("fault", [None, "health", "session", "unresponsive_daemon"])
+def test_preparation_preserves_daemon_only_on_success(
+ tmp_path: Path, shell_environment: dict[str, str], fault: str | None
+) -> None:
+ os.mkfifo(tmp_path / "daemon_ready")
+ os.mkfifo(tmp_path / "daemon_block")
+ (tmp_path / "bin/agentsh").write_text(
+ "#!/bin/bash\n"
+ 'if [ "$1" = server ]; then\n'
+ + ("trap '' TERM\n" if fault == "unresponsive_daemon" else "")
+ + "echo $$ > daemon.pid\n"
+ "echo ready > daemon_ready\n"
+ "exec cat daemon_block\n"
+ "fi\n"
+ 'echo \'{"id":"partial-session"}\'\n' + ("exit 0\n" if fault is None else "exit 23\n")
+ )
+ (tmp_path / "bin/curl").write_text(
+ "#!/bin/bash\n"
+ "if [ ! -f probe_started ]; then read -r < daemon_ready; touch probe_started; fi\n"
+ + ("echo 000\n" if fault == "health" else "echo 200\n")
+ )
+ try:
+ result = run_preparation(tmp_path, [], {**shell_environment, "PREPARATION_REAL_DAEMON": "1"})
+
+ daemon_pid = int((tmp_path / "daemon.pid").read_text())
+ if fault is None:
+ assert result.returncode == 0
+ os.kill(daemon_pid, 0)
+ else:
+ assert result.returncode == (1 if fault == "health" else 23)
+ assert "__posthog_launch_preparation_failed=daemon_session" in result.stderr
+ with pytest.raises(ProcessLookupError):
+ os.kill(daemon_pid, 0)
+ assert not (tmp_path / "preparation.sh").exists()
+ finally:
+ if (tmp_path / "daemon.pid").exists():
+ try:
+ os.kill(int((tmp_path / "daemon.pid").read_text()), signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+
+
+ ("failure", "log_available"),
+ [("upload", True), ("execute", True), ("install", True), ("daemon_session", True), ("daemon_session", False)],
+)
+def test_failed_preparation_never_launches_agent_server(failure: str, log_available: bool) -> None:
+ handle = MagicMock(object_id="sb-test")
+ handle.poll.return_value = None
+ with patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()):
+ sandbox = ModalSandbox(handle, SandboxConfig(name="test"))
+
+ def execute(command: str, timeout_seconds: int | None = None) -> ExecutionResult:
+ if command.startswith("bash /tmp/posthog-launch-preparation-"):
+ if failure == "execute":
+ raise SandboxExecutionError("execution failed", {}, cause=RuntimeError("execution failed"))
+ return ExecutionResult(stdout="", stderr=f"__posthog_launch_preparation_failed={failure}\n", exit_code=1)
+ if command.startswith("tail -c 2000 /var/log/agentsh/agentsh.log"):
+ if not log_available:
+ raise RuntimeError("log unavailable")
+ return ExecutionResult(stdout="x" * 2100 + "daemon startup failed", stderr="", exit_code=0)
+ 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,
+ "write_file",
+ return_value=ExecutionResult(stdout="", stderr="", exit_code=1 if failure == "upload" else 0),
+ ) as write_file,
+ patch("products.tasks.backend.exceptions.capture_exception") as capture_exception,
+ patch("products.tasks.backend.logic.services.modal_sandbox.logger") as logger,
+ launch_preparation_metric_context(
+ boot_path="overlap", runtime="gvisor", origin_product=None, used_snapshot=True
+ ),
+ patch("products.tasks.backend.logic.services.launch_preparation_metrics.metric_meter") as metric_meter,
+ ):
+ with pytest.raises(SandboxExecutionError) as raised:
+ sandbox.start_agent_server(repository=None, task_id="task-test", run_id="run-test", allowed_domains=[])
+
+ if failure not in ("upload", "execute"):
+ context = raised.value.context
+ assert context["preparation_stage"] == failure
+ assert context["exit_code"] == 1
+ assert context["stderr"] == f"__posthog_launch_preparation_failed={failure}\n"
+ expected_log = (
+ ("x" * 2100 + "daemon startup failed")[-2000:] if log_available and failure == "daemon_session" else ""
+ )
+ assert context["agentsh_log"] == expected_log
+ assert capture_exception.call_args.args[1]["agentsh_log"] == expected_log
+ if failure == "daemon_session":
+ assert logger.error.call_args.args[-1] == expected_log
+ metric_meter.return_value.with_additional_attributes.assert_called_once_with(
+ {
+ "boot_path": "overlap",
+ "runtime": "gvisor",
+ "origin_product": "unknown",
+ "used_snapshot": "true",
+ "status": "FAILED",
+ }
+ )
+ metric_meter.return_value.with_additional_attributes.return_value.create_histogram_timedelta.return_value.record.assert_called_once()
+ assert write_file.call_count == 1
+ commands = [call.args[0] for call in remote_execute.call_args_list]
+ assert not any("./node_modules/.bin/agent-server" in command for command in commands)
+ preparation_commands = [
+ command for command in commands if command.startswith("bash /tmp/posthog-launch-preparation-")
+ ]
+ assert len(preparation_commands) == (0 if failure == "upload" else 1)
+ if preparation_commands:
+ assert shlex.split(preparation_commands[0])[1] == write_file.call_args.args[0]
+
+
[email protected]("export_fails", [False, True])
+def test_preparation_metric_measures_only_upload_and_execution(export_fails: bool) -> None:
+ handle = MagicMock(object_id="sb-test")
+ with patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()):
+ sandbox = ModalSandbox(handle, SandboxConfig(name="test"))
+ with (
+ launch_preparation_metric_context(
+ boot_path="classic", runtime="vm", origin_product="user_created", used_snapshot=False
+ ),
+ patch.object(sandbox, "write_file", return_value=ExecutionResult(stdout="", stderr="", exit_code=0)),
+ patch.object(sandbox, "execute", return_value=ExecutionResult(stdout="", stderr="", exit_code=0)),
+ 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),
+ ):
+ clock.monotonic.side_effect = [10.0, 10.5, 11.25]
+ if export_fails:
+ metric_meter.side_effect = RuntimeError("export unavailable")
+
+ sandbox._prepare_agent_server_launch(None)
+ assert sandbox.start_agent_server(repository=None, task_id="task-test", run_id="run-test") == 0
+
+ metric_meter.assert_called_once_with()
+ if not export_fails:
+ metric_meter.return_value.with_additional_attributes.assert_called_once_with(
+ {
+ "boot_path": "classic",
+ "runtime": "vm",
+ "origin_product": "user_created",
+ "used_snapshot": "false",
+ "status": "COMPLETED",
+ }
+ )
+ metric_meter.return_value.with_additional_attributes.return_value.create_histogram_timedelta.assert_called_once_with(
+ "tasks_modal_launch_preparation_latency",
+ "Modal launch file installation and agentsh preparation, including upload",
+ unit="ms",
+ )
+ metric_meter.return_value.with_additional_attributes.return_value.create_histogram_timedelta.return_value.record.assert_called_once_with(
+ timedelta(milliseconds=1250)
+ )
+ with patch("products.tasks.backend.logic.services.launch_preparation_metrics.metric_meter") as unscoped_meter:
+ record_launch_preparation_ms(50, "COMPLETED")
+ unscoped_meter.assert_not_called()
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 bd2804159c08..aa358450b3dd 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -567,7 +567,7 @@ class TestModalSandboxAgentServer:
return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
)
- with patch.object(mock_sandbox, "_setup_agentsh") as mock_setup:
+ with patch.object(mock_sandbox, "_prepare_agent_server_launch") as mock_setup:
mock_sandbox.start_agent_server(
repository="posthog/posthog",
task_id="task-123",
@@ -575,7 +575,7 @@ class TestModalSandboxAgentServer:
mode="background",
)
- mock_setup.assert_not_called()
+ mock_setup.assert_called_once_with(None)
command = _agent_server_launch_command(mock_sandbox.execute)
import shlex
@@ -664,7 +664,7 @@ class TestModalSandboxAgentServer:
return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
)
- with patch.object(mock_sandbox, "_setup_agentsh") as mock_setup_agentsh:
+ with patch.object(mock_sandbox, "_prepare_agent_server_launch") as mock_setup_agentsh:
mock_sandbox.start_agent_server(
repository="posthog/posthog",
task_id="task-123",
@@ -673,10 +673,7 @@ class TestModalSandboxAgentServer:
allowed_domains=["example.com"],
)
- mock_setup_agentsh.assert_called_once_with(
- "/tmp/workspace",
- ["example.com"],
- )
+ mock_setup_agentsh.assert_called_once_with(["example.com"])
command = _agent_server_launch_command(mock_sandbox.execute)
assert "--createPr true" in command
assert "agentsh exec --client-timeout 2h --timeout 2h" in command
@@ -690,7 +687,7 @@ class TestModalSandboxAgentServer:
return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
)
- with patch.object(mock_sandbox, "_setup_agentsh") as mock_setup_agentsh:
+ with patch.object(mock_sandbox, "_prepare_agent_server_launch") as mock_setup_agentsh:
mock_sandbox.start_agent_server(
repository="posthog/posthog",
task_id="task-123",
@@ -699,7 +696,7 @@ class TestModalSandboxAgentServer:
allowed_domains=[],
)
- mock_setup_agentsh.assert_called_once_with("/tmp/workspace", [])
+ mock_setup_agentsh.assert_called_once_with([])
command = _agent_server_launch_command(mock_sandbox.execute)
assert "--allowedDomains" not in command
assert "agentsh exec --client-timeout 2h --timeout 2h" in command
@@ -717,7 +714,7 @@ class TestModalSandboxAgentServer:
return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
)
- with patch.object(mock_sandbox, "_setup_agentsh"):
+ with patch.object(mock_sandbox, "_prepare_agent_server_launch"):
mock_sandbox.start_agent_server(
repository="posthog/posthog",
task_id="task-123",
@@ -897,7 +894,7 @@ class TestModalSandboxAgentServer:
mock_sandbox.execute = MagicMock(side_effect=execute)
- with patch.object(mock_sandbox, "_setup_agentsh"):
+ with patch.object(mock_sandbox, "_prepare_agent_server_launch"):
with pytest.raises(SandboxExecutionError, match="Agent-server failed to start"):
mock_sandbox.start_agent_server(
repository="posthog/posthog",
@@ -906,21 +903,13 @@ class TestModalSandboxAgentServer:
)
def test_start_agent_server_raises_on_health_check_failure(self, mock_sandbox: Any):
- mock_sandbox.execute = MagicMock(
- side_effect=[
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # bundled-skills clear
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- 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="__posthog_agent_health_ms=120000", stderr="", exit_code=1, error=None),
- ]
- )
+ def execute(command: str, timeout_seconds: int | None = None) -> ExecutionResult:
+ if "./node_modules/.bin/agent-server" in command:
+ return ExecutionResult(stdout="__posthog_agent_health_ms=120000", stderr="", exit_code=1)
+ return ExecutionResult(stdout="", stderr="", exit_code=0)
- with (
- patch.object(mock_sandbox, "_setup_agentsh"),
- patch.object(mock_sandbox, "_diagnose_startup_failure", return_value={"failure_reason": "not ready"}),
- ):
+ mock_sandbox.execute = MagicMock(side_effect=execute)
+ with 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",
@@ -968,8 +957,12 @@ class TestModalSandboxAgentServer:
assert health_ms == 0
wait_for_ready.assert_not_called()
mock_free.assert_not_called()
- # Only the bundled-skills clear runs before the shortcut.
- assert [ENV_DISABLE_BUNDLED_SKILLS in call.args[0] for call in mock_sandbox.execute.call_args_list] == [True]
+ commands = [call.args[0] for call in mock_sandbox.execute.call_args_list]
+ # Bundled-skills clear, then refreshed bash-env and gh-guard files before reuse is accepted.
+ assert ENV_DISABLE_BUNDLED_SKILLS in commands[0]
+ assert any("mv" in command and "/tmp/agentsh-bash-env.sh" in command for command in commands[1:])
+ assert any("mv" in command and "/opt/posthog/bin/gh" in command for command in commands[1:])
+ 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(
@@ -979,7 +972,7 @@ class TestModalSandboxAgentServer:
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, "_setup_agentsh") as mock_setup_agentsh,
+ 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,
patch.object(mock_sandbox, "_free_agent_server_port") as mock_free,
):
@@ -992,7 +985,7 @@ class TestModalSandboxAgentServer:
)
mock_free.assert_called_once_with()
- mock_setup_agentsh.assert_called_once_with("/tmp/workspace", ["example.com"])
+ mock_setup_agentsh.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)
@@ -1005,16 +998,12 @@ class TestModalSandboxAgentServer:
mock_sandbox.wait_for_agent_server_ready(["example.com"])
def test_start_agent_server_frees_port_before_relaunch(self, mock_sandbox: Any):
- mock_sandbox.execute = MagicMock(
- side_effect=[
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # bundled-skills clear
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- 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="ok:1\n__posthog_agent_health_ms=250", stderr="", exit_code=0, error=None),
- ]
- )
+ def execute(command: str, timeout_seconds: int | None = None) -> ExecutionResult:
+ if "./node_modules/.bin/agent-server" in command:
+ return ExecutionResult(stdout="ok:1\n__posthog_agent_health_ms=250", stderr="", exit_code=0)
+ return ExecutionResult(stdout="", stderr="", exit_code=0)
+
+ mock_sandbox.execute = MagicMock(side_effect=execute)
health_ms = mock_sandbox.start_agent_server(
repository="posthog/posthog",
@@ -1254,13 +1243,13 @@ class TestModalSandboxCommandEscaping:
with (
patch.object(sandbox, "is_running", return_value=True),
- patch.object(sandbox, "_setup_agentsh"),
+ 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),
):
- mock_execute.return_value = MagicMock(exit_code=0)
+ mock_execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)
sandbox.start_agent_server(repository, task_id, run_id, mode)
command = _agent_server_launch_command(mock_execute)
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index 2f9fea3b0866..a88f0c0d50cf 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -38,6 +38,29 @@ TASKS_LATENCY_HISTOGRAM_BUCKETS = [
3_600_000.0,
]
+TASKS_LAUNCH_PREPARATION_HISTOGRAM_METRICS = ("tasks_modal_launch_preparation_latency",)
+TASKS_LAUNCH_PREPARATION_HISTOGRAM_BUCKETS = [
+ 100.0,
+ 250.0,
+ 500.0,
+ 750.0,
+ 1_000.0,
+ 1_500.0,
+ 2_000.0,
+ 2_500.0,
+ 3_000.0,
+ 4_000.0,
+ 5_000.0,
+ 6_000.0,
+ 8_000.0,
+ 10_000.0,
+ 15_000.0,
+ 20_000.0,
+ 30_000.0,
+ 45_000.0,
+ 60_000.0,
+]
+
TASKS_RUN_TOKENS_HISTOGRAM_METRICS = ("tasks_run_total_tokens",)
TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS = [
10_000.0,
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 4a8677e0a8a6..4559fc01ec8b 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
@@ -30,6 +30,7 @@ from products.tasks.backend.exceptions import (
SandboxMissingRepositoryError,
)
from products.tasks.backend.logic.services.connection_token import create_sandbox_event_ingest_token
+from products.tasks.backend.logic.services.launch_preparation_metrics import launch_preparation_metric_context
from products.tasks.backend.logic.services.sandbox import (
REPO_READY_FILE,
SNAPSHOT_KIND_DIRECTORY,
@@ -679,10 +680,14 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
"""
ctx = input.context
- with log_activity_execution(
- "start_agent_server",
- sandbox_id=input.sandbox_id,
- **ctx.to_log_context(),
+ with (
+ log_activity_execution("start_agent_server", sandbox_id=input.sandbox_id, **ctx.to_log_context()),
+ launch_preparation_metric_context(
+ boot_path=input.boot_path,
+ runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox),
+ origin_product=ctx.origin_product,
+ used_snapshot=input.used_snapshot,
+ ),
):
emit_agent_log(ctx.run_id, "debug", "Starting agent server")
@@ -812,10 +817,14 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
def launch_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
ctx = input.context
- with log_activity_execution(
- "launch_agent_server",
- sandbox_id=input.sandbox_id,
- **ctx.to_log_context(),
+ with (
+ log_activity_execution("launch_agent_server", sandbox_id=input.sandbox_id, **ctx.to_log_context()),
+ launch_preparation_metric_context(
+ boot_path=input.boot_path,
+ runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox),
+ origin_product=ctx.origin_product,
+ used_snapshot=input.used_snapshot,
+ ),
):
emit_agent_log(ctx.run_id, "debug", "Launching agent server (deferred readiness)")
@@ -875,10 +884,14 @@ def mark_repo_ready(input: MarkRepoReadyInput) -> None:
def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOutput:
ctx = input.context
- with log_activity_execution(
- "await_agent_server_ready",
- sandbox_id=input.sandbox_id,
- **ctx.to_log_context(),
+ with (
+ log_activity_execution("await_agent_server_ready", sandbox_id=input.sandbox_id, **ctx.to_log_context()),
+ launch_preparation_metric_context(
+ boot_path=input.boot_path,
+ runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox),
+ origin_product=ctx.origin_product,
+ used_snapshot=input.used_snapshot,
+ ),
):
sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
agentsh_domains = _agentsh_domains_for(ctx)
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 27a58dff2f18..1ec24138f351 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
@@ -13,6 +13,7 @@ from products.tasks.backend.exceptions import (
SandboxRateLimitedError,
SandboxTimeoutError,
)
+from products.tasks.backend.logic.services.launch_preparation_metrics import record_launch_preparation_ms
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 (
@@ -33,6 +34,7 @@ from products.tasks.backend.temporal.process_task.activities.start_agent_server
_resolve_protected_base_branch,
await_agent_server_ready,
collect_agent_shadow_result,
+ launch_agent_server,
start_agent_server,
)
@@ -161,8 +163,9 @@ 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",
- return_value=None,
+ side_effect=lambda *args, **kwargs: record_launch_preparation_ms(1250, "COMPLETED"),
)
+ preparation_meter = mocker.patch("products.tasks.backend.logic.services.launch_preparation_metrics.metric_meter")
record_observation = mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server._record_network_enforcement_observation"
)
@@ -178,6 +181,49 @@ 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()
+ preparation_meter.return_value.with_additional_attributes.assert_called_once_with(
+ {
+ "boot_path": "classic",
+ "runtime": "vm",
+ "origin_product": "unknown",
+ "used_snapshot": "unknown",
+ "status": "COMPLETED",
+ }
+ )
+
+
[email protected]("use_vm", [False, True])
+async def test_deferred_launch_labels_preparation_metric(mocker, use_vm: bool) -> None:
+ prefix = "products.tasks.backend.temporal.process_task.activities.start_agent_server"
+ mocker.patch(f"{prefix}.get_sandbox_class_for_sandbox_id")
+ mocker.patch(f"{prefix}._prepare_launch")
+ mocker.patch(f"{prefix}._launch_agent_shadow", return_value=False)
+ mocker.patch(f"{prefix}._record_agent_server_launch")
+ mocker.patch(
+ f"{prefix}._invoke_start_agent_server",
+ side_effect=lambda *args, **kwargs: record_launch_preparation_ms(1250, "COMPLETED"),
+ )
+ preparation_meter = mocker.patch("products.tasks.backend.logic.services.launch_preparation_metrics.metric_meter")
+
+ await launch_agent_server(
+ StartAgentServerInput(
+ context=_context(use_modal_vm_sandbox=use_vm),
+ sandbox_id="sandbox-id",
+ sandbox_url="https://sandbox.example",
+ boot_path="overlap",
+ used_snapshot=False,
+ )
+ )
+
+ preparation_meter.return_value.with_additional_attributes.assert_called_once_with(
+ {
+ "boot_path": "overlap",
+ "runtime": "vm" if use_vm else "gvisor",
+ "origin_product": "unknown",
+ "used_snapshot": "false",
+ "status": "COMPLETED",
+ }
+ )
@pytest.mark.parametrize("error_type", [SandboxExecutionError, SandboxTimeoutError])
@@ -292,6 +338,8 @@ async def test_combined_start_failure_records_step_statuses(mocker, error, expec
async def test_await_agent_server_ready_relaunches_on_activity_retries(mocker, attempt, expects_relaunch) -> None:
context = _context()
sandbox = mocker.Mock(id="sandbox-id")
+ sandbox.start_agent_server.side_effect = lambda **kwargs: record_launch_preparation_ms(1250, "COMPLETED")
+ preparation_meter = mocker.patch("products.tasks.backend.logic.services.launch_preparation_metrics.metric_meter")
sandbox.execute.return_value.stdout = ""
sandbox.read_agent_server_boot_metrics.return_value = (None, {})
mocker.patch(
@@ -342,6 +390,15 @@ async def test_await_agent_server_ready_relaunches_on_activity_retries(mocker, a
assert result.sandbox_url == "https://sandbox.example"
sandbox.wait_for_agent_server_ready.assert_called_once_with(None)
if expects_relaunch:
+ preparation_meter.return_value.with_additional_attributes.assert_called_once_with(
+ {
+ "boot_path": "overlap",
+ "runtime": "gvisor",
+ "origin_product": "unknown",
+ "used_snapshot": "unknown",
+ "status": "COMPLETED",
+ }
+ )
sandbox.start_agent_server.assert_called_once()
assert sandbox.start_agent_server.call_args.kwargs["wait_for_health"] is False
record_retry.assert_called_once_with(
@@ -353,6 +410,7 @@ async def test_await_agent_server_ready_relaunches_on_activity_retries(mocker, a
)
else:
sandbox.start_agent_server.assert_not_called()
+ preparation_meter.assert_not_called()
record_retry.assert_not_called()
diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.py
index dd88d919fd31..01831cbba05e 100644
--- a/products/tasks/backend/tests/test_agentsh.py
+++ b/products/tasks/backend/tests/test_agentsh.py
@@ -587,6 +587,8 @@ class TestModalSandboxAgentShWrapping(TestCase):
return ExecutionResult(stdout="", stderr="", exit_code=0)
if "chmod" in command: # gh shim install
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)