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: add task startup timings (#117055)

Jonathan Mieloo030725ff831b
diff --git a/products/tasks/backend/logic/services/launch_preparation_metrics.py b/products/tasks/backend/logic/services/launch_preparation_metrics.py
index ae8d3883e7c0..481b732a084d 100644
--- a/products/tasks/backend/logic/services/launch_preparation_metrics.py
+++ b/products/tasks/backend/logic/services/launch_preparation_metrics.py
@@ -30,6 +30,10 @@ def launch_preparation_metric_context(
def record_launch_preparation_ms(duration_ms: int, status: Literal["COMPLETED", "FAILED"]) -> None:
+ from products.tasks.backend.temporal.metrics import ( # noqa: PLC0415 — Temporal registration imports ModalSandbox
+ record_startup_step_event,
+ )
+
attributes = _launch_preparation_attributes.get()
if attributes is None:
return
@@ -41,3 +45,4 @@ def record_launch_preparation_ms(duration_ms: int, status: Literal["COMPLETED",
).record(timedelta(milliseconds=duration_ms))
except Exception:
pass
+ record_startup_step_event("launch_preparation", duration_ms, {**attributes, "status": status})
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
index e117ce57c459..8eae5132d9e7 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.py
@@ -260,6 +260,7 @@ def test_preparation_metric_measures_only_upload_and_execution(export_fails: boo
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("products.tasks.backend.temporal.metrics.record_startup_step_event") as startup_event,
patch.object(
sandbox, "_agent_server_preflight", return_value=AgentServerPreflight(reused=True, capabilities=frozenset())
),
@@ -272,6 +273,17 @@ def test_preparation_metric_measures_only_upload_and_execution(export_fails: boo
assert sandbox.start_agent_server(repository=None, task_id="task-test", run_id="run-test") == 0
metric_meter.assert_called_once_with()
+ startup_event.assert_called_once_with(
+ "launch_preparation",
+ 1250,
+ {
+ "boot_path": "classic",
+ "runtime": "vm",
+ "origin_product": "user_created",
+ "used_snapshot": "false",
+ "status": "COMPLETED",
+ },
+ )
if not export_fails:
metric_meter.return_value.with_additional_attributes.assert_called_once_with(
{
diff --git a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
index b49c53f19280..1c38fa18a5fa 100644
--- a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
+++ b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
@@ -14,6 +14,7 @@ from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import DatabaseError, close_old_connections
+import posthoganalytics
from asgiref.sync import sync_to_async
from prometheus_client import start_http_server
from temporalio.client import Client, WorkflowExecutionStatus
@@ -24,6 +25,7 @@ from temporalio.service import RPCError, RPCStatusCode
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.temporal.common.client import async_connect
+from posthog.temporal.common.scoped import scoped_temporal
from posthog.user_permissions import UserPermissions
from products.tasks.backend.logic.services.code_usage_gate import usage_limit_response
@@ -49,7 +51,12 @@ from products.tasks.backend.metrics import (
observe_task_run_workflow_start,
)
from products.tasks.backend.models import Task, TaskRun, TaskWorkflowDispatch
-from products.tasks.backend.temporal.client import _capture_run_feature_flags, start_process_task_workflow
+from products.tasks.backend.temporal.client import (
+ _capture_run_feature_flags,
+ start_process_task_workflow,
+ tag_startup_dispatch,
+)
+from products.tasks.backend.temporal.metrics import StepTimer
from products.tasks.backend.temporal.process_task.workflow import ProcessTaskInput
from products.tasks.backend.visibility import task_control_q
@@ -209,6 +216,8 @@ class Command(BaseCommand):
)
WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="failed").inc()
+ @scoped_temporal(fresh=True, capture_exceptions=False)
+ @StepTimer("dispatch", status_tag="dispatch_status")
async def _process(
self, client: Client, dispatch: TaskWorkflowDispatch, instance_id: str, semaphore: asyncio.Semaphore
) -> None:
@@ -224,6 +233,7 @@ class Command(BaseCommand):
)
WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()
return
+ tag_startup_dispatch(run)
try:
await Team.objects.aget(id=run.team_id)
is_restart = dispatch.dispatch_kind == TaskWorkflowDispatch.Kind.RESTART
@@ -239,6 +249,7 @@ class Command(BaseCommand):
and await dispatch_attempt_already_started(client, dispatch)
):
await sync_to_async(mark_accepted)(dispatch.id, instance_id)
+ posthoganalytics.tag("dispatch_status", "COMPLETED")
WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="already_started").inc()
return
if not await sync_to_async(_user_can_dispatch)(run, options, require_task_control=is_scheduled_create):
@@ -316,11 +327,13 @@ class Command(BaseCommand):
WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="rescheduled").inc()
return
await sync_to_async(mark_accepted)(dispatch.id, instance_id)
+ posthoganalytics.tag("dispatch_status", "COMPLETED")
WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="already_started").inc()
except Exception as error:
await sync_to_async(reschedule)(dispatch.id, instance_id, str(error))
WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="rescheduled").inc()
else:
await sync_to_async(mark_accepted)(dispatch.id, instance_id)
+ posthoganalytics.tag("dispatch_status", "COMPLETED")
WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="accepted").inc()
observe_task_run_workflow_start(run, outcome="started", reason="dispatcher")
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index f91018003f2e..45ed7a41b9cc 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -687,7 +687,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
event=event,
properties=all_properties,
groups=groups(team=self.team),
- send_feature_flags=True,
+ send_feature_flags=event not in {"task_created", "task_run_created"},
)
except Exception as e:
logger.warning("task.capture_event_failed", analytics_event=event, error=str(e))
@@ -787,9 +787,13 @@ class Task(Taggable, DeletedMetaFields, models.Model):
branch: str | None = None,
acting_user_id: int | None = None,
scheduled_at: datetime | None = None,
+ startup_requested_at: datetime | None = None,
) -> "TaskRun":
+ startup_requested_at = startup_requested_at or django_timezone.now()
if scheduled_at is not None and django_timezone.is_naive(scheduled_at):
raise ValueError("scheduled_at must be timezone-aware")
+ if scheduled_at is not None:
+ startup_requested_at = max(startup_requested_at, scheduled_at)
expected_created_by_id = self.created_by_id
expected_ownership_version = self.ownership_version
@@ -822,6 +826,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
state: dict = {} if task.runtime == Task.Runtime.PI else {"mode": mode}
if extra_state:
state.update({k: v for k, v in extra_state.items() if k != "mode"})
+ state["startup_requested_at"] = startup_requested_at.isoformat()
state.setdefault("repositories", task.repositories or ([task.repository] if task.repository else []))
carry_config_snapshot = (
task.origin_product == Task.OriginProduct.WORKFLOW and "config_snapshot" not in state
@@ -932,6 +937,9 @@ class Task(Taggable, DeletedMetaFields, models.Model):
"run_environment": task_run.environment,
"is_resume": is_resume,
"has_pending_message": has_pending,
+ "startup_requested_at": startup_requested_at.isoformat(),
+ "startup_run_created_at": task_run.created_at.isoformat(),
+ "startup_scheduled_at": scheduled_at.isoformat() if scheduled_at else None,
},
)
@@ -1524,6 +1532,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
mcp_gateway_server_ids: list[str] | None = None,
before_task_dispatch: Callable[[uuid.UUID], dict[str, JsonValue] | None] | None = None,
) -> "Task":
+ startup_requested_at = django_timezone.now()
from products.tasks.backend.logic.services.workflow_dispatch import (
WorkflowDispatchOptions,
enqueue_or_start_workflow,
@@ -1619,6 +1628,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
branch=branch,
acting_user_id=user_id,
scheduled_at=scheduled_at,
+ startup_requested_at=startup_requested_at,
)
if before_task_dispatch is not None:
initial_state = before_task_dispatch(task_run.id)
@@ -2939,6 +2949,7 @@ class TaskRun(models.Model):
# client's deployment-region super-property, so ship the run's
# local/cloud value under an unclobbered name too.
"run_environment": self.environment,
+ "startup_requested_at": (self.state or {}).get("startup_requested_at"),
"mode": self.mode,
"slack_session_id": self._slack_session_id(),
**self._analytics_usage_properties(),
@@ -2981,7 +2992,7 @@ class TaskRun(models.Model):
"event": event,
"properties": all_properties,
"groups": groups(team=self.team),
- "send_feature_flags": True,
+ "send_feature_flags": event != "task_run_created",
}
if event_uuid:
capture_kwargs["uuid"] = event_uuid
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index 77b975cf3f87..e520af89dbbf 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -10,11 +10,13 @@ from django.utils import timezone as django_timezone
import posthoganalytics
from asgiref.sync import sync_to_async
+from opentelemetry import trace
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.models.team.team import Team
from posthog.temporal.common.client import async_connect, sync_connect
+from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.oauth import PosthogMcpScopes
from products.tasks.backend.constants import (
@@ -45,6 +47,7 @@ from products.tasks.backend.temporal.constants import (
STEERING_PROTOCOL_QUERY_TIMEOUT,
STEERING_PROTOCOL_VERSION,
)
+from products.tasks.backend.temporal.metrics import StepTimer
from products.tasks.backend.temporal.oauth import dispatched_run_scopes
from products.tasks.backend.temporal.process_task.workflow import PendingFollowup, ProcessTaskInput
from products.tasks.backend.temporal.run_trace import run_trace_context
@@ -64,6 +67,19 @@ _BOOT_ROLLOUT_FLAGS: tuple[tuple[str, str], ...] = (
)
+def tag_startup_dispatch(task_run: TaskRun | None) -> None:
+ if task_run is not None and not task_run.task.is_scout_experiment:
+ posthoganalytics.tag("run_id", str(task_run.id))
+ posthoganalytics.tag("origin_product", task_run.task.origin_product)
+ posthoganalytics.tag("run_environment", task_run.environment)
+ trace.get_current_span().set_attributes(
+ {
+ "run_id": str(task_run.id),
+ "origin_product": task_run.task.origin_product or "unknown",
+ }
+ )
+
+
def _normalize_slack_context(slack_thread_context: Optional[Any]) -> Optional[dict[str, Any]]:
"""Convert slack_thread_context to dict if needed."""
if slack_thread_context is None:
@@ -156,6 +172,7 @@ def _evaluate_boot_rollout_flag(
return False
+@StepTimer("capture_dispatch_flags")
def _capture_run_feature_flags(run_id: str) -> dict[str, Any]:
"""Evaluate per-run rollout flags once at dispatch and stamp them into run state.
@@ -274,6 +291,8 @@ async def _aget_task_run_for_metrics(run_id: str) -> TaskRun | None:
return None
+@scoped_temporal(fresh=True, capture_exceptions=False)
+@StepTimer("dispatch", status_tag="dispatch_status")
async def execute_task_processing_workflow_async(
task_id: str,
run_id: str,
@@ -306,6 +325,7 @@ async def execute_task_processing_workflow_async(
task_run_for_metrics: TaskRun | None = None
try:
task_run_for_metrics = await _aget_task_run_for_metrics(run_id)
+ tag_startup_dispatch(task_run_for_metrics)
observe_task_run_workflow_start(task_run_for_metrics, outcome="attempted", reason="requested")
await Team.objects.select_related("organization").aget(id=team_id)
run_state = await sync_to_async(_capture_run_feature_flags)(run_id)
@@ -329,7 +349,8 @@ async def execute_task_processing_workflow_async(
extra={"workflow_id": workflow_id, "task_id": task_id, "run_id": run_id},
)
- client = await async_connect()
+ with StepTimer("temporal_connect"):
+ client = await async_connect()
await start_process_task_workflow(
client,
workflow_input,
@@ -339,6 +360,7 @@ async def execute_task_processing_workflow_async(
)
logger.info("task_processing_workflow_started", extra={"task_id": task_id, "run_id": run_id})
+ posthoganalytics.tag("dispatch_status", "COMPLETED")
observe_task_run_workflow_start(task_run_for_metrics, outcome="started", reason="accepted")
except Team.DoesNotExist as e:
@@ -352,6 +374,7 @@ async def execute_task_processing_workflow_async(
f"Failed to start task workflow: permission validation failed: {e}",
)
except WorkflowAlreadyStartedError:
+ posthoganalytics.tag("dispatch_status", "BLOCKED")
observe_task_run_workflow_start(task_run_for_metrics, outcome="blocked", reason="already_running")
logger.info(
"task_processing_workflow_already_running",
@@ -371,6 +394,8 @@ async def execute_task_processing_workflow_async(
)
[email protected](fresh=True, capture_exceptions=False)
+@StepTimer("dispatch", status_tag="dispatch_status")
def execute_task_processing_workflow(
task_id: str,
run_id: str,
@@ -397,6 +422,7 @@ def execute_task_processing_workflow(
task_run_for_metrics: TaskRun | None = None
try:
task_run_for_metrics = _get_task_run_for_metrics(run_id)
+ tag_startup_dispatch(task_run_for_metrics)
observe_task_run_workflow_start(task_run_for_metrics, outcome="attempted", reason="requested")
logger.info(
"execute_task_processing_workflow_called",
@@ -425,7 +451,8 @@ def execute_task_processing_workflow(
extra={"task_id": task_id, "task_queue": settings.TASKS_TASK_QUEUE},
)
- client = sync_connect()
+ with StepTimer("temporal_connect"):
+ client = sync_connect()
logger.info(
"task_processing_temporal_connected",
@@ -443,6 +470,7 @@ def execute_task_processing_workflow(
)
logger.info("task_processing_workflow_started", extra={"task_id": task_id, "run_id": run_id})
+ posthoganalytics.tag("dispatch_status", "COMPLETED")
observe_task_run_workflow_start(task_run_for_metrics, outcome="started", reason="accepted")
except Team.DoesNotExist as e:
@@ -456,6 +484,7 @@ def execute_task_processing_workflow(
f"Failed to start task workflow: permission validation failed: {e}",
)
except WorkflowAlreadyStartedError:
+ posthoganalytics.tag("dispatch_status", "BLOCKED")
observe_task_run_workflow_start(task_run_for_metrics, outcome="blocked", reason="already_running")
logger.info(
"task_processing_workflow_already_running",
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index e27de0c2c39d..f78c0027fda9 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -1,16 +1,23 @@
import os
import time
+import inspect
import datetime as dt
-from collections.abc import Mapping
-from typing import Any
+from collections.abc import Callable, Mapping
+from contextlib import AbstractContextManager, ContextDecorator
+from functools import wraps
+from typing import Any, TypeVar, cast
import posthoganalytics
+from opentelemetry import trace
+from opentelemetry.trace import Span
from temporalio import activity, workflow
from temporalio.common import MetricMeter
from products.tasks.backend.logic.services.model_catalogue import runtime_adapter_for
Attributes = dict[str, str | int | float | bool]
+tracer = trace.get_tracer(__name__)
+F = TypeVar("F", bound=Callable[..., object])
TASKS_LATENCY_HISTOGRAM_METRICS = (
"tasks_process_sandbox_step_latency",
@@ -454,6 +461,62 @@ def record_sandbox_created(
pass
+def record_startup_step_event(
+ step: str,
+ duration_ms: int,
+ attributes: Attributes,
+ *,
+ started_at: dt.datetime | None = None,
+) -> None:
+ try:
+ context = posthoganalytics.get_tags()
+ run_id = context.get("run_id")
+ if not isinstance(run_id, str) or not run_id:
+ return
+ properties: dict[str, object] = {
+ "$process_person_profile": False,
+ **{
+ key: context[key]
+ for key in (
+ "run_id",
+ "task_id",
+ "origin_product",
+ "run_environment",
+ "mode",
+ "run_source",
+ "runtime_adapter",
+ "provider",
+ )
+ if key in context
+ },
+ **attributes,
+ "step": step,
+ "duration_ms": duration_ms,
+ }
+ if started_at is not None:
+ properties["started_at"] = started_at.isoformat()
+ properties["finished_at"] = dt.datetime.now(dt.UTC).isoformat()
+ if activity.in_activity():
+ info = activity.info()
+ properties.update(
+ {
+ "temporal_activity_id": info.activity_id,
+ "temporal_activity_type": info.activity_type,
+ "temporal_attempt": info.attempt,
+ "temporal_workflow_id": info.workflow_id,
+ "temporal_workflow_run_id": info.workflow_run_id,
+ }
+ )
+ posthoganalytics.capture(
+ "task_startup_step_completed",
+ distinct_id=run_id,
+ properties=properties,
+ send_feature_flags=False,
+ )
+ except Exception:
+ pass
+
+
def record_agent_server_session_init_ms(
session_init_ms: int,
boot_path: str | None = None,
@@ -479,6 +542,7 @@ def record_agent_server_session_init_ms(
).record(dt.timedelta(milliseconds=session_init_ms))
except Exception:
pass
+ record_startup_step_event("agent_server_session_init", session_init_ms, attributes)
def record_agent_server_step_ms(
@@ -509,6 +573,7 @@ def record_agent_server_step_ms(
).record(dt.timedelta(milliseconds=duration_ms))
except Exception:
pass
+ record_startup_step_event(step, duration_ms, attributes)
def record_agent_server_boot_phases_ms(
@@ -618,7 +683,18 @@ def record_agent_boot_milestone_ms(
pass
-class StepTimer:
+class StepTimer(ContextDecorator):
+ def __call__(self, func: F) -> F:
+ if not inspect.iscoroutinefunction(func):
+ return super().__call__(func)
+
+ @wraps(func)
+ async def timed(*args: object, **kwargs: object) -> object:
+ with self._recreate_cm():
+ return await func(*args, **kwargs)
+
+ return cast(F, timed)
+
def __init__(
self,
step: str,
@@ -628,6 +704,7 @@ class StepTimer:
origin_product: str | None = None,
runtime: str | None = None,
sandbox_backend: str | None = None,
+ status_tag: str | None = None,
) -> None:
self.step = step
self.used_snapshot = used_snapshot
@@ -635,15 +712,32 @@ class StepTimer:
self.origin_product = origin_product
self.runtime = runtime
self.sandbox_backend = sandbox_backend
+ self.status_tag = status_tag
# 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
+ self._started_at: dt.datetime | None = None
+ self._span: AbstractContextManager[Span] | None = None
+
+ def _recreate_cm(self) -> "StepTimer":
+ return StepTimer(
+ self.step,
+ used_snapshot=self.used_snapshot,
+ boot_path=self.boot_path,
+ origin_product=self.origin_product,
+ runtime=self.runtime,
+ sandbox_backend=self.sandbox_backend,
+ status_tag=self.status_tag,
+ )
def set_used_snapshot(self, used_snapshot: bool) -> None:
self.used_snapshot = used_snapshot
def __enter__(self) -> "StepTimer":
+ self._span = tracer.start_as_current_span("tasks.step." + self.step)
+ self._span.__enter__()
+ self._started_at = dt.datetime.now(dt.UTC)
self._start_counter = time.perf_counter()
return self
@@ -653,6 +747,9 @@ class StepTimer:
delta_ms = int((time.perf_counter() - self._start_counter) * 1000)
self.elapsed_ms = delta_ms
+ if self._span is not None:
+ self._span.__exit__(exc_type, exc_value, traceback)
+ self._span = None
delta = dt.timedelta(milliseconds=delta_ms)
attributes: Attributes = {
@@ -660,6 +757,8 @@ class StepTimer:
"used_snapshot": _bool_label(self.used_snapshot),
"status": "FAILED" if exc_value is not None else "COMPLETED",
}
+ if self.status_tag is not None and exc_value is None:
+ attributes["status"] = str(posthoganalytics.get_tags().get(self.status_tag, "FAILED"))
if self.boot_path is not None:
attributes["boot_path"] = self.boot_path
if self.origin_product is not None:
@@ -678,4 +777,5 @@ class StepTimer:
except Exception:
pass
+ record_startup_step_event(self.step, delta_ms, attributes, started_at=self._started_at)
self._start_counter = None
diff --git a/products/tasks/backend/temporal/observability.py b/products/tasks/backend/temporal/observability.py
index 0eac726f2aaa..2b5ce30dc40c 100644
--- a/products/tasks/backend/temporal/observability.py
+++ b/products/tasks/backend/temporal/observability.py
@@ -8,10 +8,12 @@ from temporalio import activity, workflow
from posthog.temporal.common.logger import get_logger
from products.tasks.backend.models import LogLevel
+from products.tasks.backend.temporal.metrics import StepTimer
logger = get_logger(__name__)
+@StepTimer("agent_log")
def emit_agent_log(run_id: str, level: LogLevel, message: str) -> None:
"""Emit a console-style agent event for user-facing logs.
@@ -117,6 +119,19 @@ def log_activity_execution(
"""
bound_logger = logger.bind(**context)
+ for key in (
+ "run_id",
+ "task_id",
+ "origin_product",
+ "environment",
+ "mode",
+ "run_source",
+ "runtime_adapter",
+ "provider",
+ ):
+ if key in context:
+ posthoganalytics.tag("run_environment" if key == "environment" else key, context[key])
+
if activity.in_activity():
info = activity.info()
bound_logger = bound_logger.bind(
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 e5d6950efc6b..2c1d4398da7b 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
@@ -424,13 +424,20 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo
credentials = sandbox.get_connect_credentials()
try:
- persist_sandbox_connection(
- run_id=ctx.run_id,
- sandbox=sandbox,
- credentials=credentials,
- sandbox_created_at=sandbox_created_at,
- task_runtime=ctx.task_runtime,
- )
+ with StepTimer(
+ "persist_sandbox_connection",
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ used_snapshot=used_snapshot,
+ boot_path="classic",
+ ):
+ persist_sandbox_connection(
+ run_id=ctx.run_id,
+ sandbox=sandbox,
+ credentials=credentials,
+ sandbox_created_at=sandbox_created_at,
+ task_runtime=ctx.task_runtime,
+ )
except Exception:
try:
sandbox.destroy()
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index 225691a178ee..fbc6d0534e79 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -77,6 +77,7 @@ from products.tasks.backend.logic.services.sandbox_config import (
from products.tasks.backend.logic.services.store_skills import resolve_store_skills
from products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRun
from products.tasks.backend.temporal.constants import resolve_inactivity_timeout, resolve_max_run_duration
+from products.tasks.backend.temporal.metrics import StepTimer
from products.tasks.backend.temporal.oauth import is_interactive_signals_run
from products.tasks.backend.temporal.observability import emit_agent_log, log_with_activity_context
from products.tasks.backend.temporal.process_task.utils import (
@@ -385,6 +386,7 @@ class TaskProcessingContext:
}
+@StepTimer("flag_streaming")
def _is_agent_proxy_keep_stream_open_enabled(
*,
distinct_id: str,
@@ -471,6 +473,7 @@ def _is_pi_acp_enabled(
return False
+@StepTimer("flag_rtk")
def _is_rtk_enabled(
*,
distinct_id: str,
@@ -530,6 +533,7 @@ _SUBSCRIPTION_ADAPTERS: dict[str, _SubscriptionAdapter] = {
}
+@StepTimer("validate_subscription")
def _ensure_subscription_allowed(
*,
adapter: str,
@@ -583,6 +587,7 @@ def _plan_owner_distinct_id(team: Team, owner_id: int | None) -> str | None:
return team.all_users_with_access().filter(id=owner_id).values_list("distinct_id", flat=True).first()
+@StepTimer("validate_codex_account")
def _ensure_codex_account_connected(owner_id: int | None, run_id: str) -> None:
integration = CodexUserIntegration.for_user(owner_id) if owner_id is not None else None
if integration is None or not integration.is_connected():
@@ -594,6 +599,7 @@ def _ensure_codex_account_connected(owner_id: int | None, run_id: str) -> None:
)
+@StepTimer("flag_benjamin")
def _is_benjamin_enabled(
*,
distinct_id: str,
@@ -654,6 +660,7 @@ def _benjamin_fraction_value(value: object) -> float:
return float(value)
+@StepTimer("flag_event_ingest")
def _is_sandbox_event_ingest_enabled(
*,
distinct_id: str,
@@ -706,6 +713,7 @@ def _is_sandbox_event_ingest_enabled(
return enabled
+@StepTimer("flag_agent_telemetry")
def _is_agent_otel_telemetry_enabled(
*,
distinct_id: str,
@@ -759,6 +767,7 @@ def _require_template_compatible_with_custom_image(state: dict, custom_image_nam
)
+@StepTimer("flag_sandbox_runtime")
def _resolve_modal_vm_sandbox(
*,
distinct_id: str,
@@ -882,6 +891,7 @@ def _is_burstable_sandbox_resources_enabled(
return True
+@StepTimer("flag_clone_overlap")
def _is_overlap_clone_boot_enabled(
*,
distinct_id: str,
@@ -921,6 +931,7 @@ def _is_overlap_clone_boot_enabled(
return enabled
+@StepTimer("flag_desktop_workspace")
def _is_desktop_workspace_warm_enabled(
*,
distinct_id: str,
@@ -950,6 +961,7 @@ def _is_desktop_workspace_warm_enabled(
return enabled
+@StepTimer("flag_dev_stack_preview")
def _is_dev_stack_preview_enabled(
*,
distinct_id: str,
@@ -991,6 +1003,7 @@ def _is_dev_stack_preview_enabled(
return enabled
+@StepTimer("flag_network_allowlist")
def _is_modal_network_allowlist_enabled(
*,
distinct_id: str,
@@ -1030,6 +1043,7 @@ def _is_modal_network_allowlist_enabled(
return enabled
+@StepTimer("flag_sandbox_backend")
def _resolve_sandbox_backend(
*,
distinct_id: str,
@@ -1119,6 +1133,7 @@ def _compile_effective_network_policy(allowed_domains: list[str]) -> EffectiveNe
)
+@StepTimer("flag_pr_babysit")
def _is_pr_babysit_snapshot_enabled(
*,
distinct_id: str,
@@ -1202,18 +1217,24 @@ def _is_continue_as_new_enabled(
@activity.defn
@asyncify
@close_db_connections
[email protected](fresh=True, capture_exceptions=False)
def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProcessingContext:
"""Fetch task details and create the processing context for the workflow."""
run_id = input.run_id
+ posthoganalytics.tag("run_id", run_id)
log_with_activity_context("Fetching task processing context", run_id=run_id)
try:
- task_run = TaskRun.objects.select_related(
- "task__created_by",
- "task__team",
- "task__github_integration",
- "task__github_user_integration",
- ).get(id=run_id)
+ with StepTimer("load_task_run"):
+ task_run = TaskRun.objects.select_related(
+ "task__created_by",
+ "task__team",
+ "task__github_integration",
+ "task__github_user_integration",
+ ).get(id=run_id)
+ posthoganalytics.tag("origin_product", task_run.task.origin_product)
+ posthoganalytics.tag("run_environment", task_run.environment)
+ posthoganalytics.tag("mode", (task_run.state or {}).get("mode", "background"))
except ObjectDoesNotExist:
# The row may simply not be visible yet (creating transaction not committed) or
# be mid-cancel/delete. Retry rather than fail fatally so the transient window recovers.
@@ -1244,7 +1265,8 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
state = task_run.state or {}
trial_origin = task.is_scout_experiment
- actor_user = get_task_run_credential_user(task, state)
+ with StepTimer("resolve_actor"):
+ actor_user = get_task_run_credential_user(task, state)
if is_slack_interaction_state(state) and actor_user is None:
raise TaskInvalidStateError(
f"Task {task.id} has no valid Slack actor",
@@ -1260,7 +1282,8 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
environment_custom_image_name: str | None = None
if sandbox_environment_id:
- sandbox_environment = task_run.get_sandbox_environment()
+ with StepTimer("load_sandbox_environment"):
+ sandbox_environment = task_run.get_sandbox_environment()
if sandbox_environment is None:
raise TaskInvalidStateError(
f"Sandbox environment {sandbox_environment_id} not accessible for team {task.team_id}",
@@ -1309,9 +1332,10 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
# A per-run image (picked at task start) wins over the environment's image.
state_custom_image_id = state.get("custom_image_id")
if state_custom_image_id:
- state_custom_image = SandboxCustomImage.get_accessible_for_task(
- image_id=state_custom_image_id, team_id=task.team_id, task_created_by_id=task.created_by_id
- )
+ with StepTimer("load_custom_image"):
+ state_custom_image = SandboxCustomImage.get_accessible_for_task(
+ image_id=state_custom_image_id, team_id=task.team_id, task_created_by_id=task.created_by_id
+ )
if state_custom_image is not None and state_custom_image.is_ready:
environment_custom_image_name = state_custom_image.modal_image_name
else:
@@ -1341,16 +1365,17 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
# opt in unconditionally — independent of the org-level `tasks-pr-loop` rollout
# that gates other origins. This mirrors the babysitting the Slack coding bot
# gets for its PRs.
- pr_loop_enabled = (
- task.origin_product == Task.OriginProduct.SIGNAL_REPORT
- or posthoganalytics.feature_enabled(
- "tasks-pr-loop",
- distinct_id=distinct_id,
- groups={"organization": organization_id},
- group_properties={"organization": {"id": organization_id}},
- )
- or False
- ) # Ensure we get a boolean value even if the flag is missing
+ with StepTimer("flag_pr_loop"):
+ pr_loop_enabled = (
+ task.origin_product == Task.OriginProduct.SIGNAL_REPORT
+ or posthoganalytics.feature_enabled(
+ "tasks-pr-loop",
+ distinct_id=distinct_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ )
+ or False
+ ) # Ensure we get a boolean value even if the flag is missing
emit_agent_log(run_id, "debug", f"pr_loop_enabled: {pr_loop_enabled} for this task run")
state_updates: dict[str, Any] = {PR_LOOP_ENABLED_STATE_KEY: pr_loop_enabled}
include_live_context = state.get("include_live_context") is not False
@@ -1362,7 +1387,8 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
store_skills: list[dict[str, Any]] | None = []
state[STORE_SKILLS_STATE_KEY] = []
else:
- store_skills = resolve_store_skills(team, actor_user or task.created_by, run_id=run_id)
+ with StepTimer("store_skills"):
+ store_skills = resolve_store_skills(team, actor_user or task.created_by, run_id=run_id)
except Exception as e:
log_with_activity_context("store_skills_resolve_failed", run_id=run_id, error=str(e))
store_skills = None
@@ -1372,14 +1398,16 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
# Best-effort for the same reason as store skills.
state_remove_keys: list[str] = []
try:
- instruction_updates, state_remove_keys = agent_instructions_state_update(
- task, actor_user, ai_stage=state.get("ai_stage")
- )
+ with StepTimer("agent_instructions"):
+ instruction_updates, state_remove_keys = agent_instructions_state_update(
+ task, actor_user, ai_stage=state.get("ai_stage")
+ )
state_updates.update(instruction_updates)
except Exception as e:
log_with_activity_context("agent_instructions_resolve_failed", run_id=run_id, error=str(e))
try:
- TaskRun.update_state_atomic(task_run.id, updates=state_updates, remove_keys=state_remove_keys)
+ with StepTimer("persist_task_context"):
+ TaskRun.update_state_atomic(task_run.id, updates=state_updates, remove_keys=state_remove_keys)
except Exception as e:
log_with_activity_context("run_state_stamp_failed", run_id=run_id, error=str(e))
@@ -1423,11 +1451,12 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
run_id=run_id,
state=state,
)
- context_layer_enabled = (
- include_live_context
- and not trial_origin
- and context_layer_facade.is_context_layer_enabled(organization_id=organization_id, distinct_id=distinct_id)
- )
+ with StepTimer("flag_context_layer"):
+ context_layer_enabled = (
+ include_live_context
+ and not trial_origin
+ and context_layer_facade.is_context_layer_enabled(organization_id=organization_id, distinct_id=distinct_id)
+ )
use_modal_network_allowlist = _is_modal_network_allowlist_enabled(
distinct_id=distinct_id,
organization_id=organization_id,
@@ -1449,7 +1478,8 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
effective_network_policy: EffectiveNetworkPolicy | None = None
if allowed_domains is not None:
try:
- effective_network_policy = _compile_effective_network_policy(allowed_domains)
+ with StepTimer("network_policy"):
+ effective_network_policy = _compile_effective_network_policy(allowed_domains)
except NetworkPolicyValidationError as error:
log_with_activity_context(
"sandbox_network_policy_invalid",
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 da592d0c8e48..8c8e2abef39e 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -245,7 +245,8 @@ def _prepare_posthog_desktop_cloud_task(ctx: TaskProcessingContext, sandbox: San
f"echo $! > {state_dir}/launcher.pid"
)
try:
- result = sandbox.execute(launch, timeout_seconds=30)
+ with StepTimer("desktop_workspace_launch"):
+ result = sandbox.execute(launch, timeout_seconds=30)
except Exception as e:
logger.warning("desktop_bootstrap_launch_failed", extra={"run_id": ctx.run_id, "error": str(e)})
return
@@ -416,6 +417,7 @@ def _github_token_error(error: Exception, message: str, context: dict[str, Any])
return GitHubAuthenticationError(message, context, cause=error)
+@StepTimer("github_credentials")
def _resolve_sandbox_github_token(
ctx: TaskProcessingContext,
*,
@@ -485,6 +487,7 @@ def _resolve_sandbox_github_token(
)
+@StepTimer("load_task")
def _load_task(ctx: TaskProcessingContext) -> Task:
try:
task = Task.objects.select_related("created_by", "github_integration", "github_user_integration", "team").get(
@@ -555,6 +558,7 @@ def _sandbox_image_kind(image_source: str, custom_image_name: str | None) -> str
return "base"
+@StepTimer("environment_variables")
def _build_environment_variables(
ctx: TaskProcessingContext, task: Task, github_token: str, access_token: str
) -> dict[str, str]:
@@ -704,6 +708,7 @@ def _effective_sandbox_template(*, use_vm_sandbox: bool, requested: SandboxTempl
@activity.defn
@asyncify
[email protected](fresh=True, capture_exceptions=False)
def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> PrepareSandboxForRepositoryOutput:
ctx = input.context
@@ -749,14 +754,16 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> P
task = _load_task(ctx)
shallow_clone = not needs_full_history(task.origin_product)
- actor_user = get_task_run_credential_user(task, ctx.state)
+ with StepTimer("resolve_actor"):
+ actor_user = get_task_run_credential_user(task, ctx.state)
credential_repository = repository or (ctx.repositories[0] if ctx.repositories else None)
github_token = _resolve_sandbox_github_token(
ctx, task=task, actor_user=actor_user, repository=credential_repository, has_repo=has_repo
)
try:
- access_token = create_oauth_access_token_for_run(task, ctx.state, run_id=ctx.run_id)
+ with StepTimer("posthog_access_token"):
+ access_token = create_oauth_access_token_for_run(task, ctx.state, run_id=ctx.run_id)
except Exception as e:
raise OAuthTokenError(
f"Failed to create OAuth access token for task {ctx.task_id}",
@@ -858,6 +865,7 @@ def _pin_governs_sandbox_agent(ctx: TaskProcessingContext, config: SandboxConfig
return not used_snapshot or config.snapshot_kind == SNAPSHOT_KIND_DIRECTORY
+@StepTimer("sandbox_agent_version")
def _persist_sandbox_agent_version(run_id: str, sandbox: SandboxBase, *, compare_with_pin: bool) -> None:
version: str | None = None
try:
@@ -896,6 +904,7 @@ def _persist_sandbox_agent_version(run_id: str, sandbox: SandboxBase, *, compare
@asyncify
[email protected](fresh=True, capture_exceptions=False)
def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> CreateSandboxForRepositoryOutput:
ctx = input.context
prepared = input.prepared
@@ -905,7 +914,8 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
image_source=prepared.image_source,
**ctx.to_log_context(),
):
- check_organization_execution(ctx.team_id)
+ with StepTimer("organization_execution_check"):
+ check_organization_execution(ctx.team_id)
if not (ctx.state or {}).get("await_user_message"):
task = _load_task(ctx)
if reason := get_compute_quota_denial_reason(task):
@@ -1028,8 +1038,11 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
record_network_enforcement(
"sandbox_creation_with_policy_request", runtime, "modal_requested", "success"
)
- if not sandbox.start_cpu_billing_sampler():
- activity.logger.warning("Failed to start sandbox CPU billing sampler", extra={"sandbox_id": sandbox.id})
+ with StepTimer("cpu_sampler_start"):
+ if not sandbox.start_cpu_billing_sampler():
+ activity.logger.warning(
+ "Failed to start sandbox CPU billing sampler", extra={"sandbox_id": sandbox.id}
+ )
if sandbox.config.image_fallback:
emit_agent_log(
ctx.run_id,
@@ -1062,15 +1075,22 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
sandbox_backend=sandbox_backend,
)
- credentials = sandbox.get_connect_credentials()
- jwt_kid = persist_sandbox_connection(
- run_id=ctx.run_id,
- sandbox=sandbox,
- credentials=credentials,
- sandbox_created_at=sandbox_created_at,
- task_runtime=ctx.task_runtime,
- sandbox_backend=ctx.sandbox_backend if ctx.sandbox_backend != "modal" else None,
- )
+ with StepTimer("sandbox_connect_credentials"):
+ credentials = sandbox.get_connect_credentials()
+ with StepTimer(
+ "persist_sandbox_connection",
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ used_snapshot=actual_used_snapshot,
+ ):
+ jwt_kid = persist_sandbox_connection(
+ run_id=ctx.run_id,
+ sandbox=sandbox,
+ credentials=credentials,
+ sandbox_created_at=sandbox_created_at,
+ task_runtime=ctx.task_runtime,
+ sandbox_backend=ctx.sandbox_backend if ctx.sandbox_backend != "modal" else None,
+ )
except Exception:
try:
sandbox.destroy()
@@ -1158,6 +1178,7 @@ async def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput)
@activity.defn
@asyncify
[email protected](fresh=True, capture_exceptions=False)
def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRepositoryInSandboxOutput:
ctx = input.context
blobless_clone = _is_blobless_signals_clone_enabled(ctx)
@@ -1241,6 +1262,7 @@ def _is_missing_remote_branch_clone_error(result: ExecutionResult) -> bool:
@activity.defn
@asyncify
[email protected](fresh=True, capture_exceptions=False)
def checkout_branch_in_sandbox(input: CheckoutBranchInSandboxInput) -> CheckoutBranchInSandboxOutput:
ctx = input.context
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 b0c518f314ce..5371538a5be3 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
@@ -172,6 +172,7 @@ def _resolve_protected_base_branch(ctx: TaskProcessingContext) -> str | None:
return branch
+@StepTimer("repository_directory_check")
def _ensure_repository_on_disk(ctx: TaskProcessingContext, sandbox: SandboxBase) -> None:
"""Fail fast when the repository the agent-server will use as its cwd was never materialized.
@@ -751,8 +752,34 @@ def _record_boot_total(input: StartAgentServerInput) -> int | None:
return boot_total_ms
+def _read_agent_boot_metrics(sandbox: SandboxBase, input: StartAgentServerInput) -> tuple[int | None, dict[str, int]]:
+ ctx = input.context
+ runtime = sandbox_runtime_label(ctx.use_modal_vm_sandbox)
+ with StepTimer(
+ "read_agent_boot_metrics",
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ boot_path=input.boot_path,
+ used_snapshot=input.used_snapshot,
+ ):
+ session_init_ms, boot_phases_ms = sandbox.read_agent_server_boot_metrics()
+ if session_init_ms is not None:
+ record_agent_server_session_init_ms(
+ session_init_ms, boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
+ )
+ record_agent_server_boot_phases_ms(
+ boot_phases_ms,
+ input.boot_path,
+ used_snapshot=input.used_snapshot,
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ )
+ return session_init_ms, boot_phases_ms
+
+
@activity.defn
@asyncify
[email protected](fresh=True, capture_exceptions=False)
def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
"""Start the agent-server HTTP server in the sandbox.
@@ -773,7 +800,8 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
):
emit_agent_log(ctx.run_id, "debug", "Starting agent server")
- sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
+ with StepTimer("sandbox_lookup"):
+ sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
# Classic (non-deferred) path only: any clone has already happened by now, so a missing
# repo directory can never appear later. The deferred/overlap path clones in parallel
# and gates the session on the repo-ready barrier instead.
@@ -866,19 +894,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
emit_agent_log(ctx.run_id, "debug", f"Agent server started at {input.sandbox_url}")
activity.logger.info(f"Agent server started at {input.sandbox_url} for task {ctx.task_id}")
- session_init_ms, boot_phases_ms = sandbox.read_agent_server_boot_metrics()
- if session_init_ms is not None:
- record_agent_server_session_init_ms(
- session_init_ms, boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
- )
- record_agent_server_boot_phases_ms(
- boot_phases_ms,
- input.boot_path,
- used_snapshot=input.used_snapshot,
- origin_product=ctx.origin_product,
- runtime=runtime,
- )
-
+ session_init_ms, boot_phases_ms = _read_agent_boot_metrics(sandbox, input)
boot_total_ms = _record_boot_total(input)
_spawn_post_ready_diagnostics(ctx, sandbox, params.agentsh_domains)
@@ -899,6 +915,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
@activity.defn
@asyncify
[email protected](fresh=True, capture_exceptions=False)
def launch_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
ctx = input.context
@@ -914,7 +931,8 @@ def launch_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
):
emit_agent_log(ctx.run_id, "debug", "Launching agent server (deferred readiness)")
- sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
+ with StepTimer("sandbox_lookup"):
+ sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
repo_ready_file = REPO_READY_FILE if input.defer_for_clone else None
runtime = sandbox_runtime_label(ctx.use_modal_vm_sandbox)
with StepTimer(
@@ -945,15 +963,19 @@ def launch_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
@activity.defn
@asyncify
[email protected](fresh=True, capture_exceptions=False)
def mark_repo_ready(input: MarkRepoReadyInput) -> None:
- sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
+ posthoganalytics.tag("run_id", input.run_id)
+ with StepTimer("sandbox_lookup"):
+ sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
for repository in input.failed_repositories or []:
repo_path = sandbox_repo_path(repository)
result = sandbox.execute(f"mkdir -p {shlex.quote(repo_path)}", timeout_seconds=10)
if result.exit_code != 0:
raise RuntimeError(f"Failed to create fallback workspace for {repository}: {result.stderr}")
if input.release_barrier:
- sandbox.mark_repo_ready(REPO_READY_FILE)
+ with StepTimer("release_repository_gate"):
+ sandbox.mark_repo_ready(REPO_READY_FILE)
if input.failed_repositories:
action = "released agent with" if input.release_barrier else "created"
emit_agent_log(
@@ -967,6 +989,7 @@ def mark_repo_ready(input: MarkRepoReadyInput) -> None:
@activity.defn
@asyncify
[email protected](fresh=True, capture_exceptions=False)
def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOutput:
ctx = input.context
@@ -980,7 +1003,8 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
),
guard_organization_execution(ctx.team_id),
):
- sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
+ with StepTimer("sandbox_lookup"):
+ sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
agentsh_domains = _agentsh_domains_for(ctx)
attempt = current_activity_attempt()
runtime = sandbox_runtime_label(ctx.use_modal_vm_sandbox)
@@ -1067,19 +1091,7 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
emit_agent_log(ctx.run_id, "debug", f"Agent server ready at {input.sandbox_url}")
activity.logger.info(f"Agent server ready at {input.sandbox_url} for task {ctx.task_id}")
- session_init_ms, boot_phases_ms = sandbox.read_agent_server_boot_metrics()
- if session_init_ms is not None:
- record_agent_server_session_init_ms(
- session_init_ms, boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
- )
- record_agent_server_boot_phases_ms(
- boot_phases_ms,
- input.boot_path,
- used_snapshot=input.used_snapshot,
- origin_product=ctx.origin_product,
- runtime=runtime,
- )
-
+ session_init_ms, boot_phases_ms = _read_agent_boot_metrics(sandbox, input)
boot_total_ms = _record_boot_total(input)
_spawn_post_ready_diagnostics(ctx, sandbox, agentsh_domains)
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
index 9744f4362a0e..e9b94495ba87 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
@@ -597,14 +597,15 @@ def test_clone_failure_records_failed_latency_and_captures_command_result(mocker
"error": "execution stopped",
"team": "array",
}
- metric_meter.assert_called_once_with(
+ clone_samples = [args.args[0] for args in metric_meter.call_args_list if args.args[0]["step"] == "repository_clone"]
+ assert clone_samples == [
{
"step": "repository_clone",
"used_snapshot": "false",
"status": "FAILED",
"runtime": "gvisor",
}
- )
+ ]
assert str(capture_exception.call_args.args[0]) == "clone output"
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 9fc0c854c1b6..522c845ece28 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
@@ -401,6 +401,7 @@ async def test_combined_start_failure_records_step_statuses(mocker, error, expec
)
async def test_agent_server_boot_phases_are_recorded_as_step_metrics(mocker, activity, boot_path) -> None:
context = _context()
+ context.origin_product = "review_hog"
sandbox = mocker.Mock(id="sandbox-id")
sandbox.supports_combined_agent_server_start_and_health.return_value = False
sandbox.read_agent_server_boot_metrics.return_value = (
@@ -437,6 +438,7 @@ async def test_agent_server_boot_phases_are_recorded_as_step_metrics(mocker, act
"products.tasks.backend.temporal.process_task.activities.start_agent_server.TaskRun.update_state_atomic"
)
record_step = mocker.patch("products.tasks.backend.temporal.metrics.record_agent_server_step_ms")
+ metric_meter = mocker.patch("products.tasks.backend.temporal.metrics._metric_meter")
await activity(
StartAgentServerInput(
@@ -448,13 +450,21 @@ async def test_agent_server_boot_phases_are_recorded_as_step_metrics(mocker, act
)
)
+ read_labels = next(
+ call.args[0] for call in metric_meter.call_args_list if call.args[0]["step"] == "read_agent_boot_metrics"
+ )
+ assert read_labels["origin_product"] == "review_hog"
+ assert read_labels["runtime"] == "gvisor"
+ assert read_labels["boot_path"] == boot_path
+ assert read_labels["used_snapshot"] == "true"
+
assert [record.args for record in record_step.call_args_list] == [
("agent_server_phase_context_fetch", 40, boot_path),
("agent_server_phase_repository_ready", 1200, boot_path),
("agent_server_phase_server_total", 1400, boot_path),
]
assert all(
- record.kwargs == {"used_snapshot": True, "origin_product": None, "runtime": "gvisor"}
+ record.kwargs == {"used_snapshot": True, "origin_product": "review_hog", "runtime": "gvisor"}
for record in record_step.call_args_list
)
diff --git a/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py b/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py
index 64ae570f78f1..3b9b3940747e 100644
--- a/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py
+++ b/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py
@@ -44,7 +44,7 @@ def track_workflow_event(input: TrackWorkflowEventInput) -> None:
event=input.event_name,
properties=input.properties,
groups=input.groups or {},
- send_feature_flags=True,
+ send_feature_flags=not input.event_name.startswith("agent_first_"),
)
except Exception:
logger.exception(
diff --git a/products/tasks/backend/temporal/process_task/sandbox_connection.py b/products/tasks/backend/temporal/process_task/sandbox_connection.py
index ad03e4967ef7..5a88bb43c382 100644
--- a/products/tasks/backend/temporal/process_task/sandbox_connection.py
+++ b/products/tasks/backend/temporal/process_task/sandbox_connection.py
@@ -12,6 +12,7 @@ from products.tasks.backend.logic.services.sandbox_usage import (
open_sandbox_session,
)
from products.tasks.backend.models import TaskRun
+from products.tasks.backend.temporal.metrics import StepTimer
def persist_sandbox_connection(
@@ -23,7 +24,8 @@ def persist_sandbox_connection(
task_runtime: str | None,
sandbox_backend: str | None = None,
) -> str:
- jwt_kid = get_primary_sandbox_jwt_kid()
+ with StepTimer("sandbox_jwt_key"):
+ jwt_kid = get_primary_sandbox_jwt_kid()
sandbox_state: dict[str, Any] = {
"sandbox_id": sandbox.id,
"sandbox_url": credentials.url,
@@ -34,18 +36,22 @@ def persist_sandbox_connection(
if credentials.token:
sandbox_state["sandbox_connect_token"] = credentials.token
- TaskRun.update_state_atomic(run_id, updates=sandbox_state)
+ with StepTimer("persist_connection_state"):
+ TaskRun.update_state_atomic(run_id, updates=sandbox_state)
- cpu_usage_attribution_usec, cpu_usage_attribution_measured_at = measure_sandbox_cpu_usage(sandbox)
- billed_cpu_usage_attribution_usec = measure_sandbox_billed_cpu_usage(sandbox)
- open_sandbox_session(
- run_id=run_id,
- sandbox_id=sandbox.id,
- config=sandbox.config,
- sandbox_created_at=sandbox_created_at,
- cpu_usage_attribution_usec=cpu_usage_attribution_usec,
- billed_cpu_usage_attribution_usec=billed_cpu_usage_attribution_usec,
- cpu_usage_attribution_measured_at=cpu_usage_attribution_measured_at,
- required=task_runtime == "pi",
- )
+ with StepTimer("cpu_usage"):
+ cpu_usage_attribution_usec, cpu_usage_attribution_measured_at = measure_sandbox_cpu_usage(sandbox)
+ with StepTimer("billed_cpu_usage"):
+ billed_cpu_usage_attribution_usec = measure_sandbox_billed_cpu_usage(sandbox)
+ with StepTimer("open_usage_session"):
+ open_sandbox_session(
+ run_id=run_id,
+ sandbox_id=sandbox.id,
+ config=sandbox.config,
+ sandbox_created_at=sandbox_created_at,
+ cpu_usage_attribution_usec=cpu_usage_attribution_usec,
+ billed_cpu_usage_attribution_usec=billed_cpu_usage_attribution_usec,
+ cpu_usage_attribution_measured_at=cpu_usage_attribution_measured_at,
+ required=task_runtime == "pi",
+ )
return jwt_kid
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index 7d9442c7508e..55f528639b69 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -1518,6 +1518,56 @@ async def test_boot_milestone_contains_only_timing_and_runtime_dimensions(
)
[email protected]("timing_enabled", [False, True])
[email protected]("same_run_resume", [False, True])
+async def test_shared_startup_boundaries_are_present_only_for_new_workflows(
+ monkeypatch, timing_enabled, same_run_resume
+):
+ instance = ProcessTaskWorkflow()
+ instance._context = _build_context(github_integration_id=123)
+ instance._context.state = {
+ "startup_requested_at": "2026-01-01T00:00:00+00:00",
+ "same_run_resume": same_run_resume,
+ }
+ instance._startup_worker_started_at = datetime(2026, 1, 1, 0, 0, 2, tzinfo=UTC) if timing_enabled else None
+ instance._startup_context_loaded_at = datetime(2026, 1, 1, 0, 0, 3, tzinfo=UTC) if timing_enabled else None
+ now = datetime(2026, 1, 1, 0, 0, 10, tzinfo=UTC)
+ instance._chain_started_at = now
+ instance._agent_ready_at = now
+ track = AsyncMock()
+ monkeypatch.setattr(instance, "_track_boot_milestone", track)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=now))
+ monkeypatch.setattr(
+ process_task_workflow_module.workflow,
+ "info",
+ Mock(return_value=SimpleNamespace(start_time=datetime(2026, 1, 1, 0, 0, 1, tzinfo=UTC))),
+ )
+ monkeypatch.setattr(process_task_workflow_module, "record_agent_boot_milestone_ms", Mock())
+
+ instance._schedule_boot_milestone("agent_first_activity_observed")
+ await instance._flush_boot_telemetry_tasks()
+
+ properties = track.call_args.args[1]
+ if timing_enabled:
+ assert properties["startup_requested_at"] == "2026-01-01T00:00:00+00:00"
+ assert properties["workflow_accepted_at"] == "2026-01-01T00:00:01+00:00"
+ assert properties["worker_started_at"] == "2026-01-01T00:00:02+00:00"
+ assert properties["context_loaded_at"] == "2026-01-01T00:00:03+00:00"
+ assert properties["observed_at"] == now.isoformat()
+ if same_run_resume:
+ assert "since_startup_requested_ms" not in properties
+ assert "handoff_ms" not in properties
+ else:
+ assert properties["since_startup_requested_ms"] == 10000
+ assert properties["handoff_ms"] == 1000
+ assert properties["worker_wait_ms"] == 1000
+ assert properties["task_setup_ms"] == 1000
+ else:
+ assert "startup_requested_at" not in properties
+ assert "observed_at" not in properties
+ assert "since_startup_requested_ms" not in properties
+
+
@pytest.mark.parametrize(
("origin_product", "team_id"),
[
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 5659ead1106d..e2668239f110 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -160,6 +160,7 @@ _PATCH_ID_CANCEL_SANDBOX_CREATION_ON_COMPLETION = "tasks-cancel-sandbox-creation
_PATCH_ID_CONTINUE_AFTER_REPOSITORY_CLONE_FAILURE = "tasks-continue-after-repository-clone-failure"
_PATCH_ID_ASYNC_AGENT_SHADOW_RESULT = "tasks-async-agent-shadow-result"
_PATCH_ID_AGENT_BOOT_INTERACTION_TELEMETRY = "tasks-agent-boot-interaction-telemetry"
+_PATCH_ID_SHARED_STARTUP_TIMING = "tasks-shared-startup-timing"
class _TaskCompletedDuringSandboxCreation(Exception):
@@ -619,6 +620,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._boot_path: str | None = None
self._image_source: str | None = None
self._agent_ready_at: datetime | None = None
+ self._startup_worker_started_at: datetime | None = None
+ self._startup_context_loaded_at: datetime | None = None
# Milestones the agent hits before readiness is stamped, sampled once it is.
self._boot_milestones_before_ready: list[tuple[str, datetime]] = []
self._boot_telemetry_tasks: list[asyncio.Task[None]] = []
@@ -1299,6 +1302,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, input: ProcessTaskInput) -> ProcessTaskOutput:
+ if (
+ input.resumed_sandbox is None
+ and workflow.in_workflow()
+ and workflow.patched(_PATCH_ID_SHARED_STARTUP_TIMING)
+ ):
+ self._startup_worker_started_at = workflow.now()
sandbox_id = None
sandbox_cleaned = False
run_stream_completed = False
@@ -1318,6 +1327,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
)
try:
self._context = await self._get_task_processing_context(input)
+ if self._startup_worker_started_at is not None:
+ self._startup_context_loaded_at = workflow.now()
self._posthog_mcp_scopes = input.posthog_mcp_scopes
# A local-environment run is driven by the user's desktop agent — QUEUED does not
# mean "awaiting a cloud workflow". Executing it here would boot a sandbox the repo
@@ -2780,6 +2791,38 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"transport": "sequenced_ingest" if self.context.sandbox_event_ingest_enabled else "sse",
"prewarmed": self._prewarmed,
}
+ if self._startup_worker_started_at is not None:
+ properties.update(
+ {
+ "observed_at": now.isoformat(),
+ "workflow_accepted_at": workflow.info().start_time.isoformat(),
+ "worker_started_at": self._startup_worker_started_at.isoformat(),
+ "context_loaded_at": self._startup_context_loaded_at.isoformat()
+ if self._startup_context_loaded_at
+ else None,
+ "startup_requested_at": (self.context.state or {}).get("startup_requested_at"),
+ "run_environment": self.context.environment,
+ "agent_ready_at": self._agent_ready_at.isoformat() if self._agent_ready_at else None,
+ }
+ )
+ requested_at = properties["startup_requested_at"]
+ if isinstance(requested_at, str) and not is_same_run_resume_state(self.context.state or {}):
+ try:
+ requested = datetime.fromisoformat(requested_at)
+ if requested.tzinfo is not None and requested <= now:
+ properties["since_startup_requested_ms"] = int((now - requested).total_seconds() * 1000)
+ properties["handoff_ms"] = max(
+ 0, int((workflow.info().start_time - requested).total_seconds() * 1000)
+ )
+ except ValueError:
+ pass
+ properties["worker_wait_ms"] = max(
+ 0, int((self._startup_worker_started_at - workflow.info().start_time).total_seconds() * 1000)
+ )
+ if self._startup_context_loaded_at is not None:
+ properties["task_setup_ms"] = max(
+ 0, int((self._startup_context_loaded_at - self._startup_worker_started_at).total_seconds() * 1000)
+ )
if since_agent_ready_ms is not None:
self._record_boot_milestone_sample(event_name, since_agent_ready_ms)
else:
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index 3fb482de0f49..89d794baf34a 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -1,7 +1,7 @@
import json
import uuid
from contextlib import nullcontext
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import ClassVar
from unittest.mock import AsyncMock, patch
@@ -1127,6 +1127,23 @@ class TestTaskRun(TestCase):
self.assertNotIn("initial_permission_mode", run.state)
+ @parameterized.expand([("immediate", None), ("future", 1), ("overdue", -1)])
+ def test_create_run_stamps_server_startup_time_and_preserves_it_in_analytics(
+ self, _name: str, scheduled_days: int | None
+ ) -> None:
+ requested_at = django_timezone.now()
+ scheduled_at = requested_at + timedelta(days=scheduled_days) if scheduled_days is not None else None
+ run = self.task.create_run(
+ extra_state={"startup_requested_at": "untrusted-time"},
+ startup_requested_at=requested_at,
+ scheduled_at=scheduled_at,
+ )
+ run.refresh_from_db()
+
+ expected = max(requested_at, scheduled_at) if scheduled_at is not None else requested_at
+ self.assertEqual(run.state["startup_requested_at"], expected.isoformat())
+ self.assertEqual(run.analytics_properties()["startup_requested_at"], run.state["startup_requested_at"])
+
def test_create_run_snapshots_task_ownership_version(self):
ownership_version = str(uuid.uuid4())
self.task.state = {TASK_OWNERSHIP_VERSION_STATE_KEY: ownership_version}
diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.py
index 5d6fb210a4c8..758a13481df6 100644
--- a/products/tasks/backend/tests/test_task_run_metrics.py
+++ b/products/tasks/backend/tests/test_task_run_metrics.py
@@ -1,7 +1,12 @@
+from contextlib import nullcontext
+from datetime import timedelta
+
+import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from django.test import TestCase
+import posthoganalytics
from parameterized import parameterized
from prometheus_client import REGISTRY
@@ -10,6 +15,8 @@ from posthog.models import Organization, Team, User
from products.tasks.backend.metrics import CustomImageBuildOutcome, observe_custom_image_build, observe_sandbox_deadline
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.client import execute_task_processing_workflow
+from products.tasks.backend.temporal.metrics import StepTimer
+from products.tasks.backend.temporal.observability import log_activity_execution
from products.tasks.backend.temporal.process_task.activities.track_workflow_event import (
TrackWorkflowEventInput,
track_workflow_event,
@@ -45,6 +52,85 @@ class TestSandboxDeadlineMetrics:
assert _sample_value("posthog_tasks_sandbox_deadline_total", labels) == before + 1
+class TestStartupStepMetrics:
+ async def test_async_step_timer_waits_for_work_before_recording(self) -> None:
+ @StepTimer("dispatch")
+ async def dispatch() -> str:
+ return "started"
+
+ with (
+ posthoganalytics.new_context(fresh=True, capture_exceptions=False),
+ patch("products.tasks.backend.temporal.metrics.time.perf_counter", side_effect=[1, 3]),
+ patch("products.tasks.backend.temporal.metrics.posthoganalytics.capture") as capture,
+ ):
+ posthoganalytics.tag("run_id", "test-run")
+ assert await dispatch() == "started"
+
+ assert capture.call_args.kwargs["properties"]["duration_ms"] == 2000
+
+ @pytest.mark.parametrize("event", ["agent_first_activity_observed", "agent_first_command_dispatched"])
+ def test_startup_milestone_capture_does_not_fetch_feature_flags(self, event: str) -> None:
+ with patch(
+ "products.tasks.backend.temporal.process_task.activities.track_workflow_event.posthoganalytics.capture"
+ ) as capture:
+ track_workflow_event(TrackWorkflowEventInput(event, "test-user", {"run_id": "test-run"}))
+ assert capture.call_args.kwargs["send_feature_flags"] is False
+
+ @pytest.mark.parametrize("fails", [False, True])
+ def test_decorated_timer_keeps_nested_attempt_durations_and_failures_separate(self, fails: bool) -> None:
+ @StepTimer("flag_streaming")
+ def work(nested: bool) -> None:
+ if nested:
+ work(False)
+ elif fails:
+ raise ValueError("failed step")
+
+ meter = MagicMock()
+ with (
+ posthoganalytics.new_context(fresh=True, capture_exceptions=False),
+ patch("products.tasks.backend.temporal.metrics.time.perf_counter", side_effect=[0, 1, 2, 4]),
+ patch("products.tasks.backend.temporal.metrics._metric_meter", return_value=meter) as metric_meter,
+ patch("products.tasks.backend.temporal.metrics.posthoganalytics.capture") as capture,
+ pytest.raises(ValueError, match="failed step") if fails else nullcontext(),
+ ):
+ posthoganalytics.tag("run_id", "test-run")
+ posthoganalytics.tag("origin_product", "signals_scout")
+ work(True)
+
+ durations = [args.args[0] for args in meter.create_histogram_timedelta.return_value.record.call_args_list]
+ assert durations == [timedelta(seconds=1), timedelta(seconds=4)]
+ assert [args.args[0]["status"] for args in metric_meter.call_args_list] == [
+ "FAILED" if fails else "COMPLETED"
+ ] * 2
+ events = [call.kwargs["properties"] for call in capture.call_args_list]
+ assert [event["duration_ms"] for event in events] == [1000, 4000]
+ assert all(event["run_id"] == "test-run" and event["origin_product"] == "signals_scout" for event in events)
+ assert all(event["status"] == ("FAILED" if fails else "COMPLETED") for event in events)
+ assert all(call.kwargs["send_feature_flags"] is False for call in capture.call_args_list)
+
+ @pytest.mark.parametrize("capture_fails", [False, True])
+ def test_step_events_use_scoped_run_context_without_affecting_work(self, capture_fails: bool) -> None:
+ with patch("products.tasks.backend.temporal.metrics.posthoganalytics.capture") as capture:
+ capture.side_effect = RuntimeError("queue unavailable") if capture_fails else None
+ for run_id, origin in [("first-run", "slack"), ("second-run", "review_hog")]:
+ with (
+ posthoganalytics.new_context(fresh=True, capture_exceptions=False),
+ log_activity_execution("startup", run_id=run_id, origin_product=origin, environment="cloud"),
+ StepTimer("setup"),
+ ):
+ pass
+ with StepTimer("unrelated"):
+ pass
+
+ assert capture.call_count == 2
+ properties = [call.kwargs["properties"] for call in capture.call_args_list]
+ assert [(event["run_id"], event["origin_product"]) for event in properties] == [
+ ("first-run", "slack"),
+ ("second-run", "review_hog"),
+ ]
+ assert all(event["run_environment"] == "cloud" for event in properties)
+
+
class TestTaskRunMetrics(TestCase):
def setUp(self) -> None:
self.organization = Organization.objects.create(name="Test Org")
@@ -70,13 +156,18 @@ class TestTaskRunMetrics(TestCase):
}
before = _sample_value("posthog_tasks_task_run_created_total", labels)
- with self.captureOnCommitCallbacks(execute=True):
+ with (
+ self.captureOnCommitCallbacks(execute=True),
+ patch("products.tasks.backend.models.posthoganalytics.capture") as capture,
+ ):
self.task.create_run(
environment=TaskRun.Environment.CLOUD,
extra_state={"run_source": "manual", "runtime_adapter": "codex"},
)
assert _sample_value("posthog_tasks_task_run_created_total", labels) == before + 1
+ created_event = next(call for call in capture.call_args_list if call.kwargs.get("event") == "task_run_created")
+ assert created_event.kwargs["send_feature_flags"] is False
def test_create_run_bounds_unexpected_state_labels(self) -> None:
labels = {
@@ -288,7 +379,10 @@ class TestTaskRunMetrics(TestCase):
temporal_client = MagicMock()
temporal_client.start_workflow = AsyncMock()
- with patch("products.tasks.backend.temporal.client.sync_connect") as mock_sync_connect:
+ with (
+ patch("products.tasks.backend.temporal.client.sync_connect") as mock_sync_connect,
+ patch("products.tasks.backend.temporal.metrics.posthoganalytics.capture") as capture,
+ ):
if sync_connect_side_effect is not None:
mock_sync_connect.side_effect = sync_connect_side_effect
else:
@@ -305,6 +399,14 @@ class TestTaskRunMetrics(TestCase):
assert _sample_value("posthog_tasks_task_run_workflow_start_total", labels) == before + 1
assert mock_sync_connect.called is expect_sync_connect_called
+ dispatch = next(
+ call.kwargs["properties"]
+ for call in capture.call_args_list
+ if call.args
+ and call.args[0] == "task_startup_step_completed"
+ and call.kwargs["properties"]["step"] == "dispatch"
+ )
+ assert dispatch["status"] == ("COMPLETED" if _name == "started" else "FAILED")
@parameterized.expand(
[
diff --git a/products/tasks/backend/tests/test_temporal_client.py b/products/tasks/backend/tests/test_temporal_client.py
index 4c81ba4dbf36..88209b5f541f 100644
--- a/products/tasks/backend/tests/test_temporal_client.py
+++ b/products/tasks/backend/tests/test_temporal_client.py
@@ -195,6 +195,12 @@ class TestExecuteTaskProcessingWorkflow(TestCase):
captured = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "task_run_failed"]
self.assertEqual(len(captured), 1)
self.assertEqual(captured[0].kwargs["properties"]["error_type"], "workflow_start_failed")
+ dispatch = next(
+ c.kwargs["properties"]
+ for c in mock_capture.call_args_list
+ if c.args and c.args[0] == "task_startup_step_completed" and c.kwargs["properties"]["step"] == "dispatch"
+ )
+ self.assertEqual(dispatch["status"], "FAILED")
@parameterized.expand([("sync",), ("async",)])
def test_does_not_overwrite_run_that_already_started(self, executor: str) -> None:
diff --git a/products/tasks/backend/tests/test_workflow_dispatch.py b/products/tasks/backend/tests/test_workflow_dispatch.py
index f2d62693149c..c770540f7f5c 100644
--- a/products/tasks/backend/tests/test_workflow_dispatch.py
+++ b/products/tasks/backend/tests/test_workflow_dispatch.py
@@ -192,9 +192,20 @@ class TestWorkflowDispatchPersistence(TestCase):
self.assertEqual([row.id for row in claimed], [dispatch.id])
client = Mock(start_workflow=AsyncMock())
- with self.captureOnCommitCallbacks(execute=True):
+ with (
+ self.captureOnCommitCallbacks(execute=True),
+ patch("products.tasks.backend.temporal.metrics.posthoganalytics.capture") as capture,
+ ):
async_to_sync(Command()._process)(client, claimed[0], "dispatcher-1", asyncio.Semaphore(1))
+ dispatch_event = next(
+ call.kwargs["properties"]
+ for call in capture.call_args_list
+ if call.args
+ and call.args[0] == "task_startup_step_completed"
+ and call.kwargs["properties"]["step"] == "dispatch"
+ )
+ self.assertEqual(dispatch_event["status"], "FAILED" if scheduled and (limited or deactivated) else "COMPLETED")
dispatch.refresh_from_db()
self.task_run.refresh_from_db()
if scheduled and (limited or deactivated):