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): instrument boot phase timings and total boot latency (#68514)

Alessandro Pogliaghia3c23407324d
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index 7ef081dec2f1..2759dc473406 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -7,7 +7,11 @@ from temporalio.common import MetricMeter
Attributes = dict[str, str | int | float | bool]
-TASKS_LATENCY_HISTOGRAM_METRICS = ("tasks_process_sandbox_step_latency", "tasks_process_snapshot_create_latency")
+TASKS_LATENCY_HISTOGRAM_METRICS = (
+ "tasks_process_sandbox_step_latency",
+ "tasks_process_snapshot_create_latency",
+ "tasks_boot_total_latency",
+)
TASKS_LATENCY_HISTOGRAM_BUCKETS = [
100.0,
250.0,
@@ -133,12 +137,14 @@ def increment_sandbox_created(runtime: str) -> None:
pass
-def record_agent_server_session_init_ms(session_init_ms: int) -> None:
+def record_agent_server_session_init_ms(session_init_ms: int, boot_path: str | None = None) -> None:
try:
attributes: Attributes = {
"step": "agent_server_session_init",
"status": "COMPLETED",
}
+ if boot_path is not None:
+ attributes["boot_path"] = boot_path
_metric_meter(attributes).create_histogram_timedelta(
"tasks_process_sandbox_step_latency",
"Latency for get_sandbox_for_repository sub-steps",
@@ -148,10 +154,44 @@ def record_agent_server_session_init_ms(session_init_ms: int) -> None:
pass
+def record_boot_total_ms(
+ boot_total_ms: int,
+ *,
+ boot_path: str,
+ used_snapshot: bool | None,
+ has_repo: bool,
+ origin_product: str | None,
+) -> None:
+ """Wall-clock time from workflow start to agent-server ready, the boot headline number.
+
+ Recorded once per successful boot by the activity that completes it. `boot_path`
+ distinguishes the serial launch ("classic"), the launch-before-clone overlap
+ ("overlap"), and future boot architectures, so rollouts can be compared per cohort.
+ """
+ try:
+ attributes: Attributes = {
+ "boot_path": boot_path,
+ "used_snapshot": _bool_label(used_snapshot),
+ "has_repo": _bool_label(has_repo),
+ "origin_product": origin_product or "unknown",
+ }
+ _metric_meter(attributes).create_histogram_timedelta(
+ "tasks_boot_total_latency",
+ "Wall-clock latency from workflow start to agent-server ready",
+ unit="ms",
+ ).record(dt.timedelta(milliseconds=boot_total_ms))
+ except Exception:
+ pass
+
+
class StepTimer:
- def __init__(self, step: str, used_snapshot: bool | None = None) -> None:
+ def __init__(self, step: str, used_snapshot: bool | None = None, boot_path: str | None = None) -> None:
self.step = step
self.used_snapshot = used_snapshot
+ self.boot_path = boot_path
+ # Elapsed wall-clock of the step, readable after the context exits so callers
+ # can thread the same number into activity outputs / analytics events.
+ self.elapsed_ms: int | None = None
self._start_counter: float | None = None
def set_used_snapshot(self, used_snapshot: bool) -> None:
@@ -166,6 +206,7 @@ class StepTimer:
raise RuntimeError("StepTimer used without calling __enter__")
delta_ms = int((time.perf_counter() - self._start_counter) * 1000)
+ self.elapsed_ms = delta_ms
delta = dt.timedelta(milliseconds=delta_ms)
attributes: Attributes = {
@@ -173,6 +214,8 @@ class StepTimer:
"used_snapshot": _bool_label(self.used_snapshot),
"status": "FAILED" if exc_value is not None else "COMPLETED",
}
+ if self.boot_path is not None:
+ attributes["boot_path"] = self.boot_path
try:
_metric_meter(attributes).create_histogram_timedelta(
diff --git a/products/tasks/backend/temporal/process_task/activities/__init__.py b/products/tasks/backend/temporal/process_task/activities/__init__.py
index 247178c56f04..0b56aad03515 100644
--- a/products/tasks/backend/temporal/process_task/activities/__init__.py
+++ b/products/tasks/backend/temporal/process_task/activities/__init__.py
@@ -12,7 +12,9 @@ from .get_task_processing_context import TaskProcessingContext, get_task_process
from .post_slack_update import PostSlackUpdateInput, post_slack_update
from .provision_sandbox import (
CheckoutBranchInSandboxInput,
+ CheckoutBranchInSandboxOutput,
CloneRepositoryInSandboxInput,
+ CloneRepositoryInSandboxOutput,
CreateSandboxForRepositoryInput,
CreateSandboxForRepositoryOutput,
InjectFreshTokensOnResumeInput,
@@ -57,7 +59,9 @@ __all__ = [
"GetSandboxForRepositoryInput",
"GetSandboxForRepositoryOutput",
"CheckoutBranchInSandboxInput",
+ "CheckoutBranchInSandboxOutput",
"CloneRepositoryInSandboxInput",
+ "CloneRepositoryInSandboxOutput",
"CreateSandboxForRepositoryInput",
"CreateSandboxForRepositoryOutput",
"InjectFreshTokensOnResumeInput",
diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
index 47f544267099..fcb2d4467994 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
@@ -96,6 +96,13 @@ class GetSandboxForRepositoryOutput:
used_snapshot: bool
should_create_snapshot: bool
agent_server_launched: bool = False
+ boot_path: str = "classic"
+ image_source: str | None = None
+ # Per-phase boot durations, threaded through to the sandbox_started analytics event.
+ create_ms: int | None = None
+ clone_ms: int | None = None
+ checkout_ms: int | None = None
+ launch_ms: int | None = None
@activity.defn
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index e8bc7dce5c82..7a81f0a3ee37 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -83,6 +83,17 @@ class CreateSandboxForRepositoryOutput:
sandbox_url: str
connect_token: str | None
used_snapshot: bool | None = None
+ create_ms: int | None = None
+
+
+@dataclass
+class CloneRepositoryInSandboxOutput:
+ clone_ms: int | None = None
+
+
+@dataclass
+class CheckoutBranchInSandboxOutput:
+ checkout_ms: int | None = None
@dataclass
@@ -494,6 +505,7 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cre
(prepared.snapshot_external_id or prepared.snapshot_id) and sandbox.config.snapshot_restored
)
sandbox_creation_timer.set_used_snapshot(actual_used_snapshot)
+ create_ms = sandbox_creation_timer.elapsed_ms
snapshot_outcome = (
"used" if actual_used_snapshot else "fresh" if prepared.snapshot_source == "none" else "fallback"
)
@@ -530,12 +542,13 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cre
sandbox_url=credentials.url,
connect_token=credentials.token,
used_snapshot=actual_used_snapshot,
+ create_ms=create_ms,
)
@activity.defn
@asyncify
-def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> None:
+def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRepositoryInSandboxOutput:
ctx = input.context
with log_activity_execution(
@@ -546,7 +559,7 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> None:
emit_agent_log(ctx.run_id, "debug", f"Cloning {input.repository} into sandbox")
sandbox = Sandbox.get_by_id(input.sandbox_id)
- with StepTimer("repository_clone", used_snapshot=False):
+ with StepTimer("repository_clone", used_snapshot=False) as clone_timer:
clone_result = sandbox.clone_repository(
input.repository,
github_token=input.github_token,
@@ -556,10 +569,12 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> None:
if clone_result.exit_code != 0:
raise RuntimeError(f"Failed to clone repository {input.repository}: {clone_result.stderr}")
+ return CloneRepositoryInSandboxOutput(clone_ms=clone_timer.elapsed_ms)
+
@activity.defn
@asyncify
-def checkout_branch_in_sandbox(input: CheckoutBranchInSandboxInput) -> None:
+def checkout_branch_in_sandbox(input: CheckoutBranchInSandboxInput) -> CheckoutBranchInSandboxOutput:
ctx = input.context
with log_activity_execution(
@@ -593,13 +608,15 @@ def checkout_branch_in_sandbox(input: CheckoutBranchInSandboxInput) -> None:
f"git checkout -B {shlex.quote(input.branch)} FETCH_HEAD"
)
- with StepTimer("branch_checkout", used_snapshot=input.used_snapshot):
+ with StepTimer("branch_checkout", used_snapshot=input.used_snapshot) as checkout_timer:
result = sandbox.execute(fetch_and_checkout, timeout_seconds=5 * 60)
if result.exit_code != 0:
logger.warning("Branch checkout failed", extra={"branch": input.branch, "stderr": result.stderr})
raise RuntimeError(f"Failed to checkout branch {input.branch}")
+ return CheckoutBranchInSandboxOutput(checkout_ms=checkout_timer.elapsed_ms)
+
@activity.defn
@asyncify
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 997219ef66cb..eae0a2e25890 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,6 +1,7 @@
import shlex
import threading
from dataclasses import dataclass
+from datetime import UTC, datetime
from django.conf import settings
from django.db import connection
@@ -18,7 +19,7 @@ from products.tasks.backend.exceptions import OAuthTokenError, SandboxExecutionE
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, Sandbox, SandboxBase, sandbox_repo_path
from products.tasks.backend.models import Task, TaskRun
-from products.tasks.backend.temporal.metrics import StepTimer, record_agent_server_session_init_ms
+from products.tasks.backend.temporal.metrics import StepTimer, record_agent_server_session_init_ms, record_boot_total_ms
from products.tasks.backend.temporal.oauth import create_oauth_access_token
from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
from products.tasks.backend.temporal.process_task.utils import (
@@ -134,6 +135,13 @@ class StartAgentServerInput:
sandbox_connect_token: str | None = None
posthog_mcp_scopes: PosthogMcpScopes = "read_only"
defer_for_clone: bool = False
+ # Which boot architecture produced this run ("classic" serial launch vs "overlap"
+ # launch-before-clone); labels the latency metrics so cohorts stay comparable.
+ boot_path: str = "classic"
+ used_snapshot: bool | None = None
+ # Workflow start time (ISO 8601); when set, the activity that completes boot records
+ # the wall-clock workflow-start → agent-ready total.
+ workflow_start_at: str | None = None
@dataclass
@@ -146,6 +154,10 @@ class MarkRepoReadyInput:
class StartAgentServerOutput:
sandbox_url: str
connect_token: str | None = None
+ launch_ms: int | None = None
+ ready_wait_ms: int | None = None
+ session_init_ms: int | None = None
+ boot_total_ms: int | None = None
@dataclass
@@ -328,6 +340,30 @@ def _spawn_post_ready_diagnostics(
threading.Thread(target=_run, name=f"post-ready-diag-{ctx.run_id}", daemon=True).start()
+def _record_boot_total(input: StartAgentServerInput) -> int | None:
+ """Record workflow-start → agent-ready wall-clock; returns the total for the activity output."""
+ if not input.workflow_start_at:
+ return None
+ try:
+ started_at = datetime.fromisoformat(input.workflow_start_at)
+ # Temporal start_time is tz-aware UTC; treat a naive value as UTC rather than
+ # letting the aware-naive subtraction raise. Metrics must never fail the boot.
+ if started_at.tzinfo is None:
+ started_at = started_at.replace(tzinfo=UTC)
+ boot_total_ms = max(0, int((datetime.now(UTC) - started_at).total_seconds() * 1000))
+ except (TypeError, ValueError):
+ logger.warning("boot_total_unparseable_start_time", workflow_start_at=input.workflow_start_at)
+ return None
+ record_boot_total_ms(
+ boot_total_ms,
+ boot_path=input.boot_path,
+ used_snapshot=input.used_snapshot,
+ has_repo=input.context.repository is not None,
+ origin_product=input.context.origin_product,
+ )
+ return boot_total_ms
+
+
@activity.defn
@asyncify
def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
@@ -352,7 +388,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
_ensure_repository_on_disk(ctx, sandbox)
params = _prepare_launch(ctx, input.posthog_mcp_scopes)
- with StepTimer("agent_server_ready"):
+ with StepTimer("agent_server_ready", boot_path=input.boot_path) as ready_timer:
_invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=None, wait_for_health=True)
emit_agent_log(ctx.run_id, "debug", f"Agent server started at {input.sandbox_url}")
@@ -360,11 +396,19 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
session_init_ms = sandbox.read_agent_server_session_init_ms()
if session_init_ms is not None:
- record_agent_server_session_init_ms(session_init_ms)
+ record_agent_server_session_init_ms(session_init_ms, boot_path=input.boot_path)
+
+ boot_total_ms = _record_boot_total(input)
_spawn_post_ready_diagnostics(ctx, sandbox, params.agentsh_domains)
- return StartAgentServerOutput(sandbox_url=input.sandbox_url, connect_token=input.sandbox_connect_token)
+ return StartAgentServerOutput(
+ sandbox_url=input.sandbox_url,
+ connect_token=input.sandbox_connect_token,
+ ready_wait_ms=ready_timer.elapsed_ms,
+ session_init_ms=session_init_ms,
+ boot_total_ms=boot_total_ms,
+ )
@activity.defn
@@ -383,10 +427,15 @@ def launch_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
params = _prepare_launch(ctx, input.posthog_mcp_scopes)
repo_ready_file = REPO_READY_FILE if input.defer_for_clone else None
- _invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=repo_ready_file, wait_for_health=False)
+ with StepTimer("agent_server_launch", boot_path=input.boot_path) as launch_timer:
+ _invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=repo_ready_file, wait_for_health=False)
activity.logger.info(f"Agent server process launched for task {ctx.task_id}")
- return StartAgentServerOutput(sandbox_url=input.sandbox_url, connect_token=input.sandbox_connect_token)
+ return StartAgentServerOutput(
+ sandbox_url=input.sandbox_url,
+ connect_token=input.sandbox_connect_token,
+ launch_ms=launch_timer.elapsed_ms,
+ )
@activity.defn
@@ -411,7 +460,7 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
agentsh_domains = _agentsh_domains_for(ctx)
try:
- with StepTimer("agent_server_ready"):
+ with StepTimer("agent_server_ready", boot_path=input.boot_path) as ready_timer:
sandbox.wait_for_agent_server_ready(agentsh_domains)
except Exception:
if agentsh_domains is not None:
@@ -424,8 +473,16 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
session_init_ms = sandbox.read_agent_server_session_init_ms()
if session_init_ms is not None:
- record_agent_server_session_init_ms(session_init_ms)
+ record_agent_server_session_init_ms(session_init_ms, boot_path=input.boot_path)
+
+ boot_total_ms = _record_boot_total(input)
_spawn_post_ready_diagnostics(ctx, sandbox, agentsh_domains)
- return StartAgentServerOutput(sandbox_url=input.sandbox_url, connect_token=input.sandbox_connect_token)
+ return StartAgentServerOutput(
+ sandbox_url=input.sandbox_url,
+ connect_token=input.sandbox_connect_token,
+ ready_wait_ms=ready_timer.elapsed_ms,
+ session_init_ms=session_init_ms,
+ boot_total_ms=boot_total_ms,
+ )
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 5c709aba73ee..726dd7696768 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -529,6 +529,15 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"sandbox_url": agent_server_output.sandbox_url,
"used_snapshot": sandbox_output.used_snapshot,
"repository": self.context.repository,
+ "boot_path": sandbox_output.boot_path,
+ "image_source": sandbox_output.image_source,
+ "boot_total_ms": agent_server_output.boot_total_ms,
+ "sandbox_create_ms": sandbox_output.create_ms,
+ "repo_clone_ms": sandbox_output.clone_ms,
+ "branch_checkout_ms": sandbox_output.checkout_ms,
+ "agent_launch_ms": sandbox_output.launch_ms,
+ "agent_ready_wait_ms": agent_server_output.ready_wait_ms,
+ "agent_session_init_ms": agent_server_output.session_init_ms,
},
)
@@ -860,13 +869,17 @@ class ProcessTaskWorkflow(PostHogWorkflow):
will_checkout = bool(prepared.repository and prepared.branch and has_clone_credentials)
overlap = bool(self.context.overlap_clone_boot_enabled and will_clone)
+ boot_path = "overlap" if overlap else "classic"
+ launch_ms: int | None = None
if overlap:
await self._emit_progress("agent", "in_progress", "Starting agent", "setup")
- await self._launch_agent_server(created, defer_for_clone=True)
+ launch_output = await self._launch_agent_server(created, defer_for_clone=True, used_snapshot=used_snapshot)
+ launch_ms = launch_output.launch_ms if launch_output else None
+ clone_ms: int | None = None
if will_clone:
await self._emit_progress("clone", "in_progress", "Cloning repository", "setup")
- await workflow.execute_activity(
+ clone_output = await workflow.execute_activity(
clone_repository_in_sandbox,
CloneRepositoryInSandboxInput(
context=self.context,
@@ -878,15 +891,18 @@ class ProcessTaskWorkflow(PostHogWorkflow):
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
+ # Pre-rollout histories (and mocked tests) recorded a null result here.
+ clone_ms = getattr(clone_output, "clone_ms", None)
await self._emit_progress("clone", "completed", "Cloned repository", "setup")
state = self.context.state or {}
is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))
+ checkout_ms: int | None = None
if will_checkout and not is_resume:
branch_label_active = f"Checking out branch {prepared.branch}"
branch_label_done = f"Checked out branch {prepared.branch}"
await self._emit_progress("checkout", "in_progress", branch_label_active, "setup")
- await workflow.execute_activity(
+ checkout_output = await workflow.execute_activity(
checkout_branch_in_sandbox,
CheckoutBranchInSandboxInput(
context=self.context,
@@ -900,6 +916,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
+ # Pre-rollout histories (and mocked tests) recorded a null result here.
+ checkout_ms = getattr(checkout_output, "checkout_ms", None)
await self._emit_progress("checkout", "completed", branch_label_done, "setup")
if overlap:
@@ -912,6 +930,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):
used_snapshot=used_snapshot,
should_create_snapshot=not used_snapshot,
agent_server_launched=overlap,
+ boot_path=boot_path,
+ image_source=prepared.image_source,
+ create_ms=created.create_ms,
+ clone_ms=clone_ms,
+ checkout_ms=checkout_ms,
+ launch_ms=launch_ms,
)
async def _cleanup_sandbox(self, sandbox_id: str) -> None:
@@ -967,6 +991,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):
)
await self._emit_progress("wizard", "completed", "Ran PostHog setup wizard", "setup")
+ @staticmethod
+ def _workflow_start_at_iso() -> str | None:
+ """Workflow start time for the boot-total metric; None outside a workflow event loop (unit tests)."""
+ try:
+ return workflow.info().start_time.isoformat()
+ except Exception:
+ return None
+
async def _start_agent_server(self, sandbox_output: GetSandboxForRepositoryOutput) -> StartAgentServerOutput:
return await workflow.execute_activity(
start_agent_server,
@@ -976,13 +1008,16 @@ class ProcessTaskWorkflow(PostHogWorkflow):
sandbox_url=sandbox_output.sandbox_url,
sandbox_connect_token=sandbox_output.connect_token,
posthog_mcp_scopes=self._posthog_mcp_scopes,
+ boot_path=sandbox_output.boot_path,
+ used_snapshot=sandbox_output.used_snapshot,
+ workflow_start_at=self._workflow_start_at_iso(),
),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
async def _launch_agent_server(
- self, created: GetSandboxForRepositoryOutput, *, defer_for_clone: bool
+ self, created: GetSandboxForRepositoryOutput, *, defer_for_clone: bool, used_snapshot: bool | None = None
) -> StartAgentServerOutput:
return await workflow.execute_activity(
launch_agent_server,
@@ -993,6 +1028,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
sandbox_connect_token=created.connect_token,
posthog_mcp_scopes=self._posthog_mcp_scopes,
defer_for_clone=defer_for_clone,
+ boot_path="overlap",
+ used_snapshot=used_snapshot,
),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -1015,6 +1052,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
sandbox_url=sandbox_output.sandbox_url,
sandbox_connect_token=sandbox_output.connect_token,
posthog_mcp_scopes=self._posthog_mcp_scopes,
+ boot_path=sandbox_output.boot_path,
+ used_snapshot=sandbox_output.used_snapshot,
+ workflow_start_at=self._workflow_start_at_iso(),
),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),