: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): bound scout dispatch guards to recent runs (#115875)
posthog[bot]35394c1f52b8
diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.pyindex c83c689e614d..87e7140bb15e 100644--- a/products/signals/backend/scout_harness/limits.py+++ b/products/signals/backend/scout_harness/limits.py@@ -30,14 +30,14 @@ 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+# How many of a lane's newest runs the self-heal checks for orphans. An orphan is a run stuck in+# `QUEUED`/`IN_PROGRESS`, or a run that the Tasks inactivity timeout closed after a worker death,+# which 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+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.diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex df6c00ce91e0..4e4f8c45bdc3 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -41,7 +41,7 @@ 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,+ ORPHAN_RECENT_RUNS,SCOUT_RUN_REAPED_METADATA_KEY,STALE_RUN_CUTOFF_S,TRIAL_ACTIVITY_TIMEOUT_S,@@ -670,8 +670,7 @@ async def _arun_signals_scout(# linked TaskRun (managed by MultiTurnSession), so we don't update anything# here directly. A TaskRun stranded in IN_PROGRESS (e.g. SIGKILL before# MultiTurnSession finalizes) blocks new runs for this (team, skill) via- # `_has_running_run` until it transitions out — active recovery is a deferred- # follow-up (see `_self_heal_stale_runs`).+ # `_has_running_run` until `_self_heal_stale_runs` reaps it past the stale cutoff.runtime_s = time.monotonic() - startedlogger.warning("signals_scout: run cancelled mid-flight",@@ -1167,12 +1166,18 @@ def _has_running_run(*, team_id: int, skill_name: str) -> bool:# on `scout_config_id`: configs are `on_delete=SET_NULL`, so a config delete/recreate# mid-run would orphan the FK and silently defeat the dedupe in exactly the# config-churn case it should still cover.+ # A run older than `STALE_RUN_CUTOFF_S` is an orphan that `_self_heal_stale_runs` reaps just+ # before this check, so it does not count. The floor also keeps the read to a range scan of+ # `signal_scout_run_recent_idx` instead of the lane's whole history.+ live_cutoff = timezone.now() - timedelta(seconds=STALE_RUN_CUTOFF_S)return (SignalScoutRun.objects.unscoped().filter(team_id=team_id,skill_name=skill_name,+ created_at__gte=live_cutoff,task_run__status__in=(tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS),+ task_run__created_at__gte=live_cutoff,).exclude(metadata__has_key=SCOUT_TRIAL_METADATA_KEY).exists()@@ -1185,8 +1190,8 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:A scout run writes its own terminal `task_run.status` from inside the activity. If theworker / sandbox dies hard mid-run (SIGKILL, pod eviction, sandbox loss), that writenever 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:+ single-flights against that frozen row until `STALE_RUN_CUTOFF_S`, and the row stays+ unreported unless this reap closes it. 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 doesnot cover a crashed worker.@@ -1202,6 +1207,9 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:the next dispatch. The scout never ends its own session through that timeout, becauseevery path that survives signals completion, so that marker means the run lost its driverand never emitted `signals_scout_run_finished`. Those runs are reported too, once each.++ The reap reads only the lane's newest `ORPHAN_RECENT_RUNS` runs. This runs before every+ dispatch, so an orphan is one of the newest runs when the next dispatch comes."""now = timezone.now()cutoff = now - timedelta(seconds=STALE_RUN_CUTOFF_S)@@ -1211,16 +1219,15 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:.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]+ .values("id")[: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__created_at__lt=cutoff)+ .filter(team_id=team_id, skill_name=skill_name, id__in=recent_run_ids, 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)diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex f97389ec9b24..739972a538a9 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -3156,6 +3156,8 @@ async def test_recent_in_progress_run_is_not_reaped_and_still_blocks(ateam, aerr"status,state,age_s,expect_reaped",[("in_progress", {}, STALE_RUN_CUTOFF_S + 60, True),+ # A paused lane dispatches again long after its orphan started; the reap has no age floor.+ ("in_progress", {}, 31 * 24 * 60 * 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),