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): let scouts record due checks and see dispatched runs (#107465)

posthog[bot]a998e8213813
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index 02a3f0d36d62..1e12f7ed598e 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -508,7 +508,9 @@ The schedule is the check's own clock (`next_run_at`, optional `run_interval_min
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.
+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.
+
+`scout-report-check-list` returns a `run_state` for each check (`waiting_on_report`, `paused`, `scheduled`, `due`, `queued`, `running`, `stale`, or the terminal status), plus `waiting_on_run`, `dispatched_run_id` and `dispatched_at`. The run id is resolved from the run rows stamped with the check, so it stays null until the dispatched run starts.
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.
diff --git a/products/signals/backend/report_check_agent.py b/products/signals/backend/report_check_agent.py
index 511161c66343..ea1891fc3688 100644
--- a/products/signals/backend/report_check_agent.py
+++ b/products/signals/backend/report_check_agent.py
@@ -363,6 +363,7 @@ def run_agent_check(check: SignalReportCheck, *, now: datetime | None = None) ->
team_id=canonical_team_id,
skill_name=skill_name,
run_note=build_check_run_note(check, config),
+ check_id=str(check.id),
)
except WorkflowAlreadyStartedError:
# Another check on the same lane is still being answered. Theirs finishes, ours goes next
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 4356f764d528..55f7636fa7d0 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -147,6 +147,7 @@ def run_signals_scout(
verbose: bool = False,
triggered_by: str = TRIGGERED_BY_SCHEDULE,
run_note: str | None = None,
+ check_id: str | None = None,
) -> RunResult:
"""Synchronous entrypoint: resolves config, spawns sandbox, persists the run row.
@@ -162,6 +163,7 @@ def run_signals_scout(
verbose=verbose,
triggered_by=triggered_by,
run_note=run_note,
+ check_id=check_id,
)
)
@@ -175,6 +177,7 @@ async def arun_signals_scout(
verbose: bool = False,
triggered_by: str = TRIGGERED_BY_SCHEDULE,
run_note: str | None = None,
+ check_id: str | None = None,
) -> RunResult:
"""Async core. Safe to call from inside a running event loop (Temporal activity).
@@ -387,6 +390,7 @@ async def arun_signals_scout(
service_tier=service_tier,
triggered_by=triggered_by,
run_note=run_note,
+ check_id=check_id,
)
runtime_s = time.monotonic() - started
emitted_count, _ = await database_sync_to_async(_read_run_metrics, thread_sensitive=False)(
@@ -696,6 +700,7 @@ async def _spawn_and_run(
service_tier: str | None = None,
triggered_by: str = TRIGGERED_BY_SCHEDULE,
run_note: str | None = None,
+ check_id: str | None = None,
) -> tuple[str, str]:
"""Spawn the sandbox, create the bridge row before the first turn, run the agent.
@@ -844,6 +849,7 @@ async def _spawn_and_run(
repositories=repositories,
triggered_by=triggered_by,
run_note=run_note,
+ check_id=check_id,
)
# 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 —
@@ -1049,6 +1055,7 @@ def _create_run_row(
repositories: list[str] | None = None,
triggered_by: str = TRIGGERED_BY_SCHEDULE,
run_note: str | None = None,
+ check_id: str | None = None,
) -> SignalScoutRun:
# Stamp the routed model triple (and the OpenAI queue it asked for) onto the row's `metadata`
# so "which model ran this?" is a column read on the run API, not an analytics-event join. Keys
@@ -1120,6 +1127,10 @@ def _create_run_row(
# because the note is deliberately never stored as a scout note.
if run_note:
metadata["run_note"] = run_note
+ # The check a coordinator dispatch was started to answer. `scout-check-record-result` and
+ # `scout-report-check-list` read it to tie the check to this run.
+ if check_id:
+ metadata["check_id"] = check_id
return SignalScoutRun.objects.unscoped().create(
id=run_id,
task_run=task_run,
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index f0feb1a916ea..c5bcbf2e8b4a 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -777,6 +777,26 @@ class ScoutCheckSummarySerializer(serializers.Serializer):
last_outcome = serializers.CharField(
allow_null=True, help_text="Verdict of the most recent run; null before the first."
)
+ run_state = serializers.CharField(
+ help_text=(
+ "Where the check is in its run cycle. `waiting_on_report`: pending, no fix to measure yet. "
+ "`paused`: active, but its report is suppressed or its horizon passed, so nothing runs it. "
+ "`scheduled`: active, not due yet. `due`: due now, so a run on the check's scout may record the verdict. "
+ "`queued`: a run was dispatched and has not started. `running`: the dispatched run started and has "
+ "time left. `stale`: the dispatched run recorded nothing in its window, so the coordinator dispatches "
+ "again. Any other value is the terminal status."
+ )
+ )
+ waiting_on_run = serializers.BooleanField(
+ help_text="True while an `agent` check waits on a dispatched run to record its verdict."
+ )
+ dispatched_run_id = serializers.UUIDField(
+ allow_null=True,
+ help_text="The scout run the coordinator dispatched for the check, once it started. Null while queued.",
+ )
+ dispatched_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the coordinator last dispatched a run for the check. Null when no run waits."
+ )
class FleetFindingsSummarySerializer(serializers.Serializer):
diff --git a/products/signals/backend/scout_harness/tools/checks.py b/products/signals/backend/scout_harness/tools/checks.py
index b0e4ff5d66c4..05745bdd4b20 100644
--- a/products/signals/backend/scout_harness/tools/checks.py
+++ b/products/signals/backend/scout_harness/tools/checks.py
@@ -6,9 +6,12 @@ else closes it: the coordinator does not read the run's summary, and an agent th
then says nothing leaves a check its report can see is unanswered. That is deliberate. A verdict is
a claim recorded on the report, so it has to be a claim the run made on purpose.
-The binding is what keeps the tool narrow. A run may only close a check that its own lane was
-dispatched for and that is still waiting on a dispatch, so the broadest thing a compromised or
-confused run can do is answer the question it was actually asked.
+The binding is what keeps the tool narrow. A run may close the check it was dispatched for, which
+the dispatch stamps on the run row as `check_id`. A run on the check's own lane may also close one
+that is waiting on a run or is due now, so a scout that measures a due check in passing can record
+what it found. A due check the coordinator would not dispatch, because its report is suppressed or
+its horizon passed, is paused, and no run closes it. The broadest thing a compromised or confused run can do is answer a question its own
+scout owes.
The authoring tools are the other direction: a run that surfaces something whose fix will show in
data writes the re-measurement down instead of leaving a note for a future run to find. They write
@@ -23,13 +26,14 @@ import uuid
from datetime import datetime
from django.db.models.functions import Coalesce
+from django.utils import timezone
from posthog.dataclasses import frozen
from posthog.models import Team
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.models import SignalReport, SignalReportCheck, SignalScoutRun
-from products.signals.backend.report_check_agent import resolve_check_skill_name
+from products.signals.backend.report_check_agent import AGENT_CHECK_RESULT_WINDOW, resolve_check_skill_name
from products.signals.backend.report_check_authoring import CheckCreationError, cancel_check, create_check
from products.signals.backend.report_check_execution import CheckVerdict, record_check_verdict
from products.signals.backend.report_checks import AgentCheckConfig, parse_check_config
@@ -59,6 +63,19 @@ class RecordCheckResultResult:
runs_remaining: int
+def _pause_reason(check: SignalReportCheck, report_status: str, now: datetime) -> str | None:
+ """Why the coordinator would not dispatch this check even when it is due, or None.
+
+ These are the filters `collect_due_checks` applies besides the clock, so an undispatched check
+ is `due` to a run only when the coordinator would dispatch it too.
+ """
+ if report_status != SignalReport.Status.RESOLVED:
+ return f"its report is `{report_status}`"
+ if check.expires_at <= now:
+ return "its horizon passed"
+ return None
+
+
def _resolve_dispatched_check(team: Team, run: SignalScoutRun, check_id: str) -> SignalReportCheck:
"""The check this run is allowed to close, or a refusal saying why it is not that check.
@@ -71,7 +88,7 @@ def _resolve_dispatched_check(team: Team, run: SignalScoutRun, check_id: str) ->
uuid.UUID(str(check_id))
except (ValueError, TypeError):
raise InvalidCheckResultError(f"check {check_id} not found")
- check = SignalReportCheck.all_teams.select_related("team__organization").filter(id=check_id).first()
+ check = SignalReportCheck.all_teams.select_related("team__organization", "report").filter(id=check_id).first()
if check is None:
raise InvalidCheckResultError(f"check {check_id} not found")
canonical_team_id = team.parent_team_id or team.id
@@ -79,10 +96,32 @@ def _resolve_dispatched_check(team: Team, run: SignalScoutRun, check_id: str) ->
raise InvalidCheckResultError(f"check {check_id} not found")
if check.kind != SignalReportCheck.Kind.AGENT:
raise InvalidCheckResultError(f"check {check_id} is a `{check.kind}` check, which the coordinator measures")
+ if check.status == SignalReportCheck.Status.PENDING:
+ raise InvalidCheckResultError(
+ f"check {check_id} waits for its report to resolve, so there is no fix to measure yet"
+ )
if check.status != SignalReportCheck.Status.ACTIVE:
raise InvalidCheckResultError(f"check {check_id} already finished as `{check.status}`")
+ # The dispatch stamps the check on the run it starts, so that run answers its check even when
+ # the lane resolves differently now. It answers once: its verdict clears `dispatched_at`, and a
+ # retry after a recurring check re-arms must not spend another run.
+ if (run.metadata or {}).get("check_id") == str(check.id):
+ if check.dispatched_at is None:
+ raise InvalidCheckResultError(
+ f"check {check_id} already has the verdict for the run dispatched to answer it"
+ )
+ return check
if check.dispatched_at is None:
- raise InvalidCheckResultError(f"check {check_id} is not waiting on a run, so it is not yours to close")
+ now = timezone.now()
+ if check.next_run_at > now:
+ raise InvalidCheckResultError(
+ f"check {check_id} is not due until {check.next_run_at.isoformat()}, so it is not yours to close yet"
+ )
+ pause_reason = _pause_reason(check, check.report.status, now)
+ if pause_reason is not None:
+ raise InvalidCheckResultError(
+ f"check {check_id} is paused because {pause_reason}, so nothing is owed on it"
+ )
config = parse_check_config(check.kind, check.config)
assert isinstance(config, AgentCheckConfig)
@@ -150,9 +189,42 @@ class ScoutCheckSummary:
status: str
next_run_at: datetime
last_outcome: str | None
+ # Where the check is in its run cycle. See `_run_state`.
+ run_state: str
+ # True while an `agent` check waits on a dispatched run to record its verdict.
+ waiting_on_run: bool = False
+ # The run the coordinator dispatched, once that run has started. Null while it is queued.
+ dispatched_run_id: str | None = None
+ # When the coordinator last dispatched a run for the check.
+ dispatched_at: datetime | None = None
+
+
+def _run_state(check: SignalReportCheck, report_status: str, dispatched_run_id: str | None, now: datetime) -> str:
+ """One word for where a check is, so a scout can tell a check it may answer from one it may not.
+
+ `waiting_on_report`: pending, and no fix to measure yet. `paused`: active, but its report is
+ suppressed or its horizon passed, so the coordinator does not dispatch it. `scheduled`: active,
+ not due yet. `due`: active and due now, so a run on its lane may record the verdict. `queued`:
+ dispatched, and the run has not started. `running`: the dispatched run started and has time
+ left. `stale`: the dispatched run had its whole window and recorded nothing, so the coordinator
+ records an errored run and dispatches again. Any other value is the terminal status.
+ """
+ if check.status == SignalReportCheck.Status.PENDING:
+ return "waiting_on_report"
+ if check.status != SignalReportCheck.Status.ACTIVE:
+ return check.status
+ if check.dispatched_at is None:
+ if _pause_reason(check, report_status, now) is not None:
+ return "paused"
+ return "due" if check.next_run_at <= now else "scheduled"
+ if check.dispatched_at + AGENT_CHECK_RESULT_WINDOW <= now:
+ return "stale"
+ return "running" if dispatched_run_id else "queued"
-def _summarize(check: SignalReportCheck) -> ScoutCheckSummary:
+def _summarize(
+ check: SignalReportCheck, report_status: str, dispatched_run_id: str | None = None, now: datetime | None = None
+) -> ScoutCheckSummary:
return ScoutCheckSummary(
check_id=str(check.id),
report_id=str(check.report_id),
@@ -162,9 +234,37 @@ def _summarize(check: SignalReportCheck) -> ScoutCheckSummary:
# Provisional on a pending check, whose clock the report's resolve starts.
next_run_at=check.next_run_at,
last_outcome=check.last_outcome,
+ run_state=_run_state(check, report_status, dispatched_run_id, now or timezone.now()),
+ # Cancel and expiry leave `dispatched_at` set, so only an open check can still owe a run.
+ waiting_on_run=check.status == SignalReportCheck.Status.ACTIVE and check.dispatched_at is not None,
+ dispatched_run_id=dispatched_run_id,
+ dispatched_at=check.dispatched_at,
)
+def _dispatched_run_ids(team_id: int, checks: list[SignalReportCheck]) -> dict[str, str]:
+ """The newest run each active dispatched check was stamped on, keyed by check id.
+
+ Bounded to runs created after the oldest dispatch, because the run row carries the check only
+ in its metadata and the table grows with every scout run. Terminal checks keep their dispatch
+ timestamps, so exclude them to prevent old checks from extending the scan into old run history.
+ """
+ dispatched = {
+ str(check.id): check.dispatched_at
+ for check in checks
+ if check.status == SignalReportCheck.Status.ACTIVE and check.dispatched_at is not None
+ }
+ if not dispatched:
+ return {}
+ runs = (
+ SignalScoutRun.objects.for_team(team_id)
+ .filter(created_at__gte=min(dispatched.values()), metadata__check_id__in=list(dispatched))
+ .order_by("created_at")
+ .values_list("id", "metadata__check_id")
+ )
+ return {str(check_id): str(run_id) for run_id, check_id in runs}
+
+
def _assert_run_may_write_checks(team: Team, run: SignalScoutRun) -> None:
"""Refuse a check write from a run whose other write channels are closed.
@@ -236,15 +336,21 @@ def create_report_check(
)
except CheckCreationError as error:
raise InvalidCheckWriteError(str(error)) from None
- return _summarize(check)
+ return _summarize(check, report.status)
def list_report_checks(*, team: Team, report_id: str) -> list[ScoutCheckSummary]:
"""Every check on one report, newest first. Read it before writing: a report already carrying a
check for the claim needs no second one, and the cap is five."""
report = _resolve_report(team, report_id)
- checks = SignalReportCheck.objects.for_team(report.team_id).filter(report_id=report.id).order_by("-created_at")
- return [_summarize(check) for check in checks[:MAX_CHECKS_LISTED]]
+ checks = list(
+ SignalReportCheck.objects.for_team(report.team_id)
+ .filter(report_id=report.id)
+ .order_by("-created_at")[:MAX_CHECKS_LISTED]
+ )
+ run_ids = _dispatched_run_ids(team.parent_team_id or team.id, checks)
+ now = timezone.now()
+ return [_summarize(check, report.status, run_ids.get(str(check.id)), now) for check in checks]
def _run_attribution(run: SignalScoutRun) -> ArtefactAttribution:
@@ -260,7 +366,7 @@ def cancel_report_check(*, team: Team, run: SignalScoutRun, check_id: str) -> Sc
uuid.UUID(str(check_id))
except (ValueError, TypeError):
raise InvalidCheckWriteError(f"check {check_id} not found")
- check = SignalReportCheck.all_teams.select_related("team").filter(id=check_id).first()
+ check = SignalReportCheck.all_teams.select_related("team", "report").filter(id=check_id).first()
if check is None:
raise InvalidCheckWriteError(f"check {check_id} not found")
canonical_team_id = team.parent_team_id or team.id
@@ -268,4 +374,4 @@ def cancel_report_check(*, team: Team, run: SignalScoutRun, check_id: str) -> Sc
raise InvalidCheckWriteError(f"check {check_id} not found")
if not cancel_check(check, reason="stopped_by_scout", attribution=_run_attribution(run)):
raise InvalidCheckWriteError(f"check {check_id} already finished as `{check.status}` and cannot be cancelled")
- return _summarize(check)
+ return _summarize(check, check.report.status)
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 5232242363d9..f7ae4e9fe930 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -1760,8 +1760,9 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
),
400: OpenApiResponse(
description=(
- "The check does not exist for this project, already finished, is measured by the "
- "coordinator rather than a run, runs on another scout, or is not waiting on a run."
+ "The check does not exist for this project, already finished, waits for its report to "
+ "resolve, is measured by the coordinator rather than a run, runs on another scout, or is "
+ "neither waiting on a run nor due."
)
),
404: OpenApiResponse(description="Run not found for this project."),
@@ -1773,7 +1774,8 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"investigates and says nothing leaves the check unanswered. The verdict lands on the report as a "
"`check_result` entry people read in the inbox. `failed` retires the check, `passed` re-arms a "
"recurring one, and `errored` retries it, so send the outcome you actually reached rather than "
- "the one that closes the loop. A run may only close a check dispatched to its own scout."
+ "the one that closes the loop. A run may close the check it was dispatched for, or a check on its own "
+ "scout that is due or waiting on a run."
),
operation_id="signals_scout_record_check_result",
)
diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.py
index 17d40beca184..b35f853cbaf9 100644
--- a/products/signals/backend/temporal/agentic/scout_scheduler.py
+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py
@@ -60,6 +60,9 @@ class RunSignalsScoutInput:
# One-off steering typed alongside a manual trigger. Never set on a scheduled dispatch,
# where standing steering is a scout note instead.
run_note: str | None = None
+ # The report check a `check` dispatch answers. Stamped on the run row so the check can name
+ # its run and the run can record the check's verdict.
+ check_id: str | None = None
@frozen
@@ -197,6 +200,7 @@ async def _run_signals_scout(input: RunSignalsScoutInput) -> RunSignalsScoutOutp
repository=input.repository,
triggered_by=input.triggered_by,
run_note=input.run_note,
+ check_id=input.check_id,
)
except (OperationalError, InterfaceError):
# Transient DB connection drop (pgbouncer pool recycle / failover / deploy). Stay
@@ -316,6 +320,7 @@ async def _start_off_schedule_run(
source: str,
workflow_origin_key: str | None = None,
run_note: str | None = None,
+ check_id: str | None = None,
) -> str:
"""Start one `RunSignalsScoutWorkflow` off-schedule under `workflow_id`; return the id.
@@ -337,6 +342,7 @@ async def _start_off_schedule_run(
triggered_by=source,
workflow_origin_key=workflow_origin_key,
run_note=run_note,
+ check_id=check_id,
),
id=workflow_id,
task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
@@ -370,7 +376,9 @@ def check_run_workflow_id(team_id: int, skill_name: str) -> str:
return _off_schedule_run_workflow_id("signals-scout-check-run", team_id, skill_name)
-def start_check_signals_scout_run(client: Client, *, team_id: int, skill_name: str, run_note: str) -> str:
+def start_check_signals_scout_run(
+ client: Client, *, team_id: int, skill_name: str, run_note: str, check_id: str
+) -> str:
"""Dispatch one scout run to answer a report check; return its workflow id.
Its own id namespace, like the manual and workflow paths, so a check dispatch and a human's
@@ -388,6 +396,7 @@ def start_check_signals_scout_run(client: Client, *, team_id: int, skill_name: s
skill_name=skill_name,
source=TRIGGERED_BY_CHECK,
run_note=run_note,
+ check_id=check_id,
)
diff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.py
index 5350466c9de3..c2bad5f43119 100644
--- a/products/signals/backend/test/test_report_checks.py
+++ b/products/signals/backend/test/test_report_checks.py
@@ -924,6 +924,35 @@ class TestAgentCheckDispatch(APIBaseTest):
assert "Shipped the retry fix" in note
assert "scout-check-record-result" in note
+ def test_a_dispatched_run_is_listed_on_its_check_and_records_its_verdict(self) -> None:
+ check = self._check()
+ with patch(_CONNECT), patch(_DISPATCH, return_value="wf-1") as dispatch:
+ run_due_report_checks()
+ assert dispatch.call_args.kwargs["check_id"] == str(check.id)
+
+ (queued,) = list_report_checks(team=self.team, report_id=str(self.report.id))
+ assert (queued.run_state, queued.waiting_on_run, queued.dispatched_run_id) == ("queued", True, None)
+
+ task = Task.objects.create(team=self.team, title="t", description="d")
+ run = SignalScoutRun.objects.create(
+ task_run=TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS),
+ team=self.team,
+ scout_config=self.scout_config,
+ skill_name=FALLBACK_CHECK_SKILL_NAME,
+ skill_version=1,
+ metadata={"check_id": dispatch.call_args.kwargs["check_id"]},
+ )
+ (running,) = list_report_checks(team=self.team, report_id=str(self.report.id))
+ assert (running.run_state, running.dispatched_run_id) == ("running", str(run.id))
+
+ result = record_check_result(
+ team=self.team, run=run, check_id=str(check.id), outcome="passed", explanation="No events since the fix."
+ )
+
+ assert result.check_status == SignalReportCheck.Status.PASSED
+ (closed,) = list_report_checks(team=self.team, report_id=str(self.report.id))
+ assert (closed.run_state, closed.waiting_on_run) == (SignalReportCheck.Status.PASSED, False)
+
def test_a_check_naming_a_scout_runs_on_that_scout(self) -> None:
LLMSkill.objects.create(team=self.team, name=_OTHER_SKILL, is_latest=True, deleted=False)
SignalScoutConfig.objects.create(
@@ -1170,21 +1199,29 @@ class TestCheckResultTool(APIBaseTest):
assert "fired 30 times yesterday" in artefact.content
assert f'"run_id":"{self.scout_run.id}"' in artefact.content
- def test_a_pass_rearms_a_recurring_check_for_its_next_look(self) -> None:
+ @parameterized.expand([("on_its_lane", False), ("bound_to_the_run", True)])
+ def test_a_pass_rearms_a_recurring_check_for_its_next_look(self, _name, bind_run) -> None:
check = self._check(run_interval_minutes=MIN_CHECK_INTERVAL_MINUTES, runs_remaining=2)
+ if bind_run:
+ self.scout_run.metadata = {"check_id": str(check.id)}
+ self.scout_run.save(update_fields=["metadata"])
result = self._record(check, outcome="passed", explanation="No events since the fix merged.")
assert result.check_status == SignalReportCheck.Status.ACTIVE
assert result.runs_remaining == 1
+ with self.assertRaises(InvalidCheckResultError):
+ self._record(check, outcome="passed", explanation="No events since the fix merged.")
check.refresh_from_db()
assert check.dispatched_at is None
+ assert check.runs_remaining == 1
assert check.next_run_at > timezone.now() + timedelta(minutes=MIN_CHECK_INTERVAL_MINUTES - 5)
@parameterized.expand(
[
- ("no_run_is_waiting", {"dispatched_at": None}),
+ ("not_due_and_no_run_is_waiting", {"dispatched_at": None}),
("already_finished", {"status": SignalReportCheck.Status.CANCELLED}),
+ ("waiting_for_its_report", {"status": SignalReportCheck.Status.PENDING, "dispatched_at": None}),
("another_scout_owns_it", {"config": {"instructions": "x", "skill_name": _OTHER_SKILL}}),
("the_coordinator_measures_it", {"kind": SignalReportCheck.Kind.METRIC_THRESHOLD}),
]
@@ -1199,6 +1236,49 @@ class TestCheckResultTool(APIBaseTest):
report=self.report, type=SignalReportArtefact.ArtefactType.CHECK_RESULT
).exists()
+ @parameterized.expand(
+ [
+ ("due_and_not_dispatched_yet", {"dispatched_at": None, "next_run_at": timezone.now()}, False),
+ (
+ "dispatched_to_this_run_on_a_lane_that_resolves_elsewhere_now",
+ {"config": {"instructions": "x", "skill_name": _OTHER_SKILL}},
+ True,
+ ),
+ ]
+ )
+ def test_a_check_this_run_may_answer_is_recorded(self, _name, overrides, bind_run) -> None:
+ check = self._check(**overrides)
+ if bind_run:
+ self.scout_run.metadata = {"check_id": str(check.id)}
+ self.scout_run.save(update_fields=["metadata"])
+
+ result = self._record(check)
+
+ assert result.check_status == SignalReportCheck.Status.FAILED
+
+ @parameterized.expand(
+ [
+ ("its_report_is_ready", SignalReport.Status.READY, timedelta(days=30)),
+ ("its_report_is_suppressed", SignalReport.Status.SUPPRESSED, timedelta(days=30)),
+ ("its_horizon_passed", SignalReport.Status.RESOLVED, -timedelta(minutes=1)),
+ ]
+ )
+ def test_a_due_check_the_coordinator_would_not_dispatch_is_paused(self, _name, report_status, expires_in) -> None:
+ SignalReport.objects.filter(id=self.report.id).update(status=report_status)
+ now = timezone.now()
+ check = self._check(dispatched_at=None, next_run_at=now - timedelta(hours=1), expires_at=now + expires_in)
+
+ (listed,) = list_report_checks(team=self.team, report_id=str(self.report.id))
+ assert listed.run_state == "paused"
+ with self.assertRaises(InvalidCheckResultError):
+ self._record(check)
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ACTIVE
+ assert not SignalReportArtefact.objects.filter(
+ report=self.report, type=SignalReportArtefact.ArtefactType.CHECK_RESULT
+ ).exists()
+
def test_another_projects_check_is_not_reachable(self) -> None:
other_team = self.organization.teams.create(name="Other")
other_report = SignalReport.objects.create(team=other_team, status=SignalReport.Status.RESOLVED)
@@ -1534,11 +1614,22 @@ class TestScoutCheckTools(APIBaseTest):
assert [summary.check_id for summary in listed] == [written.check_id]
def test_cancelling_stops_the_check_and_refuses_a_second_cancel(self) -> None:
- written = self._create()
+ written = self._create(kind=SignalReportCheck.Kind.AGENT, config={"instructions": "Re-read the issue."})
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=written.check_id).update(
+ status=SignalReportCheck.Status.ACTIVE, dispatched_at=timezone.now() - timedelta(days=30)
+ )
+ self.scout_run.metadata = {"check_id": written.check_id}
+ self.scout_run.save(update_fields=["metadata"])
cancelled = cancel_report_check(team=self.team, run=self.scout_run, check_id=written.check_id)
- assert cancelled.status == SignalReportCheck.Status.CANCELLED
+ assert (cancelled.status, cancelled.waiting_on_run) == (SignalReportCheck.Status.CANCELLED, False)
+ (listed,) = list_report_checks(team=self.team, report_id=str(self.report.id))
+ assert (listed.run_state, listed.waiting_on_run, listed.dispatched_run_id) == (
+ SignalReportCheck.Status.CANCELLED,
+ False,
+ None,
+ )
with self.assertRaises(InvalidCheckWriteError):
cancel_report_check(team=self.team, run=self.scout_run, check_id=written.check_id)
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 2d65d09d7b43..855c8fb5dc69 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -5602,6 +5602,20 @@ export interface ScoutCheckSummaryApi {
* @nullable
*/
last_outcome: string | null
+ /** Where the check is in its run cycle. `waiting_on_report`: pending, no fix to measure yet. `paused`: active, but its report is suppressed or its horizon passed, so nothing runs it. `scheduled`: active, not due yet. `due`: due now, so a run on the check's scout may record the verdict. `queued`: a run was dispatched and has not started. `running`: the dispatched run started and has time left. `stale`: the dispatched run recorded nothing in its window, so the coordinator dispatches again. Any other value is the terminal status. */
+ run_state: string
+ /** True while an `agent` check waits on a dispatched run to record its verdict. */
+ waiting_on_run: boolean
+ /**
+ * The scout run the coordinator dispatched for the check, once it started. Null while queued.
+ * @nullable
+ */
+ dispatched_run_id: string | null
+ /**
+ * When the coordinator last dispatched a run for the check. Null when no run waits.
+ * @nullable
+ */
+ dispatched_at: string | null
}
/**
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 41f294dd26de..c19cc7393939 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -1593,7 +1593,7 @@ export const getSignalsScoutRecordCheckResultUrl = (projectId: string, runId: st
}
/**
- * Close the follow-up check this run was dispatched to answer. The run note carries the check id and what to establish; this call is the only thing that records the answer, so a run that investigates and says nothing leaves the check unanswered. The verdict lands on the report as a `check_result` entry people read in the inbox. `failed` retires the check, `passed` re-arms a recurring one, and `errored` retries it, so send the outcome you actually reached rather than the one that closes the loop. A run may only close a check dispatched to its own scout.
+ * Close the follow-up check this run was dispatched to answer. The run note carries the check id and what to establish; this call is the only thing that records the answer, so a run that investigates and says nothing leaves the check unanswered. The verdict lands on the report as a `check_result` entry people read in the inbox. `failed` retires the check, `passed` re-arms a recurring one, and `errored` retries it, so send the outcome you actually reached rather than the one that closes the loop. A run may close the check it was dispatched for, or a check on its own scout that is due or waiting on a run.
* @summary Record the verdict on a report check
*/
export const signalsScoutRecordCheckResult = async (
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 86f64a42c7b1..690d59ce2199 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -1286,7 +1286,7 @@ export const SignalsScoutNotesCreateBody = /* @__PURE__ */ zod
.describe('Request body for `notes-create`.')
/**
- * Close the follow-up check this run was dispatched to answer. The run note carries the check id and what to establish; this call is the only thing that records the answer, so a run that investigates and says nothing leaves the check unanswered. The verdict lands on the report as a `check_result` entry people read in the inbox. `failed` retires the check, `passed` re-arms a recurring one, and `errored` retries it, so send the outcome you actually reached rather than the one that closes the loop. A run may only close a check dispatched to its own scout.
+ * Close the follow-up check this run was dispatched to answer. The run note carries the check id and what to establish; this call is the only thing that records the answer, so a run that investigates and says nothing leaves the check unanswered. The verdict lands on the report as a `check_result` entry people read in the inbox. `failed` retires the check, `passed` re-arms a recurring one, and `errored` retries it, so send the outcome you actually reached rather than the one that closes the loop. A run may close the check it was dispatched for, or a check on its own scout that is due or waiting on a run.
* @summary Record the verdict on a report check
*/
export const signalsScoutRecordCheckResultBodyExplanationMax = 1000
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index a73663086722..ef91df93dccd 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -517,8 +517,11 @@ tools:
understand. The verdict lands on the report as a `check_result` entry in the inbox. Record what you
established rather than what closes the loop: `failed` retires the check, `passed` re-arms a recurring one,
and `errored` retries it. Nothing else closes a check, so a run that investigates and never calls this
- leaves the report with an unanswered follow-up. The call is refused for a check dispatched to another scout,
- one no run is waiting on, and one the coordinator measures itself.
+ leaves the report with an unanswered follow-up. You may also record a check on your own scout whose
+ `run_state` in `scout-report-check-list` is `due`, `queued`, `running`, or `stale`. The call is refused for
+ a check on another scout, a `pending` check whose report has not resolved, a check that is not due yet, a
+ `paused` check whose report is suppressed or whose horizon passed, a check your run already answered, and a
+ check the coordinator measures itself.
scout-config-create:
operation: signals_scout_config_create
enabled: true
@@ -968,7 +971,9 @@ tools:
the `report_id` of the report to read; no `run_id` is needed. Read this before writing a check: a report
already carrying one for the same claim needs no second, and a report holds at most five open checks at a
time. A `pending` check is waiting for the report to resolve before its clock starts; every status other
- than `pending` and `active` is terminal.
+ than `pending` and `active` is terminal. `run_state` says where an open check is: `waiting_on_report`,
+ `paused`, `scheduled`, `due`, `queued`, `running`, or `stale`. For an `agent` check, `waiting_on_run`,
+ `dispatched_run_id`, and `dispatched_at` name the run the coordinator dispatched and when.
scout-report-checks-list:
operation: signals_scout_report_check_list
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 6c311218a355..a4d48672fb71 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10203,7 +10203,7 @@
}
},
"scout-check-record-result": {
- "description": "Close the follow-up check your run was dispatched to answer, and only that check. A report check says what had to stay true after the report was acted on; your run note carries its `check_id` and what to establish. Pass the `run_id`, the `check_id`, an `outcome` of `passed` (it still holds), `failed` (it does not), or `errored` (you could not settle it either way), and an `explanation` a person reading the report will understand. The verdict lands on the report as a `check_result` entry in the inbox. Record what you established rather than what closes the loop: `failed` retires the check, `passed` re-arms a recurring one, and `errored` retries it. Nothing else closes a check, so a run that investigates and never calls this leaves the report with an unanswered follow-up. The call is refused for a check dispatched to another scout, one no run is waiting on, and one the coordinator measures itself.",
+ "description": "Close the follow-up check your run was dispatched to answer, and only that check. A report check says what had to stay true after the report was acted on; your run note carries its `check_id` and what to establish. Pass the `run_id`, the `check_id`, an `outcome` of `passed` (it still holds), `failed` (it does not), or `errored` (you could not settle it either way), and an `explanation` a person reading the report will understand. The verdict lands on the report as a `check_result` entry in the inbox. Record what you established rather than what closes the loop: `failed` retires the check, `passed` re-arms a recurring one, and `errored` retries it. Nothing else closes a check, so a run that investigates and never calls this leaves the report with an unanswered follow-up. You may also record a check on your own scout whose `run_state` in `scout-report-check-list` is `due`, `queued`, `running`, or `stale`. The call is refused for a check on another scout, a `pending` check whose report has not resolved, a check that is not due yet, a `paused` check whose report is suppressed or whose horizon passed, a check your run already answered, and a check the coordinator measures itself.",
"category": "Signals",
"feature": "signals",
"summary": "Record the verdict on a report check",
@@ -10483,7 +10483,7 @@
}
},
"scout-report-check-list": {
- "description": "Every follow-up check on one report, newest first, with its kind, status, next run and last verdict. Pass the `report_id` of the report to read; no `run_id` is needed. Read this before writing a check: a report already carrying one for the same claim needs no second, and a report holds at most five open checks at a time. A `pending` check is waiting for the report to resolve before its clock starts; every status other than `pending` and `active` is terminal.",
+ "description": "Every follow-up check on one report, newest first, with its kind, status, next run and last verdict. Pass the `report_id` of the report to read; no `run_id` is needed. Read this before writing a check: a report already carrying one for the same claim needs no second, and a report holds at most five open checks at a time. A `pending` check is waiting for the report to resolve before its clock starts; every status other than `pending` and `active` is terminal. `run_state` says where an open check is: `waiting_on_report`, `paused`, `scheduled`, `due`, `queued`, `running`, or `stale`. For an `agent` check, `waiting_on_run`, `dispatched_run_id`, and `dispatched_at` name the run the coordinator dispatched and when.",
"category": "Signals",
"feature": "signals",
"summary": "List a report's follow-up checks",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 382117256497..7bc6661ce7f4 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10778,7 +10778,7 @@
}
},
"scout-check-record-result": {
- "description": "Close the follow-up check your run was dispatched to answer, and only that check. A report check says what had to stay true after the report was acted on; your run note carries its `check_id` and what to establish. Pass the `run_id`, the `check_id`, an `outcome` of `passed` (it still holds), `failed` (it does not), or `errored` (you could not settle it either way), and an `explanation` a person reading the report will understand. The verdict lands on the report as a `check_result` entry in the inbox. Record what you established rather than what closes the loop: `failed` retires the check, `passed` re-arms a recurring one, and `errored` retries it. Nothing else closes a check, so a run that investigates and never calls this leaves the report with an unanswered follow-up. The call is refused for a check dispatched to another scout, one no run is waiting on, and one the coordinator measures itself.",
+ "description": "Close the follow-up check your run was dispatched to answer, and only that check. A report check says what had to stay true after the report was acted on; your run note carries its `check_id` and what to establish. Pass the `run_id`, the `check_id`, an `outcome` of `passed` (it still holds), `failed` (it does not), or `errored` (you could not settle it either way), and an `explanation` a person reading the report will understand. The verdict lands on the report as a `check_result` entry in the inbox. Record what you established rather than what closes the loop: `failed` retires the check, `passed` re-arms a recurring one, and `errored` retries it. Nothing else closes a check, so a run that investigates and never calls this leaves the report with an unanswered follow-up. You may also record a check on your own scout whose `run_state` in `scout-report-check-list` is `due`, `queued`, `running`, or `stale`. The call is refused for a check on another scout, a `pending` check whose report has not resolved, a check that is not due yet, a `paused` check whose report is suppressed or whose horizon passed, a check your run already answered, and a check the coordinator measures itself.",
"category": "Signals",
"feature": "signals",
"summary": "Record the verdict on a report check",
@@ -11058,7 +11058,7 @@
}
},
"scout-report-check-list": {
- "description": "Every follow-up check on one report, newest first, with its kind, status, next run and last verdict. Pass the `report_id` of the report to read; no `run_id` is needed. Read this before writing a check: a report already carrying one for the same claim needs no second, and a report holds at most five open checks at a time. A `pending` check is waiting for the report to resolve before its clock starts; every status other than `pending` and `active` is terminal.",
+ "description": "Every follow-up check on one report, newest first, with its kind, status, next run and last verdict. Pass the `report_id` of the report to read; no `run_id` is needed. Read this before writing a check: a report already carrying one for the same claim needs no second, and a report holds at most five open checks at a time. A `pending` check is waiting for the report to resolve before its clock starts; every status other than `pending` and `active` is terminal. `run_state` says where an open check is: `waiting_on_report`, `paused`, `scheduled`, `due`, `queued`, `running`, or `stale`. For an `agent` check, `waiting_on_run`, `dispatched_run_id`, and `dispatched_at` name the run the coordinator dispatched and when.",
"category": "Signals",
"feature": "signals",
"summary": "List a report's follow-up checks",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f276d860d0ce..54824070f19e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -89456,6 +89456,20 @@ export namespace Schemas {
* @nullable
*/
last_outcome: string | null;
+ /** Where the check is in its run cycle. `waiting_on_report`: pending, no fix to measure yet. `paused`: active, but its report is suppressed or its horizon passed, so nothing runs it. `scheduled`: active, not due yet. `due`: due now, so a run on the check's scout may record the verdict. `queued`: a run was dispatched and has not started. `running`: the dispatched run started and has time left. `stale`: the dispatched run recorded nothing in its window, so the coordinator dispatches again. Any other value is the terminal status. */
+ run_state: string;
+ /** True while an `agent` check waits on a dispatched run to record its verdict. */
+ waiting_on_run: boolean;
+ /**
+ * The scout run the coordinator dispatched for the check, once it started. Null while queued.
+ * @nullable
+ */
+ dispatched_run_id: string | null;
+ /**
+ * When the coordinator last dispatched a run for the check. Null when no run waits.
+ * @nullable
+ */
+ dispatched_at: string | null;
}
/**
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 405ae37c66a6..00ddbd69fa24 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -1613,7 +1613,7 @@ export const SignalsScoutRunsRetrieveParams = () => zod.object({
})
/**
- * Close the follow-up check this run was dispatched to answer. The run note carries the check id and what to establish; this call is the only thing that records the answer, so a run that investigates and says nothing leaves the check unanswered. The verdict lands on the report as a `check_result` entry people read in the inbox. `failed` retires the check, `passed` re-arms a recurring one, and `errored` retries it, so send the outcome you actually reached rather than the one that closes the loop. A run may only close a check dispatched to its own scout.
+ * Close the follow-up check this run was dispatched to answer. The run note carries the check id and what to establish; this call is the only thing that records the answer, so a run that investigates and says nothing leaves the check unanswered. The verdict lands on the report as a `check_result` entry people read in the inbox. `failed` retires the check, `passed` re-arms a recurring one, and `errored` retries it, so send the outcome you actually reached rather than the one that closes the loop. A run may close the check it was dispatched for, or a check on its own scout that is due or waiting on a run.
* @summary Record the verdict on a report check
*/
export const SignalsScoutRecordCheckResultParams = () => zod.object({