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.

chore(tasks): add prewarmed sandbox spawn and activation metrics (#65789)

Alessandro Pogliaghi5a411c639193
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 284d9ce8c95c..71e3f11c3c43 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2872,11 +2872,21 @@ def _activate_warm_run(run: TaskRun, task: Task, team_id: int, *, message: str |
"""Activate an idling warm Run: set the draft Task's description (when empty), forward the first
message to the already-running agent, and drop the ``await_user_message`` marker so the Run leaves
the warm pool. Mirrors ``message_routing._handle_first_message``; no fresh agent start."""
+ from products.tasks.backend.metrics import ( # noqa: PLC0415 — keep prometheus deps off the api import path
+ observe_prewarmed_activated,
+ )
+
if message and not (task.description or "").strip():
task.description = message
task.save(update_fields=["description", "updated_at"])
signal_task_run_user_message(run.id, task.id, team_id, content=message, artifact_ids=artifact_ids)
TaskRun.update_state_atomic(run.id, remove_keys=["await_user_message"])
+ # Only count activations of Runs that actually carry the prewarmed marker, so the activation
+ # numerator stays consistent with the workflow_start{prewarmed="true"} denominator — otherwise
+ # warm Runs provisioned before this ships (await_user_message set, prewarmed absent) would push
+ # the hit rate above 1 during the deploy transition.
+ if (run.state or {}).get("prewarmed"):
+ observe_prewarmed_activated(run)
def warm_task_sandbox(
diff --git a/products/tasks/backend/logic/services/warm.py b/products/tasks/backend/logic/services/warm.py
index 93b55b81b24d..36f61833b0da 100644
--- a/products/tasks/backend/logic/services/warm.py
+++ b/products/tasks/backend/logic/services/warm.py
@@ -157,6 +157,7 @@ class SandboxWarmer:
run_state: dict[str, Any] = {
"await_user_message": True,
+ "prewarmed": True,
"initial_permission_mode": "default",
**(extra_state or {}),
}
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 4ffb6c072de3..3930e6da9374 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -22,7 +22,7 @@ _ALLOWED_RUNTIME_ADAPTERS = {"claude", "codex"}
TASK_RUN_CREATED_TOTAL = Counter(
"posthog_tasks_task_run_created_total",
"TaskRun rows created by the Tasks product",
- labelnames=["origin_product", "run_environment", "mode", "run_source", "runtime_adapter"],
+ labelnames=["origin_product", "run_environment", "mode", "run_source", "runtime_adapter", "prewarmed"],
)
TASK_RUN_WORKFLOW_START_TOTAL = Counter(
@@ -34,11 +34,18 @@ TASK_RUN_WORKFLOW_START_TOTAL = Counter(
"mode",
"run_source",
"runtime_adapter",
+ "prewarmed",
"outcome",
"reason",
],
)
+PREWARMED_ACTIVATED_TOTAL = Counter(
+ "posthog_tasks_prewarmed_activated_total",
+ "Pre-warmed Runs that received their first user message (the warm sandbox got used, not reaped)",
+ labelnames=["origin_product"],
+)
+
TASK_RUN_FAILED_TOTAL = Counter(
"posthog_tasks_task_run_failed_total",
"TaskRun workflow failures with bounded attribution labels",
@@ -146,6 +153,7 @@ def _task_run_labels(task_run: "TaskRun | None") -> dict[str, str]:
"mode": "unknown",
"run_source": "unknown",
"runtime_adapter": "unknown",
+ "prewarmed": "unknown",
}
state = task_run.state if isinstance(task_run.state, dict) else {}
@@ -155,6 +163,7 @@ def _task_run_labels(task_run: "TaskRun | None") -> dict[str, str]:
"mode": _bounded_metric_label(state.get("mode"), _ALLOWED_MODES),
"run_source": _bounded_metric_label(state.get("run_source"), _ALLOWED_RUN_SOURCES),
"runtime_adapter": _bounded_metric_label(state.get("runtime_adapter"), _ALLOWED_RUNTIME_ADAPTERS),
+ "prewarmed": "true" if state.get("prewarmed") else "false",
}
@@ -175,6 +184,10 @@ def observe_task_run_workflow_start(
).inc()
+def observe_prewarmed_activated(task_run: "TaskRun") -> None:
+ PREWARMED_ACTIVATED_TOTAL.labels(origin_product=origin_product_label(task_run)).inc()
+
+
def origin_product_label(task_run: "TaskRun | None") -> str:
"""Bounded origin_product metric label resolved from the task run's task."""
if task_run is None:
diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.py
index 72633344a744..dc7b0a5b7f4c 100644
--- a/products/tasks/backend/tests/test_task_run_metrics.py
+++ b/products/tasks/backend/tests/test_task_run_metrics.py
@@ -39,6 +39,7 @@ class TestTaskRunMetrics(TestCase):
"mode": "background",
"run_source": "manual",
"runtime_adapter": "codex",
+ "prewarmed": "false",
}
before = _sample_value("posthog_tasks_task_run_created_total", labels)
@@ -56,6 +57,7 @@ class TestTaskRunMetrics(TestCase):
"mode": "other",
"run_source": "other",
"runtime_adapter": "other",
+ "prewarmed": "false",
}
before = _sample_value("posthog_tasks_task_run_created_total", labels)
@@ -67,6 +69,59 @@ class TestTaskRunMetrics(TestCase):
assert _sample_value("posthog_tasks_task_run_created_total", labels) == before + 1
+ def test_prewarmed_run_created_carries_prewarmed_true_label(self) -> None:
+ labels = {
+ "origin_product": "user_created",
+ "run_environment": "cloud",
+ "mode": "interactive",
+ "run_source": "unknown",
+ "runtime_adapter": "unknown",
+ "prewarmed": "true",
+ }
+ before = _sample_value("posthog_tasks_task_run_created_total", labels)
+
+ self.task.create_run(
+ environment=TaskRun.Environment.CLOUD,
+ mode="interactive",
+ extra_state={"await_user_message": True, "prewarmed": True},
+ )
+
+ assert _sample_value("posthog_tasks_task_run_created_total", labels) == before + 1
+
+ def test_activate_warm_run_increments_prewarmed_activated_counter(self) -> None:
+ from products.tasks.backend.facade import api as facade
+
+ run = self.task.create_run(
+ environment=TaskRun.Environment.CLOUD,
+ mode="interactive",
+ extra_state={"await_user_message": True, "prewarmed": True},
+ )
+ labels = {"origin_product": "user_created"}
+ before = _sample_value("posthog_tasks_prewarmed_activated_total", labels)
+
+ with patch.object(facade, "signal_task_run_user_message", return_value=True):
+ facade._activate_warm_run(run, self.task, self.team.id, message="go", artifact_ids=[])
+
+ assert _sample_value("posthog_tasks_prewarmed_activated_total", labels) == before + 1
+
+ def test_activating_run_without_prewarmed_marker_does_not_increment(self) -> None:
+ # Warm Runs provisioned before this ships have await_user_message but no prewarmed marker;
+ # activating them must not inflate the numerator (would push hit rate above 1).
+ from products.tasks.backend.facade import api as facade
+
+ run = self.task.create_run(
+ environment=TaskRun.Environment.CLOUD,
+ mode="interactive",
+ extra_state={"await_user_message": True},
+ )
+ labels = {"origin_product": "user_created"}
+ before = _sample_value("posthog_tasks_prewarmed_activated_total", labels)
+
+ with patch.object(facade, "signal_task_run_user_message", return_value=True):
+ facade._activate_warm_run(run, self.task, self.team.id, message="go", artifact_ids=[])
+
+ assert _sample_value("posthog_tasks_prewarmed_activated_total", labels) == before
+
@parameterized.expand(
[
("started", "team", None, [("attempted", "requested"), ("started", "accepted")], True),
@@ -101,6 +156,7 @@ class TestTaskRunMetrics(TestCase):
"mode": "background",
"run_source": "unknown",
"runtime_adapter": "unknown",
+ "prewarmed": "false",
}
labels_by_outcome = [
{**base_labels, "outcome": outcome, "reason": reason} for outcome, reason in expected_outcomes