Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): schedule follow-up checks on a report (#99797)

posthog[bot]00dc5bf64a50
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 12b927d3a139..67b78fbe70c2 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -335,6 +335,7 @@ rules:
|SignalReport
|SignalReportAction
|SignalReportArtefact
+ |SignalReportCheck
|SignalReportGithubComment
|SignalReportPullRequest
|SignalReportAssignment
@@ -740,6 +741,7 @@ rules:
|SignalReport
|SignalReportAction
|SignalReportArtefact
+ |SignalReportCheck
|SignalReportGithubComment
|SignalReportPullRequest
|SignalReportAssignment
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index 8d4f358b1c16..d80f5fffd9b8 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -168,6 +168,7 @@ class TestSignalsProductModuleIntegrity:
"wait_for_signal_in_clickhouse_activity",
"fetch_enabled_signals_scout_runs_activity",
"stamp_dispatched_signals_scout_runs_activity",
+ "run_due_signal_report_checks_activity",
"run_signals_scout_activity",
"resume_signals_scout_workflow_step",
"plan_scout_suggestion_runs_activity",
@@ -185,6 +186,18 @@ class TestSignalsProductModuleIntegrity:
f"Activity '{expected}' is missing from SIGNALS_PRODUCT_ACTIVITIES."
)
+ def test_every_scout_coordinator_activity_is_registered(self):
+ """A name list cannot catch an activity nobody added, and the worker rejects an unknown one."""
+ from products.signals.backend.temporal.agentic import scout_coordinator
+
+ defined = {
+ name
+ for name, value in vars(scout_coordinator).items()
+ if callable(value) and getattr(value, "__temporal_activity_definition", None) is not None
+ }
+ missing = defined - {a.__name__ for a in SIGNALS_PRODUCT_ACTIVITIES}
+ assert not missing, f"Activities defined but not registered: {sorted(missing)}"
+
class TestAIObservabilityModuleIntegrity:
def test_workflows_remain_unchanged(self):
diff --git a/products/alerts/backend/facade/evaluation.py b/products/alerts/backend/facade/evaluation.py
new file mode 100644
index 000000000000..17cb857c8f24
--- /dev/null
+++ b/products/alerts/backend/facade/evaluation.py
@@ -0,0 +1,11 @@
+"""Threshold comparison for other products to reuse.
+
+`evaluate_threshold` is the one place that decides whether a value is out of bounds, so an adopter
+that compares a measured number against a threshold (a signals report check, for instance) words a
+breach the same way an insight alert does. The series types are the input shape it expects.
+"""
+
+from products.alerts.backend.evaluation.comparator import evaluate_threshold
+from products.alerts.backend.evaluation.contract import ComparableSeries, ExtractionResult, SeriesPoint
+
+__all__ = ["ComparableSeries", "ExtractionResult", "SeriesPoint", "evaluate_threshold"]
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index 971835601824..dfc88c2a5991 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -473,6 +473,7 @@ An **append-only, attributed, schema-validated log of the work done on a report*
| `commit` | `{"repository": "owner/repo", "branch": "...", "commit_sha": "...", "message": "...", "note"?: "..."}` — one pushed commit |
| `task_run` | `{"task_id": "...", "run_id"?: "...", "product": "...", "type": "..."}` — a task run associated with the report (see below) |
| `note` | `{"note": "...", "author"?: "..."}` — free-form note (markdown allowed) |
+| `check_result` | `{"check_id": "...", "kind": "...", "title": "...", "outcome": "passed"\|"failed"\|"errored", "explanation": "...", "observed_value"?, "baseline_value"?, "threshold"?}` — one run of a report check |
**Content schemas.** `artefact_schemas.py` is the canonical, pydantic-only home of every content shape, collected in `ARTEFACT_CONTENT_SCHEMAS` (one model per type; a test asserts exact coverage). Raw payloads become typed models once, at the boundaries (`parse_artefact_content`); the model helpers derive a row's type from the content model's class (`artefact_type_for`), so a type can never mismatch its content. `repo_selection` reuses the tasks product's `RepoSelectionResult` DTO directly (kept in the dependency-light leaf module `repo_selection/types.py` so importing the schema registry doesn't pull in the sandbox runtime). Reads of legacy rows stay tolerant — parse failures are skipped or degraded, never raised.
@@ -486,6 +487,16 @@ Scouts write them via `charts` on `emit_report` / `edit_report`. On an edit `cha
The main **agentic research pipeline** authors charts too, so every signal source that funnels through it (not just scouts) can produce a visual report. The research agent's presentation step (`report_generation/research.py`) returns `charts` alongside the title and summary; the caller activity (`temporal/agentic/report.py`) replaces `SignalReport.charts` with them, and a re-research is shown the report's current charts to keep, refresh, or drop. It is gated per team by the `signals-report-charts` flag (`_team_report_charts_enabled`, on in DEBUG) so it ships dark on the fleet-wide path. Unlike the scout emit path, these charts are **not** safety-judged: the pipeline judge screens the input signals before research runs, so it never sees research-authored charts — the same as it never sees the research-authored title/summary, which are agent output from already-screened signals.
+**Report checks.** `SignalReportCheck` is the report's only forward-looking row: a title, a rationale, a kind-specific config, and the time to evaluate it. Everything else on a report describes what was already observed, so a claim that stopped holding was only ever found by a person going back to look. A check turns that into a scheduled measurement whose verdict lands in the artefact log as a `check_result`.
+
+The schedule is the check's own clock (`next_run_at`, optional `run_interval_minutes`, `runs_remaining`, `expires_at`), not something derived from a merged pull request: many fixes land in the skills store with no pull request to date a soak window from. Bounds live in `report_checks.py` — at most 5 active checks per report, a 90-day horizon, a 6-hour interval floor, at most 10 runs, and a 30-day default expiry after the last scheduled run. Terminal statuses (`passed`, `failed`, `errored`, `expired`, `cancelled`) are final, so a stored result always refers to a row whose state explains it; a new expectation is a new check.
+
+`metric_threshold` is the only kind today and needs no agent: it measures one bounded live Trends query — either its own or the query behind a `metric_id` the report already shows — and compares the result. The query rides `report_metrics.validate_live_metric_query`, so a check inherits the metric contract's node allowlist, relative window, and single-output-series rule. The comparison is the alerts product's `evaluate_threshold`, which is why the operators are `lte`, `gte`, and `between`: those map exactly onto the alerts bounds, and strict operators would mean a second comparison engine for a distinction a soak does not make.
+
+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 measures the due rows, 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. Everything is written through one funnel that re-reads the row under a lock, so a check cancelled while its query ran records nothing.
+
+Checks are created and cancelled through `SignalReportCheckViewSet` (`/signals/reports/:id/checks/`, `task:write`, same attribution as artefact writes). There is no update: editing a threshold after a result would make the recorded verdict unreadable.
+
**Report metrics.** `SignalReport.metrics` is typed report content, not an artefact log or a materialized time series. Its dependency-light schema lives in `report_metrics.py` (`ReportMetric`). Each entry has a stable id, title, semantic kind, role, display format, a required bounded live query, and an optional cached snapshot. Legacy comparison data stays compatible in storage but is not exposed as a live comparison. A report accepts at most six metrics, at most one primary metric, and at most one `affected_users` metric.
Every metric uses an `InsightVizNode` around one `TrendsQuery` over event or action sources. Consumers derive a `BoldNumber` for the whole-window value and an `ActionsBar` for longitudinal buckets. An `affected_users` metric uses exactly one series with `math: dau`. An `affected_sessions` metric uses exactly one series with `math: unique_session`. Neither kind uses formulas or group math. The default daily window starts at `-13d`, which gives 14 inclusive buckets including today. A longer window keeps only the trailing 14 buckets in the strip, while the whole-window value uses the full window. New authoring omits comparisons until the server can keep equal adjacent windows live. Non-currency units are lowercase. Revenue uses an uppercase ISO currency code such as `USD`.
diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.py
index 986ebabe36f8..3324c19607f2 100644
--- a/products/signals/backend/artefact_schemas.py
+++ b/products/signals/backend/artefact_schemas.py
@@ -631,6 +631,37 @@ class PullRequestLink(BaseModel):
url: str = Field(description="Canonical GitHub pull request URL.")
+class CheckResult(BaseModel):
+ """Content schema for a `check_result` artefact: one run of a `SignalReportCheck`.
+
+ The forward-looking half of a report's log. A report says what was true when it was written; a
+ check result says whether that still holds, measured on the check's own schedule. System-generated
+ — the check executor is the only writer, so the type is read-only through the generic artefact API.
+ """
+
+ check_id: str = Field(description="UUID of the SignalReportCheck this run belongs to.")
+ kind: str = Field(description="The check's kind, e.g. `metric_threshold`.")
+ title: str = Field(description="The check's title, copied so the log entry reads on its own.")
+ outcome: Literal["passed", "failed", "errored"] = Field(
+ description=(
+ "`passed` (the expectation held), `failed` (it did not), or `errored` (the check could not be measured)."
+ )
+ )
+ explanation: str = Field(description="One line saying what was measured and how it compared.")
+ observed_value: float | None = Field(default=None, description="The measured value; absent when the run errored.")
+ baseline_value: float | None = Field(
+ default=None, description="The value recorded when the check was written, when the author gave one."
+ )
+ threshold: str | None = Field(default=None, description="The expectation the value was compared against.")
+
+ @field_validator("explanation")
+ @classmethod
+ def explanation_must_not_be_empty(cls, v: str) -> str:
+ if not v.strip():
+ raise ValueError("must not be empty or whitespace-only")
+ return v
+
+
# ── Type mapping ─────────────────────────────────────────────────────────────────
# Content models that describe the report's current state (latest row of each type wins) vs
@@ -656,6 +687,7 @@ LogArtefactContent = (
| WorkClaim
| WorkRelease
| PullRequestLink
+ | CheckResult
)
ArtefactContent = StatusArtefactContent | LogArtefactContent | SignalFinding | Dismissal | VideoSegment
@@ -682,6 +714,7 @@ ARTEFACT_CONTENT_SCHEMAS: Mapping[str, type[BaseModel]] = {
"work_claim": WorkClaim,
"work_release": WorkRelease,
"pull_request": PullRequestLink,
+ "check_result": CheckResult,
}
_ARTEFACT_TYPE_BY_MODEL: Mapping[type[BaseModel], str] = {model: t for t, model in ARTEFACT_CONTENT_SCHEMAS.items()}
@@ -694,6 +727,8 @@ _ARTEFACT_TYPE_BY_MODEL: Mapping[type[BaseModel], str] = {model: t for t, model
# is their only writer, so accepting them through the generic API would let a caller fabricate edits
# that never happened. They stay readable (and so show up in the report's artefact log) but cannot
# be created or edited directly.
+# `check_result` is likewise system-generated — the check executor is its only writer; accepting it
+# through the API would let a caller fabricate a verdict for a soak that never ran.
# `code_review` is likewise system-generated — the ReviewHog workflow is its only writer; accepting
# it through the API would let a caller fabricate review receipts for reviews that never ran.
NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset(
@@ -706,6 +741,7 @@ NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset(
"work_claim",
"work_release",
"pull_request",
+ "check_result",
}
)
diff --git a/products/signals/backend/migrations/0135_signalreportcheck.py b/products/signals/backend/migrations/0135_signalreportcheck.py
new file mode 100644
index 000000000000..e6ecca880f9b
--- /dev/null
+++ b/products/signals/backend/migrations/0135_signalreportcheck.py
@@ -0,0 +1,126 @@
+# Generated by Django 5.2.17 on 2026-09-13 10:49
+
+import django.db.models.manager
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1352_email_lookup_indexes"),
+ ("signals", "0134_scout_exemption_role_source"),
+ ("tasks", "0123_alter_sandboxsnapshot_integration"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="SignalReportCheck",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ ("title", models.CharField(max_length=200)),
+ ("rationale", models.TextField(blank=True, default="")),
+ ("kind", models.CharField(choices=[("metric_threshold", "Metric Threshold")], max_length=30)),
+ ("config", models.JSONField(db_default={}, default=dict)),
+ ("next_run_at", models.DateTimeField()),
+ ("run_interval_minutes", models.PositiveIntegerField(blank=True, null=True)),
+ ("runs_remaining", models.PositiveIntegerField(default=1)),
+ ("expires_at", models.DateTimeField()),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("active", "Active"),
+ ("passed", "Passed"),
+ ("failed", "Failed"),
+ ("errored", "Errored"),
+ ("expired", "Expired"),
+ ("cancelled", "Cancelled"),
+ ],
+ default="active",
+ max_length=20,
+ ),
+ ),
+ ("consecutive_errors", models.PositiveIntegerField(default=0)),
+ ("last_run_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "last_outcome",
+ models.CharField(
+ blank=True,
+ choices=[("passed", "Passed"), ("failed", "Failed"), ("errored", "Errored")],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ (
+ "actor_kind",
+ models.CharField(
+ blank=True,
+ choices=[("user", "User"), ("task", "Task"), ("agent", "Agent"), ("system", "System")],
+ max_length=10,
+ null=True,
+ ),
+ ),
+ ("actor_agent", models.CharField(blank=True, max_length=200, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "report",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE, related_name="checks", to="signals.signalreport"
+ ),
+ ),
+ (
+ "task",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="tasks.task",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Signal report check",
+ "verbose_name_plural": "Signal report checks",
+ "default_manager_name": "all_teams",
+ "indexes": [
+ models.Index(
+ condition=models.Q(("status", "active")), fields=["next_run_at"], name="signals_check_due_idx"
+ ),
+ models.Index(fields=["report", "status"], name="signals_check_report_idx"),
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 903ec329a600..90348ffee338 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0134_scout_exemption_role_source
+0135_signalreportcheck
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index eff8b0c5d1e3..5e5df4560151 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -15,6 +15,7 @@ from pydantic import ValidationError
from posthog.migration_helpers import deprecate_field
from posthog.models.activity_logging.model_activity import ModelActivityMixin
+from posthog.models.scoping.manager import EnvironmentScopedManager
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.team.extensions import register_team_extension_signal
from posthog.models.utils import UUIDModel
@@ -35,6 +36,7 @@ from products.signals.backend.artefact_schemas import (
task_run_identifier_for_legacy_relationship,
)
from products.signals.backend.enums import SignalSourceProduct, signal_source_product_choices
+from products.signals.backend.report_checks import MAX_CHECK_TITLE_LENGTH
logger = logging.getLogger(__name__)
@@ -1078,6 +1080,7 @@ class SignalReportArtefact(UUIDModel):
WORK_CLAIM = "work_claim"
WORK_RELEASE = "work_release"
PULL_REQUEST = "pull_request"
+ CHECK_RESULT = "check_result"
# Every artefact is an append-only, point-in-time log entry — nothing is mutated in place by
# the producers. The two sets below classify *what an entry means*, not how it is written:
@@ -1113,6 +1116,7 @@ class SignalReportArtefact(UUIDModel):
ArtefactType.WORK_CLAIM,
ArtefactType.WORK_RELEASE,
ArtefactType.PULL_REQUEST,
+ ArtefactType.CHECK_RESULT,
}
)
@@ -1638,6 +1642,106 @@ class SignalReportAction(TeamScopedRootMixin, UUIDModel):
row.update(**updates)
+class SignalReportCheck(UUIDModel):
+ """A forward-looking claim attached to a report: at time T, evaluate this and record the verdict.
+
+ A report and its artefacts are backward-looking — every row says what was already observed.
+ This row is the other direction: it holds an expectation plus the time to test it, so a fix that
+ quietly did not hold is caught by the coordinator rather than by a person remembering to look.
+
+ Scheduling is deliberately coarse. The coordinator's tick is the only clock, soak windows are
+ days, and the check carries its own `next_run_at` rather than deriving one from a merged pull
+ request — plenty of fixes land with no pull request to date the window from.
+
+ Terminal statuses are final. A check that passed, failed, errored out, expired, or was cancelled
+ is never rescheduled; the author writes a new check instead, so a result artefact always refers
+ to a row whose state explains it.
+ """
+
+ class Kind(models.TextChoices):
+ # One bounded query, one comparison, no sandbox. `agent` follows once the scout dispatch
+ # path can carry a check.
+ METRIC_THRESHOLD = "metric_threshold"
+
+ class Status(models.TextChoices):
+ ACTIVE = "active"
+ PASSED = "passed"
+ FAILED = "failed"
+ ERRORED = "errored"
+ EXPIRED = "expired"
+ CANCELLED = "cancelled"
+
+ class Outcome(models.TextChoices):
+ PASSED = "passed"
+ FAILED = "failed"
+ ERRORED = "errored"
+
+ # Environment-scoped, not project-scoped. `SignalReport` stores the environment's own team, and a
+ # check has to sit on the same team as its report or the report's reads never find it and its
+ # result artefacts land on a team the report does not have. So no `RootTeamMixin` (its save()
+ # canonicalizes the team to the parent), and `EnvironmentScopedManager` filters by the literal id
+ # callers pass through `objects.for_team(team_id)`.
+ objects = EnvironmentScopedManager()
+ # See SignalReportRefund.all_teams for rationale.
+ all_teams = models.Manager() # noqa: DJ012
+
+ # FKs to the hot posthog_team / posthog_user tables use db_constraint=False so creating this
+ # table takes no lock on those parents (app-level enforcement only).
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ report = models.ForeignKey(SignalReport, on_delete=models.CASCADE, related_name="checks")
+ title = models.CharField(max_length=MAX_CHECK_TITLE_LENGTH)
+ rationale = models.TextField(blank=True, default="")
+ kind = models.CharField(max_length=30, choices=Kind)
+ # Validated against the kind's pydantic model at every write (see `report_checks.parse_check_config`).
+ config = models.JSONField(default=dict, db_default={})
+
+ next_run_at = models.DateTimeField()
+ # Null means one-shot. A recurring check re-arms at this interval until it runs out of runs or
+ # reaches its expiry.
+ run_interval_minutes = models.PositiveIntegerField(null=True, blank=True)
+ runs_remaining = models.PositiveIntegerField(default=1)
+ expires_at = models.DateTimeField()
+
+ status = models.CharField(max_length=20, choices=Status, default=Status.ACTIVE)
+ consecutive_errors = models.PositiveIntegerField(default=0)
+ last_run_at = models.DateTimeField(null=True, blank=True)
+ last_outcome = models.CharField(max_length=20, choices=Outcome, null=True, blank=True)
+
+ # Attribution, same columns and meaning as the artefact log's.
+ actor_kind = models.CharField(max_length=10, choices=SignalActorKind, null=True, blank=True)
+ actor_agent = models.CharField(max_length=200, null=True, blank=True)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, db_constraint=False, null=True, blank=True, related_name="+"
+ )
+ task = models.ForeignKey(
+ "tasks.Task", on_delete=models.SET_NULL, db_constraint=False, null=True, blank=True, related_name="+"
+ )
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ verbose_name = "Signal report check"
+ verbose_name_plural = "Signal report checks"
+ default_manager_name = "all_teams"
+ indexes = [
+ # The coordinator's due scan is the only fleet-wide read: `status = active AND
+ # next_run_at <= now()` ordered by `next_run_at`. Partial, so the index holds only the
+ # rows still waiting rather than every check ever written.
+ models.Index(
+ fields=["next_run_at"],
+ condition=models.Q(status="active"),
+ name="signals_check_due_idx",
+ ),
+ # The per-report read behind the detail view and the report list's summary.
+ models.Index(fields=["report", "status"], name="signals_check_report_idx"),
+ ]
+
+ @property
+ def is_terminal(self) -> bool:
+ return self.status != self.Status.ACTIVE
+
+
# ── Signals scout (headless cross-source explorer) ──────────────────────────────
#
# Core tables backing the Signals scout:
diff --git a/products/signals/backend/report_check_execution.py b/products/signals/backend/report_check_execution.py
new file mode 100644
index 000000000000..efe802e767e2
--- /dev/null
+++ b/products/signals/backend/report_check_execution.py
@@ -0,0 +1,377 @@
+"""Deterministic execution of the checks attached to signal reports.
+
+One bounded Trends query, one comparison, one artefact. The coordinator calls
+``run_due_report_checks`` on its tick; nothing here needs a sandbox, a scout enrolment, or an LLM.
+
+The comparison is the alerts product's, not a second one written here, so a check and an alert word
+a breach the same way and there is one place where "is this value out of bounds?" is decided.
+"""
+
+from __future__ import annotations
+
+import time
+from datetime import datetime, timedelta
+
+from django.db import transaction
+from django.db.models import F, Window
+from django.db.models.functions import RowNumber
+from django.utils import timezone
+
+import structlog
+
+from posthog.schema import (
+ AlertCondition,
+ AlertConditionType,
+ InsightsThresholdBounds,
+ InsightThreshold,
+ InsightThresholdType,
+)
+
+from posthog.clickhouse.query_tagging import tag_queries
+from posthog.dataclasses import frozen
+
+from products.alerts.backend.facade.evaluation import (
+ ComparableSeries,
+ ExtractionResult,
+ SeriesPoint,
+ evaluate_threshold,
+)
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.artefact_schemas import CheckResult
+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportCheck
+from products.signals.backend.report_checks import (
+ MAX_CONSECUTIVE_CHECK_ERRORS,
+ CheckComparison,
+ CheckConfigValidationError,
+ CheckOutcome,
+ MetricThresholdConfig,
+ parse_check_config,
+)
+from products.signals.backend.report_metric_refresh import measure_metric
+from products.signals.backend.report_metrics import validate_live_metric_query
+
+logger = structlog.get_logger(__name__)
+
+# Per-tick cost ceiling. A check is one cached Trends query, so this is generous — the per-team cap
+# below is what keeps one busy team from filling the tick.
+MAX_CHECK_RUNS_PER_TICK = 50
+MAX_CHECK_RUNS_PER_TEAM_PER_TICK = 10
+CHECK_RUN_TIME_BUDGET_SECONDS = 120.0
+# Rows swept per tick when their horizon passed without a run. Bounded so a backlog costs one
+# bounded UPDATE rather than a table-wide one.
+MAX_CHECK_EXPIRIES_PER_TICK = 500
+# An errored run retries on the next window instead of retiring the check, so a transient query
+# failure does not end a soak. It does not consume `runs_remaining`.
+CHECK_ERROR_RETRY_AFTER = timedelta(hours=6)
+# Same bound the scout runner puts on a stored failure reason.
+MAX_CHECK_ERROR_REASON_LENGTH = 300
+
+# 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}
+)
+
+
+@frozen
+class CheckRunSummary:
+ expired: int
+ passed: int
+ failed: int
+ errored: int
+
+
+@frozen
+class CheckVerdict:
+ outcome: CheckOutcome
+ explanation: str
+ observed_value: float | None = None
+
+
+@frozen
+class _CheckTransition:
+ """Where a check goes after one verdict. `next_run_at` is None when the check retires."""
+
+ status: str
+ next_run_at: datetime | None
+ runs_remaining: int
+
+
+def resolve_check_query(config: MetricThresholdConfig, report: SignalReport) -> dict:
+ """The query this check measures: the one stored on it, else the report metric it names.
+
+ The create path copies a named metric's query onto the check, so the fallback only serves rows
+ written another way. Such a row is re-validated here, the way the metric refresh re-validates
+ before it measures: `report.metrics` is plain JSON that can change after the check was written,
+ and the runner reads one series out of the result, so a row carrying a breakdown or several
+ output series would turn an arbitrary slice into a recorded verdict.
+ """
+
+ if config.query is not None:
+ return config.query
+ for row in report.metrics or []:
+ if isinstance(row, dict) and row.get("metric_id") == config.metric_id and isinstance(row.get("query"), dict):
+ try:
+ return validate_live_metric_query(row["query"])
+ except ValueError as error:
+ raise ValueError(
+ f"metric `{config.metric_id}` no longer measures one bounded number: {error}"
+ ) from None
+ raise ValueError(f"the report has no metric `{config.metric_id}` to measure")
+
+
+def _threshold_for(comparison: CheckComparison) -> InsightThreshold:
+ """The alerts threshold whose breach is exactly this comparison's failure.
+
+ The alerts comparator breaches on `value < lower` or `value > upper`, so `gte` is a lower bound,
+ `lte` an upper one, and `between` both.
+ """
+ if comparison.operator == "between":
+ assert comparison.bounds is not None
+ bounds = InsightsThresholdBounds(lower=comparison.bounds.lower, upper=comparison.bounds.upper)
+ elif comparison.operator == "gte":
+ bounds = InsightsThresholdBounds(lower=comparison.value)
+ else:
+ bounds = InsightsThresholdBounds(upper=comparison.value)
+ return InsightThreshold(type=InsightThresholdType.ABSOLUTE, bounds=bounds)
+
+
+def _describe_comparison(comparison: CheckComparison) -> str:
+ if comparison.operator == "between":
+ assert comparison.bounds is not None
+ return f"between {comparison.bounds.lower} and {comparison.bounds.upper}"
+ return f"at most {comparison.value}" if comparison.operator == "lte" else f"at least {comparison.value}"
+
+
+def evaluate_check_value(*, comparison: CheckComparison, observed_value: float, subject: str) -> CheckVerdict:
+ """Compare one measured value against the check's expectation."""
+
+ result = ExtractionResult(
+ series=[
+ ComparableSeries(label=subject, points=[SeriesPoint(date=None, value=observed_value)], current_index=0)
+ ],
+ subject=subject,
+ framed=False,
+ )
+ evaluation = evaluate_threshold(
+ result,
+ AlertCondition(type=AlertConditionType.ABSOLUTE_VALUE),
+ _threshold_for(comparison),
+ )
+ if evaluation.breaches:
+ return CheckVerdict(outcome="failed", explanation=evaluation.breaches[0], observed_value=observed_value)
+ return CheckVerdict(
+ outcome="passed",
+ explanation=f"{subject} ({observed_value}) is {_describe_comparison(comparison)}, as expected",
+ observed_value=observed_value,
+ )
+
+
+def _errored_explanation(error: Exception, *, subject: str) -> str:
+ """The line a report reader sees when a run could not be measured.
+
+ It opens with the check's title, as the passed and failed lines do, so a report carrying several
+ checks does not log entries a reader cannot tell apart.
+
+ Our own validation and resolution failures name something the reader can act on, so they are
+ kept. Anything else is reduced to the fixed line: a query error can carry generated SQL and a
+ server stack trace, which `ExposedCHQueryError` exists to keep out of user-facing text, and the
+ artefact log is permanent and rendered as written. `logger.exception` above holds the whole
+ error either way.
+ """
+ reason = str(error).strip() if isinstance(error, ValueError | TimeoutError) else ""
+ if not reason:
+ return f"{subject} could not be measured."
+ return f"{subject} could not be measured: {reason[:MAX_CHECK_ERROR_REASON_LENGTH]}"
+
+
+def measure_check(check: SignalReportCheck, *, deadline: float) -> CheckVerdict:
+ """Run one check and return its verdict. Never raises: a failure to measure is an `errored` verdict."""
+
+ try:
+ config = parse_check_config(check.kind, check.config)
+ assert isinstance(config, MetricThresholdConfig)
+ query = resolve_check_query(config, check.report)
+ tag_queries(trigger="signals_report_check")
+ measurement = measure_metric(query, check.report.team, deadline=deadline, include_series=False)
+ except Exception as error:
+ logger.exception("signals.report_check.measurement_failed", check_id=str(check.id), team_id=check.team_id)
+ return CheckVerdict(outcome="errored", explanation=_errored_explanation(error, subject=check.title))
+ return evaluate_check_value(comparison=config.comparison, observed_value=measurement.value, subject=check.title)
+
+
+def _next_state(check: SignalReportCheck, verdict: CheckVerdict, now: datetime) -> _CheckTransition:
+ """The check's status after this verdict, its next run time, and its remaining runs.
+
+ Re-arming anchors on `now` rather than the missed slot, so a coordinator outage cannot leave a
+ recurring check owing a burst of catch-up runs.
+ """
+ if verdict.outcome == "failed":
+ return _CheckTransition(
+ status=SignalReportCheck.Status.FAILED, next_run_at=None, runs_remaining=check.runs_remaining
+ )
+
+ if verdict.outcome == "errored":
+ if check.consecutive_errors + 1 >= MAX_CONSECUTIVE_CHECK_ERRORS:
+ return _CheckTransition(
+ status=SignalReportCheck.Status.ERRORED, next_run_at=None, runs_remaining=check.runs_remaining
+ )
+ retry_at = now + CHECK_ERROR_RETRY_AFTER
+ if retry_at > check.expires_at:
+ return _CheckTransition(
+ status=SignalReportCheck.Status.EXPIRED, next_run_at=None, runs_remaining=check.runs_remaining
+ )
+ return _CheckTransition(
+ status=SignalReportCheck.Status.ACTIVE, next_run_at=retry_at, runs_remaining=check.runs_remaining
+ )
+
+ runs_remaining = max(0, check.runs_remaining - 1)
+ if runs_remaining == 0 or check.run_interval_minutes is None:
+ return _CheckTransition(status=SignalReportCheck.Status.PASSED, next_run_at=None, runs_remaining=runs_remaining)
+ next_run_at = now + timedelta(minutes=check.run_interval_minutes)
+ if next_run_at > check.expires_at:
+ return _CheckTransition(status=SignalReportCheck.Status.PASSED, next_run_at=None, runs_remaining=runs_remaining)
+ return _CheckTransition(
+ status=SignalReportCheck.Status.ACTIVE, next_run_at=next_run_at, runs_remaining=runs_remaining
+ )
+
+
+def record_check_verdict(check: SignalReportCheck, verdict: CheckVerdict, *, now: datetime | None = None) -> None:
+ """The single persistence funnel: append the result artefact and advance or retire the check.
+
+ One transaction, and the row is re-read under a lock so a check cancelled while its query ran
+ records nothing.
+ """
+ now = now or timezone.now()
+ # The result's context is best-effort. A stored config can stop parsing part-way through a soak,
+ # because a tightened query rule invalidates a class of stored queries at once. Such a run still
+ # has to reach the errored path: raising here would record nothing, and the row would keep its
+ # past `next_run_at` and head the due queue on every tick until its horizon.
+ try:
+ parsed = parse_check_config(check.kind, check.config)
+ except CheckConfigValidationError:
+ parsed = None
+ config = parsed if isinstance(parsed, MetricThresholdConfig) else None
+
+ with transaction.atomic():
+ current = (
+ SignalReportCheck.objects.for_team(check.team_id)
+ .select_for_update()
+ .filter(id=check.id, status=SignalReportCheck.Status.ACTIVE)
+ .first()
+ )
+ if current is None:
+ return
+ transition = _next_state(current, verdict, now)
+ current.status = transition.status
+ current.runs_remaining = transition.runs_remaining
+ current.last_run_at = now
+ current.last_outcome = verdict.outcome
+ current.consecutive_errors = current.consecutive_errors + 1 if verdict.outcome == "errored" else 0
+ if transition.next_run_at is not None:
+ current.next_run_at = transition.next_run_at
+ current.save(
+ update_fields=[
+ "status",
+ "runs_remaining",
+ "last_run_at",
+ "last_outcome",
+ "consecutive_errors",
+ "next_run_at",
+ "updated_at",
+ ]
+ )
+ SignalReportArtefact.add_log(
+ team_id=current.team_id,
+ report_id=str(current.report_id),
+ content=CheckResult(
+ check_id=str(current.id),
+ kind=current.kind,
+ title=current.title,
+ outcome=verdict.outcome,
+ explanation=verdict.explanation,
+ observed_value=verdict.observed_value,
+ baseline_value=config.baseline_value if config is not None else None,
+ threshold=_describe_comparison(config.comparison) if config is not None else None,
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+
+
+def expire_overdue_checks(now: datetime) -> int:
+ """Retire active checks whose horizon passed without a run. Returns how many were retired."""
+
+ overdue = list(
+ SignalReportCheck.all_teams.filter(status=SignalReportCheck.Status.ACTIVE, expires_at__lte=now).values_list(
+ "id", flat=True
+ )[:MAX_CHECK_EXPIRIES_PER_TICK]
+ )
+ if not overdue:
+ return 0
+ return SignalReportCheck.all_teams.filter(id__in=overdue, status=SignalReportCheck.Status.ACTIVE).update(
+ status=SignalReportCheck.Status.EXPIRED, updated_at=now
+ )
+
+
+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.
+
+ The horizon is read here rather than trusted to the expiry sweep. That sweep is bounded per
+ tick, and a check sitting at its horizon is always due as well, so a backlog larger than the
+ sweep would otherwise let a row measure after the horizon it was supposed to retire at.
+ """
+
+ candidates = (
+ SignalReportCheck.all_teams.filter(
+ status=SignalReportCheck.Status.ACTIVE,
+ next_run_at__lte=now,
+ expires_at__gt=now,
+ report__status__in=CHECKABLE_REPORT_STATUSES,
+ )
+ .select_related("report", "report__team")
+ # Rank each team's rows against its own, then read those ranks in order, so every team's
+ # oldest check sorts ahead of any team's second. Ordering by `next_run_at` alone would let
+ # one team's backlog fill the whole prefix and starve every other team behind it.
+ .annotate(
+ _team_rank=Window(
+ expression=RowNumber(),
+ partition_by=[F("team_id")],
+ order_by=[F("next_run_at").asc(), F("id").asc()],
+ )
+ )
+ .order_by("_team_rank", "next_run_at", "id")[: limit * MAX_CHECK_RUNS_PER_TEAM_PER_TICK]
+ )
+ per_team: dict[int, int] = {}
+ due: list[SignalReportCheck] = []
+ for check in candidates:
+ taken = per_team.get(check.team_id, 0)
+ if taken >= MAX_CHECK_RUNS_PER_TEAM_PER_TICK:
+ continue
+ per_team[check.team_id] = taken + 1
+ due.append(check)
+ if len(due) >= limit:
+ break
+ return due
+
+
+def run_due_report_checks(*, now: datetime | None = None, limit: int = MAX_CHECK_RUNS_PER_TICK) -> CheckRunSummary:
+ """Expire what timed out, then measure and record every check due this tick."""
+
+ now = now or timezone.now()
+ expired = expire_overdue_checks(now)
+ deadline = time.monotonic() + CHECK_RUN_TIME_BUDGET_SECONDS
+ counts: dict[CheckOutcome, int] = {"passed": 0, "failed": 0, "errored": 0}
+ for check in collect_due_checks(now, limit=limit):
+ if time.monotonic() >= deadline:
+ break
+ verdict = measure_check(check, deadline=deadline)
+ try:
+ record_check_verdict(check, verdict)
+ except Exception:
+ logger.exception("signals.report_check.persist_failed", check_id=str(check.id), team_id=check.team_id)
+ continue
+ counts[verdict.outcome] += 1
+ return CheckRunSummary(expired=expired, **counts)
diff --git a/products/signals/backend/report_checks.py b/products/signals/backend/report_checks.py
new file mode 100644
index 000000000000..9e4f62e1f44c
--- /dev/null
+++ b/products/signals/backend/report_checks.py
@@ -0,0 +1,186 @@
+"""Forward-looking checks attached to a signal report.
+
+A report states what was true when it was written. A check states what must stay true afterwards:
+one bounded measurement, one comparison, and a time to run it. The coordinator runs the due ones and
+appends the verdict to the report's artefact log, so "did the fix hold?" becomes a stored fact
+instead of a person re-deriving it.
+
+The soak window is the check's own clock. A fix does not always arrive as a merged pull request —
+plenty land in the skills store with nothing to date the window from — so the author says when the
+check runs rather than the system reading it off a merge.
+
+This module stays Django-free and schema-free for the same reason as ``report_metrics``: model and
+Temporal payload modules import it during process setup.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from datetime import timedelta
+from typing import Any, Literal
+
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
+
+from products.signals.backend.report_metrics import validate_live_metric_query, validate_metric_id
+
+CheckOutcome = Literal["passed", "failed", "errored"]
+CheckOperator = Literal["lte", "gte", "between"]
+
+MAX_ACTIVE_CHECKS_PER_REPORT = 5
+MAX_CHECK_TITLE_LENGTH = 200
+MAX_CHECK_RATIONALE_LENGTH = 2_000
+# A check is a soak, not a monitor: a lane that re-measures more than four times a day is an alert
+# and belongs in the alerts product, which has the notification and deduplication machinery for it.
+MIN_CHECK_INTERVAL_MINUTES = 6 * 60
+MAX_CHECK_RUNS = 10
+MAX_CHECK_HORIZON = timedelta(days=90)
+# The horizon bounds the gap as well as the schedule. A gap wider than the horizon can never produce
+# a second run, and an unbounded one overflows the date arithmetic that plans the runs.
+MAX_CHECK_INTERVAL_MINUTES = int(MAX_CHECK_HORIZON.total_seconds() // 60)
+# A soak needs the fix to have been live a while. A week is the default first look; an author who
+# knows the window says so.
+DEFAULT_FIRST_RUN_AFTER = timedelta(days=7)
+DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN = timedelta(days=30)
+# A check whose query keeps failing is misconfigured, not unlucky. Three errored runs retire it so a
+# broken lane stops costing a query per tick.
+MAX_CONSECUTIVE_CHECK_ERRORS = 3
+
+
+class CheckThresholdBounds(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ lower: float
+ upper: float
+
+ @model_validator(mode="after")
+ def lower_must_not_exceed_upper(self) -> CheckThresholdBounds:
+ if self.lower > self.upper:
+ raise ValueError("lower must not exceed upper")
+ return self
+
+
+class CheckComparison(BaseModel):
+ """What the measured value must satisfy for the check to pass.
+
+ The operators are the ones the shared alerts comparator expresses exactly. Strict `lt` / `gt`
+ would need a second comparison engine for a distinction a soak window does not make, so they are
+ not offered: "stays at or below 10 a day" is the same expectation.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ operator: CheckOperator = Field(description="`lte`, `gte`, or `between`.")
+ value: float | None = Field(
+ default=None,
+ description="The bound for `lte` and `gte`; unused by `between`.",
+ )
+ bounds: CheckThresholdBounds | None = Field(
+ default=None,
+ description="The inclusive range for `between`; unused by `lte` and `gte`.",
+ )
+
+ @field_validator("value", mode="before")
+ @classmethod
+ def value_must_be_a_plain_number(cls, value: object) -> object:
+ if isinstance(value, bool):
+ raise ValueError("must be a number, not a boolean")
+ return value
+
+ @model_validator(mode="after")
+ def operator_must_match_its_bound(self) -> CheckComparison:
+ if self.operator == "between":
+ if self.bounds is None:
+ raise ValueError("a `between` comparison needs bounds")
+ if self.value is not None:
+ raise ValueError("a `between` comparison takes bounds, not a value")
+ else:
+ if self.value is None:
+ raise ValueError(f"a `{self.operator}` comparison needs a value")
+ if self.bounds is not None:
+ raise ValueError(f"a `{self.operator}` comparison takes a value, not bounds")
+ return self
+
+
+class MetricThresholdConfig(BaseModel):
+ """A deterministic check: measure one number, compare it, record the verdict.
+
+ The number comes either from a metric the report already shows (``metric_id``) or from a query
+ the author supplies. Both end up in the same runner, so a supplied query must satisfy the live
+ metric contract — the node allowlist, the bounded window, and the single-output-series rule.
+
+ A caller names one source. When it names a metric, the create path copies that metric's query
+ into ``query`` before the row is stored, so the check keeps measuring what its author saw even if
+ the report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.
+
+ Unknown keys are refused rather than ignored, so a misspelled field name is reported instead of
+ being dropped in silence and stored as it arrived.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ metric_id: str | None = Field(
+ default=None,
+ description=(
+ "Identifier of a metric on the report whose query this check measures. The metric's query is "
+ "copied into `query` when the check is created."
+ ),
+ )
+ query: dict[str, Any] | None = Field(
+ default=None,
+ description=(
+ "Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named "
+ "metric when the check is created."
+ ),
+ )
+ comparison: CheckComparison = Field(description="What the measured value must satisfy to pass.")
+ baseline_value: float | None = Field(
+ default=None,
+ description="The value observed when the check was written, recorded on each result for context.",
+ )
+
+ @field_validator("baseline_value", mode="before")
+ @classmethod
+ def baseline_must_be_a_plain_number(cls, value: object) -> object:
+ if isinstance(value, bool):
+ raise ValueError("must be a number, not a boolean")
+ return value
+
+ @field_validator("metric_id")
+ @classmethod
+ def metric_id_must_be_reference_safe(cls, value: str | None) -> str | None:
+ return None if value is None else validate_metric_id(value)
+
+ @field_validator("query")
+ @classmethod
+ def query_must_be_a_live_trends_node(cls, value: dict[str, Any] | None) -> dict[str, Any] | None:
+ return None if value is None else validate_live_metric_query(value)
+
+ @model_validator(mode="after")
+ def source_must_name_a_metric_or_carry_a_query(self) -> MetricThresholdConfig:
+ if self.metric_id is None and self.query is None:
+ raise ValueError("provide a metric_id or a query")
+ return self
+
+
+CHECK_CONFIG_SCHEMAS: Mapping[str, type[BaseModel]] = {
+ "metric_threshold": MetricThresholdConfig,
+}
+
+
+class CheckConfigValidationError(ValueError):
+ """A check config that does not match its kind's schema."""
+
+
+def parse_check_config(kind: str, config: object) -> BaseModel:
+ """Parse a raw config payload into its kind's model.
+
+ The single boundary parser: the REST write path and the executor both come through here, so a
+ stored config can never mismatch the kind on its row.
+ """
+ schema = CHECK_CONFIG_SCHEMAS.get(kind)
+ if schema is None:
+ raise CheckConfigValidationError(f"Unknown check kind {kind!r}")
+ try:
+ return schema.model_validate(config)
+ except ValidationError as error:
+ raise CheckConfigValidationError(str(error)) from error
diff --git a/products/signals/backend/report_metrics.py b/products/signals/backend/report_metrics.py
index bcc1118796d1..bbde9f334326 100644
--- a/products/signals/backend/report_metrics.py
+++ b/products/signals/backend/report_metrics.py
@@ -174,6 +174,147 @@ def _validate_live_metric_formula(formula: object, series_count: int) -> None:
raise ValueError(f"a live metric formula must be executable arithmetic over the series: {error}") from None
+def validate_metric_id(value: str) -> str:
+ """Normalize a metric id and refuse one nothing can reference.
+
+ Stored ids are trimmed and lowercase, and every lookup matches them by equality, so a padded or
+ uppercase reference cannot match a metric however right it looks. A check rides this too, so the
+ reference it stores is one the report could actually hold.
+ """
+ if len(value) > MAX_METRIC_ID_LENGTH:
+ raise ValueError(f"must not exceed {MAX_METRIC_ID_LENGTH} characters")
+ normalized = value.strip()
+ if not _METRIC_ID_RE.fullmatch(normalized):
+ raise ValueError(
+ "must contain only lowercase letters, numbers, underscores, or hyphens, "
+ "and must start with a lowercase letter or number"
+ )
+ return normalized
+
+
+def validate_live_metric_query(value: dict[str, Any]) -> dict[str, Any]:
+ """Refuse any query a report metric or a report check must not run.
+
+ The contract is one bounded, live, single-output-series Trends node: a relative window that
+ advances with time, an allowlisted node set, event or action sources only, and an estimated
+ point count a reader can afford. A check rides the same rules as a metric because both end up
+ in the same query runner.
+ """
+
+ validate_report_query(value, allowed_kinds=_LIVE_METRIC_QUERY_KINDS)
+ try:
+ # Import only while validating authored content: importing the generated schema at module
+ # load would put it back on every signals model and Temporal worker startup path.
+ from posthog.schema import InsightVizNode # noqa: PLC0415 — keeps the generated schema off startup
+
+ InsightVizNode.model_validate(value)
+ except ValidationError as error:
+ first_error = error.errors(include_input=False)[0]
+ location = ".".join(str(part) for part in first_error["loc"])
+ raise ValueError(
+ f"query must match the canonical InsightVizNode schema; {location}: {first_error['msg']}"
+ ) from None
+ source = value.get("source")
+ if not isinstance(source, dict) or source.get("kind") != "TrendsQuery":
+ raise ValueError("query must wrap one TrendsQuery in an InsightVizNode")
+ series = source.get("series")
+ if not isinstance(series, list) or not series or any(not isinstance(item, dict) for item in series):
+ raise ValueError("query.source.series must contain at least one Trends series")
+ if len(series) > MAX_LIVE_METRIC_QUERY_SERIES:
+ raise ValueError(f"query.source.series accepts at most {MAX_LIVE_METRIC_QUERY_SERIES} series")
+ if any(item.get("kind") not in _LIVE_METRIC_SERIES_KINDS for item in series):
+ raise ValueError("a live metric query must use only event or action series so reader access can be checked")
+ for item in series:
+ if item["kind"] == "EventsNode":
+ event = item.get("event")
+ if not isinstance(event, str) or not event.strip():
+ raise ValueError("a live metric event series needs a non-empty event name")
+ else:
+ action_id = item.get("id")
+ if not isinstance(action_id, int) or isinstance(action_id, bool) or action_id <= 0:
+ raise ValueError("a live metric action series needs a positive integer action id")
+ if source.get("breakdownFilter") or source.get("breakdown"):
+ raise ValueError("a live metric query must not use a breakdown because it represents one measurement")
+ sampling_factor = source.get("samplingFactor")
+ # `SAMPLE 0` returns no rows, and the Trends runner skips its sampling correction for a falsy
+ # factor, so a zero reads back as a genuine measurement of 0 and a `lte` check passes on it.
+ # A factor outside the range fails in ClickHouse instead, which costs the check a retry.
+ if sampling_factor is not None and (
+ not isinstance(sampling_factor, int | float)
+ or isinstance(sampling_factor, bool)
+ or not 0 < sampling_factor <= 1
+ ):
+ raise ValueError("query.source.samplingFactor must be greater than 0 and at most 1")
+ compare_filter = source.get("compareFilter")
+ if isinstance(compare_filter, dict) and compare_filter.get("compare"):
+ raise ValueError("a live metric query must not use compare mode because it represents one measurement")
+ trends_filter = source.get("trendsFilter")
+ if isinstance(trends_filter, dict):
+ if trends_filter.get("compare"):
+ raise ValueError("a live metric query must not use compare mode because it represents one measurement")
+ if (
+ trends_filter.get("display") == "Metric"
+ and trends_filter.get("metricShowChange", True) is not False
+ and trends_filter.get("metricSummary", "total") != "latest"
+ ):
+ raise ValueError(
+ "a live metric query using the Metric display must disable metricShowChange or use the latest "
+ "summary so the Trends runner does not enable compare mode"
+ )
+ date_range = source.get("dateRange")
+ if not isinstance(date_range, dict):
+ raise ValueError("query.source.dateRange.date_from must be a relative time window such as `-30d`")
+ date_from = date_range.get("date_from")
+ if not isinstance(date_from, str):
+ raise ValueError("query.source.dateRange.date_from must be a relative time window such as `-30d`")
+ relative_window = _RELATIVE_DATE_FROM_RE.fullmatch(date_from)
+ if relative_window is None:
+ raise ValueError("query.source.dateRange.date_from must be a relative time window such as `-30d`")
+ amount, unit = relative_window.groups()
+ window_seconds = int(amount) * _RELATIVE_WINDOW_SECONDS[unit]
+ if window_seconds > MAX_LIVE_METRIC_WINDOW_DAYS * _RELATIVE_WINDOW_SECONDS["d"]:
+ raise ValueError(f"query.source.dateRange must not exceed {MAX_LIVE_METRIC_WINDOW_DAYS} days for a live metric")
+ if date_range.get("date_to") not in (None, ""):
+ raise ValueError("query.source.dateRange.date_to must be empty so a live metric advances with time")
+ interval = source.get("interval")
+ if interval is None:
+ interval = "day"
+ if not isinstance(interval, str) or interval not in _LIVE_METRIC_INTERVAL_SECONDS:
+ accepted_intervals = ", ".join(_LIVE_METRIC_INTERVAL_SECONDS)
+ raise ValueError(f"query.source.interval must be one of {accepted_intervals}")
+ output_series_count = len(series)
+ selected_formulas: list[object] = []
+ if isinstance(trends_filter, dict):
+ formula_nodes = trends_filter.get("formulaNodes")
+ formulas = trends_filter.get("formulas")
+ formula = trends_filter.get("formula")
+ if isinstance(formula_nodes, list) and formula_nodes:
+ output_series_count = len(formula_nodes)
+ selected_formulas = [node.get("formula") if isinstance(node, dict) else node for node in formula_nodes]
+ elif isinstance(formulas, list) and formulas:
+ output_series_count = len(formulas)
+ selected_formulas = list(formulas)
+ elif isinstance(formula, str) and formula:
+ output_series_count = 1
+ selected_formulas = [formula]
+ if output_series_count != 1:
+ raise ValueError(
+ "a live metric query must produce exactly one output series; use one source or combine up to "
+ f"{MAX_LIVE_METRIC_QUERY_SERIES} source series with exactly one formula"
+ )
+ for selected_formula in selected_formulas:
+ _validate_live_metric_formula(selected_formula, len(series))
+ interval_seconds = _LIVE_METRIC_INTERVAL_SECONDS[interval]
+ estimated_buckets = (window_seconds + interval_seconds - 1) // interval_seconds + 1
+ estimated_points = estimated_buckets * output_series_count
+ if estimated_points > MAX_LIVE_METRIC_QUERY_POINTS:
+ raise ValueError(
+ "query.source date range, interval, and output series would produce approximately "
+ f"{estimated_points} points; live metrics accept at most {MAX_LIVE_METRIC_QUERY_POINTS}"
+ )
+ return value
+
+
class ReportMetricComparison(BaseModel):
value: float = Field(description="Baseline or previous value, formatted like the metric value.")
label: str = Field(description="Short context for the comparison, such as `Previous period`.")
@@ -282,15 +423,7 @@ class ReportMetric(BaseModel):
@field_validator("metric_id")
@classmethod
def metric_id_must_be_reference_safe(cls, value: str) -> str:
- if len(value) > MAX_METRIC_ID_LENGTH:
- raise ValueError(f"must not exceed {MAX_METRIC_ID_LENGTH} characters")
- normalized = value.strip()
- if not _METRIC_ID_RE.fullmatch(normalized):
- raise ValueError(
- "must contain only lowercase letters, numbers, underscores, or hyphens, "
- "and must start with a lowercase letter or number"
- )
- return normalized
+ return validate_metric_id(value)
@field_validator("title")
@classmethod
@@ -374,110 +507,7 @@ class ReportMetric(BaseModel):
@field_validator("query")
@classmethod
def query_must_be_a_live_trends_node(cls, value: dict[str, Any]) -> dict[str, Any]:
- validate_report_query(value, allowed_kinds=_LIVE_METRIC_QUERY_KINDS)
- try:
- # Import only while validating authored content: importing the generated schema at module
- # load would put it back on every signals model and Temporal worker startup path.
- from posthog.schema import InsightVizNode # noqa: PLC0415 — keeps the generated schema off startup
-
- InsightVizNode.model_validate(value)
- except ValidationError as error:
- first_error = error.errors(include_input=False)[0]
- location = ".".join(str(part) for part in first_error["loc"])
- raise ValueError(
- f"query must match the canonical InsightVizNode schema; {location}: {first_error['msg']}"
- ) from None
- source = value.get("source")
- if not isinstance(source, dict) or source.get("kind") != "TrendsQuery":
- raise ValueError("query must wrap one TrendsQuery in an InsightVizNode")
- series = source.get("series")
- if not isinstance(series, list) or not series or any(not isinstance(item, dict) for item in series):
- raise ValueError("query.source.series must contain at least one Trends series")
- if len(series) > MAX_LIVE_METRIC_QUERY_SERIES:
- raise ValueError(f"query.source.series accepts at most {MAX_LIVE_METRIC_QUERY_SERIES} series")
- if any(item.get("kind") not in _LIVE_METRIC_SERIES_KINDS for item in series):
- raise ValueError("a live metric query must use only event or action series so reader access can be checked")
- for item in series:
- if item["kind"] == "EventsNode":
- event = item.get("event")
- if not isinstance(event, str) or not event.strip():
- raise ValueError("a live metric event series needs a non-empty event name")
- else:
- action_id = item.get("id")
- if not isinstance(action_id, int) or isinstance(action_id, bool) or action_id <= 0:
- raise ValueError("a live metric action series needs a positive integer action id")
- if source.get("breakdownFilter") or source.get("breakdown"):
- raise ValueError("a live metric query must not use a breakdown because it represents one measurement")
- compare_filter = source.get("compareFilter")
- if isinstance(compare_filter, dict) and compare_filter.get("compare"):
- raise ValueError("a live metric query must not use compare mode because it represents one measurement")
- trends_filter = source.get("trendsFilter")
- if isinstance(trends_filter, dict):
- if trends_filter.get("compare"):
- raise ValueError("a live metric query must not use compare mode because it represents one measurement")
- if (
- trends_filter.get("display") == "Metric"
- and trends_filter.get("metricShowChange", True) is not False
- and trends_filter.get("metricSummary", "total") != "latest"
- ):
- raise ValueError(
- "a live metric query using the Metric display must disable metricShowChange or use the latest "
- "summary so the Trends runner does not enable compare mode"
- )
- date_range = source.get("dateRange")
- if not isinstance(date_range, dict):
- raise ValueError("query.source.dateRange.date_from must be a relative time window such as `-30d`")
- date_from = date_range.get("date_from")
- if not isinstance(date_from, str):
- raise ValueError("query.source.dateRange.date_from must be a relative time window such as `-30d`")
- relative_window = _RELATIVE_DATE_FROM_RE.fullmatch(date_from)
- if relative_window is None:
- raise ValueError("query.source.dateRange.date_from must be a relative time window such as `-30d`")
- amount, unit = relative_window.groups()
- window_seconds = int(amount) * _RELATIVE_WINDOW_SECONDS[unit]
- if window_seconds > MAX_LIVE_METRIC_WINDOW_DAYS * _RELATIVE_WINDOW_SECONDS["d"]:
- raise ValueError(
- f"query.source.dateRange must not exceed {MAX_LIVE_METRIC_WINDOW_DAYS} days for a live metric"
- )
- if date_range.get("date_to") not in (None, ""):
- raise ValueError("query.source.dateRange.date_to must be empty so a live metric advances with time")
- interval = source.get("interval")
- if interval is None:
- interval = "day"
- if not isinstance(interval, str) or interval not in _LIVE_METRIC_INTERVAL_SECONDS:
- accepted_intervals = ", ".join(_LIVE_METRIC_INTERVAL_SECONDS)
- raise ValueError(f"query.source.interval must be one of {accepted_intervals}")
- output_series_count = len(series)
- selected_formulas: list[object] = []
- if isinstance(trends_filter, dict):
- formula_nodes = trends_filter.get("formulaNodes")
- formulas = trends_filter.get("formulas")
- formula = trends_filter.get("formula")
- if isinstance(formula_nodes, list) and formula_nodes:
- output_series_count = len(formula_nodes)
- selected_formulas = [node.get("formula") if isinstance(node, dict) else node for node in formula_nodes]
- elif isinstance(formulas, list) and formulas:
- output_series_count = len(formulas)
- selected_formulas = list(formulas)
- elif isinstance(formula, str) and formula:
- output_series_count = 1
- selected_formulas = [formula]
- if output_series_count != 1:
- raise ValueError(
- "a live metric query must produce exactly one output series; use one source or combine up to "
- f"{MAX_LIVE_METRIC_QUERY_SERIES} source series with exactly one formula"
- )
- for selected_formula in selected_formulas:
- _validate_live_metric_formula(selected_formula, len(series))
- interval_seconds = _LIVE_METRIC_INTERVAL_SECONDS[interval]
- estimated_buckets = (window_seconds + interval_seconds - 1) // interval_seconds + 1
- estimated_points = estimated_buckets * output_series_count
- if estimated_points > MAX_LIVE_METRIC_QUERY_POINTS:
- raise ValueError(
- "query.source date range, interval, and output series would produce approximately "
- f"{estimated_points} points; live metrics accept at most {MAX_LIVE_METRIC_QUERY_POINTS}"
- )
- return value
+ return validate_live_metric_query(value)
@model_validator(mode="after")
def measurement_must_be_available_and_consistent(self) -> ReportMetric:
diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.py
index 589b4f1729dc..74f304ce933a 100644
--- a/products/signals/backend/routes.py
+++ b/products/signals/backend/routes.py
@@ -21,6 +21,12 @@ def register_routes(routers: RouterRegistry) -> None:
signal_reports_router = routers.projects.register(
r"signals/reports", signals.SignalReportViewSet, "project_signal_reports", ["team_id"]
)
+ signal_reports_router.register(
+ r"checks",
+ signals.SignalReportCheckViewSet,
+ "project_signal_report_checks",
+ ["team_id", "report_id"],
+ )
signal_reports_router.register(
r"artefacts",
signals.SignalReportArtefactViewSet,
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 9a2084e15440..c8c257733d52 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -1,9 +1,11 @@
import json
+import uuid
from collections.abc import Mapping
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import TYPE_CHECKING, cast
from django.db.models import TextChoices
+from django.utils import timezone
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field
@@ -20,6 +22,19 @@ from products.signals.backend import contracts
from products.signals.backend.billing import REFUND_INELIGIBILITY_REASONS, refund_ineligibility_reason
from products.signals.backend.contracts import DEFAULT_NOT_ACTIONABLE_KEY, STEERING_KEY, STEERING_MAX_LENGTH
from products.signals.backend.enums import SignalSourceProduct, SignalSourceType
+from products.signals.backend.report_checks import (
+ CHECK_CONFIG_SCHEMAS,
+ DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
+ DEFAULT_FIRST_RUN_AFTER,
+ MAX_CHECK_HORIZON,
+ MAX_CHECK_INTERVAL_MINUTES,
+ MAX_CHECK_RATIONALE_LENGTH,
+ MAX_CHECK_RUNS,
+ MAX_CHECK_TITLE_LENGTH,
+ MIN_CHECK_INTERVAL_MINUTES,
+ CheckConfigValidationError,
+ parse_check_config,
+)
from products.warehouse_sources.backend.facade.models import ExternalDataSchema
from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatus
@@ -35,6 +50,7 @@ from .models import (
SignalReport,
SignalReportArtefact,
SignalReportAssignment,
+ SignalReportCheck,
SignalReportRefund,
SignalReportTrackerIssue,
SignalReportWorkState,
@@ -830,6 +846,29 @@ _REPORT_METRIC_QUERY_HELP = (
)
+def report_metric_access_policy(context: dict) -> ReportMetricAccessPolicy:
+ """The viewer's policy for this request, built once per serializer context.
+
+ Report metrics, check configs, and check results all carry data materialized without a viewer,
+ so every one of them is gated by the same policy rather than by three readings of "who may see a
+ query and its value".
+ """
+ context_key = "_report_metric_access_policy"
+ cached = context.get(context_key)
+ if isinstance(cached, ReportMetricAccessPolicy):
+ return cached
+
+ request = context.get("request")
+ get_team = context.get("get_team")
+ team = get_team() if callable(get_team) else None
+ policy = ReportMetricAccessPolicy(
+ request=request if isinstance(request, Request) else None,
+ team=team if isinstance(team, Team) else None,
+ )
+ context[context_key] = policy
+ return policy
+
+
class ReportMetricSerializer(serializers.Serializer):
"""One impact measurement shown on a report."""
@@ -932,20 +971,7 @@ class ReportMetricSerializer(serializers.Serializer):
return representation
def _access_policy(self) -> ReportMetricAccessPolicy:
- context_key = "_report_metric_access_policy"
- cached = self.context.get(context_key)
- if isinstance(cached, ReportMetricAccessPolicy):
- return cached
-
- request = self.context.get("request")
- get_team = self.context.get("get_team")
- team = get_team() if callable(get_team) else None
- policy = ReportMetricAccessPolicy(
- request=request if isinstance(request, Request) else None,
- team=team if isinstance(team, Team) else None,
- )
- self.context[context_key] = policy
- return policy
+ return report_metric_access_policy(self.context)
class ReportMetricWriteSerializer(ReportMetricSerializer):
@@ -1532,6 +1558,210 @@ class ReportSignalsResponseSerializer(serializers.Serializer):
signals = SignalNodeSerializer(many=True, help_text="All signals contributing to the report.")
+# ── Report checks ───────────────────────────────────────────────────────────────
+
+
+# Shown in place of a check result's explanation when the viewer cannot read the measured data.
+CHECK_RESULT_HIDDEN_EXPLANATION = (
+ "You don't have access to the data this check measures. Ask a project admin to grant it."
+)
+
+
+def _is_uuid(value: str) -> bool:
+ try:
+ uuid.UUID(value)
+ except (ValueError, TypeError):
+ return False
+ return True
+
+
+@extend_schema_field(
+ PolymorphicProxySerializer(
+ component_name="SignalReportCheckConfig",
+ # Same cast as SignalExtra above: spectacular's PydanticExtension resolves these at
+ # schema-build time, but the stubs only know about DRF serializers.
+ serializers=cast(list, list(CHECK_CONFIG_SCHEMAS.values())),
+ resource_type_field_name=None,
+ )
+)
+class SignalReportCheckConfigField(serializers.JSONField):
+ """Kind-specific check configuration, validated against its kind's schema on every write."""
+
+
+def redact_check_config(config: Mapping[str, object], policy: ReportMetricAccessPolicy) -> dict[str, object]:
+ """Hide the data-bearing fields of a check config this viewer may not read.
+
+ The query names events, actions, and property filters with literal values, and the baseline is a
+ number measured without a viewer, so both go through the same gate as a report metric's query
+ and snapshot. The comparison and schedule stay: they are the author's expectation, not data.
+ """
+ redacted = dict(config)
+ if "query" in redacted and not policy.may_read_query(config):
+ redacted["query"] = None
+ if "baseline_value" in redacted and not policy.may_read_snapshot(config):
+ redacted["baseline_value"] = None
+ return redacted
+
+
+class SignalReportCheckSerializer(serializers.ModelSerializer):
+ config = SignalReportCheckConfigField(
+ help_text=(
+ "What the check measures and what the result must satisfy; the shape depends on `kind`. "
+ "`query` and `baseline_value` are null when you cannot read the data they describe."
+ )
+ )
+
+ def to_representation(self, instance: SignalReportCheck) -> dict[str, object]:
+ representation = dict(super().to_representation(instance))
+ config = representation.get("config")
+ if isinstance(config, Mapping):
+ representation["config"] = redact_check_config(config, report_metric_access_policy(self.context))
+ return representation
+
+ class Meta:
+ model = SignalReportCheck
+ fields = [
+ "id",
+ "title",
+ "rationale",
+ "kind",
+ "status",
+ "config",
+ "next_run_at",
+ "run_interval_minutes",
+ "runs_remaining",
+ "expires_at",
+ "last_run_at",
+ "last_outcome",
+ "consecutive_errors",
+ "created_at",
+ "updated_at",
+ ]
+ read_only_fields = fields
+ extra_kwargs = {
+ "title": {"help_text": "Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`."},
+ "rationale": {"help_text": "Why the author set the check."},
+ "kind": {"help_text": "How the check is evaluated."},
+ "status": {"help_text": "`active` while the check still runs; every other value is terminal."},
+ "next_run_at": {"help_text": "When the coordinator next evaluates the check."},
+ "run_interval_minutes": {"help_text": "Gap between runs for a recurring check; null for a one-shot."},
+ "runs_remaining": {"help_text": "Evaluations still owed before the check retires as passed."},
+ "expires_at": {"help_text": "Horizon after which the check retires without running again."},
+ "last_run_at": {"help_text": "When the check last ran; null before its first run."},
+ "last_outcome": {"help_text": "Verdict of the most recent run."},
+ "consecutive_errors": {"help_text": "Runs that could not be measured since the last clean one."},
+ }
+
+
+class SignalReportCheckWriteSerializer(serializers.Serializer):
+ """Request body for creating a check on a report.
+
+ The schedule is the check's own: `next_run_at` says when to look, rather than the system
+ deriving a soak window from a merged pull request that many fixes never have.
+ """
+
+ title = serializers.CharField(
+ max_length=MAX_CHECK_TITLE_LENGTH,
+ help_text="Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.",
+ )
+ rationale = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=MAX_CHECK_RATIONALE_LENGTH,
+ help_text="Why the check is worth running.",
+ )
+ kind = serializers.ChoiceField(
+ choices=SignalReportCheck.Kind.choices,
+ help_text="How the check is evaluated.",
+ )
+ config = SignalReportCheckConfigField(
+ help_text="What the check measures and what the result must satisfy; the shape depends on `kind`."
+ )
+ next_run_at = serializers.DateTimeField(
+ required=False,
+ help_text=(
+ "When to first evaluate the check. Must be in the future and within "
+ f"{MAX_CHECK_HORIZON.days} days. Defaults to {DEFAULT_FIRST_RUN_AFTER.days} days from now."
+ ),
+ )
+ run_interval_minutes = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=MIN_CHECK_INTERVAL_MINUTES,
+ max_value=MAX_CHECK_INTERVAL_MINUTES,
+ help_text=(
+ f"Gap between runs for a recurring check, between {MIN_CHECK_INTERVAL_MINUTES} and "
+ f"{MAX_CHECK_INTERVAL_MINUTES} minutes. Omit for a one-shot check."
+ ),
+ )
+ runs_remaining = serializers.IntegerField(
+ required=False,
+ min_value=1,
+ max_value=MAX_CHECK_RUNS,
+ help_text=f"How many times to evaluate the check, at most {MAX_CHECK_RUNS}. Defaults to 1.",
+ )
+ expires_at = serializers.DateTimeField(
+ required=False,
+ help_text=(
+ "Horizon after which the check retires unrun. Defaults to "
+ f"{DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN.days} days after the last scheduled run, or the "
+ f"{MAX_CHECK_HORIZON.days}-day horizon if that comes first."
+ ),
+ )
+
+ def validate(self, attrs: dict) -> dict:
+ now = timezone.now()
+ horizon = now + MAX_CHECK_HORIZON
+
+ next_run_at = attrs.get("next_run_at") or now + DEFAULT_FIRST_RUN_AFTER
+ if next_run_at <= now:
+ raise serializers.ValidationError({"next_run_at": "must be in the future."})
+ if next_run_at > horizon:
+ raise serializers.ValidationError({"next_run_at": f"must be within {MAX_CHECK_HORIZON.days} days."})
+
+ interval = attrs.get("run_interval_minutes")
+ runs = attrs.get("runs_remaining", 1)
+ if interval is None and runs != 1:
+ raise serializers.ValidationError(
+ {"run_interval_minutes": "a check that runs more than once needs an interval."}
+ )
+
+ last_run_at = next_run_at + timedelta(minutes=interval * (runs - 1)) if interval else next_run_at
+ if last_run_at > horizon:
+ raise serializers.ValidationError(
+ {
+ "run_interval_minutes": (
+ f"the last run must fall within {MAX_CHECK_HORIZON.days} days. "
+ "Use a shorter interval or fewer runs."
+ )
+ }
+ )
+
+ # The padding after the last run is a default, not something the caller asked for, so it
+ # gives way to the horizon. Letting it overflow would reject a legal schedule and blame an
+ # `expires_at` the caller never sent.
+ expires_at = attrs.get("expires_at") or min(last_run_at + DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN, horizon)
+ if expires_at <= next_run_at:
+ raise serializers.ValidationError({"expires_at": "must be after the first run."})
+ if expires_at > horizon:
+ raise serializers.ValidationError({"expires_at": f"must be within {MAX_CHECK_HORIZON.days} days."})
+
+ try:
+ parse_check_config(attrs["kind"], attrs["config"])
+ except CheckConfigValidationError as error:
+ raise serializers.ValidationError({"config": str(error)})
+ config = attrs["config"]
+ if isinstance(config, Mapping) and config.get("metric_id") is not None and config.get("query") is not None:
+ raise serializers.ValidationError(
+ {"config": "provide either metric_id or query, not both. The metric's query is copied onto the check."}
+ )
+
+ attrs["next_run_at"] = next_run_at
+ attrs["expires_at"] = expires_at
+ attrs["runs_remaining"] = runs
+ return attrs
+
+
class SignalReportArtefactSerializer(serializers.ModelSerializer):
claim_id = serializers.UUIDField(
read_only=True, allow_null=True, help_text="Work claim that produced this artefact."
@@ -1605,8 +1835,39 @@ class SignalReportArtefactSerializer(serializers.ModelSerializer):
uuid_to_user=reviewer_uuid_map,
)
+ if obj.type == SignalReportArtefact.ArtefactType.CHECK_RESULT and isinstance(parsed, dict):
+ return self._redact_check_result(obj, parsed)
+
return parsed
+ def _redact_check_result(self, obj: SignalReportArtefact, content: dict) -> dict:
+ """Hide a check result's measured numbers from a viewer who may not read the check's query.
+
+ The value was measured without a viewer, exactly like a report metric snapshot, so the same
+ policy decides. The outcome tag stays so the timeline still reads; the numbers and the line
+ that quotes them do not. A result whose check no longer exists fails closed.
+ """
+ policy = report_metric_access_policy(self.context)
+ configs: dict[str, object] = self.context.setdefault("_signals_check_configs", {})
+ check_id = str(content.get("check_id"))
+ if check_id not in configs:
+ configs[check_id] = (
+ SignalReportCheck.all_teams.filter(id=check_id, report_id=obj.report_id)
+ .values_list("config", flat=True)
+ .first()
+ if _is_uuid(check_id)
+ else None
+ )
+ config = configs[check_id]
+ if isinstance(config, Mapping) and policy.may_read_snapshot(config):
+ return content
+ return {
+ **content,
+ "observed_value": None,
+ "baseline_value": None,
+ "explanation": CHECK_RESULT_HIDDEN_EXPLANATION,
+ }
+
class SuggestedReviewerEntryWriteSerializer(serializers.Serializer):
"""Single entry in a PUT body for a `suggested_reviewers` artefact.
diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.py
index 53df1732f020..d851f08e75c5 100644
--- a/products/signals/backend/temporal/__init__.py
+++ b/products/signals/backend/temporal/__init__.py
@@ -2,6 +2,7 @@ from products.signals.backend.temporal.agentic.report import run_agentic_report_
from products.signals.backend.temporal.agentic.scout_coordinator import (
SignalsScoutCoordinatorWorkflow,
fetch_enabled_signals_scout_runs_activity,
+ run_due_signal_report_checks_activity,
stamp_dispatched_signals_scout_runs_activity,
)
from products.signals.backend.temporal.agentic.scout_scheduler import (
@@ -115,6 +116,7 @@ ACTIVITIES = [
fetch_error_tracking_issues_activity,
fetch_enabled_signals_scout_runs_activity,
stamp_dispatched_signals_scout_runs_activity,
+ run_due_signal_report_checks_activity,
assign_and_emit_signal_activity,
capture_signal_dropped_activity,
check_signals_quota_limited_activity,
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index e7e1df7704fd..da72f49a4c5b 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -22,6 +22,7 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
from products.signals.backend.models import SignalScoutConfig
+from products.signals.backend.report_check_execution import run_due_report_checks
from products.signals.backend.scout_harness.config_registry import live_scout_skill_names, register_missing_configs
from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
from products.signals.backend.scout_harness.limits import (
@@ -121,6 +122,34 @@ class CoordinatorWorkflowOutput:
skipped_count: int
+@frozen
+class RunDueChecksInput:
+ """No fields today; the executor reads its own bounds."""
+
+
+@frozen
+class RunDueChecksOutput:
+ expired: int
+ passed: int
+ failed: int
+ errored: int
+
+
+async def run_due_signal_report_checks_activity(_input: RunDueChecksInput) -> RunDueChecksOutput:
+ """Measure every report check due this tick.
+
+ Rides the coordinator rather than a schedule of its own: soak windows are days, so tick
+ granularity is ample, and a deterministic check costs one cached Trends query with no sandbox
+ and no scout enrolment.
+ """
+ async with Heartbeater():
+ summary = await database_sync_to_async(run_due_report_checks, thread_sensitive=False)()
+ return RunDueChecksOutput(
+ expired=summary.expired, passed=summary.passed, failed=summary.failed, errored=summary.errored
+ )
+
+
@activity.defn
async def fetch_enabled_signals_scout_runs_activity(
_input: FetchEnabledRunsInput,
@@ -667,6 +696,14 @@ class SignalsScoutCoordinatorWorkflow:
@workflow.run
async def run(self, _input: CoordinatorWorkflowInput) -> CoordinatorWorkflowOutput:
+ if workflow.patched("signals-report-checks-2026-09"):
+ await workflow.execute_activity(
+ run_due_signal_report_checks_activity,
+ RunDueChecksInput(),
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+
fetch_result = await workflow.execute_activity(
fetch_enabled_signals_scout_runs_activity,
FetchEnabledRunsInput(),
diff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.py
new file mode 100644
index 000000000000..45606a74b6a5
--- /dev/null
+++ b/products/signals/backend/test/test_report_checks.py
@@ -0,0 +1,657 @@
+from datetime import timedelta
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+from posthog.models import PropertyDefinition, Team
+
+from products.access_control.backend.facade.contracts import PropertyAccessLevel
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportCheck
+from products.signals.backend.report_check_execution import (
+ CHECK_ERROR_RETRY_AFTER,
+ CheckVerdict,
+ collect_due_checks,
+ evaluate_check_value,
+ expire_overdue_checks,
+ record_check_verdict,
+ resolve_check_query,
+ run_due_report_checks,
+)
+from products.signals.backend.report_checks import (
+ DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
+ MAX_ACTIVE_CHECKS_PER_REPORT,
+ MAX_CHECK_HORIZON,
+ MAX_CHECK_INTERVAL_MINUTES,
+ MAX_CHECK_RUNS,
+ MAX_CONSECUTIVE_CHECK_ERRORS,
+ MIN_CHECK_INTERVAL_MINUTES,
+ CheckComparison,
+ CheckConfigValidationError,
+ MetricThresholdConfig,
+ parse_check_config,
+)
+from products.signals.backend.report_metric_refresh import MetricMeasurement
+from products.signals.backend.serializers import CHECK_RESULT_HIDDEN_EXPLANATION, SignalReportCheckWriteSerializer
+from products.signals.backend.test.report_metric_test_fixtures import trends_metric_query
+from products.signals.backend.views import SignalReportCheckViewSet
+
+_MEASURE = "products.signals.backend.report_check_execution.measure_metric"
+
+_PAGEVIEWS = trends_metric_query(series=[{"kind": "EventsNode", "event": "$pageview"}])
+
+
+def _threshold_config(**overrides: object) -> dict:
+ return {"query": _PAGEVIEWS, "comparison": {"operator": "lte", "value": 10}, **overrides}
+
+
+class TestCheckComparison(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("lte_under", {"operator": "lte", "value": 10}, 4.0, "passed"),
+ ("lte_on_bound", {"operator": "lte", "value": 10}, 10.0, "passed"),
+ ("lte_over", {"operator": "lte", "value": 10}, 11.0, "failed"),
+ ("gte_over", {"operator": "gte", "value": 10}, 12.0, "passed"),
+ ("gte_on_bound", {"operator": "gte", "value": 10}, 10.0, "passed"),
+ ("gte_under", {"operator": "gte", "value": 10}, 9.0, "failed"),
+ ("between_inside", {"operator": "between", "bounds": {"lower": 1, "upper": 5}}, 3.0, "passed"),
+ ("between_below", {"operator": "between", "bounds": {"lower": 1, "upper": 5}}, 0.5, "failed"),
+ ("between_above", {"operator": "between", "bounds": {"lower": 1, "upper": 5}}, 9.0, "failed"),
+ ]
+ )
+ def test_operator_maps_to_the_bound_it_names(self, _name, comparison, observed, expected_outcome) -> None:
+ verdict = evaluate_check_value(
+ comparison=CheckComparison.model_validate(comparison),
+ observed_value=observed,
+ subject="Checkout errors",
+ )
+ assert verdict.outcome == expected_outcome
+ assert verdict.observed_value == observed
+ assert verdict.explanation.strip()
+
+ @parameterized.expand(
+ [
+ ("between_without_bounds", {"operator": "between", "value": 3}),
+ ("lte_without_value", {"operator": "lte"}),
+ ("lte_with_bounds", {"operator": "lte", "bounds": {"lower": 1, "upper": 2}}),
+ ("inverted_bounds", {"operator": "between", "bounds": {"lower": 5, "upper": 1}}),
+ ("boolean_value", {"operator": "lte", "value": True}),
+ ]
+ )
+ def test_malformed_comparison_is_refused(self, _name, comparison) -> None:
+ with self.assertRaises(CheckConfigValidationError):
+ parse_check_config("metric_threshold", {"query": _PAGEVIEWS, "comparison": comparison})
+
+ @parameterized.expand(
+ [
+ ("neither_source", {"comparison": {"operator": "lte", "value": 1}}),
+ ("empty_metric_id", {"metric_id": "", "comparison": {"operator": "lte", "value": 1}}),
+ (
+ "unknown_config_key",
+ {"query": _PAGEVIEWS, "comparison": {"operator": "lte", "value": 1}, "baselineValue": 3},
+ ),
+ (
+ "unknown_comparison_key",
+ {"query": _PAGEVIEWS, "comparison": {"operator": "lte", "value": 1, "tolerance": 2}},
+ ),
+ (
+ "unknown_bounds_key",
+ {
+ "query": _PAGEVIEWS,
+ "comparison": {"operator": "between", "bounds": {"lower": 1, "upper": 5, "step": 1}},
+ },
+ ),
+ ("uppercase_metric_id", {"metric_id": "Checkout_Errors", "comparison": {"operator": "lte", "value": 1}}),
+ (
+ "unbounded_query",
+ {
+ "query": trends_metric_query(
+ series=[{"kind": "EventsNode", "event": "$pageview"}], date_from="-400d"
+ ),
+ "comparison": {"operator": "lte", "value": 1},
+ },
+ ),
+ ]
+ )
+ def test_malformed_metric_threshold_config_is_refused(self, _name, config) -> None:
+ with self.assertRaises(CheckConfigValidationError):
+ parse_check_config("metric_threshold", config)
+
+ def test_a_padded_metric_reference_is_normalized_so_it_can_still_match(self) -> None:
+ config = parse_check_config(
+ "metric_threshold", {"metric_id": " checkout-errors ", "comparison": {"operator": "lte", "value": 1}}
+ )
+
+ assert isinstance(config, MetricThresholdConfig)
+ assert config.metric_id == "checkout-errors"
+
+ def test_unknown_kind_is_refused(self) -> None:
+ with self.assertRaises(CheckConfigValidationError):
+ parse_check_config("agent", {"instructions": "look again"})
+
+
+class TestCheckScheduleValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("first_run_in_the_past", {"next_run_at": "2020-01-01T00:00:00Z"}, "next_run_at"),
+ ("first_run_past_the_horizon", {"next_run_at": "2099-01-01T00:00:00Z"}, "next_run_at"),
+ ("repeats_without_an_interval", {"runs_remaining": 3}, "run_interval_minutes"),
+ (
+ "interval_below_the_floor",
+ {"run_interval_minutes": MIN_CHECK_INTERVAL_MINUTES - 1, "runs_remaining": 2},
+ "run_interval_minutes",
+ ),
+ (
+ "recurring_interval_past_the_horizon",
+ {"run_interval_minutes": MAX_CHECK_INTERVAL_MINUTES + 1, "runs_remaining": 2},
+ "run_interval_minutes",
+ ),
+ (
+ "one_shot_interval_past_the_horizon",
+ {"run_interval_minutes": 3_000_000_000},
+ "run_interval_minutes",
+ ),
+ ("expiry_before_the_first_run", {"expires_at": "2020-01-01T00:00:00Z"}, "expires_at"),
+ (
+ "last_run_past_the_horizon",
+ {"run_interval_minutes": 30 * 24 * 60, "runs_remaining": 5},
+ "run_interval_minutes",
+ ),
+ ("both_a_metric_and_a_query", {"config": _threshold_config(metric_id="errors")}, "config"),
+ ]
+ )
+ def test_an_impossible_request_is_refused(self, _name, overrides, field) -> None:
+ serializer = SignalReportCheckWriteSerializer(
+ data={"title": "Errors stay low", "kind": "metric_threshold", "config": _threshold_config(), **overrides}
+ )
+ assert not serializer.is_valid()
+ assert field in serializer.errors
+
+ def test_defaults_fill_in_a_whole_schedule(self) -> None:
+ serializer = SignalReportCheckWriteSerializer(
+ data={"title": "Errors stay low", "kind": "metric_threshold", "config": _threshold_config()}
+ )
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.validated_data["next_run_at"] > timezone.now()
+ assert serializer.validated_data["expires_at"] > serializer.validated_data["next_run_at"]
+ assert (
+ serializer.validated_data["expires_at"]
+ == serializer.validated_data["next_run_at"] + DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN
+ )
+ assert serializer.validated_data["runs_remaining"] == 1
+
+ @parameterized.expand(
+ [
+ ("one_shot_beyond_the_padding", 61, None, 1),
+ ("recurring_to_the_run_ceiling", 7, 7 * 24 * 60, MAX_CHECK_RUNS),
+ ]
+ )
+ def test_an_omitted_expiry_never_pushes_a_legal_schedule_past_the_horizon(
+ self, _name, first_run_in_days, interval, runs
+ ) -> None:
+ overrides: dict = {
+ "next_run_at": (timezone.now() + timedelta(days=first_run_in_days)).isoformat(),
+ "runs_remaining": runs,
+ }
+ if interval is not None:
+ overrides["run_interval_minutes"] = interval
+
+ before = timezone.now()
+ serializer = SignalReportCheckWriteSerializer(
+ data={"title": "Errors stay low", "kind": "metric_threshold", "config": _threshold_config(), **overrides}
+ )
+ valid = serializer.is_valid()
+ after = timezone.now()
+
+ assert valid, serializer.errors
+ assert before + MAX_CHECK_HORIZON <= serializer.validated_data["expires_at"] <= after + MAX_CHECK_HORIZON
+
+
+class TestReportCheckExecution(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.RESOLVED, title="Fix")
+
+ def _check(self, **overrides) -> SignalReportCheck:
+ now = timezone.now()
+ fields: dict = {
+ "team": self.team,
+ "report": self.report,
+ "title": "Checkout errors stay low",
+ "kind": SignalReportCheck.Kind.METRIC_THRESHOLD,
+ "config": _threshold_config(),
+ "next_run_at": now - timedelta(minutes=1),
+ "expires_at": now + timedelta(days=30),
+ }
+ fields.update(overrides)
+ return SignalReportCheck.objects.for_team(self.team.id).create(**fields)
+
+ def _results(self) -> list[SignalReportArtefact]:
+ return list(
+ SignalReportArtefact.objects.filter(
+ report=self.report, type=SignalReportArtefact.ArtefactType.CHECK_RESULT
+ ).order_by("created_at")
+ )
+
+ def test_a_one_shot_check_that_holds_retires_as_passed_with_a_result(self) -> None:
+ check = self._check()
+ with patch(_MEASURE, return_value=MetricMeasurement(value=3.0, measured_at=timezone.now(), series=None)):
+ summary = run_due_report_checks()
+
+ assert summary.passed == 1
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.PASSED
+ assert check.last_outcome == SignalReportCheck.Outcome.PASSED
+ assert check.last_run_at is not None
+ results = self._results()
+ assert len(results) == 1
+ assert '"outcome":"passed"' in results[0].content
+ assert '"observed_value":3.0' in results[0].content
+
+ def test_a_check_that_breaches_retires_as_failed(self) -> None:
+ check = self._check()
+ with patch(_MEASURE, return_value=MetricMeasurement(value=42.0, measured_at=timezone.now(), series=None)):
+ run_due_report_checks()
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.FAILED
+ assert '"outcome":"failed"' in self._results()[0].content
+
+ def test_a_recurring_check_rearms_until_its_runs_are_spent(self) -> None:
+ check = self._check(run_interval_minutes=MIN_CHECK_INTERVAL_MINUTES, runs_remaining=2)
+ with patch(_MEASURE, return_value=MetricMeasurement(value=1.0, measured_at=timezone.now(), series=None)):
+ run_due_report_checks()
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ACTIVE
+ assert check.runs_remaining == 1
+ assert check.next_run_at > timezone.now()
+
+ check.next_run_at = timezone.now() - timedelta(minutes=1)
+ check.save(update_fields=["next_run_at"])
+ with patch(_MEASURE, return_value=MetricMeasurement(value=1.0, measured_at=timezone.now(), series=None)):
+ run_due_report_checks()
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.PASSED
+ assert len(self._results()) == 2
+
+ def test_a_recurring_check_retires_rather_than_running_past_its_horizon(self) -> None:
+ check = self._check(
+ run_interval_minutes=MIN_CHECK_INTERVAL_MINUTES,
+ runs_remaining=2,
+ expires_at=timezone.now() + timedelta(hours=1),
+ )
+ with patch(_MEASURE, return_value=MetricMeasurement(value=1.0, measured_at=timezone.now(), series=None)):
+ run_due_report_checks()
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.PASSED
+
+ def test_a_check_that_cannot_be_measured_retries_then_retires(self) -> None:
+ check = self._check()
+ for _ in range(MAX_CONSECUTIVE_CHECK_ERRORS):
+ check.refresh_from_db()
+ check.next_run_at = timezone.now() - timedelta(minutes=1)
+ check.save(update_fields=["next_run_at"])
+ with patch(_MEASURE, side_effect=ValueError("query returned no series")):
+ run_due_report_checks()
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ERRORED
+ assert len(self._results()) == MAX_CONSECUTIVE_CHECK_ERRORS
+
+ def test_a_single_failure_to_measure_only_delays_the_check(self) -> None:
+ check = self._check()
+ with patch(_MEASURE, side_effect=ValueError("boom")):
+ summary = run_due_report_checks()
+
+ assert summary.errored == 1
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ACTIVE
+ assert check.consecutive_errors == 1
+ assert check.next_run_at >= timezone.now() + CHECK_ERROR_RETRY_AFTER - timedelta(minutes=1)
+
+ def test_a_check_whose_stored_config_stopped_parsing_records_an_errored_run(self) -> None:
+ check = self._check()
+ # A config that parsed when it was written and no longer does, as a tightened query rule leaves it.
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).update(
+ config={"comparison": {"operator": "lte", "value": 10}}
+ )
+
+ summary = run_due_report_checks()
+
+ assert summary.errored == 1
+ check.refresh_from_db()
+ assert check.consecutive_errors == 1
+ assert check.next_run_at > timezone.now()
+ results = self._results()
+ assert len(results) == 1
+ assert '"outcome":"errored"' in results[0].content
+
+ def test_an_errored_run_publishes_our_reason_but_not_a_raw_query_error(self) -> None:
+ check = self._check()
+ with patch(_MEASURE, side_effect=ValueError("metric query returned no series")):
+ run_due_report_checks()
+
+ assert "metric query returned no series" in self._results()[0].content
+
+ check.refresh_from_db()
+ check.next_run_at = timezone.now() - timedelta(minutes=1)
+ check.save(update_fields=["next_run_at"])
+ server_error = RuntimeError("DB::Exception: syntax error\nStack trace:\n0. secret internals")
+ with patch(_MEASURE, side_effect=server_error):
+ run_due_report_checks()
+
+ latest = self._results()[-1].content
+ assert '"outcome":"errored"' in latest
+ assert "Stack trace" not in latest
+ assert "secret internals" not in latest
+ # 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
+ self.report.save(update_fields=["status"])
+ assert collect_due_checks(timezone.now()) == []
+
+ self.report.status = SignalReport.Status.RESOLVED
+ 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:
+ check = self._check()
+ check.status = SignalReportCheck.Status.CANCELLED
+ check.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 self._results() == []
+
+ def test_an_unrun_check_past_its_horizon_expires(self) -> None:
+ check = self._check(
+ next_run_at=timezone.now() + timedelta(days=1), expires_at=timezone.now() - timedelta(days=1)
+ )
+ assert expire_overdue_checks(timezone.now()) == 1
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.EXPIRED
+ assert self._results() == []
+
+ def test_a_check_past_its_horizon_is_not_due_even_when_the_sweep_has_not_reached_it(self) -> None:
+ now = timezone.now()
+ # The state every check reaches at its horizon: due, still active, and past its expiry.
+ self._check(next_run_at=now - timedelta(days=2), expires_at=now - timedelta(days=1))
+
+ assert collect_due_checks(now) == []
+
+ def test_one_team_with_a_backlog_does_not_starve_another_team(self) -> None:
+ now = timezone.now()
+ for minutes in (30, 20, 10):
+ self._check(next_run_at=now - timedelta(minutes=minutes))
+ other_team = self.organization.teams.create(name="Other")
+ other_report = SignalReport.objects.create(
+ team=other_team, status=SignalReport.Status.RESOLVED, title="Other fix"
+ )
+ other_check = SignalReportCheck.objects.for_team(other_team.id).create(
+ team=other_team,
+ report=other_report,
+ title="Their checkout errors stay low",
+ kind=SignalReportCheck.Kind.METRIC_THRESHOLD,
+ config=_threshold_config(),
+ next_run_at=now - timedelta(minutes=5),
+ expires_at=now + timedelta(days=30),
+ )
+
+ due = collect_due_checks(now, limit=2)
+
+ assert other_check.id in {check.id for check in due}
+
+ def test_a_check_riding_a_report_metric_measures_that_metric(self) -> None:
+ self.report.metrics = [
+ {
+ "metric_id": "checkout-errors",
+ "title": "Checkout errors",
+ "kind": "occurrences",
+ "query": _PAGEVIEWS,
+ }
+ ]
+ self.report.save(update_fields=["metrics"])
+ config = MetricThresholdConfig.model_validate(
+ {"metric_id": "checkout-errors", "comparison": {"operator": "lte", "value": 1}}
+ )
+ assert resolve_check_query(config, self.report) == _PAGEVIEWS
+
+ def test_a_check_riding_a_metric_whose_query_stopped_conforming_errors(self) -> None:
+ # The runner reads one series out of the result, so a breakdown would turn an arbitrary
+ # slice into a recorded verdict.
+ self.report.metrics = [
+ {
+ "metric_id": "checkout-errors",
+ "title": "Checkout errors",
+ "kind": "occurrences",
+ "query": {
+ **_PAGEVIEWS,
+ "source": {**_PAGEVIEWS["source"], "breakdownFilter": {"breakdown": "$browser"}},
+ },
+ }
+ ]
+ self.report.save(update_fields=["metrics"])
+ check = self._check(config={"metric_id": "checkout-errors", "comparison": {"operator": "lte", "value": 1}})
+
+ with patch(
+ _MEASURE, return_value=MetricMeasurement(value=0.0, measured_at=timezone.now(), series=None)
+ ) as measure:
+ run_due_report_checks()
+
+ assert not measure.called
+ check.refresh_from_db()
+ assert check.last_outcome == SignalReportCheck.Outcome.ERRORED
+ assert '"outcome":"errored"' in self._results()[0].content
+
+ def test_a_check_riding_a_metric_the_report_dropped_errors_rather_than_crashing(self) -> None:
+ check = self._check(config={"metric_id": "gone", "comparison": {"operator": "lte", "value": 1}})
+ run_due_report_checks()
+
+ check.refresh_from_db()
+ assert check.last_outcome == SignalReportCheck.Outcome.ERRORED
+ assert '"outcome":"errored"' in self._results()[0].content
+
+
+class TestReportCheckAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.RESOLVED, title="Fix")
+ self.url = f"/api/projects/{self.team.id}/signals/reports/{self.report.id}/checks/"
+
+ def test_create_then_list_then_cancel(self) -> None:
+ response = self.client.post(
+ self.url,
+ {"title": "Checkout errors stay low", "kind": "metric_threshold", "config": _threshold_config()},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ check_id = response.json()["id"]
+
+ listed = self.client.get(self.url)
+ assert [row["id"] for row in listed.json()["results"]] == [check_id]
+ assert listed.json()["results"][0]["config"]["query"] == _PAGEVIEWS
+
+ cancelled = self.client.delete(f"{self.url}{check_id}/")
+ assert cancelled.status_code == status.HTTP_200_OK
+ assert cancelled.json()["status"] == "cancelled"
+
+ already_cancelled = self.client.delete(f"{self.url}{check_id}/")
+ assert already_cancelled.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_cancelling_does_not_overwrite_a_verdict_that_landed_first(self) -> None:
+ created = self.client.post(
+ self.url,
+ {"title": "Checkout errors stay low", "kind": "metric_threshold", "config": _threshold_config()},
+ format="json",
+ )
+ check_id = created.json()["id"]
+ # The row the request read before a run committed its verdict.
+ stale = SignalReportCheck.objects.for_team(self.team.id).get(id=check_id)
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=check_id).update(
+ status=SignalReportCheck.Status.PASSED, last_outcome=SignalReportCheck.Outcome.PASSED
+ )
+
+ with patch.object(SignalReportCheckViewSet, "get_object", return_value=stale):
+ refused = self.client.delete(f"{self.url}{check_id}/")
+
+ assert refused.status_code == status.HTTP_400_BAD_REQUEST
+ assert (
+ SignalReportCheck.objects.for_team(self.team.id).get(id=check_id).status == SignalReportCheck.Status.PASSED
+ )
+
+ def test_a_metric_reference_is_resolved_and_copied_when_the_check_is_created(self) -> None:
+ payload = {
+ "title": "Checkout errors stay low",
+ "kind": "metric_threshold",
+ "config": {"metric_id": "checkout-errors", "comparison": {"operator": "lte", "value": 10}},
+ }
+
+ refused = self.client.post(self.url, payload, format="json")
+
+ assert refused.status_code == status.HTTP_400_BAD_REQUEST
+ assert not SignalReportCheck.objects.for_team(self.team.id).filter(report_id=self.report.id).exists()
+
+ self.report.metrics = [
+ {"metric_id": "checkout-errors", "title": "Checkout errors", "kind": "occurrences", "query": _PAGEVIEWS}
+ ]
+ self.report.save(update_fields=["metrics"])
+ created = self.client.post(self.url, payload, format="json")
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ stored = SignalReportCheck.objects.for_team(self.team.id).get(id=created.json()["id"])
+ assert stored.config["metric_id"] == "checkout-errors"
+ assert stored.config["query"] == _PAGEVIEWS
+
+ # Rewriting the metric under the same id must not move the check's target.
+ rewritten = trends_metric_query(series=[{"kind": "EventsNode", "event": "$autocapture"}])
+ self.report.metrics = [{**self.report.metrics[0], "query": rewritten}]
+ self.report.save(update_fields=["metrics"])
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=stored.id).update(
+ next_run_at=timezone.now() - timedelta(minutes=1)
+ )
+ with patch(
+ _MEASURE, return_value=MetricMeasurement(value=0.0, measured_at=timezone.now(), series=None)
+ ) as measure:
+ run_due_report_checks()
+ assert measure.call_args.args[0] == _PAGEVIEWS
+
+ def test_a_check_created_in_a_child_environment_stays_on_that_environment(self) -> None:
+ child = Team.objects.create(organization=self.organization, name="Child", parent_team=self.team)
+ report = SignalReport.objects.create(team=child, status=SignalReport.Status.RESOLVED, title="Fix")
+ url = f"/api/projects/{child.id}/signals/reports/{report.id}/checks/"
+
+ created = self.client.post(
+ url, {"title": "Errors stay low", "kind": "metric_threshold", "config": _threshold_config()}, format="json"
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ check_id = created.json()["id"]
+
+ assert [row["id"] for row in self.client.get(url).json()["results"]] == [check_id]
+ assert SignalReportCheck.all_teams.get(id=check_id).team_id == child.id
+
+ SignalReportCheck.all_teams.filter(id=check_id).update(next_run_at=timezone.now() - timedelta(minutes=1))
+ with patch(_MEASURE, return_value=MetricMeasurement(value=0.0, measured_at=timezone.now(), series=None)):
+ run_due_report_checks()
+ result = SignalReportArtefact.objects.get(report=report, type=SignalReportArtefact.ArtefactType.CHECK_RESULT)
+ assert result.team_id == child.id
+
+ def test_a_property_restricted_member_cannot_read_a_checks_query_or_measured_values(self) -> None:
+ secret_pageviews = trends_metric_query(
+ series=[
+ {
+ "kind": "EventsNode",
+ "event": "$pageview",
+ "properties": [
+ {"key": "secret_plan", "value": ["enterprise"], "operator": "exact", "type": "event"}
+ ],
+ }
+ ]
+ )
+ created = self.client.post(
+ self.url,
+ {
+ "title": "Enterprise pageviews stay low",
+ "kind": "metric_threshold",
+ "config": _threshold_config(query=secret_pageviews, baseline_value=3),
+ },
+ format="json",
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ check_id = created.json()["id"]
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=check_id).update(
+ next_run_at=timezone.now() - timedelta(minutes=1)
+ )
+ with patch(_MEASURE, return_value=MetricMeasurement(value=4.0, measured_at=timezone.now(), series=None)):
+ run_due_report_checks()
+ artefacts_url = f"/api/projects/{self.team.id}/signals/reports/{self.report.id}/artefacts/"
+
+ def check_result() -> dict:
+ return next(
+ row["content"]
+ for row in self.client.get(artefacts_url).json()["results"]
+ if row["type"] == "check_result"
+ )
+
+ assert check_result()["observed_value"] == 4.0
+
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=PropertyDefinition.objects.create(
+ team=self.team, name="secret_plan", property_type="String", type=PropertyDefinition.Type.EVENT
+ ),
+ organization_member=self.organization_membership,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+
+ config = self.client.get(f"{self.url}{check_id}/").json()["config"]
+ assert config["query"] is None
+ assert config["baseline_value"] is None
+ assert config["comparison"] == {"operator": "lte", "value": 10}
+
+ hidden = check_result()
+ assert hidden["outcome"] == "passed"
+ assert hidden["observed_value"] is None
+ assert hidden["baseline_value"] is None
+ assert hidden["explanation"] == CHECK_RESULT_HIDDEN_EXPLANATION
+
+ def test_an_invalid_config_is_rejected_by_the_endpoint(self) -> None:
+ response = self.client.post(
+ self.url,
+ {"title": "Nonsense", "kind": "metric_threshold", "config": {"comparison": {"operator": "lte"}}},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_a_report_carries_a_bounded_number_of_active_checks(self) -> None:
+ payload = {"title": "Errors stay low", "kind": "metric_threshold", "config": _threshold_config()}
+ for _ in range(MAX_ACTIVE_CHECKS_PER_REPORT):
+ assert self.client.post(self.url, payload, format="json").status_code == status.HTTP_201_CREATED
+
+ refused = self.client.post(self.url, payload, format="json")
+ assert refused.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_another_teams_report_is_not_reachable(self) -> None:
+ other_team = self.organization.teams.create(name="Other")
+ other_report = SignalReport.objects.create(team=other_team, status=SignalReport.Status.READY)
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/signals/reports/{other_report.id}/checks/",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
diff --git a/products/signals/backend/test/test_report_metrics.py b/products/signals/backend/test/test_report_metrics.py
index 8ee2450217c5..95d8b92ad269 100644
--- a/products/signals/backend/test/test_report_metrics.py
+++ b/products/signals/backend/test/test_report_metrics.py
@@ -112,6 +112,19 @@ class TestReportMetric(SimpleTestCase):
content["query"]["source"]["trendsFilter"] = trends_filter
assert ReportMetric.model_validate(content).query is not None
+ def test_live_query_rejects_a_sampling_factor_outside_the_valid_range(self) -> None:
+ for sampling_factor in (0, -0.5, 1.5, "0.5"):
+ with self.subTest(sampling_factor=sampling_factor):
+ content = _affected_users_metric().model_dump(mode="json")
+ content["query"]["source"]["samplingFactor"] = sampling_factor
+
+ with self.assertRaisesRegex(ValidationError, "samplingFactor must be greater than 0"):
+ ReportMetric.model_validate(content)
+
+ content = _affected_users_metric().model_dump(mode="json")
+ content["query"]["source"]["samplingFactor"] = 0.5
+ assert ReportMetric.model_validate(content).query is not None
+
def test_rejects_unique_groups_labeled_as_affected_users(self) -> None:
content = _affected_users_metric().model_dump(mode="json")
content["query"]["source"]["series"][0]["math_group_type_index"] = 0
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index 88d2f25ef694..f19c8deb6fea 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -73,6 +73,7 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (
_overdue_seconds,
_slot_anchor,
fetch_enabled_signals_scout_runs_activity,
+ run_due_signal_report_checks_activity,
stamp_dispatched_signals_scout_runs_activity,
)
from products.skills.backend.models.skills import LLMSkill
@@ -2015,20 +2016,63 @@ def _fake_info(workflow_id: str = "tick-1"):
return type("Info", (), {"workflow_id": workflow_id, "start_time": _TICK_STARTED_AT})()
+# `workflow.patched` reads the workflow runtime, which a direct `run()` does not have. True is the
+# live path; False is what an in-flight coordinator replaying a pre-patch history takes.
+def _patch_check_gate(enabled: bool = True):
+ return patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.patched",
+ return_value=enabled,
+ )
+
+
@pytest.mark.asyncio
async def test_workflow_returns_zero_counts_when_no_planned_runs():
coordinator = SignalsScoutCoordinatorWorkflow()
- with patch(
- "products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
- new_callable=AsyncMock,
- return_value=FetchEnabledRunsOutput(planned_runs=[]),
+ with (
+ _patch_check_gate(),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
+ new_callable=AsyncMock,
+ return_value=FetchEnabledRunsOutput(planned_runs=[]),
+ ),
):
output = await coordinator.run(CoordinatorWorkflowInput())
assert output == CoordinatorWorkflowOutput(0, 0, 0)
+ "gate_open,expected_activities",
+ [
+ (True, [run_due_signal_report_checks_activity, fetch_enabled_signals_scout_runs_activity]),
+ (False, [fetch_enabled_signals_scout_runs_activity]),
+ ],
+)
+async def test_report_checks_run_only_on_the_patched_path(gate_open, expected_activities):
+ # An in-flight coordinator replays its recorded history through the closed gate. Commanding the
+ # new activity there fails that replay with a non-determinism error, which under
+ # `ScheduleOverlapPolicy.SKIP` starves every later tick.
+ executed: list[Any] = []
+
+ async def fake_execute_activity(activity, *args, **kwargs):
+ executed.append(activity)
+ return FetchEnabledRunsOutput(planned_runs=[])
+
+ coordinator = SignalsScoutCoordinatorWorkflow()
+ with (
+ _patch_check_gate(gate_open),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
+ side_effect=fake_execute_activity,
+ ),
+ ):
+ await coordinator.run(CoordinatorWorkflowInput())
+
+ assert executed == expected_activities
+
+
@pytest.mark.asyncio
async def test_workflow_dispatches_children_fire_and_forget():
# `dispatch_smear_seconds` left at its default, which is also what an in-flight coordinator
@@ -2066,6 +2110,7 @@ async def test_workflow_dispatches_children_fire_and_forget():
coordinator = SignalsScoutCoordinatorWorkflow()
with (
+ _patch_check_gate(),
patch(
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
side_effect=fake_execute_activity,
@@ -2125,6 +2170,7 @@ async def test_smeared_fan_out_paces_batches_and_stamps_each_one():
coordinator = SignalsScoutCoordinatorWorkflow()
with (
+ _patch_check_gate(),
patch(
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
side_effect=fake_execute_activity,
@@ -2182,6 +2228,7 @@ async def test_smeared_fan_out_stops_sleeping_once_the_window_is_spent():
coordinator = SignalsScoutCoordinatorWorkflow()
with (
+ _patch_check_gate(),
patch(
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
side_effect=fake_execute_activity,
@@ -2240,6 +2287,7 @@ async def test_hard_dispatch_error_does_not_stamp():
coordinator = SignalsScoutCoordinatorWorkflow()
with (
+ _patch_check_gate(),
patch(
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
side_effect=fake_execute_activity,
@@ -2256,5 +2304,8 @@ async def test_hard_dispatch_error_does_not_stamp():
with pytest.raises(RuntimeError, match="temporal unavailable"):
await coordinator.run(CoordinatorWorkflowInput())
- # Only the planning activity ran — the stamp activity never executed.
- assert execute_activity_calls == [fetch_enabled_signals_scout_runs_activity]
+ # Only the report checks and the planning activity ran — the stamp activity never executed.
+ assert execute_activity_calls == [
+ run_due_signal_report_checks_activity,
+ fetch_enabled_signals_scout_runs_activity,
+ ]
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index a13cd109951d..0f44bab22e3a 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -112,6 +112,7 @@ from products.signals.backend.models import (
SignalReport,
SignalReportAction,
SignalReportArtefact,
+ SignalReportCheck,
SignalReportRefund,
SignalSourceConfig,
SignalTeamConfig,
@@ -121,6 +122,12 @@ from products.signals.backend.pull_requests import import_report_pull_requests
from products.signals.backend.quota import self_driving_quota_enforcement_enabled, self_driving_quota_gate
from products.signals.backend.repo_corrections import sanitized_repository
from products.signals.backend.report_assignments import InvalidPullRequestUrl, ReportClaimConflict, claim_report
+from products.signals.backend.report_check_execution import resolve_check_query
+from products.signals.backend.report_checks import (
+ MAX_ACTIVE_CHECKS_PER_REPORT,
+ MetricThresholdConfig,
+ parse_check_config,
+)
from products.signals.backend.report_claims import (
actor_owns_claim,
get_active_claim,
@@ -158,6 +165,8 @@ from products.signals.backend.serializers import (
SignalReportArtefactSerializer,
SignalReportArtefactWriteResponseSerializer,
SignalReportArtefactWriteSerializer,
+ SignalReportCheckSerializer,
+ SignalReportCheckWriteSerializer,
SignalReportClaimSerializer,
SignalReportListSerializer,
SignalReportMetricRefreshRequestSerializer,
@@ -4172,6 +4181,165 @@ def _record_reviewer_edit(
)
+@extend_schema_view(
+ list=extend_schema(
+ summary="List a report's checks",
+ description=(
+ "List the forward-looking checks on a report. A check says what must stay true after "
+ "the report was acted on, and the coordinator records each verdict as a `check_result` "
+ "artefact on the report."
+ ),
+ parameters=[_REPORT_ID_PARAMETER],
+ responses={200: SignalReportCheckSerializer(many=True)},
+ operation_id="signals_report_checks_list",
+ ),
+ retrieve=extend_schema(
+ summary="Get a single check",
+ parameters=[_REPORT_ID_PARAMETER],
+ responses={200: SignalReportCheckSerializer},
+ operation_id="signals_report_checks_retrieve",
+ ),
+ create=extend_schema(
+ summary="Create a check on a report",
+ description=(
+ "Schedule a re-measurement of the report's claim. A `metric_threshold` check runs one "
+ "bounded Trends query and compares the result, so it needs no agent run."
+ ),
+ parameters=[_REPORT_ID_PARAMETER],
+ request=SignalReportCheckWriteSerializer,
+ responses={201: SignalReportCheckSerializer},
+ operation_id="signals_report_checks_create",
+ ),
+ destroy=extend_schema(
+ summary="Cancel a check",
+ description="Stop an active check. Its recorded results stay on the report.",
+ parameters=[_REPORT_ID_PARAMETER],
+ responses={200: SignalReportCheckSerializer},
+ operation_id="signals_report_checks_destroy",
+ ),
+)
+class SignalReportCheckViewSet(
+ TeamAndOrgViewSetMixin,
+ mixins.ListModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.CreateModelMixin,
+ mixins.DestroyModelMixin,
+ viewsets.GenericViewSet,
+):
+ """Checks attached to a signal report: read, create, and cancel.
+
+ There is no update: a check is a claim about the future, and editing its threshold after a
+ result would make the recorded verdict unreadable. Cancel it and write a new one.
+
+ Writes are attributed the same way artefact writes are — to the task named by the
+ `X-PostHog-Task-Id` header when present, else to the requesting user.
+ """
+
+ serializer_class = SignalReportCheckSerializer
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ scope_object = "task"
+ queryset = SignalReportCheck.objects.unscoped().order_by("-created_at")
+ http_method_names = ["get", "post", "delete", "head", "options"]
+
+ def _validated_report(self) -> SignalReport:
+ report_id = self.parents_query_dict["report_id"]
+ try:
+ uuid.UUID(str(report_id))
+ except (ValueError, TypeError):
+ raise NotFound()
+ report = (
+ SignalReport.objects.filter(id=report_id, team=self.team)
+ .exclude(status=SignalReport.Status.DELETED)
+ .first()
+ )
+ if report is None:
+ raise NotFound()
+ return report
+
+ def safely_get_queryset(self, queryset):
+ return queryset.filter(report_id=self._validated_report().id, team=self.team)
+
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ report = self._validated_report()
+ write_serializer = SignalReportCheckWriteSerializer(data=request.data)
+ write_serializer.is_valid(raise_exception=True)
+ spec = write_serializer.validated_data
+
+ # Resolve a metric reference now and store the query it points at, rather than at each run.
+ # An unresolvable reference would otherwise sit idle for the whole soak window before
+ # retiring, and a reference resolved late would measure whatever the metric had become.
+ stored_config = spec["config"]
+ config = parse_check_config(spec["kind"], stored_config)
+ if isinstance(config, MetricThresholdConfig) and config.metric_id is not None:
+ try:
+ stored_config = {**stored_config, "query": resolve_check_query(config, report)}
+ except ValueError as error:
+ return Response(
+ {"error": f"This check cannot run: {error}."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ # Resolved before the locked transaction — a bad X-PostHog-Task-Id header must 400 before
+ # anything mutates, and its task lookup has no business inside the lock.
+ attribution = resolve_request_attribution(request, self.team.id)
+
+ with transaction.atomic():
+ # The cap is a count and then an insert, so it only holds if concurrent creates
+ # serialize. Row-lock the report first, the lock `enforce_report_task_cap` takes to cap
+ # a report's tasks the same way.
+ locked_report = SignalReport.objects.select_for_update().filter(id=report.id, team_id=self.team.id).first()
+ if locked_report is None:
+ raise NotFound()
+
+ active_checks = SignalReportCheck.objects.for_team(self.team.id).filter(
+ report_id=locked_report.id, status=SignalReportCheck.Status.ACTIVE
+ )
+ if active_checks.count() >= MAX_ACTIVE_CHECKS_PER_REPORT:
+ return Response(
+ {"error": f"A report may carry at most {MAX_ACTIVE_CHECKS_PER_REPORT} active checks."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ check = SignalReportCheck.objects.for_team(locked_report.team_id).create(
+ # The report's own environment team, never a canonicalized one: the report's reads
+ # and its artefact log filter by it.
+ team_id=locked_report.team_id,
+ report_id=locked_report.id,
+ title=spec["title"],
+ rationale=spec.get("rationale", ""),
+ kind=spec["kind"],
+ config=stored_config,
+ next_run_at=spec["next_run_at"],
+ run_interval_minutes=spec.get("run_interval_minutes"),
+ runs_remaining=spec["runs_remaining"],
+ expires_at=spec["expires_at"],
+ actor_kind=attribution.kind,
+ actor_agent=attribution.agent_name,
+ created_by_id=attribution.user_id,
+ task_id=attribution.task_id,
+ )
+ return Response(self.get_serializer(check).data, status=status.HTTP_201_CREATED)
+
+ def destroy(self, request: Request, *args, **kwargs) -> Response:
+ check = cast(SignalReportCheck, self.get_object())
+ # One conditional update rather than a read and then a write. A run that commits its verdict
+ # between the two leaves a result artefact on the report, and an unconditional write would
+ # overwrite the status that artefact explains.
+ cancelled = (
+ SignalReportCheck.objects.for_team(self.team.id)
+ .filter(id=check.id, status=SignalReportCheck.Status.ACTIVE)
+ .update(status=SignalReportCheck.Status.CANCELLED, updated_at=timezone.now())
+ )
+ check.refresh_from_db()
+ if not cancelled:
+ return Response(
+ {"error": f"This check already finished as '{check.status}' and cannot be cancelled."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ return Response(self.get_serializer(check).data)
+
+
@extend_schema_view(
list=extend_schema(
summary="List a report's artefacts",
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 5aadb501d1f6..89974dce8206 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -2097,6 +2097,7 @@ export interface SignalReportStateRequestApi {
* * `work_claim` - Work Claim
* * `work_release` - Work Release
* * `pull_request` - Pull Request
+ * * `check_result` - Check Result
*/
export type SignalReportArtefactArtefactTypeEnumApi =
(typeof SignalReportArtefactArtefactTypeEnumApi)[keyof typeof SignalReportArtefactArtefactTypeEnumApi]
@@ -2122,6 +2123,7 @@ export const SignalReportArtefactArtefactTypeEnumApi = {
WorkClaim: 'work_claim',
WorkRelease: 'work_release',
PullRequest: 'pull_request',
+ CheckResult: 'check_result',
} as const
export type SignalReportArtefactApiContent = { [key: string]: unknown } | unknown[]
@@ -2236,6 +2238,212 @@ export interface CommitDiffResponseApi {
readonly truncated: boolean
}
+/**
+ * * `metric_threshold` - Metric Threshold
+ */
+export type SignalReportCheckKindEnumApi =
+ (typeof SignalReportCheckKindEnumApi)[keyof typeof SignalReportCheckKindEnumApi]
+
+export const SignalReportCheckKindEnumApi = {
+ MetricThreshold: 'metric_threshold',
+} as const
+
+/**
+ * * `active` - Active
+ * * `passed` - Passed
+ * * `failed` - Failed
+ * * `errored` - Errored
+ * * `expired` - Expired
+ * * `cancelled` - Cancelled
+ */
+export type SignalReportCheckStatusEnumApi =
+ (typeof SignalReportCheckStatusEnumApi)[keyof typeof SignalReportCheckStatusEnumApi]
+
+export const SignalReportCheckStatusEnumApi = {
+ Active: 'active',
+ Passed: 'passed',
+ Failed: 'failed',
+ Errored: 'errored',
+ Expired: 'expired',
+ Cancelled: 'cancelled',
+} as const
+
+export type CheckComparisonOperatorEnumApi =
+ (typeof CheckComparisonOperatorEnumApi)[keyof typeof CheckComparisonOperatorEnumApi]
+
+export const CheckComparisonOperatorEnumApi = {
+ Lte: 'lte',
+ Gte: 'gte',
+ Between: 'between',
+} as const
+
+export interface CheckThresholdBoundsApi {
+ lower: number
+ upper: number
+}
+
+/**
+ * What the measured value must satisfy for the check to pass.
+ *
+ * The operators are the ones the shared alerts comparator expresses exactly. Strict `lt` / `gt`
+ * would need a second comparison engine for a distinction a soak window does not make, so they are
+ * not offered: "stays at or below 10 a day" is the same expectation.
+ */
+export interface CheckComparisonApi {
+ /** `lte`, `gte`, or `between`. */
+ operator: CheckComparisonOperatorEnumApi
+ /** The bound for `lte` and `gte`; unused by `between`. */
+ value?: number | null
+ /** The inclusive range for `between`; unused by `lte` and `gte`. */
+ bounds?: CheckThresholdBoundsApi | null
+}
+
+/**
+ * Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created.
+ */
+export type MetricThresholdConfigApiQuery = { [key: string]: unknown } | null
+
+/**
+ * A deterministic check: measure one number, compare it, record the verdict.
+ *
+ * The number comes either from a metric the report already shows (``metric_id``) or from a query
+ * the author supplies. Both end up in the same runner, so a supplied query must satisfy the live
+ * metric contract — the node allowlist, the bounded window, and the single-output-series rule.
+ *
+ * A caller names one source. When it names a metric, the create path copies that metric's query
+ * into ``query`` before the row is stored, so the check keeps measuring what its author saw even if
+ * the report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.
+ *
+ * Unknown keys are refused rather than ignored, so a misspelled field name is reported instead of
+ * being dropped in silence and stored as it arrived.
+ */
+export interface MetricThresholdConfigApi {
+ /** Identifier of a metric on the report whose query this check measures. The metric's query is copied into `query` when the check is created. */
+ metric_id?: string | null
+ /** Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. */
+ query?: MetricThresholdConfigApiQuery
+ /** What the measured value must satisfy to pass. */
+ comparison: CheckComparisonApi
+ /** The value observed when the check was written, recorded on each result for context. */
+ baseline_value?: number | null
+}
+
+export type SignalReportCheckConfigApi = MetricThresholdConfigApi
+
+/**
+ * * `passed` - Passed
+ * * `failed` - Failed
+ * * `errored` - Errored
+ */
+export type SignalReportCheckOutcomeEnumApi =
+ (typeof SignalReportCheckOutcomeEnumApi)[keyof typeof SignalReportCheckOutcomeEnumApi]
+
+export const SignalReportCheckOutcomeEnumApi = {
+ Passed: 'passed',
+ Failed: 'failed',
+ Errored: 'errored',
+} as const
+
+export interface SignalReportCheckApi {
+ readonly id: string
+ /** Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`. */
+ readonly title: string
+ /** Why the author set the check. */
+ readonly rationale: string
+ /** How the check is evaluated.
+ *
+ * * `metric_threshold` - Metric Threshold */
+ readonly kind: SignalReportCheckKindEnumApi
+ /** `active` while the check still runs; every other value is terminal.
+ *
+ * * `active` - Active
+ * * `passed` - Passed
+ * * `failed` - Failed
+ * * `errored` - Errored
+ * * `expired` - Expired
+ * * `cancelled` - Cancelled */
+ readonly status: SignalReportCheckStatusEnumApi
+ /** What the check measures and what the result must satisfy; the shape depends on `kind`. `query` and `baseline_value` are null when you cannot read the data they describe. */
+ config: SignalReportCheckConfigApi
+ /** When the coordinator next evaluates the check. */
+ readonly next_run_at: string
+ /**
+ * Gap between runs for a recurring check; null for a one-shot.
+ * @nullable
+ */
+ readonly run_interval_minutes: number | null
+ /** Evaluations still owed before the check retires as passed. */
+ readonly runs_remaining: number
+ /** Horizon after which the check retires without running again. */
+ readonly expires_at: string
+ /**
+ * When the check last ran; null before its first run.
+ * @nullable
+ */
+ readonly last_run_at: string | null
+ /** Verdict of the most recent run.
+ *
+ * * `passed` - Passed
+ * * `failed` - Failed
+ * * `errored` - Errored */
+ readonly last_outcome: SignalReportCheckOutcomeEnumApi | null
+ /** Runs that could not be measured since the last clean one. */
+ readonly consecutive_errors: number
+ readonly created_at: string
+ readonly updated_at: string
+}
+
+export interface PaginatedSignalReportCheckListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: SignalReportCheckApi[]
+}
+
+/**
+ * Request body for creating a check on a report.
+ *
+ * The schedule is the check's own: `next_run_at` says when to look, rather than the system
+ * deriving a soak window from a merged pull request that many fixes never have.
+ */
+export interface SignalReportCheckWriteApi {
+ /**
+ * Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.
+ * @maxLength 200
+ */
+ title: string
+ /**
+ * Why the check is worth running.
+ * @maxLength 2000
+ */
+ rationale?: string
+ /** How the check is evaluated.
+ *
+ * * `metric_threshold` - Metric Threshold */
+ kind: SignalReportCheckKindEnumApi
+ /** What the check measures and what the result must satisfy; the shape depends on `kind`. */
+ config: SignalReportCheckConfigApi
+ /** When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now. */
+ next_run_at?: string
+ /**
+ * Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.
+ * @minimum 360
+ * @maximum 129600
+ * @nullable
+ */
+ run_interval_minutes?: number | null
+ /**
+ * How many times to evaluate the check, at most 10. Defaults to 1.
+ * @minimum 1
+ * @maximum 10
+ */
+ runs_remaining?: number
+ /** Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first. */
+ expires_at?: string
+}
+
export interface SignalReportBulkStateRequestApi {
/** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk). Dismissing or resolving closes the report's open implementation PR, if it has one.
*
@@ -5294,6 +5502,17 @@ export type SignalsReportArtefactsListParams = {
offset?: number
}
+export type SignalsReportChecksListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type SignalsReportsPrCiStatusesParams = {
/**
* Comma-separated report UUIDs to resolve CI state for, at most 100 per request.
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 3f7183f8fd40..f43d7af2121e 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -21,6 +21,7 @@ import type {
ForgetResponseApi,
PaginatedPauseStateResponseListApi,
PaginatedSignalReportArtefactListApi,
+ PaginatedSignalReportCheckListApi,
PaginatedSignalReportListListApi,
PaginatedSignalSourceConfigListApi,
PatchedPullRequestReviewCommentUpdateApi,
@@ -62,6 +63,8 @@ import type {
SignalReportArtefactWriteResponseApi,
SignalReportBulkStateRequestApi,
SignalReportBulkStateResponseApi,
+ SignalReportCheckApi,
+ SignalReportCheckWriteApi,
SignalReportClaimApi,
SignalReportFeedbackRequestApi,
SignalReportFeedbackResponseApi,
@@ -85,6 +88,7 @@ import type {
SignalUserAutonomyConfigCreateApi,
SignalsProcessingListParams,
SignalsReportArtefactsListParams,
+ SignalsReportChecksListParams,
SignalsReportPrChecksParams,
SignalsReportPrCommentsParams,
SignalsReportPrReviewCommentDestroyParams,
@@ -822,6 +826,110 @@ export const signalsReportArtefactsDiff = async (
})
}
+export const getSignalsReportChecksListUrl = (
+ projectId: string,
+ reportId: string,
+ params?: SignalsReportChecksListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/signals/reports/${reportId}/checks/?${stringifiedParams}`
+ : `/api/projects/${projectId}/signals/reports/${reportId}/checks/`
+}
+
+/**
+ * List the forward-looking checks on a report. A check says what must stay true after the report was acted on, and the coordinator records each verdict as a `check_result` artefact on the report.
+ * @summary List a report's checks
+ */
+export const signalsReportChecksList = async (
+ projectId: string,
+ reportId: string,
+ params?: SignalsReportChecksListParams,
+ options?: RequestInit
+): Promise<PaginatedSignalReportCheckListApi> => {
+ return apiMutator<PaginatedSignalReportCheckListApi>(getSignalsReportChecksListUrl(projectId, reportId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSignalsReportChecksCreateUrl = (projectId: string, reportId: string) => {
+ return `/api/projects/${projectId}/signals/reports/${reportId}/checks/`
+}
+
+/**
+ * Schedule a re-measurement of the report's claim. A `metric_threshold` check runs one bounded Trends query and compares the result, so it needs no agent run.
+ * @summary Create a check on a report
+ */
+export const signalsReportChecksCreate = async (
+ projectId: string,
+ reportId: string,
+ signalReportCheckWriteApi: SignalReportCheckWriteApi,
+ options?: RequestInit
+): Promise<SignalReportCheckApi> => {
+ return apiMutator<SignalReportCheckApi>(getSignalsReportChecksCreateUrl(projectId, reportId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(signalReportCheckWriteApi),
+ })
+}
+
+export const getSignalsReportChecksRetrieveUrl = (projectId: string, reportId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${reportId}/checks/${id}/`
+}
+
+/**
+ * Checks attached to a signal report: read, create, and cancel.
+ *
+ * There is no update: a check is a claim about the future, and editing its threshold after a
+ * result would make the recorded verdict unreadable. Cancel it and write a new one.
+ *
+ * Writes are attributed the same way artefact writes are — to the task named by the
+ * `X-PostHog-Task-Id` header when present, else to the requesting user.
+ * @summary Get a single check
+ */
+export const signalsReportChecksRetrieve = async (
+ projectId: string,
+ reportId: string,
+ id: string,
+ options?: RequestInit
+): Promise<SignalReportCheckApi> => {
+ return apiMutator<SignalReportCheckApi>(getSignalsReportChecksRetrieveUrl(projectId, reportId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSignalsReportChecksDestroyUrl = (projectId: string, reportId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${reportId}/checks/${id}/`
+}
+
+/**
+ * Stop an active check. Its recorded results stay on the report.
+ * @summary Cancel a check
+ */
+export const signalsReportChecksDestroy = async (
+ projectId: string,
+ reportId: string,
+ id: string,
+ options?: RequestInit
+): Promise<SignalReportCheckApi> => {
+ return apiMutator<SignalReportCheckApi>(getSignalsReportChecksDestroyUrl(projectId, reportId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getSignalsReportsBulkStateCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/signals/reports/bulk-state/`
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 3a4ea5bbbd83..1626a29f64e2 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -313,6 +313,107 @@ export const SignalsReportArtefactsPartialUpdateBody = /* @__PURE__ */ zod
"Body for replacing the content of an existing artefact (addressed by id).\n\nPer-type schema validation happens in the view, which knows the artefact's type."
)
+/**
+ * Schedule a re-measurement of the report's claim. A `metric_threshold` check runs one bounded Trends query and compares the result, so it needs no agent run.
+ * @summary Create a check on a report
+ */
+export const signalsReportChecksCreateBodyTitleMax = 200
+
+export const signalsReportChecksCreateBodyRationaleMax = 2000
+
+export const signalsReportChecksCreateBodyRunIntervalMinutesMin = 360
+export const signalsReportChecksCreateBodyRunIntervalMinutesMax = 129600
+
+export const signalsReportChecksCreateBodyRunsRemainingMax = 10
+
+export const SignalsReportChecksCreateBody = /* @__PURE__ */ zod
+ .object({
+ title: zod
+ .string()
+ .max(signalsReportChecksCreateBodyTitleMax)
+ .describe('Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.'),
+ rationale: zod
+ .string()
+ .max(signalsReportChecksCreateBodyRationaleMax)
+ .optional()
+ .describe('Why the check is worth running.'),
+ kind: zod
+ .enum(['metric_threshold'])
+ .describe('\* `metric_threshold` - Metric Threshold')
+ .describe('How the check is evaluated.\n\n\* `metric_threshold` - Metric Threshold'),
+ config: zod
+ .object({
+ metric_id: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ "Identifier of a metric on the report whose query this check measures. The metric's query is copied into `query` when the check is created."
+ ),
+ query: zod
+ .union([zod.record(zod.string(), zod.unknown()), zod.null()])
+ .optional()
+ .describe(
+ 'Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created.'
+ ),
+ comparison: zod
+ .object({
+ operator: zod.enum(['lte', 'gte', 'between']).describe('`lte`, `gte`, or `between`.'),
+ value: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('The bound for `lte` and `gte`; unused by `between`.'),
+ bounds: zod
+ .union([
+ zod.object({
+ lower: zod.number(),
+ upper: zod.number(),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('The inclusive range for `between`; unused by `lte` and `gte`.'),
+ })
+ .describe('What the measured value must satisfy to pass.'),
+ baseline_value: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('The value observed when the check was written, recorded on each result for context.'),
+ })
+ .describe(
+ "A deterministic check: measure one number, compare it, record the verdict.\n\nThe number comes either from a metric the report already shows (``metric_id``) or from a query\nthe author supplies. Both end up in the same runner, so a supplied query must satisfy the live\nmetric contract — the node allowlist, the bounded window, and the single-output-series rule.\n\nA caller names one source. When it names a metric, the create path copies that metric's query\ninto ``query`` before the row is stored, so the check keeps measuring what its author saw even if\nthe report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.\n\nUnknown keys are refused rather than ignored, so a misspelled field name is reported instead of\nbeing dropped in silence and stored as it arrived."
+ )
+ .describe('What the check measures and what the result must satisfy; the shape depends on `kind`.'),
+ next_run_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now.'
+ ),
+ run_interval_minutes: zod
+ .number()
+ .min(signalsReportChecksCreateBodyRunIntervalMinutesMin)
+ .max(signalsReportChecksCreateBodyRunIntervalMinutesMax)
+ .nullish()
+ .describe(
+ 'Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.'
+ ),
+ runs_remaining: zod
+ .number()
+ .min(1)
+ .max(signalsReportChecksCreateBodyRunsRemainingMax)
+ .optional()
+ .describe('How many times to evaluate the check, at most 10. Defaults to 1.'),
+ expires_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first.'
+ ),
+ })
+ .describe(
+ "Request body for creating a check on a report.\n\nThe schedule is the check's own: `next_run_at` says when to look, rather than the system\nderiving a soak window from a merged pull request that many fixes never have."
+ )
+
/**
* Transition many reports to a new state in one call.
*
diff --git a/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx b/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx
index 8083ac491d64..351ba436a2d5 100644
--- a/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx
+++ b/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx
@@ -8,6 +8,7 @@ import {
IconCommit,
IconFlag,
IconGitRepository,
+ IconCalendar,
IconListCheck,
IconListTreeConnected,
IconPeople,
@@ -40,6 +41,7 @@ import {
artefactAttributionLabel,
artefactLocationLabel,
artefactTypeLabel,
+ CheckResultContent,
CodeReviewContent,
CodeReferenceContent,
CommitContent,
@@ -128,6 +130,7 @@ const ARTEFACT_MARKER: Record<string, ComponentType<{ className?: string }>> = {
summary_change: IconPencil,
related_to: IconListTreeConnected,
code_review: IconListCheck,
+ check_result: IconCalendar,
}
function dismissReasonLabel(reason: string): string {
@@ -291,6 +294,29 @@ const CODE_REVIEW_OUTCOME: Record<NonNullable<CodeReviewContent['outcome']>, { l
failed: { label: 'Review failed', type: 'danger' },
}
+const CHECK_OUTCOME: Record<NonNullable<CheckResultContent['outcome']>, { label: string; type: LemonTagType }> = {
+ passed: { label: 'Still holds', type: 'success' },
+ failed: { label: 'No longer holds', type: 'danger' },
+ errored: { label: "Couldn't measure", type: 'warning' },
+}
+
+function CheckResultBody({ content }: { content: CheckResultContent }): JSX.Element | null {
+ if (!content.explanation?.trim()) {
+ return null
+ }
+ return (
+ <div className="flex w-full flex-col items-start gap-1">
+ <span className="text-xs text-default">{content.explanation}</span>
+ {content.threshold ? (
+ <span className="text-xs text-tertiary">
+ Expected {content.threshold}
+ {typeof content.baseline_value === 'number' ? `, was ${content.baseline_value} when set` : ''}
+ </span>
+ ) : null}
+ </div>
+ )
+}
+
function CodeReviewBody({ content }: { content: CodeReviewContent }): JSX.Element | null {
const counts = content.counts
const reviewUrl = content.review_url || content.pr_url
@@ -403,6 +429,15 @@ function renderArtefactSummary(artefact: SignalReportArtefact): JSX.Element | nu
</LemonTag>
) : null
}
+ case 'check_result': {
+ const outcome = (content as CheckResultContent).outcome
+ const meta = outcome ? CHECK_OUTCOME[outcome] : null
+ return meta ? (
+ <LemonTag size="small" type={meta.type}>
+ {meta.label}
+ </LemonTag>
+ ) : null
+ }
default:
return null
}
@@ -470,6 +505,8 @@ function renderArtefactBody({
return <RelatedReportBody content={content as RelatedToContent} />
case 'code_review':
return <CodeReviewBody content={content as CodeReviewContent} />
+ case 'check_result':
+ return <CheckResultBody content={content as CheckResultContent} />
case 'title_change': {
const c = content as TitleChangeContent
return <ContentChangeBody previous={c.old_title} current={c.new_title ?? ''} />
diff --git a/products/signals/frontend/inbox/components/detail/artefactTypes.ts b/products/signals/frontend/inbox/components/detail/artefactTypes.ts
index 923bf1db0e2d..9edb4e2c74b6 100644
--- a/products/signals/frontend/inbox/components/detail/artefactTypes.ts
+++ b/products/signals/frontend/inbox/components/detail/artefactTypes.ts
@@ -81,6 +81,17 @@ export interface CodeReviewContent {
}
}
+export interface CheckResultContent {
+ check_id?: string
+ kind?: string
+ title?: string
+ outcome?: 'passed' | 'failed' | 'errored'
+ explanation?: string
+ observed_value?: number | null
+ baseline_value?: number | null
+ threshold?: string | null
+}
+
export interface TitleChangeContent {
old_title?: string | null
new_title: string
@@ -112,6 +123,7 @@ export const ARTEFACT_TYPE_LABELS: Record<string, string> = {
summary_change: 'Summary edited',
related_to: 'Related report',
code_review: 'Code review',
+ check_result: 'Follow-up check',
}
export function artefactTypeLabel(type: string): string {
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index e84686436213..c5fe177b406e 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -955,6 +955,18 @@ tools:
signals-report-artefacts-diff:
operation: signals_report_artefacts_diff
enabled: false
+ signals-report-checks-create:
+ operation: signals_report_checks_create
+ enabled: false
+ signals-report-checks-destroy:
+ operation: signals_report_checks_destroy
+ enabled: false
+ signals-report-checks-list:
+ operation: signals_report_checks_list
+ enabled: false
+ signals-report-checks-retrieve:
+ operation: signals_report_checks_retrieve
+ enabled: false
signals-report-pr-checks:
operation: signals_report_pr_checks
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c89fdee76eff..cd4cb6fc9c37 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17837,6 +17837,36 @@ export namespace Schemas {
RecentSignals: 'recent_signals',
} as const;
+ export type CheckComparisonOperatorEnum = typeof CheckComparisonOperatorEnum[keyof typeof CheckComparisonOperatorEnum];
+
+
+ export const CheckComparisonOperatorEnum = {
+ Lte: 'lte',
+ Gte: 'gte',
+ Between: 'between',
+ } as const;
+
+ export interface CheckThresholdBounds {
+ lower: number;
+ upper: number;
+ }
+
+ /**
+ * What the measured value must satisfy for the check to pass.
+ *
+ * The operators are the ones the shared alerts comparator expresses exactly. Strict `lt` / `gt`
+ * would need a second comparison engine for a distinction a soak window does not make, so they are
+ * not offered: "stays at or below 10 a day" is the same expectation.
+ */
+ export interface CheckComparison {
+ /** `lte`, `gte`, or `between`. */
+ operator: CheckComparisonOperatorEnum;
+ /** The bound for `lte` and `gte`; unused by `between`. */
+ value?: number | null;
+ /** The inclusive range for `between`; unused by `lte` and `gte`. */
+ bounds?: CheckThresholdBounds | null;
+ }
+
export interface CheckDatabaseNameResponse {
name: string;
available: boolean;
@@ -54128,6 +54158,36 @@ export namespace Schemas {
Week: 'week',
} as const;
+ /**
+ * Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created.
+ */
+ export type MetricThresholdConfigQuery = { [key: string]: unknown } | null;
+
+ /**
+ * A deterministic check: measure one number, compare it, record the verdict.
+ *
+ * The number comes either from a metric the report already shows (``metric_id``) or from a query
+ * the author supplies. Both end up in the same runner, so a supplied query must satisfy the live
+ * metric contract — the node allowlist, the bounded window, and the single-output-series rule.
+ *
+ * A caller names one source. When it names a metric, the create path copies that metric's query
+ * into ``query`` before the row is stored, so the check keeps measuring what its author saw even if
+ * the report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.
+ *
+ * Unknown keys are refused rather than ignored, so a misspelled field name is reported instead of
+ * being dropped in silence and stored as it arrived.
+ */
+ export interface MetricThresholdConfig {
+ /** Identifier of a metric on the report whose query this check measures. The metric's query is copied into `query` when the check is created. */
+ metric_id?: string | null;
+ /** Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. */
+ query?: MetricThresholdConfigQuery;
+ /** What the measured value must satisfy to pass. */
+ comparison: CheckComparison;
+ /** The value observed when the check was written, recorded on each result for context. */
+ baseline_value?: number | null;
+ }
+
/**
* * `funnel` - funnel
* * `mean_count` - mean_count
@@ -59271,6 +59331,7 @@ export namespace Schemas {
* * `work_claim` - Work Claim
* * `work_release` - Work Release
* * `pull_request` - Pull Request
+ * * `check_result` - Check Result
*/
export type SignalReportArtefactArtefactTypeEnum = typeof SignalReportArtefactArtefactTypeEnum[keyof typeof SignalReportArtefactArtefactTypeEnum];
@@ -59296,6 +59357,7 @@ export namespace Schemas {
WorkClaim: 'work_claim',
WorkRelease: 'work_release',
PullRequest: 'pull_request',
+ CheckResult: 'check_result',
} as const;
export type SignalActorKindEnum = typeof SignalActorKindEnum[keyof typeof SignalActorKindEnum];
@@ -59360,6 +59422,110 @@ export namespace Schemas {
results: SignalReportArtefact[];
}
+ /**
+ * * `metric_threshold` - Metric Threshold
+ */
+ export type SignalReportCheckKindEnum = typeof SignalReportCheckKindEnum[keyof typeof SignalReportCheckKindEnum];
+
+
+ export const SignalReportCheckKindEnum = {
+ MetricThreshold: 'metric_threshold',
+ } as const;
+
+ /**
+ * * `active` - Active
+ * * `passed` - Passed
+ * * `failed` - Failed
+ * * `errored` - Errored
+ * * `expired` - Expired
+ * * `cancelled` - Cancelled
+ */
+ export type SignalReportCheckStatusEnum = typeof SignalReportCheckStatusEnum[keyof typeof SignalReportCheckStatusEnum];
+
+
+ export const SignalReportCheckStatusEnum = {
+ Active: 'active',
+ Passed: 'passed',
+ Failed: 'failed',
+ Errored: 'errored',
+ Expired: 'expired',
+ Cancelled: 'cancelled',
+ } as const;
+
+ export type SignalReportCheckConfig = MetricThresholdConfig;
+
+ /**
+ * * `passed` - Passed
+ * * `failed` - Failed
+ * * `errored` - Errored
+ */
+ export type SignalReportCheckOutcomeEnum = typeof SignalReportCheckOutcomeEnum[keyof typeof SignalReportCheckOutcomeEnum];
+
+
+ export const SignalReportCheckOutcomeEnum = {
+ Passed: 'passed',
+ Failed: 'failed',
+ Errored: 'errored',
+ } as const;
+
+ export interface SignalReportCheck {
+ readonly id: string;
+ /** Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`. */
+ readonly title: string;
+ /** Why the author set the check. */
+ readonly rationale: string;
+ /** How the check is evaluated.
+ *
+ * * `metric_threshold` - Metric Threshold */
+ readonly kind: SignalReportCheckKindEnum;
+ /** `active` while the check still runs; every other value is terminal.
+ *
+ * * `active` - Active
+ * * `passed` - Passed
+ * * `failed` - Failed
+ * * `errored` - Errored
+ * * `expired` - Expired
+ * * `cancelled` - Cancelled */
+ readonly status: SignalReportCheckStatusEnum;
+ /** What the check measures and what the result must satisfy; the shape depends on `kind`. `query` and `baseline_value` are null when you cannot read the data they describe. */
+ config: SignalReportCheckConfig;
+ /** When the coordinator next evaluates the check. */
+ readonly next_run_at: string;
+ /**
+ * Gap between runs for a recurring check; null for a one-shot.
+ * @nullable
+ */
+ readonly run_interval_minutes: number | null;
+ /** Evaluations still owed before the check retires as passed. */
+ readonly runs_remaining: number;
+ /** Horizon after which the check retires without running again. */
+ readonly expires_at: string;
+ /**
+ * When the check last ran; null before its first run.
+ * @nullable
+ */
+ readonly last_run_at: string | null;
+ /** Verdict of the most recent run.
+ *
+ * * `passed` - Passed
+ * * `failed` - Failed
+ * * `errored` - Errored */
+ readonly last_outcome: SignalReportCheckOutcomeEnum | null;
+ /** Runs that could not be measured since the last clean one. */
+ readonly consecutive_errors: number;
+ readonly created_at: string;
+ readonly updated_at: string;
+ }
+
+ export interface PaginatedSignalReportCheckList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: SignalReportCheck[];
+ }
+
/**
* * `potential` - Potential
* * `candidate` - Candidate
@@ -81018,6 +81184,48 @@ export namespace Schemas {
not_found_count: number;
}
+ /**
+ * Request body for creating a check on a report.
+ *
+ * The schedule is the check's own: `next_run_at` says when to look, rather than the system
+ * deriving a soak window from a merged pull request that many fixes never have.
+ */
+ export interface SignalReportCheckWrite {
+ /**
+ * Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.
+ * @maxLength 200
+ */
+ title: string;
+ /**
+ * Why the check is worth running.
+ * @maxLength 2000
+ */
+ rationale?: string;
+ /** How the check is evaluated.
+ *
+ * * `metric_threshold` - Metric Threshold */
+ kind: SignalReportCheckKindEnum;
+ /** What the check measures and what the result must satisfy; the shape depends on `kind`. */
+ config: SignalReportCheckConfig;
+ /** When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now. */
+ next_run_at?: string;
+ /**
+ * Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.
+ * @minimum 360
+ * @maximum 129600
+ * @nullable
+ */
+ run_interval_minutes?: number | null;
+ /**
+ * How many times to evaluate the check, at most 10. Defaults to 1.
+ * @minimum 1
+ * @maximum 10
+ */
+ runs_remaining?: number;
+ /** Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first. */
+ expires_at?: string;
+ }
+
export interface SignalReportClaim {
/** Active claim ID returned by an earlier call. Stale claims are rejected. */
claim_id?: string;
@@ -103801,6 +104009,17 @@ export namespace Schemas {
offset?: number;
};
+ export type SignalsReportChecksListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type SignalsReportsPrCiStatusesParams = {
/**
* Comma-separated report UUIDs to resolve CI state for, at most 100 per request.
diff --git a/tach.toml b/tach.toml
index dc79731021f7..0b8760a09ab8 100644
--- a/tach.toml
+++ b/tach.toml
@@ -177,8 +177,9 @@ layer = "modules"
# alerts — external consumers go through the facade: facade.contracts for the
# destination and delivery types, facade.destinations for destination configuration and
# dispatch, facade.email for alert mail, facade.lifecycle for the shared state machine,
-# facade.scheduling for the scheduling math, facade.delivery_slo for delivery SLOs, and
-# facade.api for the insight-alert reads and writes. presentation.views carries the DRF
+# facade.scheduling for the scheduling math, facade.delivery_slo for delivery SLOs,
+# facade.evaluation for the threshold comparator, and facade.api for the insight-alert reads
+# and writes. presentation.views carries the DRF
# surface adopter products mount or reuse in process, which a facade may not hold.
[[interfaces]]
expose = [