: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): stop paused scouts from spending report check retries (#107895)
posthog[bot]39cc02e7c942
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex ebf4f7ce19c6..b997552bec0c 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -224,6 +224,7 @@ post_save:products.signals.backend.receivers.close_pr_when_report_dismissedpost_save:products.signals.backend.receivers.emit_report_embedding_on_document_changepost_save:products.signals.backend.receivers.mark_scout_suggestions_stale_on_fleet_changepost_save:products.signals.backend.receivers.reconcile_report_embedding_on_verdict_saved+post_save:products.signals.backend.receivers.requeue_report_checks_on_scout_resumepost_save:products.signals.backend.receivers.roll_up_plan_parents_when_report_closespost_save:products.signals.backend.receivers.schedule_handover_for_report_changepost_save:products.signals.backend.receivers.schedule_handover_for_work_changediff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 5e659ade847e..29cf3e59b29e 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -506,7 +506,7 @@ The schedule is the check's own clock (`next_run_at`, optional `run_interval_min`agent` is the kind for a claim no single number settles, which is most of the inbox: "did the exception stop?" needs the issue looked up and its recent events read rather than a threshold compared. Its config is `{instructions, skill_name?, probe_hints}`, all of it untrusted prompt material. `report_check_agent.py` owns the lane. A due check is dispatched as a scout run with `triggered_by="check"` — a fourth dispatch source next to `schedule` / `manual` / `workflow`, so it shares the fleet, spend, and single-flight gates in `run_gates.py` but stamps no `last_run_at` and never feeds the failure-streak breaker, whose threshold is sized on the scout's own cadence. The run note carries the check id, title, rationale, instructions, probe hints, the report, and the note whoever resolved or dismissed it typed; the prompt renders it as the run's assignment (`prompt._CHECK_NOTE_TEMPLATE`) rather than as the nudge a manual run's note is.-Most reports are pipeline-authored and have no scout behind them, so `skill_name` is optional: a check that names none runs on `signals-scout-inbox-validation`, the fleet's follow-up scout, which is an operational scout and so is seeded enabled on every enrolled team. When the lane genuinely cannot run — the project is not enrolled, the skill is withheld or gone — the check records an `errored` result naming the reason, so a reader finds out on the report rather than waiting out a silent horizon. A refusal that can clear (a run of the same scout in flight, a daily run budget, a spend gate, a paused scout) defers the check by an hour instead, spending no error. A paused scout is in that group because three errored runs during a pause would retire the check before the scout resumes. The check does not move to another scout while it waits.+Most reports are pipeline-authored and have no scout behind them, so `skill_name` is optional: a check that names none runs on `signals-scout-inbox-validation`, the fleet's follow-up scout, which is an operational scout and so is seeded enabled on every enrolled team. When the lane genuinely cannot run — the project is not enrolled, the skill is withheld or gone — the check records an `errored` result naming the reason, so a reader finds out on the report rather than waiting out a silent horizon. A refusal that can clear (a run of the same scout in flight, a daily run budget, a spend gate, a paused scout) defers the check by an hour instead, spending no error. A paused scout is in that group because three errored runs during a pause would retire the check before the scout resumes. The check does not move to another scout while it waits. A dispatched run that records no verdict counts as an errored run, unless its scout is paused when the result window ends: then the check waits too. When a scout is enabled again, the checks deferred on it become due at once, so the next tick dispatches them. `reactivate_pause_errored_report_checks` repairs the checks an older dispatch retired as `errored` for a paused scout.A dispatch is not a verdict. The row stays `active` with `dispatched_at` stamped, and only `scout-check-record-result` (`scout_harness/tools/checks.py`) closes it. The dispatch passes `check_id` through the workflow input, and the runner stamps it on the run row's `metadata`. That run may close its check once, also when the lane now resolves to another scout. Its verdict clears `dispatched_at`, so a retry after a recurring check re-arms is refused. A run on the check's own lane may also close an `active` check that is due now or waits on a run, so a scout that measures a due check in passing can record the result. A `pending` check is refused, because its report has not resolved. A due check the coordinator would not dispatch is refused too, because its report is suppressed or its horizon passed. A run that ends without calling the tool leaves `dispatched_at` set, and the first tick past `AGENT_CHECK_RESULT_WINDOW` records an errored result saying so.diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.mdindex 4bdc7b24119a..185984e7d1c5 100644--- a/products/signals/backend/management/AGENTS.md+++ b/products/signals/backend/management/AGENTS.md@@ -219,6 +219,23 @@ uv run manage.py resume_setup_paused_operational_scouts --apply --team-id 1Idempotent. A resumed row no longer matches.+## Reactivating report checks a paused scout retired++Dispatch once treated a paused scout as a permanent refusal, so three ticks of a pause retired an `agent` check as `errored`.+`reactivate_pause_errored_report_checks` makes such a check active and due again with a clear error count.+A check matches only when its last result is the paused-scout refusal, its report is still resolved, and its horizon has not passed.+If the scout is still paused, the reactivated check waits for the resume without spending errors.++```bash+# Dry run (the default): how many checks match, and the first team ids+uv run manage.py reactivate_pause_errored_report_checks++# Write, optionally for one environment+uv run manage.py reactivate_pause_errored_report_checks --apply --team-id 1+```++Idempotent. A reactivated check no longer matches.+## Tips- Compare runs by saving output: `list_signal_reports --json > run_baseline.json`diff --git a/products/signals/backend/management/commands/reactivate_pause_errored_report_checks.py b/products/signals/backend/management/commands/reactivate_pause_errored_report_checks.pynew file mode 100644index 000000000000..9a2a16e7e7b3--- /dev/null+++ b/products/signals/backend/management/commands/reactivate_pause_errored_report_checks.py@@ -0,0 +1,32 @@+from argparse import ArgumentParser+from typing import cast++from django.core.management.base import BaseCommand++from products.signals.backend.report_check_agent import reactivate_checks_errored_by_scout_pause+++class Command(BaseCommand):+ help = (+ "Reactivate agent report checks that dispatch retired as errored only because their scout was "+ "paused. Only checks on a resolved report with time left before their horizon match. Dry run "+ "unless --apply is passed. Safe to rerun: a reactivated check no longer matches."+ )++ def add_arguments(self, parser: ArgumentParser) -> None:+ mode = parser.add_mutually_exclusive_group()+ mode.add_argument("--dry-run", action="store_true", help="Print what would change. The default.")+ mode.add_argument("--apply", action="store_true", help="Reactivate the matched checks.")+ parser.add_argument("--team-id", type=int, help="Limit the run to one environment.")+ parser.add_argument("--show-team-ids", type=int, default=20, help="How many team ids to print.")++ def handle(self, *args: object, **options: object) -> None:+ apply = bool(options["apply"])+ summary = reactivate_checks_errored_by_scout_pause(apply=apply, team_id=cast(int | None, options["team_id"]))+ self.stdout.write("Mode: apply" if apply else "Mode: dry run (pass --apply to write)")+ line = f"Matched checks: {summary.matched}"+ if apply:+ line += f", reactivated {summary.reactivated}"+ self.stdout.write(line)+ shown = summary.team_ids[: cast(int, options["show_team_ids"])]+ self.stdout.write(f"Teams: {len(summary.team_ids)}. First team ids: {shown}")diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.pyindex 1e0b7c13338f..268d7ac6569c 100644--- a/products/signals/backend/receivers.py+++ b/products/signals/backend/receivers.py@@ -980,6 +980,29 @@ def mark_scout_suggestions_stale_on_fleet_change(sender: Any, instance: Any, **klogger.warning("scout_suggestions: failed to mark batch stale", team_id=instance.team_id, exc_info=True)+@receiver(post_save, sender="signals.SignalScoutConfig")+def requeue_report_checks_on_scout_resume(sender: Any, instance: Any, **kwargs: Any) -> None:+ """A resumed scout answers the report checks its pause deferred on the next coordinator tick.+ Saves that leave the scout paused, or that cannot change `enabled`, skip the write, and nothing+ here may fail the config write."""+ update_fields = kwargs.get("update_fields")+ if not instance.enabled or (update_fields is not None and "enabled" not in update_fields):+ return+ try:+ from products.signals.backend.report_check_agent import (+ requeue_checks_waiting_on_scout, # noqa: PLC0415 — keeps the scout run gates off the django.setup() path+ )++ requeue_checks_waiting_on_scout(instance.team_id, instance.skill_name)+ except Exception:+ logger.warning(+ "signals.report_check.requeue_on_resume_failed",+ team_id=instance.team_id,+ skill_name=instance.skill_name,+ exc_info=True,+ )++@receiver(post_save, sender=SignalReportArtefact)def sync_suggested_reviewer_index_on_save(sender: type[SignalReportArtefact],diff --git a/products/signals/backend/report_check_agent.py b/products/signals/backend/report_check_agent.pyindex 38a87affacbe..e6f14b369287 100644--- a/products/signals/backend/report_check_agent.py+++ b/products/signals/backend/report_check_agent.py@@ -20,6 +20,7 @@ import jsonfrom datetime import datetime, timedeltafrom django.db import transaction+from django.db.models import Qfrom django.utils import timezoneimport structlog@@ -61,6 +62,10 @@ CHECK_DISPATCH_DEFER_AFTER = timedelta(hours=1)MAX_CHECK_NOTE_REPORT_TITLE_LENGTH = 300MAX_CHECK_NOTE_RESOLUTION_LENGTH = 1_000+# The end of the explanation a paused-scout refusal writes. Dispatch once recorded that refusal as an+# errored result, so the repair of those checks matches it (`reactivate_checks_errored_by_scout_pause`).+SCOUT_PAUSED_REFUSAL_SUFFIX = "scout is paused, so the check could not run."+@frozenclass CheckDispatchRefusal:@@ -213,7 +218,7 @@ def _refuse_dispatch(skill_name: str, canonical_team_id: int) -> CheckDispatchReif not config.enabled:return CheckDispatchRefusal(reason="scout_paused",- detail=f"The `{skill_name}` scout is paused, so the check could not run.",+ detail=f"The `{skill_name}` {SCOUT_PAUSED_REFUSAL_SUFFIX}",retryable=True,)@@ -228,6 +233,127 @@ def _refuse_dispatch(skill_name: str, canonical_team_id: int) -> CheckDispatchRereturn None+def _lane_paused(canonical_team_id: int, skill_name: str) -> bool:+ """Whether a person or the harness paused this lane. A retired lane is not a pause: its checks+ fall back to another scout (`resolve_check_skill_name`)."""+ return (+ SignalScoutConfig.all_teams.filter(team_id=canonical_team_id, skill_name=skill_name, enabled=False)+ .exclude(pause_reason=SignalScoutConfig.PauseReason.RETIRED)+ .exists()+ )+++def _paused_dispatched_lane(check: SignalReportCheck) -> str | None:+ """The lane of a dispatched check when that lane is paused now, else None."""+ try:+ config = parse_check_config(check.kind, check.config)+ if not isinstance(config, AgentCheckConfig):+ return None+ report_team = check.report.team+ canonical_team_id = report_team.parent_team_id or report_team.id+ skill_name = resolve_check_skill_name(config, canonical_team_id)+ return skill_name if _lane_paused(canonical_team_id, skill_name) else None+ except Exception:+ logger.exception("signals.report_check.agent_pause_read_failed", check_id=str(check.id), team_id=check.team_id)+ return None+++def requeue_checks_waiting_on_scout(canonical_team_id: int, skill_name: str, *, now: datetime | None = None) -> int:+ """Make the checks a refusal deferred on this lane due now, so a resumed scout answers them on the+ next tick rather than up to `CHECK_DISPATCH_DEFER_AFTER` later. Returns how many moved.++ A deferral is the only thing that puts a check at most `CHECK_DISPATCH_DEFER_AFTER` away, because a+ re-armed check waits at least `MIN_CHECK_INTERVAL_MINUTES`. A check that is due inside that window+ for another reason only runs a little early.+ """+ now = now or timezone.now()+ lane = Q(config__skill_name=skill_name)+ if skill_name == FALLBACK_CHECK_SKILL_NAME:+ lane |= ~Q(config__has_key="skill_name") | Q(config__skill_name=None)+ team_ids = Team.objects.filter(Q(id=canonical_team_id) | Q(parent_team_id=canonical_team_id)).values("id")+ return SignalReportCheck.all_teams.filter(+ lane,+ team_id__in=team_ids,+ kind=SignalReportCheck.Kind.AGENT,+ status=SignalReportCheck.Status.ACTIVE,+ dispatched_at__isnull=True,+ report__status=SignalReport.Status.RESOLVED,+ next_run_at__gt=now,+ next_run_at__lte=now + CHECK_DISPATCH_DEFER_AFTER,+ ).update(next_run_at=now, updated_at=now)+++@frozen+class PauseErroredChecksSummary:+ matched: int+ reactivated: int+ team_ids: list[int]+++def reactivate_checks_errored_by_scout_pause(+ *, apply: bool, team_id: int | None = None, now: datetime | None = None+) -> PauseErroredChecksSummary:+ """Put back the agent checks that dispatch retired as `errored` only because their scout was paused.++ Dispatch once treated a paused scout as a permanent refusal, so three ticks of a pause retired the+ check. A check matches when its last result is that refusal, and its report is still resolved and+ its horizon has not passed. A match becomes active and due again with a clear error count. If its+ scout is still paused, it then waits for the resume like any other check.+ """+ now = now or timezone.now()+ candidates = SignalReportCheck.all_teams.filter(+ kind=SignalReportCheck.Kind.AGENT,+ status=SignalReportCheck.Status.ERRORED,+ last_outcome=SignalReportCheck.Outcome.ERRORED,+ expires_at__gt=now,+ report__status=SignalReport.Status.RESOLVED,+ )+ if team_id is not None:+ candidates = candidates.filter(team_id=team_id)++ matched: list[SignalReportCheck] = []+ for check in candidates.only("id", "team_id", "report_id").iterator():+ latest = (+ SignalReportArtefact.objects.filter(+ team_id=check.team_id,+ report_id=check.report_id,+ type=SignalReportArtefact.ArtefactType.CHECK_RESULT,+ content__contains=str(check.id),+ )+ .order_by("-created_at")+ .values_list("content", flat=True)+ .first()+ )+ if latest is None:+ continue+ try:+ explanation = json.loads(latest).get("explanation")+ except (TypeError, ValueError, AttributeError):+ continue+ if isinstance(explanation, str) and explanation.endswith(SCOUT_PAUSED_REFUSAL_SUFFIX):+ matched.append(check)++ reactivated = 0+ if apply:+ for check in matched:+ reactivated += (+ SignalReportCheck.objects.for_team(check.team_id)+ .filter(id=check.id, status=SignalReportCheck.Status.ERRORED)+ .update(+ status=SignalReportCheck.Status.ACTIVE,+ consecutive_errors=0,+ dispatched_at=None,+ next_run_at=now,+ updated_at=now,+ )+ )+ return PauseErroredChecksSummary(+ matched=len(matched),+ reactivated=reactivated,+ team_ids=sorted({check.team_id for check in matched}),+ )++def _claim_for_dispatch(check: SignalReportCheck, now: datetime) -> bool:"""Stamp the check as dispatched, and say whether this caller is the one that stamped it.@@ -281,6 +407,15 @@ def run_agent_check(check: SignalReportCheck, *, now: datetime | None = None) ->now = now or timezone.now()if check.dispatched_at is not None:+ paused_skill_name = _paused_dispatched_lane(check)+ if paused_skill_name is not None:+ # The lane was paused while the check waited, so the pause explains the missing verdict.+ # The check waits for the resume without spending an error, the same as a paused refusal.+ _release_dispatch_claim(check, now)+ capture_report_check_dispatch(+ check.team, check, outcome="deferred", skill_name=paused_skill_name, reason="scout_paused"+ )+ return "deferred"# The window passed with the row still stamped, so the run this check was waiting on ended# without calling the tool: it crashed, ran out of budget, or finished on something else.# That is an errored run, so it retries on the next window and retires after three.diff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.pyindex 9bffee6aee2a..7397dbcfc7c3 100644--- a/products/signals/backend/test/test_report_checks.py+++ b/products/signals/backend/test/test_report_checks.py@@ -38,6 +38,7 @@ from products.signals.backend.report_check_agent import (CHECK_DISPATCH_DEFER_AFTER,FALLBACK_CHECK_SKILL_NAME,build_check_run_note,+ reactivate_checks_errored_by_scout_pause,resolve_check_skill_name,run_agent_check,)@@ -1616,9 +1617,8 @@ class TestAgentCheckDispatch(APIBaseTest):scout_config.enabled = Truescout_config.save()- SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).update(- next_run_at=timezone.now() - timedelta(minutes=1)- )+ check.refresh_from_db()+ assert check.next_run_at <= timezone.now()with patch(_CONNECT), patch(_DISPATCH, return_value="wf-1") as dispatch:summary = run_due_report_checks()@@ -1673,19 +1673,63 @@ class TestAgentCheckDispatch(APIBaseTest):assert check.dispatched_at is Noneassert check.status == SignalReportCheck.Status.ACTIVE- def test_a_run_that_never_records_a_result_errors_the_check(self) -> None:+ @parameterized.expand([("live_lane", True), ("paused_lane", False)])+ def test_a_run_that_never_records_a_result_errors_the_check_unless_its_lane_is_paused(+ self, _name, lane_enabled+ ) -> None:now = timezone.now()check = self._check(dispatched_at=now - AGENT_CHECK_RESULT_WINDOW, next_run_at=now - timedelta(minutes=1))+ self.scout_config.enabled = lane_enabled+ self.scout_config.save()with patch(_CONNECT), patch(_DISPATCH) as dispatch:summary = run_due_report_checks()- assert summary.errored == 1dispatch.assert_not_called()check.refresh_from_db()assert check.dispatched_at is None- assert check.consecutive_errors == 1- assert "ended without recording a result" in self._results()[0].content+ assert check.status == SignalReportCheck.Status.ACTIVE+ if lane_enabled:+ assert summary.errored == 1+ assert check.consecutive_errors == 1+ assert "ended without recording a result" in self._results()[0].content+ else:+ assert summary.deferred == 1+ assert check.consecutive_errors == 0+ assert self._results() == []+ assert check.next_run_at > now + CHECK_DISPATCH_DEFER_AFTER - timedelta(minutes=5)++ @parameterized.expand(+ [+ (+ "paused_refusal",+ "The `signals-scout-inbox-validation` scout is paused, so the check could not run.",+ True,+ ),+ ("other_error", "the follow-up run ended without recording a result.", False),+ ]+ )+ def test_the_repair_reactivates_only_checks_a_paused_refusal_retired(self, _name, reason, reactivated) -> None:+ check = self._check(consecutive_errors=MAX_CONSECUTIVE_CHECK_ERRORS - 1)+ record_check_verdict(+ check, CheckVerdict(outcome="errored", explanation=f"{check.title}: {reason}"), now=timezone.now()+ )+ check.refresh_from_db()+ assert check.status == SignalReportCheck.Status.ERRORED++ dry_run = reactivate_checks_errored_by_scout_pause(apply=False)+ summary = reactivate_checks_errored_by_scout_pause(apply=True)++ assert (dry_run.matched, dry_run.reactivated) == (int(reactivated), 0)+ assert summary.reactivated == int(reactivated)+ check.refresh_from_db()+ if reactivated:+ assert check.status == SignalReportCheck.Status.ACTIVE+ assert check.consecutive_errors == 0+ with patch(_CONNECT), patch(_DISPATCH, return_value="wf-1"):+ assert run_due_report_checks().dispatched == 1+ else:+ assert check.status == SignalReportCheck.Status.ERROREDclass TestCheckResultTool(APIBaseTest):