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.

fix(tasks): emit one task_run_failed with error type and message tail (#70079)

Fernando Gomes608b30482bac
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index bda275611bc8..eb71fbdd9c95 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -221,7 +221,7 @@ def kill_stale_queued_task_runs() -> None:
)
swept, errors = _sweep_each(
stale_ids,
- lambda run_id: tasks_facade.fail_task_run(run_id, REASON),
+ lambda run_id: tasks_facade.fail_task_run(run_id, REASON, error_type="stale_queued_cleanup"),
STALE_QUEUED_TASK_RUN_SWEPT_COUNTER,
STALE_QUEUED_TASK_RUN_ERRORS_COUNTER,
)
@@ -241,7 +241,7 @@ def kill_stale_queued_task_runs() -> None:
prewarmed_ids = tasks_facade.get_stale_prewarmed_queued_task_run_ids(PREWARMED_STALE_AFTER, BATCH_SIZE)
prewarmed_swept, prewarmed_errors = _sweep_each(
prewarmed_ids,
- lambda run_id: tasks_facade.fail_task_run(run_id, PREWARMED_REASON),
+ lambda run_id: tasks_facade.fail_task_run(run_id, PREWARMED_REASON, error_type="stale_queued_cleanup"),
PREWARMED_QUEUED_TASK_RUN_SWEPT_COUNTER,
PREWARMED_QUEUED_TASK_RUN_ERRORS_COUNTER,
)
diff --git a/posthog/tasks/test/test_kill_stale_queued_task_runs.py b/posthog/tasks/test/test_kill_stale_queued_task_runs.py
index 2e72f29a0876..4b5d76613f27 100644
--- a/posthog/tasks/test/test_kill_stale_queued_task_runs.py
+++ b/posthog/tasks/test/test_kill_stale_queued_task_runs.py
@@ -62,12 +62,16 @@ class TestKillStaleQueuedTaskRuns(TestCase):
TaskRun = apps.get_model("tasks", "TaskRun")
run = self._make_run(TaskRun.Status.QUEUED, datetime.timedelta(hours=25))
- kill_stale_queued_task_runs()
+ with patch("products.tasks.backend.models.posthoganalytics.capture") as mock_capture:
+ kill_stale_queued_task_runs()
run.refresh_from_db()
self.assertEqual(run.status, TaskRun.Status.FAILED)
self.assertIn("stuck in QUEUED", run.error_message or "")
self.assertIsNotNone(run.completed_at)
+ 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"], "stale_queued_cleanup")
def test_leaves_recently_queued_run_alone(self) -> None:
TaskRun = apps.get_model("tasks", "TaskRun")
@@ -216,11 +220,11 @@ class TestKillStaleQueuedTaskRuns(TestCase):
original_mark_failed = TaskRun.mark_failed
call_count = {"n": 0}
- def flaky_mark_failed(self: Any, error: str) -> None:
+ def flaky_mark_failed(self: Any, error: str, error_type: str | None = None) -> None:
call_count["n"] += 1
if call_count["n"] == 1:
raise RuntimeError("synthetic failure")
- return original_mark_failed(self, error)
+ return original_mark_failed(self, error, error_type=error_type)
with (
patch.object(TaskRun, "mark_failed", flaky_mark_failed),
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 5ed9e732c599..70073ad8965b 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -584,6 +584,7 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
task_run.id,
"Scout run abandoned: no terminal status past the runtime ceiling "
"(worker/sandbox lost before finalize).",
+ error_type="stale_run_reaped",
)
if not claimed:
continue
diff --git a/products/tasks/backend/error_telemetry.py b/products/tasks/backend/error_telemetry.py
new file mode 100644
index 000000000000..d3c0dcf01209
--- /dev/null
+++ b/products/tasks/backend/error_telemetry.py
@@ -0,0 +1,14 @@
+"""Shared shaping of error details for task run failure telemetry."""
+
+ERROR_MESSAGE_TELEMETRY_LIMIT = 500
+
+
+def truncate_error_message(message: str | None, limit: int = ERROR_MESSAGE_TELEMETRY_LIMIT) -> str:
+ """Truncate an error message keeping its tail.
+
+ Agent and wizard failures bury the root cause at the end of their output
+ (boilerplate preamble first, actual error last), so head truncation hides it.
+ """
+ if not message:
+ return ""
+ return message if len(message) <= limit else message[-limit:]
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index e5e1c34c9f04..24272b54a5da 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -41,6 +41,7 @@ from products.tasks.backend.constants import (
RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS,
is_blocked_sandbox_env_key,
)
+from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.logic.code_workstreams.default_workflow import build_default_bindings
from products.tasks.backend.logic.code_workstreams.validation import validate_bindings
from products.tasks.backend.logic.services.image_builder import (
@@ -880,7 +881,7 @@ def update_task_run_state(
return TaskRun.update_state_atomic(run_id, updates=updates, remove_keys=remove_keys)
-def fail_task_run(run_id: str | UUID, error: str) -> bool:
+def fail_task_run(run_id: str | UUID, error: str, error_type: str | None = None) -> bool:
"""Mark a QUEUED run as failed. Returns whether a run was acted on.
Refetches filtered on ``status=QUEUED`` so a run that left the queue between the
@@ -891,7 +892,7 @@ def fail_task_run(run_id: str | UUID, error: str) -> bool:
).first() # nosemgrep: celery-task-team-scope-audit
if run is None:
return False
- run.mark_failed(error)
+ run.mark_failed(error, error_type=error_type)
return True
@@ -923,7 +924,7 @@ def complete_idle_local_task_run(run_id: str | UUID) -> bool:
return True
-def claim_and_fail_stale_run(run_id: str | UUID, error: str) -> bool:
+def claim_and_fail_stale_run(run_id: str | UUID, error: str, error_type: str | None = None) -> bool:
"""Compare-and-set reap of a stranded run. Returns whether this caller won the claim.
Atomically flips a run still in ``QUEUED``/``IN_PROGRESS`` to ``FAILED`` via a conditional
@@ -939,7 +940,7 @@ def claim_and_fail_stale_run(run_id: str | UUID, error: str) -> bool:
return False
run = TaskRun.objects.filter(pk=run_id).first() # nosemgrep: celery-task-team-scope-audit
if run is not None:
- run.mark_failed(error)
+ run.mark_failed(error, error_type=error_type)
return True
@@ -1827,6 +1828,17 @@ def update_task_run(
if new_status in _TERMINAL_TASK_RUN_STATUSES and old_status != new_status:
if new_status == TaskRun.Status.FAILED:
observe_agent_turn_failed(run)
+ # This PATCH performed the DB transition, so it owns the task_run_failed
+ # capture. The workflow's status-update activity sees the row already
+ # FAILED and skips its own capture, keeping the event single-emitted.
+ run.capture_event(
+ "task_run_failed",
+ {
+ "error_message": truncate_error_message(run.error_message),
+ "error_type": "agent_reported",
+ "duration_seconds": run._duration_seconds(),
+ },
+ )
observe_wizard_run_unbound(run)
signal_workflow_completion(run.id, new_status, validated_data.get("error_message"))
if new_status == TaskRun.Status.CANCELLED:
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 7418aeed9ac6..dc5363a14587 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -41,6 +41,7 @@ from posthog.storage import object_storage
from posthog.temporal.oauth import PosthogMcpScopes
from products.tasks.backend.constants import DEFAULT_TRUSTED_DOMAINS
+from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_event
from products.tasks.backend.metrics import observe_task_run_created, observe_task_run_dispatch_callback
from products.tasks.backend.redis import evaluate_dedicated_stream_flag, run_uses_dedicated_stream
@@ -1450,7 +1451,7 @@ class TaskRun(models.Model):
error=str(e),
)
- def mark_failed(self, error: str):
+ def mark_failed(self, error: str, error_type: str | None = None) -> None:
"""Mark the progress as failed with an error message."""
self.status = self.Status.FAILED
self.error_message = error
@@ -1460,7 +1461,8 @@ class TaskRun(models.Model):
self.capture_event(
"task_run_failed",
{
- "error_message": error[:500],
+ "error_message": truncate_error_message(error),
+ "error_type": error_type or "unspecified",
"duration_seconds": self._duration_seconds(),
},
)
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index c961ee2a2eac..7a3a93220848 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -16,6 +16,7 @@ from posthog.temporal.common.client import async_connect, sync_connect
from posthog.temporal.oauth import PosthogMcpScopes
from products.tasks.backend.constants import SANDBOX_EVENT_INGEST_FEATURE_FLAG
+from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.metrics import observe_task_run_workflow_start
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.build_image.workflow import BuildSandboxImageInput
@@ -65,7 +66,8 @@ def _terminalize_unstarted_task_run(run_id: str, error_message: str) -> bool:
task_run.capture_event(
"task_run_failed",
{
- "error_message": error_message[:500],
+ "error_message": truncate_error_message(error_message),
+ "error_type": "workflow_start_failed",
"duration_seconds": task_run._duration_seconds(),
},
)
diff --git a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py
index c74295fcd5fb..b6391d910295 100644
--- a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py
@@ -427,6 +427,7 @@ class TestHandleFollowup:
assert workflow._task_completed is True
assert workflow._completion_status == "failed"
assert workflow._completion_error == "Follow-up delivery failed: sandbox is dead"
+ assert workflow._completion_error_type == "followup_delivery_failed"
ack = workflow._pending_outbound[-1]
assert ack.target_signal == PARENT_ACK_SIGNAL
assert ack.args[0] == "send_followup_message"
@@ -459,6 +460,7 @@ class TestHandleFollowup:
assert workflow._task_completed is True
assert workflow._completion_status == "failed"
assert workflow._completion_error == "Follow-up delivery failed: send_followup failed: sandbox unreachable"
+ assert workflow._completion_error_type == "followup_delivery_failed"
ack = workflow._pending_outbound[-1]
assert ack.args[3] == "send_followup failed: sandbox unreachable"
@@ -688,6 +690,7 @@ class TestRun:
"failed",
error_message="database connection closed",
run_id="run-id",
+ error_type="RuntimeError",
)
# A terminal completion signal is enqueued even on failure paths so
# the orchestrator never waits indefinitely on a silent child.
@@ -934,7 +937,7 @@ class TestRunStatusTransitions:
update_status_mock.assert_not_awaited()
else:
status, message = expected_call
- update_status_mock.assert_awaited_once_with(status, error_message=message)
+ update_status_mock.assert_awaited_once_with(status, error_message=message, error_type=None)
class TestCompletionStatusOnExceptionPaths:
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index 4ab6cb3ba4fc..0e2ebaff7907 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -23,6 +23,7 @@ from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.oauth import PosthogMcpScopes
+from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.logic.services.sandbox import is_public_sandbox_repo
from products.tasks.backend.temporal.constants import (
OUTBOUND_RETRY_BACKOFF,
@@ -244,6 +245,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
self._task_completed: bool = False
self._completion_status: str = "completed"
self._completion_error: Optional[str] = None
+ self._completion_error_type: Optional[str] = None
self._sandbox_gone: bool = False
self._heartbeat_received: bool = False
@@ -485,15 +487,17 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
# setting it here the orchestrator would see `success=True` for
# a run that died on an unhandled exception.
self._completion_status = "failed"
- self._completion_error = str(e)[:500]
+ self._completion_error = truncate_error_message(str(e))
current_sandbox_id = sandbox_id or self._sandbox_id_for_cleanup
- error_message = str(e)[:500]
+ error_message = truncate_error_message(str(e))
if self._context:
if self._current_progress_step is not None:
failed_step, failed_label, failed_group = self._current_progress_step
await self._emit_progress(
failed_step, "failed", failed_label, failed_group, detail=error_message[:200]
)
+ # Metrics and logs only: the status-update activity below owns the
+ # task_run_failed analytics capture, keyed on the DB transition.
await self._track_workflow_event(
"task_run_failed",
{
@@ -513,8 +517,11 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
"sandbox_id": current_sandbox_id,
**self._activity_error_properties(e),
},
+ capture_analytics=False,
)
- await self._update_task_run_status("failed", error_message=error_message, run_id=run_id)
+ await self._update_task_run_status(
+ "failed", error_message=error_message, run_id=run_id, error_type=type(e).__name__
+ )
return ExecuteSandboxOutput(
success=False,
@@ -603,6 +610,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
return
self._completion_status = status
self._completion_error = error_message
+ # Completion signals originate from the agent reporting its own terminal
+ # state (via the run PATCH endpoint, relayed by the orchestrator).
+ self._completion_error_type = "agent_reported" if status == "failed" else None
self._task_completed = True
self._enqueue_ack(signal_name=COMPLETE_TASK_SIGNAL, ack_id=ack_id)
@@ -714,6 +724,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
)
self._completion_status = "failed"
self._completion_error = f"Follow-up delivery failed: {cause_message or e}"
+ self._completion_error_type = "followup_delivery_failed"
self._task_completed = True
self._enqueue_ack(
signal_name=SEND_FOLLOWUP_SIGNAL,
@@ -1012,7 +1023,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))
return self.context.mode != "interactive" and not is_resume
- async def _track_workflow_event(self, event_name: str, properties: dict) -> None:
+ async def _track_workflow_event(self, event_name: str, properties: dict, capture_analytics: bool = True) -> None:
await workflow.execute_activity(
track_workflow_event,
TrackWorkflowEventInput(
@@ -1023,6 +1034,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
"organization": self.context.organization_id,
"project": self.context.team_uuid,
},
+ capture_analytics=capture_analytics,
),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=1),
@@ -1062,6 +1074,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
status: str,
error_message: Optional[str] = None,
run_id: Optional[str] = None,
+ error_type: Optional[str] = None,
) -> None:
await workflow.execute_activity(
update_task_run_status,
@@ -1069,6 +1082,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
run_id=run_id if run_id is not None else self.context.run_id,
status=status,
error_message=error_message,
+ error_type=error_type,
),
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -1081,7 +1095,11 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
# propagated through complete_task transitions out of in_progress;
# the except blocks in run() cover the other terminal paths.
if self._task_completed and self._completion_status in {"failed", "cancelled"}:
- await self._update_task_run_status(self._completion_status, error_message=self._completion_error)
+ await self._update_task_run_status(
+ self._completion_status,
+ error_message=self._completion_error,
+ error_type=self._completion_error_type,
+ )
async def _run_credential_refresh_until_sandbox_gone(self, sandbox_id: str) -> None:
exit_reason = await run_credential_refresh_loop(self.context, sandbox_id)
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 98fb72894b88..84ef4494e2a5 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
@@ -115,6 +115,34 @@ class TestUpdateTaskRunStatusActivity:
assert mock_record.call_args.kwargs["rtk_enabled"] is True
assert mock_record.call_args.kwargs["status"] == status
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize(
+ "error_type,expected_error_type",
+ [
+ ("ActivityError", "ActivityError"),
+ (None, "unspecified"),
+ ],
+ )
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_failed_transition_carries_error_type_and_message_tail(
+ self, mock_capture, activity_environment, test_task_run, error_type, expected_error_type
+ ):
+ error_message = "x" * 1400 + "TypeError: cannot read boot manifest"
+ input_data = UpdateTaskRunStatusInput(
+ run_id=str(test_task_run.id),
+ status=TaskRun.Status.FAILED,
+ error_message=error_message,
+ error_type=error_type,
+ )
+ 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") == "task_run_failed"]
+ assert len(captured) == 1
+ props = captured[0].kwargs["properties"]
+ assert props["error_type"] == expected_error_type
+ assert len(props["error_message"]) == 500
+ assert props["error_message"].endswith("TypeError: cannot read boot manifest")
+
@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):
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 c1058197d7bc..f8e11c508ad2 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
@@ -17,6 +17,11 @@ class TrackWorkflowEventInput:
distinct_id: str
properties: dict[str, Any]
groups: dict[str, str] | None = None
+ # When False, only record metrics and logs — the analytics capture is owned
+ # elsewhere (e.g. update_task_run_status captures task_run_failed on the DB
+ # transition). Optional with a default so payloads from in-flight workflows
+ # started before this field existed still deserialize.
+ capture_analytics: bool = True
@activity.defn
@@ -26,6 +31,9 @@ def track_workflow_event(input: TrackWorkflowEventInput) -> None:
if input.event_name == "task_run_failed":
observe_task_run_failed(input.properties)
+ if not input.capture_analytics:
+ return
+
posthoganalytics.capture(
distinct_id=input.distinct_id,
event=input.event_name,
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 d93fcd36ddee..37f61ad069e5 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
@@ -7,6 +7,7 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
+from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.metrics import observe_wizard_run_unbound
from products.tasks.backend.models import TaskRun
from products.tasks.backend.temporal.metrics import record_run_token_usage
@@ -23,6 +24,9 @@ class UpdateTaskRunStatusInput:
status: str
error_message: Optional[str] = None
timed_out_inactivity: bool = False
+ # Optional with a default so payloads from in-flight workflows started
+ # before this field existed still deserialize.
+ error_type: Optional[str] = None
@activity.defn
@@ -73,10 +77,10 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:
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.
+ This activity performs the DB status transition, so it is the single canonical
+ emitter of the terminal analytics events for workflow-driven runs — the workflow
+ itself only records metrics and logs for failures. Guarded on the actual
+ transition so activity retries and repeat updates don't double-count.
"""
try:
if input.status == TaskRun.Status.COMPLETED:
@@ -85,7 +89,8 @@ def _capture_terminal_analytics(task_run: TaskRun, input: UpdateTaskRunStatusInp
task_run.capture_event(
"task_run_failed",
{
- "error_message": (input.error_message or task_run.error_message or "")[:500],
+ "error_message": truncate_error_message(input.error_message or task_run.error_message),
+ "error_type": input.error_type or "unspecified",
"duration_seconds": task_run._duration_seconds(),
},
)
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 4d3f9220f86f..8c9b9092c91a 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -663,6 +663,7 @@ class TestProcessTaskWorkflowUnit:
"failed",
error_message="database connection closed",
run_id="run-id",
+ error_type="RuntimeError",
)
track_workflow_event_mock.assert_not_awaited()
post_slack_update_mock.assert_not_awaited()
@@ -698,6 +699,7 @@ class TestProcessTaskWorkflowUnit:
"failed",
error_message="Sandbox not in running state.",
run_id="run-id",
+ error_type="ActivityError",
)
async def test_run_skips_relay_when_sandbox_event_ingest_is_enabled(self, monkeypatch):
@@ -867,6 +869,7 @@ class TestProcessTaskWorkflowUnit:
update_task_run_status_mock.assert_any_await(
"completed",
error_message=SANDBOX_GONE_ERROR_MESSAGE,
+ error_type=None,
)
cleanup_sandbox_mock.assert_awaited_once_with("sandbox-123")
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index f94a960c7627..5c19826e7a3f 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -17,6 +17,7 @@ from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.oauth import PosthogMcpScopes
from products.tasks.backend.constants import SNAPSHOT_KIND_FILESYSTEM
+from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.logic.services.sandbox import is_public_sandbox_repo
from products.tasks.backend.temporal.create_snapshot.workflow import CreateSnapshotForRepositoryInput
from products.tasks.backend.temporal.process_task.activities.get_pr_context import GetPrContextInput, get_pr_context
@@ -207,6 +208,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._task_completed: bool = False
self._completion_status: str = "completed"
self._completion_error: Optional[str] = None
+ self._completion_error_type: Optional[str] = None
self._heartbeat_received: bool = False
self._prewarmed: bool = False
self._first_user_message_received: bool = False
@@ -684,7 +686,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):
permission_response_task = None
if self._task_completed:
- await self._update_task_run_status(self._completion_status, error_message=self._completion_error)
+ await self._update_task_run_status(
+ self._completion_status,
+ error_message=self._completion_error,
+ error_type=self._completion_error_type,
+ )
elif timed_out:
await self._update_task_run_status("completed", timed_out_inactivity=True)
@@ -735,7 +741,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# the UI show the persisted message, so surface the cause instead.
cause = e.cause if isinstance(e, temporalio.exceptions.ActivityError) else None
cause_message = getattr(cause, "message", None) or (str(cause) if cause is not None else None)
- error_message = (cause_message or str(e))[:500]
+ error_message = truncate_error_message(cause_message or str(e))
if self._context:
if self._current_progress_step is not None:
failed_step, failed_label, failed_group = self._current_progress_step
@@ -746,6 +752,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
failed_group,
detail=error_message[:200],
)
+ # Metrics and logs only: the status-update activity below owns the
+ # task_run_failed analytics capture, keyed on the DB transition.
await self._track_workflow_event(
"task_run_failed",
{
@@ -761,12 +769,15 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"model": self.context.model,
"reasoning_effort": self.context.reasoning_effort,
"error_type": type(e).__name__,
- "error_message": str(e)[:500],
+ "error_message": truncate_error_message(str(e)),
"sandbox_id": current_sandbox_id,
**self._activity_error_properties(e),
},
+ capture_analytics=False,
)
- await self._update_task_run_status("failed", error_message=error_message, run_id=run_id)
+ await self._update_task_run_status(
+ "failed", error_message=error_message, run_id=run_id, error_type=type(e).__name__
+ )
if self._context:
await self._post_slack_update()
@@ -1228,7 +1239,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))
return self.context.mode != "interactive" and not is_resume
- async def _track_workflow_event(self, event_name: str, properties: dict) -> None:
+ async def _track_workflow_event(self, event_name: str, properties: dict, capture_analytics: bool = True) -> None:
track_input = TrackWorkflowEventInput(
event_name=event_name,
distinct_id=self.context.distinct_id,
@@ -1237,6 +1248,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"organization": self.context.organization_id,
"project": self.context.team_uuid,
},
+ capture_analytics=capture_analytics,
)
await workflow.execute_activity(
track_workflow_event,
@@ -1297,6 +1309,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
error_message: Optional[str] = None,
run_id: Optional[str] = None,
timed_out_inactivity: bool = False,
+ error_type: Optional[str] = None,
) -> None:
await workflow.execute_activity(
update_task_run_status,
@@ -1305,6 +1318,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
status=status,
error_message=error_message,
timed_out_inactivity=timed_out_inactivity,
+ error_type=error_type,
),
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -1507,6 +1521,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):
async def complete_task(self, status: str = "completed", error_message: Optional[str] = None) -> None:
self._completion_status = status
self._completion_error = error_message
+ # Completion signals come from the agent reporting its own terminal state
+ # through the run PATCH endpoint (which flips the row first, so the status
+ # activity usually sees no transition and skips its capture).
+ self._completion_error_type = "agent_reported" if status == "failed" else None
self._task_completed = True
# ─── Slack agent-design streaming ─── (per-turn signals from relay_sandbox_events)
@@ -1697,4 +1715,5 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# immediately instead of waiting for the inactivity timeout.
self._completion_status = "failed"
self._completion_error = f"Follow-up delivery failed: {cause_message or e}"
+ self._completion_error_type = "followup_delivery_failed"
self._task_completed = True
diff --git a/products/tasks/backend/temporal/task_management/workflow.py b/products/tasks/backend/temporal/task_management/workflow.py
index d604be997ab4..77f1fe781aab 100644
--- a/products/tasks/backend/temporal/task_management/workflow.py
+++ b/products/tasks/backend/temporal/task_management/workflow.py
@@ -12,6 +12,7 @@ from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.oauth import PosthogMcpScopes
+from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.temporal.constants import (
ACK_TIMEOUT,
CI_FOLLOW_UP_DELAY,
@@ -381,7 +382,7 @@ class TaskManagementWorkflow(PostHogWorkflow):
raise
except Exception as e:
- error_message = str(e)[:500]
+ error_message = truncate_error_message(str(e))
await self._track_workflow_event(
"task_management_failed",
{
@@ -391,7 +392,7 @@ class TaskManagementWorkflow(PostHogWorkflow):
"error_message": error_message,
},
)
- await self._update_task_run_status("failed", error_message=error_message)
+ await self._update_task_run_status("failed", error_message=error_message, error_type=type(e).__name__)
return TaskRunManagementOutput(
success=False,
error=error_message,
@@ -971,6 +972,7 @@ class TaskManagementWorkflow(PostHogWorkflow):
self,
status: str,
error_message: Optional[str] = None,
+ error_type: Optional[str] = None,
) -> None:
run_id = self._run_id
if run_id is None:
@@ -981,6 +983,7 @@ class TaskManagementWorkflow(PostHogWorkflow):
run_id=run_id,
status=status,
error_message=error_message,
+ error_type=error_type,
),
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index 03238a8f209a..0e5e2297ca69 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -781,13 +781,20 @@ class TestTaskRun(TestCase):
status=TaskRun.Status.IN_PROGRESS,
)
- error_msg = "Something went wrong"
- run.mark_failed(error_msg)
+ error_msg = "x" * 1400 + "Error: the root cause sits at the tail"
+ with patch("products.tasks.backend.models.posthoganalytics.capture") as mock_capture:
+ run.mark_failed(error_msg, error_type="stale_queued_cleanup")
run.refresh_from_db()
self.assertEqual(run.status, TaskRun.Status.FAILED)
self.assertEqual(run.error_message, error_msg)
self.assertIsNotNone(run.completed_at)
+ captured = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "task_run_failed"]
+ self.assertEqual(len(captured), 1)
+ props = captured[0].kwargs["properties"]
+ self.assertEqual(props["error_type"], "stale_queued_cleanup")
+ self.assertEqual(len(props["error_message"]), 500)
+ self.assertTrue(props["error_message"].endswith("Error: the root cause sits at the tail"))
def test_output_jsonfield(self):
run = TaskRun.objects.create(
diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.py
index 63541d8ca187..bb7e0f4b1984 100644
--- a/products/tasks/backend/tests/test_task_run_metrics.py
+++ b/products/tasks/backend/tests/test_task_run_metrics.py
@@ -190,7 +190,13 @@ class TestTaskRunMetrics(TestCase):
assert mock_sync_connect.called is expect_sync_connect_called
- def test_task_run_failed_event_increments_failure_counter(self) -> None:
+ @parameterized.expand(
+ [
+ ("captures_analytics", True),
+ ("metrics_only", False),
+ ]
+ )
+ def test_task_run_failed_event_increments_failure_counter(self, _name: str, capture_analytics: bool) -> None:
distinct_id = self.user.distinct_id
assert distinct_id is not None
@@ -208,7 +214,7 @@ class TestTaskRunMetrics(TestCase):
with patch(
"products.tasks.backend.temporal.process_task.activities.track_workflow_event.posthoganalytics.capture"
- ):
+ ) as mock_capture:
track_workflow_event(
TrackWorkflowEventInput(
event_name="task_run_failed",
@@ -224,10 +230,37 @@ class TestTaskRunMetrics(TestCase):
"temporal_activity_retry_state": "MAXIMUM_ATTEMPTS_REACHED",
"cause_error_type": "RuntimeError",
},
+ capture_analytics=capture_analytics,
)
)
assert _sample_value("posthog_tasks_task_run_failed_total", labels) == before + 1
+ assert mock_capture.called is capture_analytics
+
+ def test_patch_terminal_failure_captures_single_typed_task_run_failed(self) -> None:
+ from products.tasks.backend.facade import api as facade
+
+ run = self.task.create_run(environment=TaskRun.Environment.CLOUD)
+ long_error = "w" * 1400 + "Error: wizard exited with code 7"
+
+ with (
+ patch.object(facade, "signal_workflow_completion"),
+ patch("products.tasks.backend.models.posthoganalytics.capture") as mock_capture,
+ ):
+ for _ in range(2): # the repeat PATCH must not double-capture
+ facade.update_task_run(
+ run.id,
+ self.task.id,
+ self.team.id,
+ validated_data={"status": "failed", "error_message": long_error},
+ )
+
+ captured = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "task_run_failed"]
+ assert len(captured) == 1
+ props = captured[0].kwargs["properties"]
+ assert props["error_type"] == "agent_reported"
+ assert len(props["error_message"]) == 500
+ assert props["error_message"].endswith("Error: wizard exited with code 7")
@parameterized.expand(
[
diff --git a/products/tasks/backend/tests/test_temporal_client.py b/products/tasks/backend/tests/test_temporal_client.py
index edc38204e0bb..f6e729b15935 100644
--- a/products/tasks/backend/tests/test_temporal_client.py
+++ b/products/tasks/backend/tests/test_temporal_client.py
@@ -75,10 +75,14 @@ class TestExecuteTaskProcessingWorkflow(TestCase):
with (
patch(connect_target, connect_mock),
patch("products.tasks.backend.temporal.client.posthoganalytics.feature_enabled", return_value=False),
+ patch("products.tasks.backend.models.posthoganalytics.capture") as mock_capture,
):
self._execute_workflow(executor, run, self.user.id)
self._assert_run_failed(run, "Failed to start task workflow: temporal unavailable")
+ 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")
@parameterized.expand([("sync",), ("async",)])
def test_does_not_overwrite_run_that_already_started(self, executor: str) -> None:
diff --git a/products/tasks/docs/INSTRUMENTATION.md b/products/tasks/docs/INSTRUMENTATION.md
index 2d4702bbb68d..8f61b5ae372e 100644
--- a/products/tasks/docs/INSTRUMENTATION.md
+++ b/products/tasks/docs/INSTRUMENTATION.md
@@ -78,13 +78,15 @@ Tracked when `TaskRun.mark_completed()` is called. Additional properties:
### `task_run_failed`
-Tracked when `TaskRun.mark_failed()` is called. Additional properties:
+Captured exactly once per failed run, by whichever component performs the DB transition to `FAILED`:
+`TaskRun.mark_failed()` (janitor sweeps via the facade), the `update_task_run_status` Temporal activity (workflow failures), the facade run PATCH path (agent-reported failures), or `_terminalize_unstarted_task_run` (workflow dispatch failures).
+Additional properties:
-| Property | Type | Description |
-| ------------------ | ------- | -------------------------------------- |
-| `error_type` | `str` | Exception class name |
-| `error_message` | `str` | Error message (truncated to 500 chars) |
-| `duration_seconds` | `float` | Time from creation to failure |
+| Property | Type | Description |
+| ------------------ | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `error_type` | `str` | Stable failure source: exception class name (workflow failures), `agent_reported`, `stale_queued_cleanup`, `workflow_start_failed`, `followup_delivery_failed`, `stale_run_reaped`; `unspecified` when unknown |
+| `error_message` | `str` | Error message (truncated to the **last** 500 chars — the root cause sits at the tail) |
+| `duration_seconds` | `float` | Time from creation to failure |
## Workflow Events
@@ -127,17 +129,18 @@ Tracked when the workflow is cancelled via `CancelledError`.
| `repository` | `str` | Repository in `org/repo` format |
| `team_id` | `int` | Team ID |
-### `task_run_failed` (workflow)
+### `task_run_failed` (workflow, metrics only)
-Tracked when the workflow fails with an exception.
+Recorded when the workflow fails with an exception — **not captured as an analytics event** (the `update_task_run_status` activity owns the analytics capture on the DB transition, see above).
+The workflow emission feeds the `posthog_tasks_task_run_failed_total` Prometheus counter and structured logging with these properties:
-| Property | Type | Description |
-| --------------- | ----- | -------------------------------------- |
-| `run_id` | `str` | UUID of the run |
-| `task_id` | `str` | UUID of the task |
-| `error_type` | `str` | Exception class name |
-| `error_message` | `str` | Error message (truncated to 500 chars) |
-| `sandbox_id` | `str` | Sandbox identifier (if available) |
+| Property | Type | Description |
+| --------------- | ----- | ------------------------------------------- |
+| `run_id` | `str` | UUID of the run |
+| `task_id` | `str` | UUID of the task |
+| `error_type` | `str` | Exception class name |
+| `error_message` | `str` | Error message (truncated to last 500 chars) |
+| `sandbox_id` | `str` | Sandbox identifier (if available) |
## Webhook Events