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): run report checks only on resolved reports (#107331)

posthog[bot]af52c71ecfb3
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index 281e0ede32c1..02a3f0d36d62 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -506,11 +506,11 @@ 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, a person paused the scout, 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 clears on its own (a run of the same scout in flight, a daily run budget, a spend gate) defers the check by an hour instead, spending no error.
+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 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. A run may close only a check its own lane was dispatched for and that is still waiting on a dispatch, so the tool can answer the question the run was asked and nothing else. A run that ends without calling it leaves `dispatched_at` set, and the first tick past `AGENT_CHECK_RESULT_WINDOW` records an errored result saying so.
-Execution rides the scout coordinator tick (`run_due_signal_report_checks_activity`, gated behind a `workflow.patched` marker). Each tick expires what timed out, then advances the due rows by one step, capped per tick and per team. A pass on a recurring check re-arms it anchored on `now` so an outage cannot owe a burst of catch-up runs; a breach retires the check as `failed`; a run that cannot be measured retries and only retires after three consecutive errors. A check stops running while its report is suppressed or soft-deleted and runs again when the report comes back, but its horizon keeps advancing, so one that outlives `expires_at` while paused expires. A check that names a report metric stores a copy of that metric's query at creation, so a later edit to the metric does not change what the check measures. Both kinds are written through one funnel (`record_check_verdict`) that re-reads the row under a lock, so a check cancelled while its run was working records nothing.
+Execution rides the scout coordinator tick (`run_due_signal_report_checks_activity`, gated behind a `workflow.patched` marker). Each tick expires what timed out, then advances the due rows by one step, capped per tick and per team. A pass on a recurring check re-arms it anchored on `now` so an outage cannot owe a burst of catch-up runs; a breach retires the check as `failed`; a run that cannot be measured retries and only retires after three consecutive errors. A check runs only while its report is resolved. Each tick moves an `active` check whose report is not resolved back to `pending` (`park_checks_on_unresolved_reports`), which covers a report that was reopened or archived and any row written active on an open report. The move keeps the check's soak (or the gap its author left before the first run), clears its error streak and any open dispatch, and resets its horizon, so the next resolve arms it with a fresh soak and retry accounting starts again after that resolve. A check that names a report metric stores a copy of that metric's query at creation, so a later edit to the metric does not change what the check measures. Both kinds are written through one funnel (`record_check_verdict`) that re-reads the row under a lock, so a check cancelled while its run was working records nothing.
A check written _before_ the fix exists has no date to carry. The research pipeline's verification turn is that case: it authors the check in the same pass that writes the report. Such a check is stored `pending` with a `soak_minutes` window, and the report's transition to `resolved` is what sets `next_run_at` — a merged pull request's webhook, a manual resolve in the inbox, and an MCP state write all end in the same `save`, so the resolve is the clock for every kind of fix, including the ones that never had a pull request. `receivers.arm_pending_checks_when_report_resolved` is the choke point. A pending check counts against the per-report cap, is never collected as due, and expires at the 90-day horizon if its report never resolves.
diff --git a/products/signals/backend/report_check_agent.py b/products/signals/backend/report_check_agent.py
index 5c1c51d0ae28..511161c66343 100644
--- a/products/signals/backend/report_check_agent.py
+++ b/products/signals/backend/report_check_agent.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import json
from datetime import datetime, timedelta
+from django.db import transaction
from django.utils import timezone
import structlog
@@ -39,8 +40,7 @@ logger = structlog.get_logger(__name__)
# The lane a check runs on when its author named no skill. The fleet's follow-up scout already
# exists to re-measure resolved reports, and it is an operational scout, so it is seeded enabled on
# every enrolled team and exempt from the inactivity sweep and the enabled-scout cap. A person can
-# still pause it by hand, which the dispatch path reports as an errored run rather than working
-# around.
+# still pause it by hand. The dispatch path then waits for the resume rather than working around it.
FALLBACK_CHECK_SKILL_NAME = "signals-scout-inbox-validation"
# How long a dispatched run has to record its verdict before the coordinator gives up on it. A scout
@@ -50,8 +50,8 @@ FALLBACK_CHECK_SKILL_NAME = "signals-scout-inbox-validation"
# dispatched over the top of a live one.
AGENT_CHECK_RESULT_WINDOW = timedelta(hours=2)
-# How long a check waits after a dispatch the fleet refused for a reason that passes on its own: a
-# run of the same scout already in flight, a project at its daily run budget, a paused spend gate.
+# How long a check waits after a dispatch the fleet refused for a reason that can pass: a run of the
+# same scout already in flight, a project at its daily run budget, a paused spend gate, a paused scout.
# Shorter than the errored-run retry because none of these says anything is wrong with the check.
CHECK_DISPATCH_DEFER_AFTER = timedelta(hours=1)
@@ -66,11 +66,13 @@ MAX_CHECK_NOTE_RESOLUTION_LENGTH = 1_000
class CheckDispatchRefusal:
"""Why a check could not be dispatched this tick.
- `retryable` splits the two things a refusal can mean. A project at its daily run budget, or a
- lane already running, will be dispatchable again without anyone doing anything, so the check
- waits. A project not enrolled in scouts, or a lane a person paused, will not, so the check
- records an errored run: the report's log is where a reader finds out their follow-up never ran,
- and three of those retire the check instead of leaving it to expire in silence.
+ `retryable` splits the two things a refusal can mean. A project at its daily run budget, a lane
+ already running, or a paused lane can become dispatchable again, so the check waits without
+ spending its error budget. A paused lane is in that group because a pause is often temporary,
+ and three errored runs during a pause would retire the check before the scout resumes. A project
+ not enrolled in scouts, or a lane that does not exist, will not, so the check records an errored
+ run: the report's log is where a reader finds out their follow-up never ran, and three of those
+ retire the check instead of leaving it to expire in silence.
"""
reason: str
@@ -90,7 +92,7 @@ def resolve_check_skill_name(config: AgentCheckConfig, canonical_team_id: int |
one is gone.
A pause is deliberately not one of those reasons. Somebody switched that scout off on purpose,
- and reporting the refusal is more honest than quietly running the question somewhere else.
+ so the check waits for that scout rather than quietly running the question somewhere else.
"""
skill_name = config.skill_name or FALLBACK_CHECK_SKILL_NAME
if canonical_team_id is None or skill_name == FALLBACK_CHECK_SKILL_NAME:
@@ -211,7 +213,7 @@ def _refuse_dispatch(skill_name: str, canonical_team_id: int) -> CheckDispatchRe
return CheckDispatchRefusal(
reason="scout_paused",
detail=f"The `{skill_name}` scout is paused, so the check could not run.",
- retryable=False,
+ retryable=True,
)
team = Team.objects.select_related("organization").get(pk=canonical_team_id)
@@ -233,12 +235,16 @@ def _claim_for_dispatch(check: SignalReportCheck, now: datetime) -> bool:
run is waiting on. The conditional update is also the concurrency guard: a check cancelled
between collection and dispatch, or already claimed by an overlapping tick, matches nothing.
"""
- claimed = (
- SignalReportCheck.objects.for_team(check.team_id)
- .filter(id=check.id, status=SignalReportCheck.Status.ACTIVE, dispatched_at__isnull=True)
- .update(dispatched_at=now, next_run_at=now + AGENT_CHECK_RESULT_WINDOW, updated_at=now)
- )
- return bool(claimed)
+ with transaction.atomic():
+ report = SignalReport.objects.select_for_update().filter(id=check.report_id, team_id=check.team_id).first()
+ if report is None or report.status != SignalReport.Status.RESOLVED:
+ return False
+ claimed = (
+ SignalReportCheck.objects.for_team(check.team_id)
+ .filter(id=check.id, status=SignalReportCheck.Status.ACTIVE, dispatched_at__isnull=True)
+ .update(dispatched_at=now, next_run_at=now + AGENT_CHECK_RESULT_WINDOW, updated_at=now)
+ )
+ return bool(claimed)
def _release_dispatch_claim(check: SignalReportCheck, now: datetime) -> None:
diff --git a/products/signals/backend/report_check_authoring.py b/products/signals/backend/report_check_authoring.py
index f1cabeda00d5..3530adfde2b2 100644
--- a/products/signals/backend/report_check_authoring.py
+++ b/products/signals/backend/report_check_authoring.py
@@ -34,12 +34,11 @@ from products.signals.backend.report_checks import (
DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
MAX_ACTIVE_CHECKS_PER_REPORT,
MAX_CHECK_HORIZON,
- MAX_CHECK_SOAK_HOURS,
- MIN_CHECK_SOAK_HOURS,
CheckConfigValidationError,
CheckSpec,
MetricThresholdConfig,
parse_check_config,
+ soak_minutes_from_gap,
)
logger = structlog.get_logger(__name__)
@@ -116,6 +115,8 @@ def create_check(
if next_run_at is None:
assert soak_minutes is not None
next_run_at = now + timedelta(minutes=soak_minutes)
+ if soak_minutes is None:
+ soak_minutes = soak_minutes_from_gap(next_run_at, now)
if expires_at is None:
expires_at = min(
_last_run_at(next_run_at, run_interval_minutes, runs_remaining)
@@ -126,7 +127,7 @@ def create_check(
status = SignalReportCheck.Status.PENDING
if soak_minutes is None:
assert next_run_at is not None
- soak_minutes = _soak_from_first_run(next_run_at, now)
+ soak_minutes = soak_minutes_from_gap(next_run_at, now)
# Provisional, and rewritten at arm time. The horizon is real though: a report that
# never resolves retires its pending checks rather than holding them forever.
next_run_at = now + timedelta(minutes=soak_minutes)
@@ -279,16 +280,6 @@ def arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_at:
return armed
-def _soak_from_first_run(next_run_at: datetime, now: datetime) -> int:
- """The soak a dated check keeps when its report has not resolved yet.
-
- The author left a gap before the first run to allow for deploy and soak time, so that gap is
- what the check waits out once the report resolves, bounded by what a soak may be.
- """
- minutes = round((next_run_at - now).total_seconds() / 60)
- return max(MIN_CHECK_SOAK_HOURS * 60, min(minutes, MAX_CHECK_SOAK_HOURS * 60))
-
-
def _last_run_at(next_run_at: datetime, run_interval_minutes: int | None, runs_remaining: int) -> datetime:
if not run_interval_minutes:
return next_run_at
diff --git a/products/signals/backend/report_check_execution.py b/products/signals/backend/report_check_execution.py
index 7dee67214878..0684925061b7 100644
--- a/products/signals/backend/report_check_execution.py
+++ b/products/signals/backend/report_check_execution.py
@@ -54,12 +54,15 @@ from products.signals.backend.report_check_telemetry import (
capture_report_checks_expired,
)
from products.signals.backend.report_checks import (
+ DEFAULT_CHECK_SOAK_HOURS,
+ MAX_CHECK_HORIZON,
MAX_CONSECUTIVE_CHECK_ERRORS,
CheckComparison,
CheckConfigValidationError,
CheckOutcome,
MetricThresholdConfig,
parse_check_config,
+ soak_minutes_from_gap,
)
from products.signals.backend.report_metric_refresh import measure_metric
from products.signals.backend.report_metrics import validate_live_metric_query
@@ -83,14 +86,8 @@ MAX_CHECK_ERROR_REASON_LENGTH = 300
# a fix that stopped holding is a finding somebody already decided was worth fixing once.
CHECK_FAILURE_SIGNAL_WEIGHT = 1.0
-# A check stops running while its report is soft-deleted or suppressed, and runs again when the report
-# comes back. Its horizon keeps advancing meanwhile: a check that outlives `expires_at` while paused
-# expires like any other, because the soak window is the author's deadline, not the report's.
-CHECKABLE_REPORT_STATUSES = tuple(
- status
- for status in SignalReport.Status.values
- if status not in {SignalReport.Status.DELETED, SignalReport.Status.SUPPRESSED}
-)
+# Rows moved back to `pending` per tick because their report is not resolved. Bounded the same way.
+MAX_CHECK_PARKS_PER_TICK = 500
@frozen
@@ -291,6 +288,9 @@ def record_check_verdict(
config = parsed if isinstance(parsed, MetricThresholdConfig) else None
with transaction.atomic():
+ report = SignalReport.objects.select_for_update().filter(id=check.report_id, team_id=check.team_id).first()
+ if report is None or report.status != SignalReport.Status.RESOLVED:
+ return
current = (
SignalReportCheck.objects.for_team(check.team_id)
.select_for_update()
@@ -504,6 +504,54 @@ def _report_expired_checks(overdue: list[SignalReportCheck]) -> None:
logger.exception("signals.report_check.expired_report_failed")
+def park_checks_on_unresolved_reports(now: datetime) -> int:
+ """Move active checks whose report is not resolved back to `pending`. Returns how many moved.
+
+ A check can be active on an unresolved report in three ways: a report that left `resolved`
+ (reopened, archived, or restored somewhere else), a row written active before the create path
+ made the report decide, and any write path that skips `create_check`. Such a check must not run
+ or spend its error budget before a fix is live. As a pending row, the next resolve arms it
+ through `arm_pending_checks` with a fresh soak, and the expiry sweep retires it if the report
+ never resolves.
+
+ A dated row keeps the gap its author left as its soak. The error streak and any open dispatch
+ are cleared, so retry accounting starts again after the next resolve.
+ """
+ active = list(
+ SignalReportCheck.all_teams.filter(status=SignalReportCheck.Status.ACTIVE)
+ .exclude(report__status=SignalReport.Status.RESOLVED)
+ .only("id", "team_id", "created_at", "next_run_at", "soak_minutes", "last_run_at", "dispatched_at")[
+ :MAX_CHECK_PARKS_PER_TICK
+ ]
+ )
+ parked = 0
+ for check in active:
+ soak_minutes = check.soak_minutes
+ if soak_minutes is None:
+ # A legacy row's retry or recurring date no longer identifies its initial soak.
+ soak_minutes = (
+ DEFAULT_CHECK_SOAK_HOURS * 60
+ if check.last_run_at is not None or check.dispatched_at is not None
+ else soak_minutes_from_gap(check.next_run_at, check.created_at)
+ )
+ parked += (
+ SignalReportCheck.all_teams.filter(id=check.id, status=SignalReportCheck.Status.ACTIVE)
+ .exclude(report__status=SignalReport.Status.RESOLVED)
+ .update(
+ status=SignalReportCheck.Status.PENDING,
+ soak_minutes=soak_minutes,
+ next_run_at=now + timedelta(minutes=soak_minutes),
+ expires_at=now + MAX_CHECK_HORIZON,
+ consecutive_errors=0,
+ dispatched_at=None,
+ updated_at=now,
+ )
+ )
+ if parked:
+ logger.info("signals.report_check.parked_on_unresolved_report", parked=parked)
+ return parked
+
+
def collect_due_checks(now: datetime, *, limit: int = MAX_CHECK_RUNS_PER_TICK) -> list[SignalReportCheck]:
"""The checks to run this tick, most overdue first and capped per team.
@@ -517,7 +565,10 @@ def collect_due_checks(now: datetime, *, limit: int = MAX_CHECK_RUNS_PER_TICK) -
status=SignalReportCheck.Status.ACTIVE,
next_run_at__lte=now,
expires_at__gt=now,
- report__status__in=CHECKABLE_REPORT_STATUSES,
+ # A check re-measures a fix, so it runs only while its report is resolved. The park step
+ # moves any other active row back to `pending`; this filter keeps a row it has not reached
+ # yet out of the tick.
+ report__status=SignalReport.Status.RESOLVED,
)
.select_related("report", "report__team", "team__organization")
# Rank each team's rows against its own, then read those ranks in order, so every team's
@@ -546,7 +597,7 @@ def collect_due_checks(now: datetime, *, limit: int = MAX_CHECK_RUNS_PER_TICK) -
def run_due_report_checks(*, now: datetime | None = None, limit: int = MAX_CHECK_RUNS_PER_TICK) -> CheckRunSummary:
- """Expire what timed out, then advance every check due this tick by one step.
+ """Expire what timed out, park what lost its resolve, then advance every due check by one step.
A `metric_threshold` check is measured and recorded here. An `agent` check is dispatched (or
its overdue dispatch is written off), and the run it started records the verdict later, so the
@@ -555,6 +606,7 @@ def run_due_report_checks(*, now: datetime | None = None, limit: int = MAX_CHECK
now = now or timezone.now()
expired = expire_overdue_checks(now)
+ park_checks_on_unresolved_reports(now)
deadline = time.monotonic() + CHECK_RUN_TIME_BUDGET_SECONDS
counts: dict[str, int] = {"passed": 0, "failed": 0, "errored": 0, "dispatched": 0, "deferred": 0}
for check in collect_due_checks(now, limit=limit):
diff --git a/products/signals/backend/report_checks.py b/products/signals/backend/report_checks.py
index 8cc6545746d4..b84c26728995 100644
--- a/products/signals/backend/report_checks.py
+++ b/products/signals/backend/report_checks.py
@@ -24,7 +24,7 @@ Temporal payload modules import it during process setup.
from __future__ import annotations
from collections.abc import Mapping
-from datetime import timedelta
+from datetime import datetime, timedelta
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
@@ -257,6 +257,16 @@ class AgentCheckConfig(BaseModel):
return hints
+def soak_minutes_from_gap(next_run_at: datetime, since: datetime) -> int:
+ """The soak a dated check keeps while its report has not resolved.
+
+ The author left a gap before the first run to allow for deploy and soak time, so that gap is
+ what the check waits out once the report resolves, bounded by what a soak may be.
+ """
+ minutes = round((next_run_at - since).total_seconds() / 60)
+ return max(MIN_CHECK_SOAK_HOURS * 60, min(minutes, MAX_CHECK_SOAK_HOURS * 60))
+
+
CHECK_CONFIG_SCHEMAS: Mapping[str, type[BaseModel]] = {
"metric_threshold": MetricThresholdConfig,
"agent": AgentCheckConfig,
diff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.py
index 37dbd95dba79..5350466c9de3 100644
--- a/products/signals/backend/test/test_report_checks.py
+++ b/products/signals/backend/test/test_report_checks.py
@@ -34,6 +34,7 @@ from products.signals.backend.report_check_agent import (
FALLBACK_CHECK_SKILL_NAME,
build_check_run_note,
resolve_check_skill_name,
+ run_agent_check,
)
from products.signals.backend.report_check_authoring import (
CheckCreationError,
@@ -65,6 +66,7 @@ from products.signals.backend.report_checks import (
MAX_CHECK_SOAK_HOURS,
MAX_CONSECUTIVE_CHECK_ERRORS,
MIN_CHECK_INTERVAL_MINUTES,
+ MIN_CHECK_SOAK_HOURS,
AgentCheckConfig,
CheckComparison,
CheckConfigValidationError,
@@ -472,25 +474,65 @@ class TestReportCheckExecution(APIBaseTest):
# Named like the passed and failed lines, so a report with several checks stays readable.
assert "Checkout errors stay low could not be measured" in latest
- def test_a_suppressed_report_pauses_its_checks(self) -> None:
- self._check()
- self.report.status = SignalReport.Status.SUPPRESSED
+ @parameterized.expand(
+ [
+ ("reopened", SignalReport.Status.READY),
+ ("archived", SignalReport.Status.SUPPRESSED),
+ ("awaiting_input", SignalReport.Status.PENDING_INPUT),
+ ]
+ )
+ def test_an_active_check_on_an_unresolved_report_waits_for_the_next_resolve(self, _name, report_status) -> None:
+ # An active row on an open report: a report that left `resolved`, or a row written before
+ # the create path let the report decide. It must not run, and its old error streak must not
+ # count against the soak that follows the next resolve.
+ check = self._check(consecutive_errors=MAX_CONSECUTIVE_CHECK_ERRORS - 1)
+ self.report.status = report_status
self.report.save(update_fields=["status"])
+
+ with patch(_MEASURE) as measure:
+ summary = run_due_report_checks()
+
+ assert not measure.called
+ assert summary.errored == 0
+ assert self._results() == []
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.PENDING
+ assert check.consecutive_errors == 0
+
+ before = timezone.now()
+ with self.captureOnCommitCallbacks(execute=True):
+ self.report.status = SignalReport.Status.RESOLVED
+ self.report.save(update_fields=["status"])
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ACTIVE
+ assert check.next_run_at >= before + timedelta(hours=MIN_CHECK_SOAK_HOURS)
assert collect_due_checks(timezone.now()) == []
- self.report.status = SignalReport.Status.RESOLVED
+ def test_an_active_check_on_an_unresolved_report_is_never_due(self) -> None:
+ self._check()
+ self.report.status = SignalReport.Status.READY
self.report.save(update_fields=["status"])
- assert len(collect_due_checks(timezone.now())) == 1
- def test_a_check_cancelled_while_its_query_ran_records_nothing(self) -> None:
+ assert collect_due_checks(timezone.now()) == []
+
+ @parameterized.expand([("cancelled",), ("reopened",)])
+ def test_a_check_invalidated_while_its_query_ran_records_nothing(self, reason: str) -> None:
check = self._check()
- check.status = SignalReportCheck.Status.CANCELLED
- check.save(update_fields=["status"])
+ if reason == "cancelled":
+ check.status = SignalReportCheck.Status.CANCELLED
+ check.save(update_fields=["status"])
+ else:
+ self.report.status = SignalReport.Status.READY
+ self.report.save(update_fields=["status"])
record_check_verdict(check, CheckVerdict(outcome="passed", explanation="held", observed_value=1.0))
check.refresh_from_db()
- assert check.status == SignalReportCheck.Status.CANCELLED
+ assert check.status == (
+ SignalReportCheck.Status.CANCELLED if reason == "cancelled" else SignalReportCheck.Status.ACTIVE
+ )
+ assert check.last_run_at is None
assert self._results() == []
def test_an_unrun_check_past_its_horizon_expires(self) -> None:
@@ -848,6 +890,19 @@ class TestAgentCheckDispatch(APIBaseTest):
assert check.next_run_at > timezone.now() + AGENT_CHECK_RESULT_WINDOW - timedelta(minutes=5)
assert self._results() == []
+ def test_a_report_reopened_after_collection_does_not_dispatch_a_check(self) -> None:
+ check = self._check()
+ self.report.status = SignalReport.Status.READY
+ self.report.save(update_fields=["status"])
+
+ with patch(_CONNECT), patch(_DISPATCH) as dispatch:
+ assert run_agent_check(check) == "deferred"
+
+ dispatch.assert_not_called()
+ check.refresh_from_db()
+ assert check.dispatched_at is None
+ assert self._results() == []
+
def test_the_run_note_carries_the_brief_and_the_resolution_note(self) -> None:
SignalReportArtefact.append_dismissal(
team_id=self.team.id,
@@ -883,7 +938,6 @@ class TestAgentCheckDispatch(APIBaseTest):
@parameterized.expand(
[
- ("paused_lane", {"enabled": False, "status": SignalScoutConfig.Status.PAUSED_BY_USER}, "is paused"),
(
"warned_lane_still_runs",
{
@@ -949,29 +1003,45 @@ class TestAgentCheckDispatch(APIBaseTest):
assert dispatch.call_args.kwargs["skill_name"] == FALLBACK_CHECK_SKILL_NAME
assert self._results() == []
- def test_a_check_on_a_scout_a_person_paused_still_reports_the_refusal(self) -> None:
- # A pause is somebody's decision, so saying the check could not run is more honest than
- # quietly answering the question on another scout.
- LLMSkill.objects.create(team=self.team, name="signals-scout-health-checks", is_latest=True, deleted=False)
- SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-health-checks", enabled=False)
- self._check(
- config={
- "instructions": "Re-read the issue and say whether it still fires.",
- "skill_name": "signals-scout-health-checks",
- }
- )
+ @parameterized.expand([("named_lane", "signals-scout-health-checks"), ("fallback_lane", None)])
+ def test_a_check_on_a_paused_scout_waits_for_the_resume_without_spending_errors(self, _name, skill_name) -> None:
+ # A pause is somebody's decision, so the check neither runs on another scout nor burns its
+ # error budget while the pause lasts.
+ if skill_name is None:
+ scout_config = self.scout_config
+ scout_config.enabled = False
+ scout_config.save()
+ config = {"instructions": "Re-read the issue and say whether it still fires."}
+ else:
+ LLMSkill.objects.create(team=self.team, name=skill_name, is_latest=True, deleted=False)
+ scout_config = SignalScoutConfig.objects.create(team=self.team, skill_name=skill_name, enabled=False)
+ config = {"instructions": "Re-read the issue and say whether it still fires.", "skill_name": skill_name}
+ check = self._check(config=config)
- with patch(_CONNECT), patch(_DISPATCH) as dispatch, patch(_CAPTURE) as capture:
- with self.captureOnCommitCallbacks(execute=True):
+ for _ in range(MAX_CONSECUTIVE_CHECK_ERRORS):
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).update(
+ next_run_at=timezone.now() - timedelta(minutes=1)
+ )
+ with patch(_CONNECT), patch(_DISPATCH) as dispatch:
summary = run_due_report_checks()
+ assert summary.deferred == 1
+ dispatch.assert_not_called()
- assert summary.errored == 1
- dispatch.assert_not_called()
- assert "is paused" in self._results()[0].content
- properties = capture.call_args.kwargs["properties"]
- assert capture.call_args.kwargs["event"] == "signals_report_check_evaluated"
- assert properties["reason"] == "scout_paused"
- assert properties["skill_name"] == "signals-scout-health-checks"
+ assert self._results() == []
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ACTIVE
+ assert check.consecutive_errors == 0
+
+ scout_config.enabled = True
+ scout_config.save()
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).update(
+ next_run_at=timezone.now() - timedelta(minutes=1)
+ )
+ with patch(_CONNECT), patch(_DISPATCH, return_value="wf-1") as dispatch:
+ summary = run_due_report_checks()
+
+ assert summary.dispatched == 1
+ assert dispatch.call_args.kwargs["skill_name"] == (skill_name or FALLBACK_CHECK_SKILL_NAME)
def test_an_unenrolled_project_records_an_errored_result(self) -> None:
self._enrol({"guaranteed_team_ids": []})
@@ -1428,16 +1498,26 @@ class TestScoutCheckTools(APIBaseTest):
assert check.status == SignalReportCheck.Status.ACTIVE
assert before + soak <= check.next_run_at <= timezone.now() + soak
- def test_a_check_on_a_resolved_report_runs_on_the_date_the_run_named(self) -> None:
+ def test_a_recurring_check_keeps_its_initial_soak_after_reopening(self) -> None:
self.report.status = SignalReport.Status.RESOLVED
self.report.save(update_fields=["status"])
first_run = timezone.now() + timedelta(days=3)
- check = SignalReportCheck.objects.for_team(self.team.id).get(id=self._create(next_run_at=first_run).check_id)
+ check = SignalReportCheck.objects.for_team(self.team.id).get(
+ id=self._create(next_run_at=first_run, run_interval_minutes=24 * 60, runs_remaining=3).check_id
+ )
assert check.status == SignalReportCheck.Status.ACTIVE
assert check.next_run_at == first_run
- assert check.soak_minutes is None
+ assert check.soak_minutes == 3 * 24 * 60
+ record_check_verdict(check, CheckVerdict(outcome="passed", explanation="held"), now=first_run)
+ self.report.status = SignalReport.Status.READY
+ self.report.save(update_fields=["status"])
+ run_due_report_checks(now=first_run + timedelta(hours=1))
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.PENDING
+ assert check.soak_minutes == 3 * 24 * 60
def test_a_date_beyond_the_longest_soak_becomes_the_longest_soak(self) -> None:
check = SignalReportCheck.objects.for_team(self.team.id).get(