Skip to content

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

fix(signals): wait for full post-resolution metric windows (#110300)

Mikayla Thompson26c23da2edae
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index 0bb9f0c9c841..78b5d3523452 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -22,6 +22,12 @@ A `part_of` link written on a step that already closed runs the check as well, b
It continues up a plan of plans, and skips a plan that is waiting on a replacement.
It also skips a plan that carries its own open, draft, or unknown PR, because that plan's own work decides its status.
+## Follow-up measurement timing
+
+Metric follow-up checks wait until their full trailing query window contains only post-resolution data. The configured soak is an independent minimum wait. Reopening a report clears the measurement anchor; resolving it again starts a new window. Legacy active metric checks without an anchor start their window at the next coordinator tick and recalculate expiry from the remaining schedule, capped at 90 days from that tick. Legacy rows do not distinguish supplied expiries from defaults, so both follow this re-arming policy. Checks with an existing anchor retain their expiry. A window that cannot finish before expiry records an inconclusive result instead of scheduling an unreachable run. Agent checks keep their soak-based schedule.
+
+New metric checks validate numeric goals and baselines against their metric kind, format, unit, and query. Existing check configurations remain readable.
+
## Proposed impact measurement
The organization authoring flag lets research propose up to six active `impact_measurement_plan` artefacts for measurable outcomes. Each bounded query, goal, aggregation grain, and decision rule lives in an artefact, not in the report's observation metrics. Authoring rejects query filters and conversion goals whose shape the report access policy cannot check, including HogQL property filters. It also omits an observation metric when its query has an unsupported filter; research keeps that evidence in report prose when no readable structured query exists. A readable observation remains without a plan when only the eligibility query is unsupported. Individual resource grants, token scopes, and property restrictions still apply when someone reads a report. A minimum-data rule also needs an eligibility query for qualifying opportunities. A later research pass reviews the current plans against new evidence. It preserves unchanged plans, appends an unapproved version for a material revision, or appends a retired version when the outcome is no longer relevant or measurable. A plan changed by a person during research takes precedence over that pass. Earlier versions remain for review. The report's "Keep an eye on this for me" action activates current proposals when the display flag is on. Activation appends a new version and does not schedule a check or change the report state. The approval action currently accepts an authenticated person; the artefact schema does not require a person as its approver.
diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.py
index db0a2b45b03b..779e1a79520e 100644
--- a/products/signals/backend/artefact_schemas.py
+++ b/products/signals/backend/artefact_schemas.py
@@ -1039,7 +1039,7 @@ class CheckCancelled(CheckLifecycleEntry):
the type rather than a nullable field.
"""
- reason: Literal["stopped_by_person", "stopped_by_scout", "replaced_by_research"] = Field(
+ reason: Literal["stopped_by_person", "stopped_by_scout", "replaced_by_research", "replaced_by_request"] = Field(
description="Which path stopped the check."
)
diff --git a/products/signals/backend/migrations/0160_report_check_measurement_start.py b/products/signals/backend/migrations/0160_report_check_measurement_start.py
new file mode 100644
index 000000000000..0c5394bea241
--- /dev/null
+++ b/products/signals/backend/migrations/0160_report_check_measurement_start.py
@@ -0,0 +1,13 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("signals", "0159_signalscoutbackgroundband")]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalreportcheck",
+ name="measurement_start_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index aca9ad3c81d0..f2520d406fcf 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0159_signalscoutbackgroundband
+0160_report_check_measurement_start
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 76a127fb2736..03def7585366 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -2232,9 +2232,8 @@ class SignalReportCheck(UUIDModel):
config = models.JSONField(default=dict, db_default={})
next_run_at = models.DateTimeField()
- # How long after the report resolves a PENDING check waits before its first run. Null on a check
- # created ACTIVE, which named its own `next_run_at` instead. Kept after the check is armed, so a
- # reader can see what window the verdict was measured over.
+ measurement_start_at = models.DateTimeField(null=True, blank=True)
+ # Minimum wait after resolution, separate from the query window a metric check must fill.
soak_minutes = models.PositiveIntegerField(null=True, blank=True)
# Null means one-shot. A recurring check re-arms at this interval until it runs out of runs or
# reaches its expiry.
diff --git a/products/signals/backend/report_check_authoring.py b/products/signals/backend/report_check_authoring.py
index 3530adfde2b2..bc1c1236a13c 100644
--- a/products/signals/backend/report_check_authoring.py
+++ b/products/signals/backend/report_check_authoring.py
@@ -30,19 +30,23 @@ from products.signals.backend.models import SignalReport, SignalReportCheck
from products.signals.backend.report_check_artefacts import write_check_cancelled, write_check_scheduled
from products.signals.backend.report_check_execution import resolve_check_query
from products.signals.backend.report_check_telemetry import capture_report_check_created
+from products.signals.backend.report_check_timing import metric_check_ready_at
from products.signals.backend.report_checks import (
- DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
MAX_ACTIVE_CHECKS_PER_REPORT,
MAX_CHECK_HORIZON,
CheckConfigValidationError,
CheckSpec,
MetricThresholdConfig,
+ check_schedule_expires_at,
parse_check_config,
soak_minutes_from_gap,
+ validate_metric_check_for_write,
)
logger = structlog.get_logger(__name__)
+_METRIC_DISPLAY_FIELDS = frozenset({"metric_kind", "value_format", "unit"})
+
class CheckCreationError(ValueError):
"""A check that cannot be written: a bad config, an unresolvable metric, or a full report."""
@@ -80,24 +84,7 @@ def create_check(
if (next_run_at is None) == (soak_minutes is None):
raise CheckCreationError("a check names either a next_run_at or a soak_minutes, not both and not neither")
- try:
- parsed = parse_check_config(kind, config)
- except CheckConfigValidationError as error:
- raise CheckCreationError(str(error)) from None
-
- stored_config = dict(config)
- if isinstance(parsed, MetricThresholdConfig) and parsed.metric_id is not None:
- if parsed.query is not None:
- raise CheckCreationError(
- "provide either metric_id or query, not both. The metric's query is copied onto the check."
- )
- # Resolved now and stored, rather than at each run: an unresolvable reference would
- # otherwise sit idle for the whole soak window before retiring, and one resolved late would
- # measure whatever the metric had become.
- try:
- stored_config["query"] = resolve_check_query(parsed, report)
- except ValueError as error:
- raise CheckCreationError(f"This check cannot run: {error}.") from None
+ stored_config = _stored_config(report, kind, config)
now = timezone.now()
@@ -105,6 +92,11 @@ def create_check(
locked_report = SignalReport.objects.select_for_update().filter(id=report.id, team_id=report.team_id).first()
if locked_report is None:
raise CheckCreationError("The report this check belongs to is gone.")
+ metric_ready_at = None
+ if kind == SignalReportCheck.Kind.METRIC_THRESHOLD:
+ metric_ready_at = metric_check_ready_at(stored_config["query"], locked_report.team, now)
+ if metric_ready_at >= now + MAX_CHECK_HORIZON:
+ raise CheckCreationError("The full measurement window must fit within the check's 90-day horizon.")
open_checks = SignalReportCheck.objects.for_team(locked_report.team_id).filter(
report_id=locked_report.id, status__in=SignalReportCheck.OPEN_STATUSES
)
@@ -117,11 +109,16 @@ def create_check(
next_run_at = now + timedelta(minutes=soak_minutes)
if soak_minutes is None:
soak_minutes = soak_minutes_from_gap(next_run_at, now)
+ if metric_ready_at is not None:
+ next_run_at = max(next_run_at, metric_ready_at)
+ if expires_at is not None and expires_at <= next_run_at:
+ raise CheckCreationError("The expiry must allow a full post-resolution measurement window.")
if expires_at is None:
- expires_at = min(
- _last_run_at(next_run_at, run_interval_minutes, runs_remaining)
- + DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
- now + MAX_CHECK_HORIZON,
+ expires_at = check_schedule_expires_at(
+ next_run_at=next_run_at,
+ run_interval_minutes=run_interval_minutes,
+ runs_remaining=runs_remaining,
+ start_at=now,
)
else:
status = SignalReportCheck.Status.PENDING
@@ -141,6 +138,9 @@ def create_check(
rationale=rationale,
kind=kind,
config=stored_config,
+ measurement_start_at=now
+ if status == SignalReportCheck.Status.ACTIVE and metric_ready_at is not None
+ else None,
status=status,
next_run_at=next_run_at,
soak_minutes=soak_minutes,
@@ -162,6 +162,65 @@ def create_check(
return check
+def _stored_config(report: SignalReport, kind: str, config: dict) -> dict:
+ try:
+ parsed = parse_check_config(kind, config)
+ except CheckConfigValidationError as error:
+ raise CheckCreationError(str(error)) from None
+
+ stored_config = dict(config)
+ if isinstance(parsed, MetricThresholdConfig) and parsed.metric_id is not None:
+ if parsed.query is not None:
+ raise CheckCreationError(
+ "provide either metric_id or query, not both. The metric's query is copied onto the check."
+ )
+ # Resolved now and stored, rather than at each run: an unresolvable reference would
+ # otherwise sit idle for the whole soak window before retiring, and one resolved late would
+ # measure whatever the metric had become.
+ try:
+ stored_config["query"] = resolve_check_query(parsed, report)
+ except ValueError as error:
+ raise CheckCreationError(f"This check cannot run: {error}.") from None
+ # The query comes from the named metric, so its display fields do too. Values the caller
+ # sends could draw that query with another metric's format or unit.
+ stored_config = _with_metric_display(
+ report,
+ {key: value for key, value in stored_config.items() if key not in _METRIC_DISPLAY_FIELDS},
+ parsed.metric_id,
+ )
+ try:
+ parse_check_config(kind, stored_config)
+ except CheckConfigValidationError as error:
+ raise CheckCreationError(str(error)) from None
+
+ if isinstance(parsed, MetricThresholdConfig):
+ stored_config = _with_metric_display(report, stored_config, parsed.metric_id)
+ try:
+ normalized = parse_check_config(kind, stored_config)
+ assert isinstance(normalized, MetricThresholdConfig)
+ validate_metric_check_for_write(normalized)
+ except CheckConfigValidationError as error:
+ raise CheckCreationError(str(error)) from None
+ # Accept metadata before writers persist it, so old workers can read checks during rollout.
+ return {key: value for key, value in stored_config.items() if key not in _METRIC_DISPLAY_FIELDS}
+
+
+def _with_metric_display(report: SignalReport, config: dict, metric_id: str | None) -> dict:
+ """Fill a metric check's display fields from the report metric it names, keeping any it already has."""
+ filled = dict(config)
+ for metric in report.metrics or []:
+ if isinstance(metric, dict) and metric.get("metric_id") == metric_id:
+ filled.setdefault("metric_kind", metric.get("kind", "custom"))
+ filled.setdefault("value_format", metric.get("value_format", "number"))
+ filled.setdefault("unit", metric.get("unit"))
+ break
+ if "comparison" in filled:
+ filled["metric_kind"] = filled.get("metric_kind") or "custom"
+ filled["value_format"] = filled.get("value_format") or "number"
+ filled.setdefault("unit", None)
+ return filled
+
+
def create_checks_from_specs(
*,
report: SignalReport,
@@ -256,16 +315,27 @@ def arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_at:
are derived from the row's own soak and schedule.
"""
pending = list(
- SignalReportCheck.objects.for_team(team_id).filter(report_id=report_id, status=SignalReportCheck.Status.PENDING)
+ SignalReportCheck.objects.for_team(team_id)
+ .filter(report_id=report_id, status=SignalReportCheck.Status.PENDING)
+ .select_related("report__team")
)
- horizon = resolved_at + MAX_CHECK_HORIZON
armed = 0
for check in pending:
next_run_at = resolved_at + timedelta(minutes=check.soak_minutes or 0)
- expires_at = min(
- _last_run_at(next_run_at, check.run_interval_minutes, check.runs_remaining)
- + DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
- horizon,
+ if check.kind == SignalReportCheck.Kind.METRIC_THRESHOLD:
+ try:
+ config = parse_check_config(check.kind, check.config)
+ assert isinstance(config, MetricThresholdConfig)
+ query = resolve_check_query(config, check.report)
+ next_run_at = max(next_run_at, metric_check_ready_at(query, check.report.team, resolved_at))
+ except (CheckConfigValidationError, ValueError):
+ # An invalid legacy config must not prevent the report's other checks from arming.
+ pass
+ expires_at = check_schedule_expires_at(
+ next_run_at=next_run_at,
+ run_interval_minutes=check.run_interval_minutes,
+ runs_remaining=check.runs_remaining,
+ start_at=resolved_at,
)
armed += (
SignalReportCheck.objects.for_team(team_id)
@@ -273,14 +343,9 @@ def arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_at:
.update(
status=SignalReportCheck.Status.ACTIVE,
next_run_at=next_run_at,
+ measurement_start_at=resolved_at if check.kind == SignalReportCheck.Kind.METRIC_THRESHOLD else None,
expires_at=expires_at,
updated_at=resolved_at,
)
)
return armed
-
-
-def _last_run_at(next_run_at: datetime, run_interval_minutes: int | None, runs_remaining: int) -> datetime:
- if not run_interval_minutes:
- return next_run_at
- return next_run_at + timedelta(minutes=run_interval_minutes * max(0, runs_remaining - 1))
diff --git a/products/signals/backend/report_check_execution.py b/products/signals/backend/report_check_execution.py
index ab93cb2ee1ca..971d101a4e32 100644
--- a/products/signals/backend/report_check_execution.py
+++ b/products/signals/backend/report_check_execution.py
@@ -18,6 +18,7 @@ from __future__ import annotations
import time
from datetime import datetime, timedelta
from functools import partial
+from typing import cast
from django.db import transaction
from django.db.models import F, Window
@@ -53,6 +54,7 @@ from products.signals.backend.report_check_telemetry import (
capture_report_check_evaluated,
capture_report_checks_expired,
)
+from products.signals.backend.report_check_timing import metric_check_ready_at, metric_check_window_start
from products.signals.backend.report_checks import (
AWAITING_DATA_RETRY_WAITS,
DEFAULT_CHECK_SOAK_HOURS,
@@ -63,6 +65,7 @@ from products.signals.backend.report_checks import (
CheckInconclusiveReason,
CheckOutcome,
MetricThresholdConfig,
+ check_schedule_expires_at,
parse_check_config,
soak_minutes_from_gap,
)
@@ -223,6 +226,26 @@ def measure_check(check: SignalReportCheck, *, deadline: float) -> CheckVerdict:
config = parse_check_config(check.kind, check.config)
assert isinstance(config, MetricThresholdConfig)
query = resolve_check_query(config, check.report)
+ if check.measurement_start_at is not None:
+ now = timezone.now()
+ window_start = metric_check_window_start(query, check.report.team, now)
+ if window_start < check.measurement_start_at:
+ return CheckVerdict(
+ outcome="inconclusive", reason="awaiting_data", explanation="Waiting for a full measurement window."
+ )
+ # Pin this run's bounds so a cached relative query cannot include pre-resolution data.
+ query = {
+ **query,
+ "source": {
+ **query["source"],
+ "dateRange": {
+ **query["source"]["dateRange"],
+ "date_from": window_start.isoformat(),
+ "date_to": now.isoformat(),
+ "explicitDate": True,
+ },
+ },
+ }
tag_queries(trigger="signals_report_check")
measurement = measure_metric(query, check.report.team, deadline=deadline, include_series=False)
except Exception as error:
@@ -578,6 +601,7 @@ def park_checks_on_unresolved_reports(now: datetime) -> int:
.update(
status=SignalReportCheck.Status.PENDING,
soak_minutes=soak_minutes,
+ measurement_start_at=None,
next_run_at=now + timedelta(minutes=soak_minutes),
expires_at=now + MAX_CHECK_HORIZON,
consecutive_errors=0,
@@ -669,7 +693,46 @@ def run_due_report_checks(*, now: datetime | None = None, limit: int = MAX_CHECK
"signals.report_check.agent_step_failed", check_id=str(check.id), team_id=check.team_id
)
continue
- verdict = measure_check(check, deadline=deadline)
+ verdict: CheckVerdict | None = None
+ if check.kind == SignalReportCheck.Kind.METRIC_THRESHOLD:
+ start_at = check.measurement_start_at or now
+ try:
+ query = resolve_check_query(
+ cast(MetricThresholdConfig, parse_check_config(check.kind, check.config)), check.report
+ )
+ ready_at = metric_check_ready_at(query, check.report.team, start_at)
+ except (CheckConfigValidationError, ValueError):
+ ready_at = now
+ if check.measurement_start_at is None or now < ready_at:
+ next_run_at = max(check.next_run_at, ready_at)
+ expires_at = check.expires_at
+ if check.measurement_start_at is None:
+ expires_at = check_schedule_expires_at(
+ next_run_at=next_run_at,
+ run_interval_minutes=check.run_interval_minutes,
+ runs_remaining=check.runs_remaining,
+ start_at=start_at,
+ )
+ if next_run_at >= expires_at:
+ verdict = CheckVerdict(
+ outcome="inconclusive",
+ reason="unmeasurable",
+ explanation="The full measurement window cannot fit before this check expires.",
+ )
+ else:
+ SignalReportCheck.objects.for_team(check.team_id).filter(
+ id=check.id,
+ status=SignalReportCheck.Status.ACTIVE,
+ measurement_start_at=check.measurement_start_at,
+ ).update(
+ measurement_start_at=start_at,
+ next_run_at=next_run_at,
+ expires_at=expires_at,
+ updated_at=now,
+ )
+ continue
+ if verdict is None:
+ verdict = measure_check(check, deadline=deadline)
try:
record_check_verdict(check, verdict)
except Exception:
diff --git a/products/signals/backend/report_check_timing.py b/products/signals/backend/report_check_timing.py
new file mode 100644
index 000000000000..6d286b8caa8a
--- /dev/null
+++ b/products/signals/backend/report_check_timing.py
@@ -0,0 +1,45 @@
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import TYPE_CHECKING, Any
+
+from posthog.utils import relative_date_parse
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+
+def metric_check_window_start(query: dict[str, Any], team: Team, now: datetime) -> datetime:
+ from posthog.schema import DateRange, IntervalType # noqa: PLC0415 — keeps the generated schema off startup
+
+ from posthog.hogql_queries.utils.query_date_range import (
+ QueryDateRange, # noqa: PLC0415 — keeps query runners off startup
+ )
+
+ return (
+ QueryDateRange(
+ date_range=DateRange.model_validate(query["source"]["dateRange"]),
+ team=team,
+ interval=IntervalType.DAY,
+ now=now,
+ exact_timerange=bool(query["source"]["dateRange"].get("explicitDate")),
+ )
+ .date_from()
+ .astimezone(UTC)
+ )
+
+
+def metric_check_ready_at(query: dict[str, Any], team: Team, start_at: datetime) -> datetime:
+ date_range = query["source"]["dateRange"]
+ date_from = date_range["date_from"]
+ candidate = relative_date_parse(date_from, team.timezone_info, now=start_at, increase=True)
+ step = timedelta(hours=1) if date_from.endswith("h") else timedelta(days=1)
+ if not date_range.get("explicitDate"):
+ rounded = candidate.replace(minute=0, second=0, microsecond=0)
+ if not date_from.endswith("h"):
+ rounded = rounded.replace(hour=0)
+ candidate = rounded if rounded == candidate else rounded + step
+ # Calendar month subtraction can reach before the anchor even after adding one month.
+ while metric_check_window_start(query, team, candidate) < start_at.astimezone(UTC):
+ candidate += step
+ return candidate.astimezone(UTC)
diff --git a/products/signals/backend/report_checks.py b/products/signals/backend/report_checks.py
index 4a88e721b842..849b2558ccc4 100644
--- a/products/signals/backend/report_checks.py
+++ b/products/signals/backend/report_checks.py
@@ -29,7 +29,15 @@ 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
+from products.signals.backend.report_metrics import (
+ MAX_METRIC_UNIT_LENGTH,
+ ReportMetric,
+ ReportMetricKind,
+ ReportMetricValueFormat,
+ validate_live_metric_query,
+ validate_metric_id,
+ validate_metric_number,
+)
CheckOutcome = Literal["passed", "failed", "errored", "inconclusive"]
# Why an `inconclusive` verdict could not settle the claim. Only `awaiting_data` keeps the check open.
@@ -72,6 +80,19 @@ MAX_CONSECUTIVE_CHECK_ERRORS = 3
AWAITING_DATA_RETRY_WAITS = (timedelta(hours=24), timedelta(hours=72), timedelta(days=7))
+def check_schedule_expires_at(
+ *,
+ next_run_at: datetime,
+ run_interval_minutes: int | None,
+ runs_remaining: int,
+ start_at: datetime,
+) -> datetime:
+ last_run_at = next_run_at
+ if run_interval_minutes:
+ last_run_at += timedelta(minutes=run_interval_minutes * max(0, runs_remaining - 1))
+ return min(last_run_at + DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN, start_at + MAX_CHECK_HORIZON)
+
+
class CheckThresholdBounds(BaseModel):
model_config = ConfigDict(extra="forbid")
@@ -168,6 +189,13 @@ class MetricThresholdConfig(BaseModel):
default=None,
description="The value observed when the check was written, recorded on each result for context.",
)
+ metric_kind: ReportMetricKind | None = Field(
+ default=None, description="How to draw this measurement; copied from a referenced metric."
+ )
+ value_format: ReportMetricValueFormat | None = Field(
+ default=None, description="How to format measured values; copied from a referenced metric."
+ )
+ unit: str | None = Field(default=None, max_length=MAX_METRIC_UNIT_LENGTH, description="Optional value suffix.")
@field_validator("baseline_value", mode="before")
@classmethod
@@ -298,6 +326,32 @@ def parse_check_config(kind: str, config: object) -> BaseModel:
raise CheckConfigValidationError(str(error)) from error
+def validate_metric_check_for_write(config: MetricThresholdConfig) -> None:
+ if config.query is None:
+ raise CheckConfigValidationError("The metric query must be resolved before writing a check.")
+ kind = config.metric_kind or "custom"
+ value_format = config.value_format or "number"
+ try:
+ ReportMetric(
+ metric_id=config.metric_id or "check",
+ title="Follow-up measurement",
+ kind=kind,
+ query=config.query,
+ value_format=value_format,
+ unit=config.unit,
+ )
+ if config.baseline_value is not None:
+ validate_metric_number(kind, value_format, config.baseline_value, "baseline")
+ comparison = config.comparison
+ if comparison.bounds is not None:
+ validate_metric_number(kind, value_format, comparison.bounds.lower, "lower bound")
+ validate_metric_number(kind, value_format, comparison.bounds.upper, "upper bound")
+ elif comparison.value is not None:
+ validate_metric_number(kind, value_format, comparison.value, "goal")
+ except ValueError as error:
+ raise CheckConfigValidationError(str(error)) from error
+
+
class CheckSpec(BaseModel):
"""A check whose clock starts when its report resolves, written before any fix exists.
diff --git a/products/signals/backend/report_metrics.py b/products/signals/backend/report_metrics.py
index 35ff4ccd7ee6..2dbe81af7794 100644
--- a/products/signals/backend/report_metrics.py
+++ b/products/signals/backend/report_metrics.py
@@ -100,6 +100,22 @@ REPORT_METRIC_VALUE_FORMATS: tuple[ReportMetricValueFormat, ...] = (
"currency",
)
+
+def validate_metric_number(
+ kind: ReportMetricKind, value_format: ReportMetricValueFormat, value: float, label: str
+) -> None:
+ if not math.isfinite(value):
+ raise ValueError(f"{label} must be finite")
+ if value_format == "count" and (value < 0 or not value.is_integer()):
+ raise ValueError(f"a count {label} must be a non-negative whole number")
+ if kind == "duration" and value < 0:
+ raise ValueError(f"a duration {label} must be non-negative")
+ if kind in {"conversion_rate", "error_rate"}:
+ upper_bound = 1 if value_format == "percentage_scaled" else 100
+ if not 0 <= value <= upper_bound:
+ raise ValueError(f"a rate {label} must be between 0 and {upper_bound}")
+
+
_LIVE_METRIC_QUERY_KINDS = frozenset({"InsightVizNode"})
_LIVE_METRIC_SERIES_KINDS = frozenset({"ActionsNode", "EventsNode"})
_RELATIVE_WINDOW_SECONDS = {"h": 3_600, "d": 86_400, "w": 604_800, "m": 2_635_200, "y": 31_622_400}
@@ -585,13 +601,8 @@ class ReportMetric(BaseModel):
raise ValueError("goal_value must be finite")
if self.goal_value is not None and self.decision_window_days is None and self.minimum_data_points is None:
raise ValueError("a goal requires a suggested decision window or minimum data points")
- if self.goal_value is not None and self.value_format == "count":
- if self.goal_value < 0 or not self.goal_value.is_integer():
- raise ValueError("a count goal must be a non-negative whole number")
- if self.goal_value is not None and self.kind in {"conversion_rate", "error_rate"}:
- upper_bound = 1 if self.value_format == "percentage_scaled" else 100
- if not 0 <= self.goal_value <= upper_bound:
- raise ValueError(f"a rate goal must be between 0 and {upper_bound}")
+ if self.goal_value is not None:
+ validate_metric_number(self.kind, self.value_format, self.goal_value, "goal")
if (self.value is None) != (self.value_at is None):
raise ValueError("value and value_at must be provided together")
self._drop_a_snapshot_measured_in_the_future()
@@ -637,35 +648,22 @@ class ReportMetric(BaseModel):
raise ValueError("a duration metric must use duration formatting")
if self.unit not in {"ms", "s"}:
raise ValueError("a duration metric must use `ms` or `s` as its unit")
- if self.goal_value is not None and self.goal_value < 0:
- raise ValueError("a duration goal must be non-negative")
- if self.value is not None and self.value < 0:
- raise ValueError("a duration snapshot must be non-negative")
- if self.comparison is not None and self.comparison.value < 0:
- raise ValueError("a duration comparison must be non-negative")
if self.kind == "revenue":
if self.value_format != "currency":
raise ValueError("a revenue metric must use currency formatting")
if self.unit is None or re.fullmatch(r"[A-Z]{3}", self.unit) is None:
raise ValueError("a revenue metric must use a three-letter ISO currency code as its unit")
- if self.value_format == "count" and self.value is not None:
- if self.value < 0 or not self.value.is_integer():
- raise ValueError("a count snapshot must be a non-negative whole number")
+ if self.value is not None:
+ validate_metric_number(self.kind, self.value_format, self.value, "snapshot")
if self.value_format == "count" and self.series is not None:
if any(point < 0 or not point.is_integer() for point in self.series):
raise ValueError("a count series must contain non-negative whole numbers")
- if self.value_format == "count" and self.comparison is not None:
- if self.comparison.value < 0 or not self.comparison.value.is_integer():
- raise ValueError("a count comparison must be a non-negative whole number")
+ if self.comparison is not None:
+ validate_metric_number(self.kind, self.value_format, self.comparison.value, "comparison")
percentage_formats = {"percentage", "percentage_scaled"}
if self.kind in {"conversion_rate", "error_rate"}:
if self.value_format not in percentage_formats:
raise ValueError("a conversion_rate or error_rate metric must use percentage formatting")
- upper_bound = 1 if self.value_format == "percentage_scaled" else 100
- if self.value is not None and not 0 <= self.value <= upper_bound:
- raise ValueError(f"a {self.value_format} rate snapshot must be between 0 and {upper_bound}")
- if self.comparison is not None and not 0 <= self.comparison.value <= upper_bound:
- raise ValueError(f"a {self.value_format} rate comparison must be between 0 and {upper_bound}")
if self.value_format in percentage_formats:
trends_filter = self.query["source"].get("trendsFilter")
axis_format = trends_filter.get("aggregationAxisFormat") if isinstance(trends_filter, dict) else None
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 6f3f3cb291e4..ef0b71e02c15 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -1955,8 +1955,8 @@ class SignalReportCheckSerializer(serializers.ModelSerializer):
},
"soak_minutes": {
"help_text": (
- "How long after the report resolves a `pending` check waits before its first run. "
- "Null on a check that named its own `next_run_at`."
+ "Minimum wait after resolution, in minutes. Metric checks also wait for a full post-resolution "
+ "query window. Null on legacy checks that did not record a soak."
)
},
"run_interval_minutes": {"help_text": "Gap between runs for a recurring check; null for a one-shot."},
diff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.py
index b3e227668248..0ac913a3c789 100644
--- a/products/signals/backend/test/test_report_checks.py
+++ b/products/signals/backend/test/test_report_checks.py
@@ -1,7 +1,8 @@
import json
import time
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, patch
@@ -53,6 +54,7 @@ from products.signals.backend.report_check_execution import (
resolve_check_query,
run_due_report_checks,
)
+from products.signals.backend.report_check_timing import metric_check_ready_at, metric_check_window_start
from products.signals.backend.report_checks import (
AWAITING_DATA_RETRY_WAITS,
DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
@@ -74,6 +76,7 @@ from products.signals.backend.report_checks import (
CheckSpec,
MetricThresholdConfig,
parse_check_config,
+ validate_metric_check_for_write,
)
from products.signals.backend.report_metric_refresh import MetricMeasurement
from products.signals.backend.scout_harness.tools.checks import (
@@ -191,6 +194,142 @@ class TestCheckComparison(SimpleTestCase):
with self.assertRaises(CheckConfigValidationError):
parse_check_config("vibes", {"instructions": "look again"})
+ @parameterized.expand(
+ [
+ ("count_query_with_percentage_format", _threshold_config(value_format="percentage_scaled")),
+ ("affected_users_with_event_count", _threshold_config(metric_kind="affected_users", value_format="count")),
+ ("duration_without_unit", _threshold_config(metric_kind="duration", value_format="duration")),
+ (
+ "negative_count_goal",
+ _threshold_config(value_format="count", comparison={"operator": "lte", "value": -1}),
+ ),
+ ("fractional_count_baseline", _threshold_config(value_format="count", baseline_value=1.5)),
+ (
+ "fractional_count_bound",
+ _threshold_config(
+ value_format="count", comparison={"operator": "between", "bounds": {"lower": 1, "upper": 2.5}}
+ ),
+ ),
+ (
+ "negative_duration_baseline",
+ _threshold_config(metric_kind="duration", value_format="duration", unit="s", baseline_value=-1),
+ ),
+ ("nonfinite_goal", _threshold_config(comparison={"operator": "lte", "value": float("inf")})),
+ (
+ "nonfinite_bound",
+ _threshold_config(comparison={"operator": "between", "bounds": {"lower": 0, "upper": float("inf")}}),
+ ),
+ (
+ "scaled_rate_over_one",
+ _threshold_config(
+ metric_kind="error_rate",
+ value_format="percentage_scaled",
+ query={
+ **_PAGEVIEWS,
+ "source": {
+ **_PAGEVIEWS["source"],
+ "trendsFilter": {"formula": "A / B", "aggregationAxisFormat": "percentage_scaled"},
+ "series": _PAGEVIEWS["source"]["series"] * 2,
+ },
+ },
+ comparison={"operator": "lte", "value": 1.1},
+ ),
+ ),
+ (
+ "rate_baseline_over_100",
+ _threshold_config(
+ metric_kind="conversion_rate",
+ value_format="percentage",
+ query={
+ **_PAGEVIEWS,
+ "source": {
+ **_PAGEVIEWS["source"],
+ "trendsFilter": {"formula": "A / B * 100", "aggregationAxisFormat": "percentage"},
+ "series": _PAGEVIEWS["source"]["series"] * 2,
+ },
+ },
+ baseline_value=101,
+ ),
+ ),
+ ]
+ )
+ def test_new_numeric_and_display_rules_do_not_reject_legacy_reads(self, _name: str, config: dict) -> None:
+ parsed = parse_check_config("metric_threshold", config)
+ assert isinstance(parsed, MetricThresholdConfig)
+ with self.assertRaises(CheckConfigValidationError):
+ validate_metric_check_for_write(parsed)
+
+ @parameterized.expand(
+ [
+ ("whole_count", "custom", "count", None, 10.0, {}),
+ ("nonnegative_duration", "duration", "duration", "ms", 1.5, {}),
+ ("negative_custom", "custom", "number", None, -1.5, {}),
+ ("negative_revenue", "revenue", "currency", "USD", -1.5, {}),
+ (
+ "scaled_rate",
+ "error_rate",
+ "percentage_scaled",
+ None,
+ 1.0,
+ {"aggregationAxisFormat": "percentage_scaled"},
+ ),
+ (
+ "percentage_points",
+ "conversion_rate",
+ "percentage",
+ None,
+ 100.0,
+ {"aggregationAxisFormat": "percentage"},
+ ),
+ ]
+ )
+ def test_valid_numeric_formats_remain_writable(
+ self, _name: str, kind: str, value_format: str, unit: str | None, value: float, trends_filter: dict
+ ) -> None:
+ query = {**_PAGEVIEWS, "source": {**_PAGEVIEWS["source"], "trendsFilter": trends_filter}}
+ config = MetricThresholdConfig.model_validate(
+ _threshold_config(
+ query=query,
+ metric_kind=kind,
+ value_format=value_format,
+ unit=unit,
+ baseline_value=value,
+ comparison={"operator": "lte", "value": value},
+ )
+ )
+ validate_metric_check_for_write(config)
+
+
+class TestMetricCheckTiming(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("daily_rounding", "UTC", "2026-10-01T12:30:00+00:00", "-13d", False, "2026-10-15T00:00:00+00:00"),
+ ("hourly_rounding", "UTC", "2026-10-01T12:30:00+00:00", "-2h", False, "2026-10-01T15:00:00+00:00"),
+ ("explicit_time", "UTC", "2026-10-01T12:30:00+00:00", "-13d", True, "2026-10-14T12:30:00+00:00"),
+ ("month_end", "UTC", "2026-01-31T00:00:00+00:00", "-1m", False, "2026-03-01T00:00:00+00:00"),
+ (
+ "spring_dst",
+ "America/Los_Angeles",
+ "2026-03-07T20:30:00+00:00",
+ "-1d",
+ False,
+ "2026-03-09T07:00:00+00:00",
+ ),
+ ("fall_dst", "America/Los_Angeles", "2026-10-31T19:30:00+00:00", "-1d", False, "2026-11-02T08:00:00+00:00"),
+ ]
+ )
+ def test_full_query_window_starts_after_resolution(
+ self, _name: str, zone: str, start: str, date_from: str, explicit: bool, ready: str
+ ) -> None:
+ team = Team(timezone=zone)
+ anchor = datetime.fromisoformat(start)
+ query = trends_metric_query(series=[{"kind": "EventsNode", "event": "$pageview"}], date_from=date_from)
+ query["source"]["dateRange"]["explicitDate"] = explicit
+ ready_at = metric_check_ready_at(query, team, anchor)
+ assert ready_at == datetime.fromisoformat(ready)
+ assert metric_check_window_start(query, team, ready_at) >= anchor
+ assert metric_check_window_start(query, team, ready_at - timedelta(seconds=1)) < anchor
+
class TestAgentCheckConfig(SimpleTestCase):
@parameterized.expand(
@@ -322,6 +461,7 @@ class TestReportCheckExecution(APIBaseTest):
"title": "Checkout errors stay low",
"kind": SignalReportCheck.Kind.METRIC_THRESHOLD,
"config": _threshold_config(),
+ "measurement_start_at": now - timedelta(days=32),
"next_run_at": now - timedelta(minutes=1),
"expires_at": now + timedelta(days=30),
}
@@ -335,6 +475,80 @@ class TestReportCheckExecution(APIBaseTest):
).order_by("created_at")
)
+ @parameterized.expand(
+ [
+ ("legacy_without_anchor", None, None, 1),
+ ("legacy_recurring_near_expiry", None, 24 * 60, 3),
+ ("legacy_recurring_horizon", None, 30 * 24 * 60, 3),
+ ("prematurely_due", datetime(2026, 10, 1, 12, tzinfo=UTC), None, 1),
+ ]
+ )
+ def test_incomplete_window_defers_without_a_verdict(
+ self, _name: str, anchor: datetime | None, interval: int | None, runs: int
+ ) -> None:
+ now = datetime(2026, 10, 2, 12, tzinfo=UTC)
+ with time_machine.travel(now, tick=False):
+ check = self._check(measurement_start_at=anchor, run_interval_minutes=interval, runs_remaining=runs)
+ original_expiry = check.expires_at
+ with patch(_MEASURE) as measure:
+ summary = run_due_report_checks()
+ check.refresh_from_db()
+ assert not measure.called
+ assert summary.passed == summary.failed == summary.inconclusive == summary.errored == 0
+ assert self._results() == []
+ assert check.measurement_start_at == (anchor or now)
+ assert check.next_run_at == metric_check_ready_at(_PAGEVIEWS, self.team, anchor or now)
+ assert check.next_run_at < check.expires_at <= now + MAX_CHECK_HORIZON
+ if anchor is None:
+ last_run_at = check.next_run_at + timedelta(minutes=(interval or 0) * (runs - 1))
+ assert check.expires_at == min(
+ last_run_at + DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN, now + MAX_CHECK_HORIZON
+ )
+ assert check.expires_at > original_expiry
+ else:
+ assert check.expires_at == original_expiry
+ assert check.consecutive_errors == 0
+ assert check.runs_remaining == runs
+
+ with time_machine.travel(check.next_run_at, tick=False):
+ with patch(_MEASURE, return_value=MetricMeasurement(value=3, measured_at=check.next_run_at, series=None)):
+ summary = run_due_report_checks()
+ check.refresh_from_db()
+ assert summary.expired == 0
+ assert summary.passed == 1
+ assert check.runs_remaining == runs - 1
+ assert len(self._results()) == 1
+
+ @parameterized.expand(
+ [
+ ("legacy_window_exceeds_horizon", None, "-90d"),
+ ("anchored_deadline_before_window", datetime(2026, 10, 2, 12, tzinfo=UTC), "-30d"),
+ ]
+ )
+ def test_unreachable_window_records_inconclusive(self, _name: str, anchor: datetime | None, date_from: str) -> None:
+ now = datetime(2026, 10, 2, 12, tzinfo=UTC)
+ with time_machine.travel(now, tick=False):
+ check = self._check(
+ measurement_start_at=anchor,
+ config=_threshold_config(
+ query=trends_metric_query(
+ series=[{"kind": "EventsNode", "event": "$pageview"}], date_from=date_from
+ )
+ ),
+ )
+ original_expiry = check.expires_at
+ with patch(_MEASURE) as measure:
+ summary = run_due_report_checks()
+ check.refresh_from_db()
+ assert not measure.called
+ assert summary.inconclusive == 1
+ assert summary.expired == 0
+ assert check.status == SignalReportCheck.Status.INCONCLUSIVE
+ assert check.last_outcome_reason == "unmeasurable"
+ assert check.expires_at == original_expiry
+ assert check.next_run_at < now
+ assert len(self._results()) == 1
+
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)):
@@ -499,15 +713,19 @@ class TestReportCheckExecution(APIBaseTest):
check.refresh_from_db()
assert check.status == SignalReportCheck.Status.PENDING
assert check.consecutive_errors == 0
+ assert check.measurement_start_at is None
before = timezone.now()
with self.captureOnCommitCallbacks(execute=True):
self.report.status = SignalReport.Status.RESOLVED
self.report.save(update_fields=["status"])
- check.refresh_from_db()
- assert check.status == SignalReportCheck.Status.ACTIVE
- assert check.next_run_at >= before + timedelta(hours=MIN_CHECK_SOAK_HOURS)
+ armed = SignalReportCheck.objects.for_team(self.team.id).get(id=check.id)
+ assert armed.status == SignalReportCheck.Status.ACTIVE
+ assert armed.measurement_start_at is not None
+ assert before <= armed.measurement_start_at <= timezone.now()
+ assert armed.next_run_at == metric_check_ready_at(_PAGEVIEWS, self.team, armed.measurement_start_at)
+ assert armed.next_run_at >= before + timedelta(hours=MIN_CHECK_SOAK_HOURS)
assert collect_due_checks(timezone.now()) == []
def test_an_active_check_on_an_unresolved_report_is_never_due(self) -> None:
@@ -765,25 +983,41 @@ class TestReportCheckAPI(APIBaseTest):
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}
+ {
+ "metric_id": "checkout-errors",
+ "title": "Checkout errors",
+ "kind": "occurrences",
+ "value_format": "count",
+ "query": _PAGEVIEWS,
+ }
]
self.report.save(update_fields=["metrics"])
- stored = self._create(config=config)
+ stored = self._create(config={**config, "value_format": "percentage", "unit": "failure"})
assert stored.config["metric_id"] == "checkout-errors"
assert stored.config["query"] == _PAGEVIEWS
+ assert not {"metric_kind", "value_format", "unit"}.intersection(stored.config)
+ overridden = self._create(config={**config, "metric_kind": "custom", "value_format": "number", "unit": "USD"})
+ assert not {"metric_kind", "value_format", "unit"}.intersection(overridden.config)
# 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)
+ next_run_at=timezone.now() - timedelta(minutes=1), measurement_start_at=timezone.now() - timedelta(days=32)
)
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
+ measured_query = measure.call_args.args[0]
+ assert {key: value for key, value in measured_query["source"].items() if key != "dateRange"} == {
+ key: value for key, value in _PAGEVIEWS["source"].items() if key != "dateRange"
+ }
+ assert measured_query["source"]["dateRange"]["explicitDate"] is True
+ assert datetime.fromisoformat(measured_query["source"]["dateRange"]["date_from"]) >= timezone.now() - timedelta(
+ days=32
+ )
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)
@@ -795,7 +1029,9 @@ class TestReportCheckAPI(APIBaseTest):
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))
+ SignalReportCheck.all_teams.filter(id=check_id).update(
+ next_run_at=timezone.now() - timedelta(minutes=1), measurement_start_at=timezone.now() - timedelta(days=32)
+ )
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)
@@ -820,7 +1056,7 @@ class TestReportCheckAPI(APIBaseTest):
).id
)
SignalReportCheck.objects.for_team(self.team.id).filter(id=check_id).update(
- next_run_at=timezone.now() - timedelta(minutes=1)
+ next_run_at=timezone.now() - timedelta(minutes=1), measurement_start_at=timezone.now() - timedelta(days=32)
)
with patch(_MEASURE, return_value=MetricMeasurement(value=4.0, measured_at=timezone.now(), series=None)):
run_due_report_checks()
@@ -1422,7 +1658,7 @@ class TestPendingChecks(APIBaseTest):
# Well past the soak, but the clock has not started: the report is still open.
assert collect_due_checks(timezone.now() + timedelta(days=7)) == []
- def test_resolving_the_report_arms_the_check_for_resolve_plus_soak(self) -> None:
+ def test_resolving_the_report_waits_for_a_full_query_window_after_the_soak(self) -> None:
check = self._pending()
before = timezone.now()
@@ -1430,8 +1666,10 @@ class TestPendingChecks(APIBaseTest):
check.refresh_from_db()
assert check.status == SignalReportCheck.Status.ACTIVE
- soak = timedelta(hours=DEFAULT_CHECK_SOAK_HOURS)
- assert before + soak <= check.next_run_at <= timezone.now() + soak
+ assert check.measurement_start_at is not None
+ assert before <= check.measurement_start_at <= timezone.now()
+ assert check.soak_minutes == DEFAULT_CHECK_SOAK_HOURS * 60
+ assert check.next_run_at == metric_check_ready_at(_PAGEVIEWS, self.team, check.measurement_start_at)
assert collect_due_checks(check.next_run_at + timedelta(minutes=1)) == [check]
@parameterized.expand(
@@ -1469,6 +1707,57 @@ class TestPendingChecks(APIBaseTest):
check.refresh_from_db()
assert check.next_run_at == armed_at
+ def test_longer_soak_and_agent_timing_are_preserved(self) -> None:
+ metric = create_check(
+ report=self.report,
+ title="Short metric",
+ kind="metric_threshold",
+ config=_threshold_config(
+ query=trends_metric_query(series=[{"kind": "EventsNode", "event": "$pageview"}], date_from="-1d")
+ ),
+ attribution=ArtefactAttribution.system(),
+ soak_minutes=3 * 24 * 60,
+ )
+ agent = create_check(
+ report=self.report,
+ title="Investigate",
+ kind="agent",
+ config={"instructions": "Look for the exception."},
+ attribution=ArtefactAttribution.system(),
+ soak_minutes=24 * 60,
+ )
+ resolved_at = timezone.now()
+ arm_pending_checks(team_id=self.team.id, report_id=self.report.id, resolved_at=resolved_at)
+ metric.refresh_from_db()
+ agent.refresh_from_db()
+ assert metric.next_run_at == resolved_at + timedelta(days=3)
+ assert agent.next_run_at == resolved_at + timedelta(days=1)
+ assert agent.measurement_start_at is None
+
+ def test_query_window_longer_than_the_horizon_is_rejected_before_resolution(self) -> None:
+ with self.assertRaisesRegex(CheckCreationError, "90-day horizon"):
+ create_check(
+ report=self.report,
+ title="Yearly metric",
+ kind="metric_threshold",
+ config=_threshold_config(
+ query=trends_metric_query(series=[{"kind": "EventsNode", "event": "$pageview"}], date_from="-365d")
+ ),
+ attribution=ArtefactAttribution.system(),
+ soak_minutes=60,
+ )
+
+ def test_invalid_legacy_config_does_not_prevent_other_checks_from_arming(self) -> None:
+ invalid = self._pending()
+ valid = self._pending()
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=invalid.id).update(config={})
+ self._resolve()
+ invalid.refresh_from_db()
+ valid.refresh_from_db()
+ assert invalid.status == valid.status == SignalReportCheck.Status.ACTIVE
+ assert valid.measurement_start_at is not None
+ assert valid.next_run_at == metric_check_ready_at(_PAGEVIEWS, self.team, valid.measurement_start_at)
+
def test_a_pending_check_retires_when_its_report_never_resolves(self) -> None:
check = self._pending()
@@ -1513,6 +1802,7 @@ class TestFailedCheckResurfaces(APIBaseTest):
"title": "Checkout errors stay low",
"kind": SignalReportCheck.Kind.METRIC_THRESHOLD,
"config": _threshold_config(baseline_value=40.0),
+ "measurement_start_at": now - timedelta(days=32),
"next_run_at": now - timedelta(minutes=1),
"expires_at": now + timedelta(days=30),
}
@@ -1630,7 +1920,7 @@ class TestScoutCheckTools(APIBaseTest):
"kind": SignalReportCheck.Kind.METRIC_THRESHOLD,
"config": _threshold_config(baseline_value=40.0),
"next_run_at": now + timedelta(days=3),
- "expires_at": now + timedelta(days=30),
+ "expires_at": now + timedelta(days=60),
}
payload.update(overrides)
return create_report_check(team=self.team, run=self.scout_run, **payload)
@@ -1663,9 +1953,11 @@ class TestScoutCheckTools(APIBaseTest):
self.report.save(update_fields=["status"])
check.refresh_from_db()
- soak = timedelta(days=3)
assert check.status == SignalReportCheck.Status.ACTIVE
- assert before + soak <= check.next_run_at <= timezone.now() + soak
+ assert check.measurement_start_at is not None
+ assert before <= check.measurement_start_at <= timezone.now()
+ assert check.soak_minutes == 3 * 24 * 60
+ assert check.next_run_at == metric_check_ready_at(_PAGEVIEWS, self.team, check.measurement_start_at)
def test_a_recurring_check_keeps_its_initial_soak_after_reopening(self) -> None:
self.report.status = SignalReport.Status.RESOLVED
@@ -1677,7 +1969,8 @@ class TestScoutCheckTools(APIBaseTest):
)
assert check.status == SignalReportCheck.Status.ACTIVE
- assert check.next_run_at == first_run
+ assert check.measurement_start_at is not None
+ assert check.next_run_at == metric_check_ready_at(_PAGEVIEWS, self.team, check.measurement_start_at)
assert check.soak_minutes == 3 * 24 * 60
record_check_verdict(check, CheckVerdict(outcome="passed", explanation="held"), now=first_run)
self.report.status = SignalReport.Status.READY
@@ -1817,10 +2110,11 @@ class TestResearchAuthoredChecks(APIBaseTest):
report=self.report, specs=[self._spec()], attribution=ArtefactAttribution.system()
)
- # Nothing left to wait for, so the check is armed rather than held for a resolve that already happened.
- soak = timedelta(hours=DEFAULT_CHECK_SOAK_HOURS)
assert written[0].status == SignalReportCheck.Status.ACTIVE
- assert before + soak <= written[0].next_run_at <= timezone.now() + soak
+ assert written[0].measurement_start_at is not None
+ assert before <= written[0].measurement_start_at <= timezone.now()
+ assert written[0].soak_minutes == DEFAULT_CHECK_SOAK_HOURS * 60
+ assert written[0].next_run_at == metric_check_ready_at(_PAGEVIEWS, self.team, written[0].measurement_start_at)
def test_a_longer_soak_is_honoured_for_a_fix_that_reaches_users_slowly(self) -> None:
written = create_checks_from_specs(
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index c420629a3a88..1de27af3c108 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -2804,6 +2804,40 @@ export interface CheckComparisonApi {
bounds?: CheckThresholdBoundsApi | null
}
+/**
+ * How to draw this measurement; copied from a referenced metric.
+ */
+export type MetricThresholdConfigApiMetricKind =
+ | (typeof MetricThresholdConfigApiMetricKind)[keyof typeof MetricThresholdConfigApiMetricKind]
+ | null
+
+export const MetricThresholdConfigApiMetricKind = {
+ AffectedUsers: 'affected_users',
+ AffectedSessions: 'affected_sessions',
+ Occurrences: 'occurrences',
+ ConversionRate: 'conversion_rate',
+ ErrorRate: 'error_rate',
+ Duration: 'duration',
+ Revenue: 'revenue',
+ Custom: 'custom',
+} as const
+
+/**
+ * How to format measured values; copied from a referenced metric.
+ */
+export type MetricThresholdConfigApiValueFormat =
+ | (typeof MetricThresholdConfigApiValueFormat)[keyof typeof MetricThresholdConfigApiValueFormat]
+ | null
+
+export const MetricThresholdConfigApiValueFormat = {
+ Number: 'number',
+ Count: 'count',
+ Percentage: 'percentage',
+ PercentageScaled: 'percentage_scaled',
+ Duration: 'duration',
+ Currency: 'currency',
+} as const
+
/**
* Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. `dateRange.date_from` must be a relative window such as `-13d`, and `date_to` must be empty, so the check measures the days before each run rather than the days before it was written. The query must produce exactly one output series: use one event or action series, or combine up to ten of them with exactly one formula. Use no breakdown and no compare mode. A `trendsFilter.display` of `Metric` turns compare mode on, so `metricShowChange` is switched off for you unless `metricSummary` is `latest`, which keeps compare mode off already.
*/
@@ -2832,6 +2866,12 @@ export interface MetricThresholdConfigApi {
comparison: CheckComparisonApi
/** The value observed when the check was written, recorded on each result for context. */
baseline_value?: number | null
+ /** How to draw this measurement; copied from a referenced metric. */
+ metric_kind?: MetricThresholdConfigApiMetricKind
+ /** How to format measured values; copied from a referenced metric. */
+ value_format?: MetricThresholdConfigApiValueFormat
+ /** Optional value suffix. */
+ unit?: string | null
}
/**
@@ -2910,7 +2950,7 @@ export interface SignalReportCheckApi {
/** When the coordinator next evaluates the check. Provisional while the check is `pending`: the report resolving is what sets it. */
readonly next_run_at: string
/**
- * How long after the report resolves a `pending` check waits before its first run. Null on a check that named its own `next_run_at`.
+ * Minimum wait after resolution, in minutes. Metric checks also wait for a full post-resolution query window. Null on legacy checks that did not record a soak.
* @nullable
*/
readonly soak_minutes: number | null
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 67b97ed56a96..ed1cab0432ac 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -2367,6 +2367,8 @@ export const signalsScoutReportCheckCreateBodyTitleMax = 200
export const signalsScoutReportCheckCreateBodyRationaleMax = 2000
+export const signalsScoutReportCheckCreateBodyConfigOneOneUnitOneMax = 40
+
export const signalsScoutReportCheckCreateBodyConfigOneTwoInstructionsMax = 2000
export const signalsScoutReportCheckCreateBodyConfigOneTwoSkillNameOneMax = 200
@@ -2434,6 +2436,43 @@ export const SignalsScoutReportCheckCreateBody = /* @__PURE__ */ zod
.describe(
'The value observed when the check was written, recorded on each result for context.'
),
+ metric_kind: zod
+ .union([
+ zod.enum([
+ 'affected_users',
+ 'affected_sessions',
+ 'occurrences',
+ 'conversion_rate',
+ 'error_rate',
+ 'duration',
+ 'revenue',
+ 'custom',
+ ]),
+ zod.null(),
+ ])
+ .optional()
+ .describe('How to draw this measurement; copied from a referenced metric.'),
+ value_format: zod
+ .union([
+ zod.enum([
+ 'number',
+ 'count',
+ 'percentage',
+ 'percentage_scaled',
+ 'duration',
+ 'currency',
+ ]),
+ zod.null(),
+ ])
+ .optional()
+ .describe('How to format measured values; copied from a referenced metric.'),
+ unit: zod
+ .union([
+ zod.string().max(signalsScoutReportCheckCreateBodyConfigOneOneUnitOneMax),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Optional value suffix.'),
})
.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."
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d53e3b628457..ccd87f9ed141 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25079,6 +25079,38 @@ export namespace Schemas {
Agent: 'agent',
} as const;
+ /**
+ * How to draw this measurement; copied from a referenced metric.
+ */
+ export type MetricThresholdConfigMetricKind = typeof MetricThresholdConfigMetricKind[keyof typeof MetricThresholdConfigMetricKind] | null;
+
+
+ export const MetricThresholdConfigMetricKind = {
+ AffectedUsers: 'affected_users',
+ AffectedSessions: 'affected_sessions',
+ Occurrences: 'occurrences',
+ ConversionRate: 'conversion_rate',
+ ErrorRate: 'error_rate',
+ Duration: 'duration',
+ Revenue: 'revenue',
+ Custom: 'custom',
+ } as const;
+
+ /**
+ * How to format measured values; copied from a referenced metric.
+ */
+ export type MetricThresholdConfigValueFormat = typeof MetricThresholdConfigValueFormat[keyof typeof MetricThresholdConfigValueFormat] | null;
+
+
+ export const MetricThresholdConfigValueFormat = {
+ Number: 'number',
+ Count: 'count',
+ Percentage: 'percentage',
+ PercentageScaled: 'percentage_scaled',
+ Duration: 'duration',
+ Currency: 'currency',
+ } as const;
+
/**
* Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. `dateRange.date_from` must be a relative window such as `-13d`, and `date_to` must be empty, so the check measures the days before each run rather than the days before it was written. The query must produce exactly one output series: use one event or action series, or combine up to ten of them with exactly one formula. Use no breakdown and no compare mode. A `trendsFilter.display` of `Metric` turns compare mode on, so `metricShowChange` is switched off for you unless `metricSummary` is `latest`, which keeps compare mode off already.
*/
@@ -25107,6 +25139,12 @@ export namespace Schemas {
comparison: CheckComparison;
/** The value observed when the check was written, recorded on each result for context. */
baseline_value?: number | null;
+ /** How to draw this measurement; copied from a referenced metric. */
+ metric_kind?: MetricThresholdConfigMetricKind;
+ /** How to format measured values; copied from a referenced metric. */
+ value_format?: MetricThresholdConfigValueFormat;
+ /** Optional value suffix. */
+ unit?: string | null;
}
export type SignalReportCheckConfig = MetricThresholdConfig | AgentCheckConfig;
@@ -69487,7 +69525,7 @@ export namespace Schemas {
/** When the coordinator next evaluates the check. Provisional while the check is `pending`: the report resolving is what sets it. */
readonly next_run_at: string;
/**
- * How long after the report resolves a `pending` check waits before its first run. Null on a check that named its own `next_run_at`.
+ * Minimum wait after resolution, in minutes. Metric checks also wait for a full post-resolution query window. Null on legacy checks that did not record a soak.
* @nullable
*/
readonly soak_minutes: number | null;
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 58506bcae1ac..dcce31f13dcc 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -2720,6 +2720,8 @@ export const signalsScoutReportCheckCreateBodyTitleMax = 200
export const signalsScoutReportCheckCreateBodyRationaleMax = 2000
+export const signalsScoutReportCheckCreateBodyConfigOneOneUnitOneMax = 40
+
export const signalsScoutReportCheckCreateBodyConfigOneTwoInstructionsMax = 2000
export const signalsScoutReportCheckCreateBodyConfigOneTwoSkillNameOneMax = 200
@@ -2787,6 +2789,43 @@ export const SignalsScoutReportCheckCreateBody = () => zod
.describe(
'The value observed when the check was written, recorded on each result for context.'
),
+ metric_kind: zod
+ .union([
+ zod.enum([
+ 'affected_users',
+ 'affected_sessions',
+ 'occurrences',
+ 'conversion_rate',
+ 'error_rate',
+ 'duration',
+ 'revenue',
+ 'custom',
+ ]),
+ zod.null(),
+ ])
+ .optional()
+ .describe('How to draw this measurement; copied from a referenced metric.'),
+ value_format: zod
+ .union([
+ zod.enum([
+ 'number',
+ 'count',
+ 'percentage',
+ 'percentage_scaled',
+ 'duration',
+ 'currency',
+ ]),
+ zod.null(),
+ ])
+ .optional()
+ .describe('How to format measured values; copied from a referenced metric.'),
+ unit: zod
+ .union([
+ zod.string().max(signalsScoutReportCheckCreateBodyConfigOneOneUnitOneMax),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Optional value suffix.'),
})
.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."