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(llma): reap orphaned scout runs so a dead run can't wedge a lane (#65028)

Andrew Maguire428d53e76f65
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 4df1421e11a1..9fdd128952b3 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -98,8 +98,10 @@ one sandbox session → zero or more emitted signals.
live on `task_run`, not on the bridge row. Single-flight is a best-effort app-layer guard:
`_has_running_run` skips dispatch when a prior run for the same `(team, skill_name)` has
`task_run.status = IN_PROGRESS`. The old `WHERE status='running'` partial unique index was
- dropped in the bridge simplification; a `task_run.status`-based constraint plus active
- stale-run recovery (`_self_heal_stale_runs` is a no-op today) is a tracked follow-up.
+ dropped in the bridge simplification; `_self_heal_stale_runs` now reaps the orphan case at
+ the app layer (failing any `QUEUED`/`IN_PROGRESS` run older than `STALE_RUN_CUTOFF_S` before
+ the guard), so a worker crash no longer wedges a lane permanently. A `task_run.status`-based
+ DB constraint is still a possible follow-up for stronger single-flight guarantees.
- The sandbox is opened with the team's MCP token plus the harness-internal tools.
The skill body is loaded into the system prompt; each scout has its own
`SignalScoutConfig` row (keyed on `(team, skill_name)`) whose `enabled` flag and
@@ -166,9 +168,10 @@ one sandbox session → zero or more emitted signals.
every team.
- Run lifecycle lives on the linked `TaskRun` (`task_run.status`), managed by
`MultiTurnSession` — the `SignalScoutRun` bridge row carries no status of its own. A
- `TaskRun` stranded in `IN_PROGRESS` (worker SIGKILL before finalize) blocks new runs for
- that `(team, skill)` via `_has_running_run` until it transitions out; active recovery of
- such rows is a deferred follow-up (`_self_heal_stale_runs` is currently a no-op).
+ `TaskRun` stranded in `IN_PROGRESS` (worker SIGKILL before finalize) would block new runs
+ for that `(team, skill)` via `_has_running_run` — so `_self_heal_stale_runs` fails any such
+ run older than `STALE_RUN_CUTOFF_S` before the guard, letting the lane recover within a tick
+ or two instead of wedging until manual intervention.
- Emit path goes through `emit_signal()` and only `emit_signal()`. Do not write to
the embeddings pipeline or `SignalReport` directly from harness code.
- **If you add or rename a workflow/activity in `temporal/agentic/`, update
diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.py
index bda3e91c6156..548e6f5cebbb 100644
--- a/products/signals/backend/scout_harness/limits.py
+++ b/products/signals/backend/scout_harness/limits.py
@@ -20,6 +20,16 @@ ACTIVITY_SLACK_S = 60
# self-heal in `runner.py` uses this as the staleness base.
WORKFLOW_HARD_CEILING_S = DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S
+# Age past which an in-flight scout run is treated as orphaned and reaped by the
+# stale-run self-heal in `runner.py`. A run older than the activity's hard ceiling cannot
+# still be legitimately executing — Temporal kills the activity at `WORKFLOW_HARD_CEILING_S`
+# — so a `QUEUED`/`IN_PROGRESS` TaskRun past this cutoff is an orphan left behind by a
+# crashed worker/sandbox that never wrote a terminal status. Set to a generous multiple of
+# the ceiling so a run merely at the wall (about to fail or finish) is never reaped out from
+# under itself; a lane blocked by an orphan then self-clears within one or two coordinator
+# ticks.
+STALE_RUN_CUTOFF_S = 2 * WORKFLOW_HARD_CEILING_S
+
# Per-team ceiling on ENABLED scout configs — the per-team cost cap. Each enabled scout
# is a recurring LLM sandbox run, so this bounds what one team can switch on. Set high so
# teams can freely author scouts with minimal friction; it's a backstop against runaway
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 88f802f7e24a..25a27f4cded7 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -4,6 +4,7 @@ import time
import asyncio
import logging
from dataclasses import dataclass
+from datetime import timedelta
from typing import Any
from django.utils import timezone
@@ -17,7 +18,7 @@ from posthog.sync import database_sync_to_async
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
-from products.signals.backend.scout_harness.limits import DEFAULT_MAX_RUNTIME_S
+from products.signals.backend.scout_harness.limits import DEFAULT_MAX_RUNTIME_S, STALE_RUN_CUTOFF_S
from products.signals.backend.scout_harness.prompt import SignalScoutRunSummary, build_run_prompt
from products.signals.backend.scout_harness.skill_loader import LoadedSkill, load_skill_for_run
from products.signals.backend.temporal.agentic import (
@@ -106,12 +107,15 @@ async def arun_signals_scout(
)
config = await database_sync_to_async(_resolve_config, thread_sensitive=False)(team, skill.name)
- # Hook for stale-run recovery — currently a no-op (see `_self_heal_stale_runs`). The
- # partial unique index that made orphaned RUNNING rows block dispatch was dropped when
- # `SignalScoutRun` became a `TaskRun` bridge (status now lives on `task_run.status`), so
- # stale bridge rows no longer gate new runs at the DB level. Kept as a seam for the
- # `task_run.status`-based recovery follow-up.
- await database_sync_to_async(_self_heal_stale_runs, thread_sensitive=False)(team_id, skill_name)
+ # Stale-run recovery, before the skip-if-running guard below. A scout run writes its own
+ # terminal `task_run.status` from inside the activity; if the worker/sandbox dies hard
+ # mid-run that write never lands, leaving the TaskRun stuck `IN_PROGRESS` — which would
+ # otherwise block every future dispatch for this `(team, skill)` forever via
+ # `_has_running_run`. Reap such orphans here so the lane self-heals. Keyed on the same
+ # canonical `(team, skill_name)` the guard uses so it reaps exactly the rows the guard sees.
+ await database_sync_to_async(_self_heal_stale_runs, thread_sensitive=False)(
+ team.parent_team_id or team.id, skill.name
+ )
# Skip-if-running guard, keyed on (team, skill_name). Different skills for the same
# team are allowed to run concurrently — the coordinator can dispatch several due
@@ -402,24 +406,54 @@ def _has_running_run(*, team_id: int, skill_name: str) -> bool:
def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
- """No-op pending the task_run-based partial unique index follow-up.
-
- The original self-heal recovered RUNNING rows orphaned by a worker / sandbox
- crash, because a DB-level partial unique index on
- `(team_id, skill_name) WHERE status='running'` would otherwise block all
- future dispatches for the same (team, skill). That index was dropped during
- the 2026-05-21 restack — it referenced `SignalScoutRun.status`, which no
- longer exists on the slim bridge row (status lives on `task_run.status`).
-
- `_has_running_run` queries `task_run__status=IN_PROGRESS` so single-flighting
- still works at the app layer; stale bridge rows no longer block dispatch,
- they just take up space. The Tasks subsystem owns `task_run.status` and has
- its own timeout / cleanup path, so cross-product writes from here would be
- inappropriate. Restore real recovery logic once a `task_run.status`-based
- DB constraint lands as a follow-up.
+ """Reap orphaned in-flight runs so a dead run can't block the lane forever.
+
+ A scout run writes its own terminal `task_run.status` from inside the activity. If the
+ worker / sandbox dies hard mid-run (SIGKILL, pod eviction, sandbox loss), that write
+ never lands and the TaskRun is frozen at `QUEUED`/`IN_PROGRESS`. `_has_running_run`
+ then single-flights against that frozen row and skips every future dispatch for this
+ `(team, skill)` indefinitely — there is no other release. Nothing else reconciles it:
+ Temporal has already torn the workflow down (the activity is killed at
+ `WORKFLOW_HARD_CEILING_S` with `maximum_attempts=1`), and the Tasks cleanup path does
+ not cover a crashed worker.
+
+ A run older than `STALE_RUN_CUTOFF_S` (a generous multiple of that ceiling) cannot
+ still be legitimately executing, so it is an orphan and we mark it failed. The cutoff's
+ 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.
"""
- _ = team_id, skill_name
- return
+ cutoff = timezone.now() - timedelta(seconds=STALE_RUN_CUTOFF_S)
+ stale_runs = (
+ SignalScoutRun.objects.unscoped()
+ .filter(
+ team_id=team_id,
+ skill_name=skill_name,
+ task_run__status__in=(TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS),
+ task_run__created_at__lt=cutoff,
+ )
+ .select_related("task_run")
+ )
+ for run in stale_runs:
+ try:
+ run.task_run.mark_failed(
+ "Scout run abandoned: no terminal status past the runtime ceiling "
+ "(worker/sandbox lost before finalize)."
+ )
+ logger.warning(
+ "signals_scout: reaped stale in-progress run before dispatch",
+ extra={
+ "team_id": team_id,
+ "skill_name": skill_name,
+ "run_id": str(run.id),
+ "task_run_id": str(run.task_run_id),
+ },
+ )
+ except Exception:
+ logger.exception(
+ "signals_scout: failed to reap stale in-progress run; continuing",
+ extra={"team_id": team_id, "skill_name": skill_name, "run_id": str(run.id)},
+ )
def _create_run_row(
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index fbbb8f8835f5..380427b9c3ad 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import random
import asyncio
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
import pytest
from posthog.test.base import BaseTest
@@ -17,6 +17,7 @@ from posthog.models.scoping import team_scope
from posthog.sync import database_sync_to_async
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
+from products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_S
from products.signals.backend.scout_harness.prompt import build_run_prompt
from products.signals.backend.scout_harness.runner import RunResult, arun_signals_scout
from products.signals.backend.scout_harness.skill_loader import (
@@ -480,6 +481,80 @@ async def test_skip_if_running_lock_keys_on_team_and_skill_not_just_team(ateam,
assert result.skip_reason is None
+async def test_stale_in_progress_run_is_reaped_and_unblocks_dispatch(ateam, aerrors_skill):
+ # An IN_PROGRESS run orphaned by a crashed worker must not block the lane forever. The
+ # stale-run self-heal fails any run older than STALE_RUN_CUTOFF_S before the skip-if-running
+ # guard, so a fresh dispatch proceeds and the orphan is marked FAILED.
+ config = await database_sync_to_async(SignalScoutConfig.objects.create)(
+ team=ateam, skill_name="signals-scout-errors"
+ )
+ task_run = await database_sync_to_async(_make_task_run)(ateam)
+ # An IN_PROGRESS run whose start is older than the cutoff = an orphan from a crashed worker.
+ 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),
+ )
+ await database_sync_to_async(SignalScoutRun.objects.create)(
+ task_run=task_run,
+ team=ateam,
+ scout_config=config,
+ skill_name="signals-scout-errors",
+ skill_version=1,
+ )
+
+ spawn_calls: list[dict] = []
+
+ async def fake_spawn(**kwargs):
+ spawn_calls.append(kwargs)
+ return "ok", str(task_run.id)
+
+ with patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn):
+ result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
+
+ # The orphan was reaped, so the guard didn't block — dispatch went through.
+ assert len(spawn_calls) == 1
+ assert result.run_id is not None
+ assert result.skip_reason is None
+ # The stale run is now terminal.
+ reaped = await database_sync_to_async(TaskRun.objects.get)(id=task_run.id)
+ assert reaped.status == TaskRun.Status.FAILED
+
+
+async def test_recent_in_progress_run_is_not_reaped_and_still_blocks(ateam, aerrors_skill):
+ # A genuinely in-flight run (younger than the cutoff) must still single-flight — the
+ # self-heal must not reap a live run out from under itself.
+ config = await database_sync_to_async(SignalScoutConfig.objects.create)(
+ team=ateam, skill_name="signals-scout-errors"
+ )
+ 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=30),
+ )
+ await database_sync_to_async(SignalScoutRun.objects.create)(
+ task_run=task_run,
+ team=ateam,
+ scout_config=config,
+ skill_name="signals-scout-errors",
+ skill_version=1,
+ )
+
+ with patch(
+ "products.signals.backend.scout_harness.runner.MultiTurnSession.start",
+ new_callable=AsyncMock,
+ side_effect=AssertionError("session.start should not run while a live run is IN_PROGRESS"),
+ ):
+ result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
+
+ assert result.skip_reason is not None
+ still_running = await database_sync_to_async(TaskRun.objects.get)(id=task_run.id)
+ assert still_running.status == TaskRun.Status.IN_PROGRESS
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_cancelled_run_re_raises(ateam, aerrors_skill):