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(signals): emit scout run started + reaped lifecycle events (#65034)

Andrew Maguiree5d0cb843ee0
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 9fdd128952b3..cd43639e6046 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -113,6 +113,13 @@ one sandbox session → zero or more emitted signals.
(`/project/{team_id}/tasks/{task_id}?runId={task_run_id}`) and is the join key for the
LLM-analytics token / cost roll-up. Failure context (status, error, full chat log via
LLMA) lives on the `TaskRun`; the harness persists no run state on the bridge row.
+- Each run emits scout-owned lifecycle analytics events (best-effort, keyed on the team):
+ `signals_scout_run_started` (the run cleared the guards and a TaskRun exists),
+ `signals_scout_run_finished` (terminal: `completed`/`failed`/`cancelled` + runtime + emit
+ count), and `signals_scout_run_reaped` (a stranded orphan was reaped by
+ `_self_heal_stale_runs`). They join on `run_id`/`task_run_id` and are the event-derived
+ (no-warehouse-lag) basis for throughput, stall, and worker-death alerting — a `started`
+ with no `finished` is a run that died before finalize; a reaped run emits no `finished`.
- Emit happens via the harness's `emit_signal_*` tools, which call `emit_signal()`
with `source_product="signals_scout"` and `source_type="cross_source_issue"`.
From there the signal flows through the same emitter → buffer → grouping v2 path
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 25a27f4cded7..3c69eb3f8c06 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -328,6 +328,18 @@ async def _spawn_and_run(
config=config,
skill=skill,
)
+ # Lifecycle start marker. The row + TaskRun now exist and the run has cleared the
+ # reap + single-flight guards, so this counts exactly the runs that actually start —
+ # a skipped dispatch emits nothing. Pairs with `signals_scout_run_finished` for
+ # event-derived throughput and stall detection (started with no finished = a run
+ # that died before finalize), with no warehouse-sync lag.
+ _capture_run_started(
+ team=team,
+ config=config,
+ skill=skill,
+ run_id=run_id,
+ task_run_id=str(task_run.id),
+ )
session, result = await MultiTurnSession.start(
prompt=prompt,
@@ -424,7 +436,7 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
never block the new run, so each is guarded independently.
"""
cutoff = timezone.now() - timedelta(seconds=STALE_RUN_CUTOFF_S)
- stale_runs = (
+ stale_runs = list(
SignalScoutRun.objects.unscoped()
.filter(
team_id=team_id,
@@ -434,9 +446,29 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
)
.select_related("task_run")
)
+ if not stale_runs:
+ return
+ # 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:
- run.task_run.mark_failed(
+ task_run = run.task_run
+ # 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 = TaskRun.objects.filter(
+ id=task_run.id,
+ status__in=(TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS),
+ ).update(status=TaskRun.Status.FAILED)
+ if not claimed:
+ continue
+ status_before = task_run.status
+ age_seconds = (now - task_run.created_at).total_seconds()
+ task_run.mark_failed(
"Scout run abandoned: no terminal status past the runtime ceiling "
"(worker/sandbox lost before finalize)."
)
@@ -449,6 +481,18 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
"task_run_id": str(run.task_run_id),
},
)
+ # A reaped run never reaches the finalize path, so it emits no
+ # `signals_scout_run_finished`. This event makes the strand observable with no
+ # warehouse lag — a spike is the worker-death / mass-stall shape, caught within a
+ # tick of the cutoff rather than days late.
+ _capture_run_reaped(
+ team=team,
+ skill_name=skill_name,
+ run_id=run.id,
+ task_run_id=str(run.task_run_id),
+ status_before=status_before,
+ age_seconds=age_seconds,
+ )
except Exception:
logger.exception(
"signals_scout: failed to reap stale in-progress run; continuing",
@@ -496,6 +540,82 @@ def _read_run_metrics(run_id: Any, team_id: int) -> tuple[int, str | None]:
return emitted_count or 0, str(task_run_id) if task_run_id else None
+def _capture_run_started(
+ *,
+ team: Team,
+ config: SignalScoutConfig,
+ skill: LoadedSkill,
+ run_id: Any,
+ task_run_id: str,
+) -> None:
+ """Emit the scout-owned run-started analytics event.
+
+ The lifecycle counterpart to `signals_scout_run_finished`, fired once the TaskRun + bridge
+ row exist and the run has cleared the reap + single-flight guards. Keyed on the team (same
+ shape as the finished event) so the two join on `run_id`: `started` minus `finished` is the
+ in-flight / stalled set, and a `started` with no `finished` is a run that died before
+ finalize — an event-derived stall signal with no warehouse lag. Best-effort: a capture
+ failure must never block the run.
+ """
+ try:
+ posthoganalytics.capture(
+ event="signals_scout_run_started",
+ distinct_id=str(team.uuid),
+ properties={
+ "skill_name": skill.name,
+ "skill_version": skill.version,
+ "scout_config_id": str(config.id),
+ "run_id": str(run_id),
+ "task_run_id": task_run_id,
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.warning(
+ "signals_scout: failed to capture run-started analytics event",
+ extra={"team_id": team.id, "run_id": str(run_id), "skill_name": skill.name},
+ )
+
+
+def _capture_run_reaped(
+ *,
+ team: Team,
+ skill_name: str,
+ run_id: Any,
+ task_run_id: str,
+ status_before: str,
+ age_seconds: float,
+) -> None:
+ """Emit a scout-owned event when a stranded run is reaped (see `_self_heal_stale_runs`).
+
+ A run orphaned by a hard worker death never reaches the finalize path, so it emits no
+ `signals_scout_run_finished` — the reap is otherwise visible only in the logs. This event
+ surfaces the strand directly: a rising count is the worker-death / mass-stall shape, and
+ `status_before` + `age_seconds` distinguish a routine one-off from a fleet event. Keyed on
+ the team to match the other scout lifecycle events. Best-effort: a capture failure must
+ never block the reap or the new run.
+ """
+ try:
+ posthoganalytics.capture(
+ event="signals_scout_run_reaped",
+ distinct_id=str(team.uuid),
+ properties={
+ "skill_name": skill_name,
+ "run_id": str(run_id),
+ "task_run_id": task_run_id,
+ "status_before": status_before,
+ "age_seconds": round(age_seconds, 1),
+ "stale_cutoff_seconds": STALE_RUN_CUTOFF_S,
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.warning(
+ "signals_scout: failed to capture run-reaped analytics event",
+ extra={"team_id": team.id, "run_id": str(run_id), "skill_name": skill_name},
+ )
+
+
def _capture_run_finished(
*,
team: Team,
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index 28c88db26003..55e2fd91da70 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -340,10 +340,12 @@ async def test_successful_run_captures_run_finished_event(ateam, aerrors_skill):
):
run_result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
- capture.assert_called_once()
- assert capture.call_args.kwargs["event"] == "signals_scout_run_finished"
- assert capture.call_args.kwargs["distinct_id"] == str(ateam.uuid)
- props = capture.call_args.kwargs["properties"]
+ # A successful run emits the started marker (in the bridge-row hook) then the finished event.
+ events = [c.kwargs["event"] for c in capture.call_args_list]
+ assert events == ["signals_scout_run_started", "signals_scout_run_finished"]
+ finished = next(c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_run_finished")
+ assert finished.kwargs["distinct_id"] == str(ateam.uuid)
+ props = finished.kwargs["properties"]
assert props["skill_name"] == "signals-scout-errors"
assert props["skill_version"] == 1
assert props["status"] == TaskRun.Status.COMPLETED.value
@@ -354,6 +356,42 @@ async def test_successful_run_captures_run_finished_event(ateam, aerrors_skill):
assert isinstance(props["runtime_seconds"], float)
+async def test_successful_run_captures_run_started_event(ateam, aerrors_skill):
+ # The started marker fires once the TaskRun + bridge row exist (the on_task_run_created
+ # hook), so it counts only runs that actually start. Pairs with the finished event for
+ # event-derived throughput / stall detection with no warehouse lag.
+ session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam)
+
+ with (
+ patch(
+ "products.signals.backend.scout_harness.runner.MultiTurnSession.start",
+ new=_fake_start_invoking_hook(session, result),
+ ),
+ patch(
+ "products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",
+ return_value="env-id",
+ ),
+ patch(
+ "products.signals.backend.scout_harness.runner.resolve_user_id_for_team",
+ return_value=42,
+ ),
+ patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,
+ ):
+ run_result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
+
+ started = next(c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_run_started")
+ assert started.kwargs["distinct_id"] == str(ateam.uuid)
+ props = started.kwargs["properties"]
+ assert props["skill_name"] == "signals-scout-errors"
+ assert props["skill_version"] == 1
+ assert props["run_id"] == run_result.run_id
+ assert props["task_run_id"] == str(session.task_run.id)
+ config = await database_sync_to_async(SignalScoutConfig.objects.get)(team=ateam, skill_name="signals-scout-errors")
+ assert props["scout_config_id"] == str(config.id)
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_failed_run_captures_run_finished_event(ateam, aerrors_skill):
@@ -555,6 +593,48 @@ async def test_recent_in_progress_run_is_not_reaped_and_still_blocks(ateam, aerr
assert still_running.status == TaskRun.Status.IN_PROGRESS
+async def test_stale_run_reap_captures_run_reaped_event(ateam, aerrors_skill):
+ # 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
+ # is what makes the worker-death / mass-stall shape alertable with no warehouse lag.
+ 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=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,
+ )
+
+ async def fake_spawn(**_kwargs):
+ return "ok", str(task_run.id)
+
+ with (
+ patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn),
+ patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,
+ ):
+ 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")
+ 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["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
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_cancelled_run_re_raises(ateam, aerrors_skill):