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): emit per-run token usage on terminal analytics and metrics (#69184)

Alessandro Pogliaghi5ef3da5192c4
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.py
index a34e4ebc31c3..52afa3e53e20 100644
--- a/posthog/temporal/common/worker.py
+++ b/posthog/temporal/common/worker.py
@@ -72,7 +72,12 @@ from products.logs.backend.facade.temporal import (
LOGS_ALERTING_LATENCY_HISTOGRAM_METRICS,
LogsAlertingMetricsInterceptor,
)
-from products.tasks.backend.facade.temporal import TASKS_LATENCY_HISTOGRAM_BUCKETS, TASKS_LATENCY_HISTOGRAM_METRICS
+from products.tasks.backend.facade.temporal import (
+ TASKS_LATENCY_HISTOGRAM_BUCKETS,
+ TASKS_LATENCY_HISTOGRAM_METRICS,
+ TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS,
+ TASKS_RUN_TOKENS_HISTOGRAM_METRICS,
+)
logger = get_write_only_logger()
@@ -282,6 +287,7 @@ async def create_worker(
)
)
| dict(zip(TASKS_LATENCY_HISTOGRAM_METRICS, itertools.repeat(TASKS_LATENCY_HISTOGRAM_BUCKETS)))
+ | dict(zip(TASKS_RUN_TOKENS_HISTOGRAM_METRICS, itertools.repeat(TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS)))
| dict(
zip(
EVAL_REPORTS_LATENCY_HISTOGRAM_METRICS,
diff --git a/products/tasks/backend/facade/temporal.py b/products/tasks/backend/facade/temporal.py
index 3d56d649977c..2b94009b8f0b 100644
--- a/products/tasks/backend/facade/temporal.py
+++ b/products/tasks/backend/facade/temporal.py
@@ -17,7 +17,12 @@ from products.tasks.backend.temporal.client import (
signal_task_followup_message,
)
from products.tasks.backend.temporal.code_workstreams.schedule import create_evaluate_code_workstreams_schedule
-from products.tasks.backend.temporal.metrics import TASKS_LATENCY_HISTOGRAM_BUCKETS, TASKS_LATENCY_HISTOGRAM_METRICS
+from products.tasks.backend.temporal.metrics import (
+ TASKS_LATENCY_HISTOGRAM_BUCKETS,
+ TASKS_LATENCY_HISTOGRAM_METRICS,
+ TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS,
+ TASKS_RUN_TOKENS_HISTOGRAM_METRICS,
+)
from products.tasks.backend.temporal.process_task.activities.post_slack_update import (
PostSlackUpdateInput,
post_slack_update,
@@ -28,6 +33,8 @@ __all__ = [
"ACTIVITIES",
"TASKS_LATENCY_HISTOGRAM_BUCKETS",
"TASKS_LATENCY_HISTOGRAM_METRICS",
+ "TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS",
+ "TASKS_RUN_TOKENS_HISTOGRAM_METRICS",
"WORKFLOWS",
"PostSlackUpdateInput",
"ProcessTaskWorkflow",
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 9c183ef485a5..b5834c43dc4f 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -1304,6 +1304,40 @@ class TaskRun(models.Model):
error=str(e),
)
+ def effective_rtk(self) -> bool | None:
+ """rtk posture for analytics: the launch-persisted effective value, falling
+ back to the user's explicit override for runs that never launched."""
+ state = self.state if isinstance(self.state, dict) else {}
+ rtk = state.get("rtk_effective", state.get("rtk_enabled"))
+ return rtk if isinstance(rtk, bool) else None
+
+ def _analytics_usage_properties(self) -> dict:
+ """Token usage and rtk posture for analytics events.
+
+ The agent-server merges cumulative usage into ``state.token_usage`` as turns
+ settle.
+ """
+ props: dict = {}
+ state = self.state if isinstance(self.state, dict) else {}
+ usage = state.get("token_usage")
+ if isinstance(usage, dict):
+ for key in (
+ "input_tokens",
+ "output_tokens",
+ "cache_read_tokens",
+ "cache_write_tokens",
+ "thought_tokens",
+ "total_tokens",
+ "turns",
+ ):
+ value = usage.get(key)
+ if isinstance(value, int | float) and not isinstance(value, bool):
+ props["usage_turns" if key == "turns" else key] = value
+ rtk = self.effective_rtk()
+ if rtk is not None:
+ props["rtk_enabled"] = rtk
+ return props
+
def capture_event(self, event: str, properties: dict | None = None, event_uuid: str | None = None) -> None:
try:
distinct_id = (
@@ -1320,7 +1354,12 @@ class TaskRun(models.Model):
"title": self.task.title,
"signal_report_id": str(self.task.signal_report_id) if self.task.signal_report_id else None,
"environment": self.environment,
+ # The bare `environment` property gets clobbered by the analytics
+ # client's deployment-region super-property, so ship the run's
+ # local/cloud value under an unclobbered name too.
+ "run_environment": self.environment,
"mode": self.mode,
+ **self._analytics_usage_properties(),
}
if properties:
all_properties.update(properties)
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index f7be42bfcf30..cdf40cc1c775 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -1,6 +1,7 @@
import time
import datetime as dt
from collections.abc import Mapping
+from typing import Any
from temporalio import activity
from temporalio.common import MetricMeter
@@ -28,6 +29,30 @@ TASKS_LATENCY_HISTOGRAM_BUCKETS = [
3_600_000.0,
]
+TASKS_RUN_TOKENS_HISTOGRAM_METRICS = ("tasks_run_total_tokens",)
+TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS = [
+ 10_000.0,
+ 50_000.0,
+ 100_000.0,
+ 250_000.0,
+ 500_000.0,
+ 1_000_000.0,
+ 2_500_000.0,
+ 5_000_000.0,
+ 10_000_000.0,
+ 25_000_000.0,
+ 50_000_000.0,
+ 100_000_000.0,
+]
+
+_RUN_TOKEN_KINDS = {
+ "input": "input_tokens",
+ "output": "output_tokens",
+ "cache_read": "cache_read_tokens",
+ "cache_write": "cache_write_tokens",
+ "thought": "thought_tokens",
+}
+
def _metric_meter(additional_attributes: Mapping[str, str | int | float | bool] | None = None) -> MetricMeter:
if not activity.in_activity():
@@ -108,6 +133,40 @@ def record_snapshot_create_latency_ms(snapshot_kind: str, outcome: str, latency_
pass
+def record_run_token_usage(
+ usage: Mapping[str, Any],
+ *,
+ origin_product: str | None,
+ run_environment: str | None,
+ rtk_enabled: bool | None,
+) -> None:
+ """Record a terminal run's token expenditure (from ``TaskRun.state.token_usage``).
+
+ Best-effort: a metric failure must never affect the status transition.
+ """
+ try:
+ base_attributes: Attributes = {
+ "origin_product": origin_product or "unknown",
+ "run_environment": run_environment or "unknown",
+ "rtk_enabled": _bool_label(rtk_enabled),
+ }
+ for kind, key in _RUN_TOKEN_KINDS.items():
+ value = usage.get(key)
+ if isinstance(value, int | float) and not isinstance(value, bool) and value > 0:
+ _metric_meter({**base_attributes, "kind": kind}).create_counter(
+ "tasks_run_tokens_total",
+ "Token expenditure of terminal task runs, by token kind",
+ ).add(int(value))
+ total = usage.get("total_tokens")
+ if isinstance(total, int | float) and not isinstance(total, bool) and total > 0:
+ _metric_meter(base_attributes).create_histogram(
+ "tasks_run_total_tokens",
+ "Total tokens spent per terminal task run",
+ ).record(int(total))
+ except Exception:
+ pass
+
+
def increment_credential_refresh(kind: str, outcome: str) -> None:
"""Record a sandbox credential refresh outcome.
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 306094ebe82b..b34bcd845511 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
@@ -306,6 +306,14 @@ def _invoke_start_agent_server(
# 30m window skip the redundant refresh.
if params.mcp_configs:
mark_mcp_token_issued(ctx.run_id)
+
+ # Persist the effective rtk posture the agent launched with, so terminal
+ # analytics can cohort runs by it (the state override alone misses the
+ # kill-switch flag). Best-effort: never fail the launch over it.
+ try:
+ TaskRun.update_state_atomic(ctx.run_id, updates={"rtk_effective": ctx.rtk_enabled})
+ except Exception:
+ logger.warning("persist_rtk_effective_failed", run_id=ctx.run_id, exc_info=True)
except Exception as e:
if params.agentsh_domains is not None:
_emit_agentsh_log_tail(ctx, sandbox)
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
index 6062277332b5..1cfdbf68a1ad 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
@@ -9,6 +9,8 @@ from products.tasks.backend.temporal.process_task.activities.update_task_run_sta
update_task_run_status,
)
+TOKEN_USAGE = {"input_tokens": 1200, "output_tokens": 300, "total_tokens": 1500, "turns": 3}
+
@pytest.mark.requires_secrets
class TestUpdateTaskRunStatusActivity:
@@ -55,6 +57,54 @@ class TestUpdateTaskRunStatusActivity:
mock_publish_stream_state_event.assert_called_once()
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize(
+ "status,expected_event",
+ [
+ (TaskRun.Status.COMPLETED, "task_run_completed"),
+ (TaskRun.Status.FAILED, "task_run_failed"),
+ ],
+ )
+ @patch("products.tasks.backend.temporal.process_task.activities.update_task_run_status.record_run_token_usage")
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_terminal_transition_captures_analytics_with_usage(
+ self, mock_capture, mock_record, activity_environment, test_task_run, status, expected_event
+ ):
+ test_task_run.state = {
+ **(test_task_run.state or {}),
+ "token_usage": dict(TOKEN_USAGE),
+ "rtk_effective": True,
+ }
+ test_task_run.save(update_fields=["state"])
+
+ input_data = UpdateTaskRunStatusInput(
+ run_id=str(test_task_run.id),
+ status=status,
+ error_message="boom" if status == TaskRun.Status.FAILED else None,
+ )
+ async_to_sync(activity_environment.run)(update_task_run_status, input_data)
+
+ captured = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == expected_event]
+ assert len(captured) == 1
+ props = captured[0].kwargs["properties"]
+ assert props["input_tokens"] == 1200
+ assert props["total_tokens"] == 1500
+ assert props["usage_turns"] == 3
+ assert props["rtk_enabled"] is True
+ assert props["run_environment"] == test_task_run.environment
+ mock_record.assert_called_once()
+ assert mock_record.call_args.kwargs["rtk_enabled"] is True
+
+ @pytest.mark.django_db(transaction=True)
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_repeated_terminal_update_does_not_double_capture(self, mock_capture, activity_environment, test_task_run):
+ input_data = UpdateTaskRunStatusInput(run_id=str(test_task_run.id), status=TaskRun.Status.COMPLETED)
+ async_to_sync(activity_environment.run)(update_task_run_status, input_data)
+ async_to_sync(activity_environment.run)(update_task_run_status, input_data)
+
+ completed = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "task_run_completed"]
+ assert len(completed) == 1
+
@pytest.mark.django_db(transaction=True)
def test_handles_non_existent_task_run(self, activity_environment):
non_existent_run_id = "550e8400-e29b-41d4-a716-446655440000"
diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
index dc221fa3dfa7..965c057e0727 100644
--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
@@ -8,6 +8,7 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.models import TaskRun
+from products.tasks.backend.temporal.metrics import record_run_token_usage
from products.tasks.backend.temporal.observability import log_with_activity_context
@@ -29,11 +30,14 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:
)
try:
- task_run = TaskRun.objects.get(id=input.run_id)
+ # Terminal transitions capture analytics that traverse task, team, and
+ # task.created_by; join them upfront instead of three lazy queries.
+ task_run = TaskRun.objects.select_related("task", "team", "task__created_by").get(id=input.run_id)
except TaskRun.DoesNotExist:
activity.logger.warning(f"TaskRun {input.run_id} not found for status update")
return
+ old_status = task_run.status
task_run.status = input.status
if input.error_message:
@@ -45,8 +49,44 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:
task_run.save(update_fields=["status", "error_message", "completed_at", "updated_at"])
task_run.publish_stream_state_event()
+ if input.status in [TaskRun.Status.COMPLETED, TaskRun.Status.FAILED] and old_status != input.status:
+ _capture_terminal_analytics(task_run, input)
+
log_with_activity_context(
"Task run status updated",
run_id=input.run_id,
status=input.status,
)
+
+
+def _capture_terminal_analytics(task_run: TaskRun, input: UpdateTaskRunStatusInput) -> None:
+ """Emit the terminal analytics event and token-expenditure metrics.
+
+ The workflow is the terminal authority for cloud runs, but this activity used to
+ flip the status without emitting the terminal analytics events, so
+ ``task_run_completed`` effectively never fired for cloud runs. Guarded on the
+ actual transition so activity retries and repeat updates don't double-count.
+ """
+ try:
+ if input.status == TaskRun.Status.COMPLETED:
+ task_run.capture_event("task_run_completed", {"duration_seconds": task_run._duration_seconds()})
+ else:
+ task_run.capture_event(
+ "task_run_failed",
+ {
+ "error_message": (input.error_message or task_run.error_message or "")[:500],
+ "duration_seconds": task_run._duration_seconds(),
+ },
+ )
+
+ state = task_run.state if isinstance(task_run.state, dict) else {}
+ usage = state.get("token_usage")
+ if isinstance(usage, dict):
+ record_run_token_usage(
+ usage,
+ origin_product=task_run.task.origin_product,
+ run_environment=task_run.environment,
+ rtk_enabled=task_run.effective_rtk(),
+ )
+ except Exception:
+ activity.logger.warning(f"Failed to capture terminal analytics for run {task_run.id}", exc_info=True)