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(signals): report scout runs whose worker died after the agent went idle (#113601)

posthog[bot]5ef6af37346f
diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.py
index c162e093fb2d..6f28e651e300 100644
--- a/products/signals/backend/scout_harness/limits.py
+++ b/products/signals/backend/scout_harness/limits.py
@@ -30,6 +30,19 @@ WORKFLOW_HARD_CEILING_S = DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S
# ticks.
STALE_RUN_CUTOFF_S = 2 * WORKFLOW_HARD_CEILING_S
+# How many of a lane's newest runs the self-heal checks for a worker death after the TaskRun left
+# `QUEUED`/`IN_PROGRESS`. The Tasks inactivity timeout closes such a TaskRun on its own, so the
+# run is no longer stuck, only unreported. Every dispatch of the lane runs the self-heal first, so
+# the orphan is one of the newest runs at the next dispatch. The bound is a run count and not an
+# age, because an age window expires before a 30-day interval, a monthly cron, or a paused lane
+# dispatches again. The count also keeps the per-dispatch scan to a short read of the
+# `(team, skill_name, -created_at)` index.
+FINISHED_ORPHAN_RECENT_RUNS = 10
+
+# Bridge-row `metadata` key the self-heal stamps when it reports a run that the Tasks inactivity
+# timeout closed. It makes the reap a one-time claim, so a later dispatch does not report it again.
+SCOUT_RUN_REAPED_METADATA_KEY = "reaped_at"
+
# Cap on the one-off steering note an on-demand ("Run now") dispatch carries. It renders verbatim
# into that run's prompt, so it is held to the 1,000 characters `report_steering` cuts a durable
# note to: steering meant for one run must not crowd out the run's own instructions.
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 0ebfe0f946df..007173352138 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -12,7 +12,8 @@ from typing import Any
from uuid import UUID
from django.db import transaction
-from django.db.models import F
+from django.db.models import F, Func, JSONField, Q, Value
+from django.db.models.functions import Coalesce
from django.utils import timezone
import posthoganalytics
@@ -40,6 +41,8 @@ from products.signals.backend.scout_harness.limits import (
DEFAULT_MAX_RUNTIME_S,
FAILURE_STREAK_MAX_RUNS,
FAILURE_STREAK_MIN_SPAN_MINUTES,
+ FINISHED_ORPHAN_RECENT_RUNS,
+ SCOUT_RUN_REAPED_METADATA_KEY,
STALE_RUN_CUTOFF_S,
TRIGGERED_BY_SCHEDULE,
failure_streak_pause_threshold,
@@ -1175,17 +1178,34 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
slack means a run merely at the wall — about to fail or finish on its own — is never
reaped out from under itself. Best-effort and silent: a failure to reap one row must
never block the new run, so each is guarded independently.
+
+ A worker death also strands runs that no longer block the lane. Once the agent goes idle,
+ the Tasks inactivity timeout closes the TaskRun as `COMPLETED` or `FAILED`, often before
+ the next dispatch. The scout never ends its own session through that timeout, because
+ every path that survives signals completion, so that marker means the run lost its driver
+ and never emitted `signals_scout_run_finished`. Those runs are reported too, once each.
"""
- cutoff = timezone.now() - timedelta(seconds=STALE_RUN_CUTOFF_S)
+ now = timezone.now()
+ cutoff = now - timedelta(seconds=STALE_RUN_CUTOFF_S)
+ active_statuses = (tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS)
+ recent_run_ids = (
+ SignalScoutRun.objects.unscoped()
+ .filter(team_id=team_id, skill_name=skill_name)
+ .exclude(metadata__has_key=SCOUT_TRIAL_METADATA_KEY)
+ .order_by("-created_at")
+ .values("id")[:FINISHED_ORPHAN_RECENT_RUNS]
+ )
+ closed_by_inactivity = Q(
+ task_run__status__in=(tasks_facade.TaskRunStatus.COMPLETED, tasks_facade.TaskRunStatus.FAILED),
+ **{f"task_run__state__{tasks_facade.TIMED_OUT_INACTIVITY_STATE_KEY}": True},
+ id__in=recent_run_ids,
+ )
stale_runs = list(
SignalScoutRun.objects.unscoped()
- .filter(
- team_id=team_id,
- skill_name=skill_name,
- task_run__status__in=(tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS),
- task_run__created_at__lt=cutoff,
- )
+ .filter(team_id=team_id, skill_name=skill_name, task_run__created_at__lt=cutoff)
+ .filter(Q(task_run__status__in=active_statuses) | closed_by_inactivity)
.exclude(metadata__has_key=SCOUT_TRIAL_METADATA_KEY)
+ .exclude(metadata__has_key=SCOUT_RUN_REAPED_METADATA_KEY)
.select_related("task_run")
)
if not stale_runs:
@@ -1193,7 +1213,6 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
# Resolve the team once, only when there is actually something to reap, so the reaped
# event carries the same team / groups shape as the other scout lifecycle events.
team = _get_team(team_id)
- now = timezone.now()
for run in stale_runs:
try:
task_run = run.task_run
@@ -1201,17 +1220,20 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
# the conditional update below doesn't refresh it, so these stay the original values.
status_before = task_run.status
age_seconds = (now - task_run.created_at).total_seconds()
- # Compare-and-set claim on the status transition. Two triggers for the same
- # `(team, skill)` can reach this self-heal concurrently and load the same stale
- # row; the conditional UPDATE lets exactly one win — the other matches zero rows
- # once the first commits `FAILED`. Only the winner falls through to emit, so a
- # single stranded run can't double-count in the worker-death / mass-stall signal.
- claimed = tasks_facade.claim_and_fail_stale_run(
- task_run.id,
- "Scout run abandoned: no terminal status past the runtime ceiling "
- "(worker/sandbox lost before finalize).",
- error_type="stale_run_reaped",
- )
+ # Compare-and-set claim, on the status transition for a live TaskRun and on the
+ # bridge row for a closed one. Two triggers for the same `(team, skill)` can reach
+ # this self-heal concurrently and load the same stale row; the conditional UPDATE
+ # lets exactly one win — the other matches zero rows. Only the winner falls through
+ # to emit, so a single stranded run can't double-count in the worker-death signal.
+ if status_before in active_statuses:
+ claimed = tasks_facade.claim_and_fail_stale_run(
+ task_run.id,
+ "Scout run abandoned: no terminal status past the runtime ceiling "
+ "(worker/sandbox lost before finalize).",
+ error_type="stale_run_reaped",
+ )
+ else:
+ claimed = _claim_finished_orphan(run_id=run.id, team_id=team_id)
if not claimed:
continue
logger.warning(
@@ -1242,6 +1264,31 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
)
+def _claim_finished_orphan(*, run_id: Any, team_id: int) -> bool:
+ """Compare-and-set claim on a run whose TaskRun is already terminal. Returns whether this caller won.
+
+ The TaskRun status cannot carry the claim here, so the bridge row does: the conditional
+ update stamps `SCOUT_RUN_REAPED_METADATA_KEY` only while it is absent, and the loser of a
+ concurrent reap matches zero rows.
+ """
+ stamp = Value({SCOUT_RUN_REAPED_METADATA_KEY: timezone.now().isoformat()}, output_field=JSONField())
+ return bool(
+ SignalScoutRun.objects.unscoped()
+ .filter(team_id=team_id, id=run_id)
+ .exclude(metadata__has_key=SCOUT_RUN_REAPED_METADATA_KEY)
+ .update(
+ metadata=Func(
+ Coalesce(F("metadata"), Value({}, output_field=JSONField())),
+ stamp,
+ arg_joiner=" || ",
+ template="(%(expressions)s)",
+ output_field=JSONField(),
+ ),
+ updated_at=timezone.now(),
+ )
+ )
+
+
def _create_run_row(
*,
run_id: Any,
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index e55a94e3319e..6bf5cc058471 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -3080,7 +3080,21 @@ async def test_recent_in_progress_run_is_not_reaped_and_still_blocks(ateam, aerr
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_stale_run_reap_captures_run_reaped_event(ateam, aerrors_skill):
+ "status,state,age_s,expect_reaped",
+ [
+ ("in_progress", {}, STALE_RUN_CUTOFF_S + 60, True),
+ # A worker death after the agent went idle: the Tasks inactivity timeout closes the TaskRun
+ # before the next dispatch, so the run no longer blocks the lane but still never reported.
+ ("completed", {"timed_out_inactivity": True}, STALE_RUN_CUTOFF_S + 60, True),
+ ("failed", {"timed_out_inactivity": True}, STALE_RUN_CUTOFF_S + 60, True),
+ # A 30-day lane dispatches again only a month after its orphan started.
+ ("completed", {"timed_out_inactivity": True}, 31 * 24 * 60 * 60, True),
+ # A run the scout ended itself already emitted `signals_scout_run_finished`.
+ ("completed", {}, STALE_RUN_CUTOFF_S + 60, False),
+ ],
+)
+async def test_stale_run_reap_captures_run_reaped_event(ateam, aerrors_skill, status, state, age_s, expect_reaped):
TaskRun = apps.get_model("tasks", "TaskRun")
# Reaping an orphan emits `signals_scout_run_reaped` — the strand's only event (a reaped
# run never reaches the finalize path, so it emits no `signals_scout_run_finished`). This
@@ -3090,8 +3104,9 @@ async def test_stale_run_reap_captures_run_reaped_event(ateam, aerrors_skill):
)
task_run = await database_sync_to_async(_make_task_run)(ateam)
await database_sync_to_async(TaskRun.objects.filter(id=task_run.id).update)(
- status=TaskRun.Status.IN_PROGRESS,
- created_at=datetime.now(UTC) - timedelta(seconds=STALE_RUN_CUTOFF_S + 60),
+ status=status,
+ state=state,
+ created_at=datetime.now(UTC) - timedelta(seconds=age_s),
)
await database_sync_to_async(SignalScoutRun.objects.create)(
task_run=task_run,
@@ -3109,13 +3124,19 @@ async def test_stale_run_reap_captures_run_reaped_event(ateam, aerrors_skill):
patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,
):
await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
+ # A second dispatch must not report the same run again.
+ await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
- reaped = next(c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_run_reaped")
+ reaped_calls = [c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_run_reaped"]
+ assert len(reaped_calls) == (1 if expect_reaped else 0)
+ if not expect_reaped:
+ return
+ reaped = reaped_calls[0]
assert reaped.kwargs["distinct_id"] == str(ateam.uuid)
props = reaped.kwargs["properties"]
assert props["skill_name"] == "signals-scout-errors"
assert props["task_run_id"] == str(task_run.id)
- assert props["status_before"] == TaskRun.Status.IN_PROGRESS
+ assert props["status_before"] == status
assert props["stale_cutoff_seconds"] == STALE_RUN_CUTOFF_S
# Age is measured from the orphan's TaskRun.created_at, so it clears the cutoff.
assert props["age_seconds"] >= STALE_RUN_CUTOFF_S
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index b894cd583911..45678cffca08 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -55,6 +55,9 @@ TASK_ANALYSIS_ACTIVITIES_STATE_KEY = "task_analysis_activities"
# Consumers read the stamp, so the decision stays stable for the run's whole lifetime.
AGENT_OTEL_TELEMETRY_STATE_KEY = "agent_otel_telemetry_enabled"
PR_LOOP_ENABLED_STATE_KEY = "pr_loop_enabled"
+# TaskRun.state marker for runs completed by the inactivity timeout; kept out of
+# error_message so a normal completion never reads as a failure.
+TIMED_OUT_INACTIVITY_STATE_KEY = "timed_out_inactivity"
# The skills-store stubs the sandbox agent writes into its skill roots at session start.
STORE_SKILLS_STATE_KEY = "store_skills"
AGENT_INSTRUCTIONS_STATE_KEY = "agent_instructions"
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 2522e336ae67..a170dac6c026 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -90,6 +90,7 @@ from products.tasks.backend.constants import (
TASK_ANALYSIS_ACTIVITIES_STATE_KEY,
TASK_ANALYSIS_FEATURE_FLAG,
TASK_SESSION_MAX_SIZE_BYTES,
+ TIMED_OUT_INACTIVITY_STATE_KEY as TIMED_OUT_INACTIVITY_STATE_KEY, # re-exported for the scout reaper
get_required_model_flag,
is_blocked_sandbox_env_key,
is_same_run_resume_state,
@@ -267,6 +268,7 @@ __all__ = [
"create_task_run_stream_read_token",
"resolve_stream_base_url",
"claim_and_fail_stale_run",
+ "TIMED_OUT_INACTIVITY_STATE_KEY",
"delete_sandbox_custom_image",
"delete_sandbox_environment",
"ensure_personal_channel_id",
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 d529228fc83e..c47a741ddb8f 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
@@ -10,6 +10,7 @@ from temporalio.exceptions import ApplicationError
from posthog.temporal.common.utils import asyncify
+from products.tasks.backend.constants import TIMED_OUT_INACTIVITY_STATE_KEY
from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.logic.services.gateway_usage import refresh_task_run_cost
from products.tasks.backend.logic.services.workflow_step_resume import resume_workflow_step_for_run
@@ -18,9 +19,6 @@ from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.metrics import record_run_token_usage
from products.tasks.backend.temporal.observability import log_with_activity_context
-# TaskRun.state marker for runs completed by the inactivity timeout; kept out of
-# error_message so a normal completion never reads as a failure.
-TIMED_OUT_INACTIVITY_STATE_KEY = "timed_out_inactivity"
# TaskRun.state marker for runs stopped by the hard wall-clock cap. Written without an
# error_message: the marker is the machine-readable reason, and a fabricated prose
# message would just get parroted back to users by every error surface.