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): add check approval and atomic metric replacement (#110308)

Mikayla Thompsonb3e1017bdb0e
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index 78b5d3523452..c6c7700f5a11 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -28,6 +28,16 @@ Metric follow-up checks wait until their full trailing query window contains onl
New metric checks validate numeric goals and baselines against their metric kind, format, unit, and query. Existing check configurations remain readable.
+## Follow-up check editing
+
+Approval records a person's quality signal without changing the check schedule. Only open checks can be approved. Approval advances the check's update timestamp so older list responses cannot undo it on screen; retries preserve the original approval and timestamp. Atomic metric replacement cancels the old check and creates an unapproved replacement, preserving recurring runs and the configured soak, including zero minutes. Replacement cannot override the soak. Creation and replacement share schedule validation: the full metric schedule, including its soak and measurement window, must finish before the 90-day horizon. Invalid replacements leave the old check running. A replacement rejects a check moved by a concurrent report merge; reload the report and retry on the survivor. Units cannot contain null characters or unpaired Unicode surrogates. The requester must have access to the replacement query.
+
+Custom HogQL aggregations are parsed before a metric or check is authored. Invalid syntax returns a validation error; a rejected replacement keeps the original check and its activity history intact.
+
+Research captures the open checks' versions before starting. If any check changes before its result is stored, that pass leaves the checks alone. Research that does not review existing checks also preserves person-selected and approved checks.
+
+The `inbox-report-checks-replace` MCP tool requires `task:write` and `query:read`. Query-specific event, action, and cohort permissions still apply. The `signals-report-checks-replace` rollout flag hides the tool unless enabled. Keep it disabled until the replacement API is deployed in every region. This gate is separate from the Expected impact display flag.
+
## 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/migrations/0161_add_report_check_approval.py b/products/signals/backend/migrations/0161_add_report_check_approval.py
new file mode 100644
index 000000000000..e7735ca55b30
--- /dev/null
+++ b/products/signals/backend/migrations/0161_add_report_check_approval.py
@@ -0,0 +1,32 @@
+# Generated by Django 5.2.17 on 2026-09-30 17:45
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0160_report_check_measurement_start"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalreportcheck",
+ name="approved_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="signalreportcheck",
+ name="approved_by",
+ field=models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index f2520d406fcf..53f9952928cb 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0160_report_check_measurement_start
+0161_add_report_check_approval
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 03def7585366..8852cebc1cd1 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -2230,6 +2230,10 @@ class SignalReportCheck(UUIDModel):
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={})
+ approved_at = models.DateTimeField(null=True, blank=True)
+ approved_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, db_constraint=False, null=True, blank=True, related_name="+"
+ )
next_run_at = models.DateTimeField()
measurement_start_at = models.DateTimeField(null=True, blank=True)
diff --git a/products/signals/backend/report_check_artefacts.py b/products/signals/backend/report_check_artefacts.py
index 5d762cb8caf1..3c663de705b2 100644
--- a/products/signals/backend/report_check_artefacts.py
+++ b/products/signals/backend/report_check_artefacts.py
@@ -98,7 +98,7 @@ def write_check_expired(check: SignalReportCheck, expired_at: datetime) -> None:
def write_check_cancelled(
check: SignalReportCheck,
*,
- reason: Literal["stopped_by_person", "stopped_by_scout", "replaced_by_research"],
+ reason: Literal["stopped_by_person", "stopped_by_scout", "replaced_by_research", "replaced_by_request"],
attribution: ArtefactAttribution,
) -> None:
"""Record that a check was stopped before it could decide.
diff --git a/products/signals/backend/report_check_authoring.py b/products/signals/backend/report_check_authoring.py
index bc1c1236a13c..f07c9960378c 100644
--- a/products/signals/backend/report_check_authoring.py
+++ b/products/signals/backend/report_check_authoring.py
@@ -26,12 +26,14 @@ from django.utils import timezone
import structlog
from products.signals.backend.artefact_attribution import ArtefactAttribution
-from products.signals.backend.models import SignalReport, SignalReportCheck
+from products.signals.backend.models import SignalActorKind, 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_research import research_can_reconcile_checks
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_SOAK_HOURS,
MAX_ACTIVE_CHECKS_PER_REPORT,
MAX_CHECK_HORIZON,
CheckConfigValidationError,
@@ -42,6 +44,7 @@ from products.signals.backend.report_checks import (
soak_minutes_from_gap,
validate_metric_check_for_write,
)
+from products.signals.backend.report_metric_access import ReportMetricAccessPolicy
logger = structlog.get_logger(__name__)
@@ -52,6 +55,10 @@ class CheckCreationError(ValueError):
"""A check that cannot be written: a bad config, an unresolvable metric, or a full report."""
+class CheckQueryAccessError(PermissionError):
+ """The requester cannot read the measurement they would schedule."""
+
+
def create_check(
*,
report: SignalReport,
@@ -92,11 +99,23 @@ 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.")
+ if soak_minutes is None:
+ assert next_run_at is not None
+ soak_minutes = soak_minutes_from_gap(next_run_at, now)
+ first_run_at = (
+ next_run_at
+ if next_run_at is not None and locked_report.status == SignalReport.Status.RESOLVED
+ else now + timedelta(minutes=soak_minutes)
+ )
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.")
+ first_run_at = max(first_run_at, metric_ready_at)
+ last_run_at = first_run_at + timedelta(minutes=(run_interval_minutes or 0) * max(0, runs_remaining - 1))
+ if last_run_at >= now + MAX_CHECK_HORIZON:
+ raise CheckCreationError(
+ "The remaining runs must fit within the check's 90-day horizon. Use a shorter query window."
+ )
open_checks = SignalReportCheck.objects.for_team(locked_report.team_id).filter(
report_id=locked_report.id, status__in=SignalReportCheck.OPEN_STATUSES
)
@@ -104,13 +123,8 @@ def create_check(
raise CheckCreationError(f"A report may carry at most {MAX_ACTIVE_CHECKS_PER_REPORT} active checks.")
if locked_report.status == SignalReport.Status.RESOLVED:
status = SignalReportCheck.Status.ACTIVE
- if next_run_at is None:
- assert soak_minutes is not None
- next_run_at = now + timedelta(minutes=soak_minutes)
- if soak_minutes is None:
- soak_minutes = soak_minutes_from_gap(next_run_at, now)
+ next_run_at = first_run_at
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:
@@ -122,9 +136,6 @@ def create_check(
)
else:
status = SignalReportCheck.Status.PENDING
- if soak_minutes is None:
- assert next_run_at is not None
- soak_minutes = soak_minutes_from_gap(next_run_at, now)
# Provisional, and rewritten at arm time. The horizon is real though: a report that
# never resolves retires its pending checks rather than holding them forever.
next_run_at = now + timedelta(minutes=soak_minutes)
@@ -201,8 +212,7 @@ def _stored_config(report: SignalReport, kind: str, config: dict) -> dict:
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}
+ return stored_config
def _with_metric_display(report: SignalReport, config: dict, metric_id: str | None) -> dict:
@@ -226,14 +236,13 @@ def create_checks_from_specs(
report: SignalReport,
specs: list[CheckSpec],
attribution: ArtefactAttribution,
+ checks_snapshot: dict[str, str] | None = None,
) -> list[SignalReportCheck]:
"""Write a research run's check specs on the report it just finished.
- The specs replace the report's pending checks rather than joining them. Every pending row on the
- report was written against an older version of this prose, which this pass has just rewritten.
- Left in place, those rows would fill the per-report cap, and the resolve would arm them against
- prose they were not written for. A pass that returns no specs leaves them alone, because
- the verification turn is best-effort and an empty result can be a failed turn.
+ The specs replace unapproved research-owned pending checks. This turn does not review existing
+ checks, so person-selected and approved checks remain. A pass that returns no specs leaves them
+ alone, because the verification turn is best-effort and an empty result can be a failed turn.
A spec the report cannot carry is dropped with a log rather than failing the run, the way an
unvalidatable chart is: the prose is the report's point, and a check that names a metric the
@@ -241,46 +250,91 @@ def create_checks_from_specs(
"""
if not specs:
return []
- # Only the pending rows, never a check the resolve already armed: this pass replaces prose that
- # has not been measured against yet.
- for replaced in SignalReportCheck.objects.for_team(report.team_id).filter(
- report_id=report.id, status=SignalReportCheck.Status.PENDING
- ):
- cancel_check(
- replaced,
- reason="replaced_by_research",
- attribution=attribution,
- from_statuses=(SignalReportCheck.Status.PENDING,),
+ with transaction.atomic():
+ report = SignalReport.objects.select_for_update().get(id=report.id, team_id=report.team_id)
+ existing = list(
+ SignalReportCheck.objects.for_team(report.team_id)
+ .select_for_update()
+ .filter(report_id=report.id, status__in=SignalReportCheck.OPEN_STATUSES)
+ .order_by("id")
)
- written: list[SignalReportCheck] = []
- for spec in specs:
- try:
- written.append(
- create_check(
- report=report,
- title=spec.title,
- rationale=spec.rationale,
+ if not research_can_reconcile_checks(existing, checks_snapshot):
+ return []
+ for replaced in existing:
+ if replaced.status != SignalReportCheck.Status.PENDING:
+ continue
+ if replaced.actor_kind in (SignalActorKind.USER, SignalActorKind.AGENT) or replaced.approved_at is not None:
+ continue
+ cancel_check(
+ replaced,
+ reason="replaced_by_research",
+ attribution=attribution,
+ from_statuses=(SignalReportCheck.Status.PENDING,),
+ )
+ written: list[SignalReportCheck] = []
+ for spec in specs:
+ try:
+ written.append(
+ create_check(
+ report=report,
+ title=spec.title,
+ rationale=spec.rationale,
+ kind=spec.kind,
+ config=spec.config,
+ attribution=attribution,
+ soak_minutes=spec.soak_hours * 60,
+ )
+ )
+ except CheckCreationError as error:
+ logger.warning(
+ "signals.report_check.research_spec_dropped",
+ report_id=str(report.id),
+ team_id=report.team_id,
kind=spec.kind,
- config=spec.config,
- attribution=attribution,
- soak_minutes=spec.soak_hours * 60,
+ reason=str(error),
)
- )
- except CheckCreationError as error:
- logger.warning(
- "signals.report_check.research_spec_dropped",
- report_id=str(report.id),
- team_id=report.team_id,
- kind=spec.kind,
- reason=str(error),
- )
- return written
+ return written
+
+
+def replace_metric_check(
+ *,
+ check: SignalReportCheck,
+ title: str,
+ rationale: str,
+ config: dict,
+ attribution: ArtefactAttribution,
+ access_policy: ReportMetricAccessPolicy,
+) -> SignalReportCheck:
+ """Replace one open metric check atomically, keeping it live if the new check is invalid."""
+ if check.kind != SignalReportCheck.Kind.METRIC_THRESHOLD:
+ raise CheckCreationError("Only metric checks can be replaced this way.")
+ with transaction.atomic():
+ report = SignalReport.objects.select_for_update().get(id=check.report_id, team_id=check.team_id)
+ locked = SignalReportCheck.objects.for_team(check.team_id).select_for_update().get(id=check.id)
+ if locked.report_id != report.id:
+ raise CheckCreationError("This check moved to another report. Reload the report before replacing it.")
+ stored_config = _stored_config(report, SignalReportCheck.Kind.METRIC_THRESHOLD, config)
+ if not access_policy.may_read_query(stored_config):
+ raise CheckQueryAccessError("The measurement query is not available to you.")
+ if not cancel_check(locked, reason="replaced_by_request", attribution=attribution):
+ raise CheckCreationError("This check has already finished. Review its result before adding another.")
+ return create_check(
+ report=report,
+ title=title,
+ rationale=rationale,
+ kind=SignalReportCheck.Kind.METRIC_THRESHOLD,
+ config=config,
+ attribution=attribution,
+ soak_minutes=locked.soak_minutes if locked.soak_minutes is not None else DEFAULT_CHECK_SOAK_HOURS * 60,
+ run_interval_minutes=locked.run_interval_minutes,
+ runs_remaining=locked.runs_remaining,
+ )
def cancel_check(
check: SignalReportCheck,
*,
- reason: Literal["stopped_by_person", "stopped_by_scout", "replaced_by_research"],
+ reason: Literal["stopped_by_person", "stopped_by_scout", "replaced_by_research", "replaced_by_request"],
attribution: ArtefactAttribution,
from_statuses: Sequence[str] = SignalReportCheck.OPEN_STATUSES,
) -> bool:
diff --git a/products/signals/backend/report_check_research.py b/products/signals/backend/report_check_research.py
new file mode 100644
index 000000000000..dd516a6a717c
--- /dev/null
+++ b/products/signals/backend/report_check_research.py
@@ -0,0 +1,18 @@
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from products.signals.backend.models import SignalReportCheck
+
+
+def check_versions(checks: Iterable[SignalReportCheck]) -> dict[str, str]:
+ return {str(check.id): check.updated_at.isoformat() for check in checks}
+
+
+def research_can_reconcile_checks(checks: list[SignalReportCheck], snapshot: Mapping[str, str] | None) -> bool:
+ if snapshot is None:
+ # Old activity results cannot establish whether research saw a person's selection.
+ return not any(check.actor_kind in ("user", "agent") or check.approved_at is not None for check in checks)
+ return check_versions(checks) == snapshot
diff --git a/products/signals/backend/report_checks.py b/products/signals/backend/report_checks.py
index 849b2558ccc4..4aa33e20812d 100644
--- a/products/signals/backend/report_checks.py
+++ b/products/signals/backend/report_checks.py
@@ -29,6 +29,7 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
+from products.signals.backend.report_charts import _unstorable_text
from products.signals.backend.report_metrics import (
MAX_METRIC_UNIT_LENGTH,
ReportMetric,
@@ -197,6 +198,13 @@ class MetricThresholdConfig(BaseModel):
)
unit: str | None = Field(default=None, max_length=MAX_METRIC_UNIT_LENGTH, description="Optional value suffix.")
+ @field_validator("unit")
+ @classmethod
+ def unit_must_be_storable(cls, value: str | None) -> str | None:
+ if value is not None and (reason := _unstorable_text(value)) is not None:
+ raise ValueError(f"unit must not contain {reason}")
+ return value
+
@field_validator("baseline_value", mode="before")
@classmethod
def baseline_must_be_a_plain_number(cls, value: object) -> object:
diff --git a/products/signals/backend/report_metrics.py b/products/signals/backend/report_metrics.py
index f8d7c28385e2..55be2b646920 100644
--- a/products/signals/backend/report_metrics.py
+++ b/products/signals/backend/report_metrics.py
@@ -200,6 +200,15 @@ 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_live_metric_hogql(expression: str) -> None:
+ from posthog.hogql.parser import parse_expr # noqa: PLC0415 — keeps the query parser off startup
+
+ try:
+ parse_expr(expression)
+ except (BaseHogQLError, SyntaxError, RecursionError) as error:
+ raise ValueError(f"a live metric math_hogql must be a valid HogQL expression: {error}") from None
+
+
def validate_metric_id(value: str) -> str:
"""Normalize a metric id and refuse one nothing can reference.
@@ -262,6 +271,9 @@ def validate_live_metric_query(value: dict[str, Any]) -> dict[str, Any]:
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")
+ expression = item.get("math_hogql")
+ if item.get("math") == "hogql" and expression is not None:
+ _validate_live_metric_hogql(expression)
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")
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index bd9383398571..0f7259a03954 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -40,6 +40,7 @@ from products.signals.backend.report_checks import (
MAX_CHECK_TITLE_LENGTH,
MIN_CHECK_INTERVAL_MINUTES,
CheckConfigValidationError,
+ MetricThresholdConfig,
parse_check_config,
)
from products.warehouse_sources.backend.facade.models import ExternalDataSchema
@@ -1907,6 +1908,11 @@ class SignalReportCheckConfigField(serializers.JSONField):
"""Kind-specific check configuration, validated against its kind's schema on every write."""
+@extend_schema_field(MetricThresholdConfig) # type: ignore[arg-type]
+class MetricThresholdCheckConfigField(serializers.JSONField):
+ """Metric threshold check configuration, for requests that accept no other kind."""
+
+
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.
@@ -1946,6 +1952,7 @@ class SignalReportCheckSerializer(serializers.ModelSerializer):
"kind",
"status",
"config",
+ "approved_at",
"next_run_at",
"soak_minutes",
"run_interval_minutes",
@@ -1998,6 +2005,23 @@ class SignalReportCheckSerializer(serializers.ModelSerializer):
}
+class SignalReportCheckReplacementSerializer(serializers.Serializer):
+ title = serializers.CharField(max_length=MAX_CHECK_TITLE_LENGTH, help_text="Label for the new metric check.")
+ rationale = serializers.CharField(
+ required=False, allow_blank=True, max_length=MAX_CHECK_RATIONALE_LENGTH, help_text="Why this check is better."
+ )
+ config = MetricThresholdCheckConfigField(
+ help_text="Metric threshold configuration, including a bounded query and comparison."
+ )
+
+ def validate_config(self, value: dict) -> dict:
+ try:
+ parse_check_config(SignalReportCheck.Kind.METRIC_THRESHOLD, value)
+ except CheckConfigValidationError as error:
+ raise serializers.ValidationError(str(error))
+ return value
+
+
class SignalReportCheckWriteSerializer(serializers.Serializer):
"""Request body for creating a check on a report.
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index 4cd815e0dec6..9bce5ef2e7ca 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -33,11 +33,18 @@ from products.signals.backend.artefact_schemas import (
from products.signals.backend.auto_start import ReviewerContent
from products.signals.backend.enums import ReportLinkKind
from products.signals.backend.impact_measurement_plans import latest_measurement_plans
-from products.signals.backend.models import ArtefactAttribution, SignalActorKind, SignalReport, SignalReportArtefact
+from products.signals.backend.models import (
+ ArtefactAttribution,
+ SignalActorKind,
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportCheck,
+)
from products.signals.backend.receivers import _is_safety_suppressed
from products.signals.backend.recurrence import fixed_dismissal_at
from products.signals.backend.repo_corrections import SCOUT_REPOSITORY_CONTENT_NEEDLE, WRONG_REPO_CONTENT_NEEDLE
from products.signals.backend.report_charts import ReportChart, chart_batch_error
+from products.signals.backend.report_check_research import check_versions
from products.signals.backend.report_content_gates import (
team_expected_impact_authoring_enabled,
team_report_metrics_enabled,
@@ -120,6 +127,7 @@ class RunAgenticReportOutput:
# writes the metrics they reference — a check naming a metric the report never got is dropped
# there rather than stored pointing at nothing. `None` predates the field and writes none.
checks: list[dict[str, Any]] | None = None
+ checks_snapshot: dict[str, str] | None = None
# The plan of dependent pull requests, as `ReportLayer` dicts. The ready transition turns each
# one into a child report. `None` predates the field and creates none.
layers: list[dict[str, Any]] | None = None
@@ -150,6 +158,14 @@ def _parse_artefact_content(
) from error
+def _load_check_snapshot(team_id: int, report_id: str) -> dict[str, str]:
+ return check_versions(
+ SignalReportCheck.objects.for_team(team_id).filter(
+ report_id=report_id, status__in=SignalReportCheck.OPEN_STATUSES
+ )
+ )
+
+
async def _load_previous_research(team_id: int, report_id: str) -> ReportResearchOutput | None:
"""Reconstruct the previous report state."""
report = (
@@ -970,6 +986,9 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
input.team_id
)
# 2. Load previous research if this is a re-promoted report
+ checks_snapshot = await database_sync_to_async(_load_check_snapshot, thread_sensitive=False)(
+ input.team_id, input.report_id
+ )
previous_research = await _load_previous_research(input.team_id, input.report_id)
previous_measurement_plans = (
await database_sync_to_async(_load_previous_measurement_plans, thread_sensitive=False)(
@@ -1062,6 +1081,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
metric_id: row_id for metric_id, (row_id, _) in previous_measurement_plans.items()
},
checks=[check.model_dump(mode="json") for check in result.checks],
+ checks_snapshot=checks_snapshot,
layers=[layer.model_dump(mode="json") for layer in result.layers],
research_task_id=result.research_task_id,
charts_enabled=True,
diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.py
index f4a7402db512..34cff41f1e58 100644
--- a/products/signals/backend/temporal/summary.py
+++ b/products/signals/backend/temporal/summary.py
@@ -156,6 +156,7 @@ class ReportDecision:
# Check specs the research run's verification turn authored, and the research task they are
# attributed to. Empty for the no-repo branch, which does no research.
checks: list[dict[str, Any]] = field(default_factory=list)
+ checks_snapshot: dict[str, str] | None = None
layers: list[dict[str, Any]] = field(default_factory=list)
research_task_id: str | None = None
# The chart rollout state the research run saw (see `RunAgenticReportOutput.charts_enabled`).
@@ -467,6 +468,7 @@ class SignalReportSummaryWorkflow:
retire_measurement_plan_metric_ids=agentic_result.retire_measurement_plan_metric_ids,
previous_measurement_plan_ids=agentic_result.previous_measurement_plan_ids,
checks=agentic_result.checks or [],
+ checks_snapshot=agentic_result.checks_snapshot,
layers=agentic_result.layers or [],
research_task_id=agentic_result.research_task_id,
charts_enabled=agentic_result.charts_enabled,
@@ -539,6 +541,7 @@ class SignalReportSummaryWorkflow:
previous_measurement_plan_ids=decision.previous_measurement_plan_ids,
plans_task_id=decision.research_task_id,
checks=decision.checks,
+ checks_snapshot=decision.checks_snapshot,
checks_task_id=decision.research_task_id,
layers=decision.layers,
suggested_prompts=decision.suggested_prompts,
@@ -855,6 +858,7 @@ class MarkReportReadyInput:
# transaction as the metrics they reference. Empty or `None` writes none, which is also what an
# older workflow history that predates the field replays as.
checks: list[dict[str, Any]] | None = None
+ checks_snapshot: dict[str, str] | None = None
# Task the check rows are attributed to: the research sandbox that authored the specs.
checks_task_id: str | None = None
# The research plan of dependent pull requests, as `ReportLayer` dicts. Each becomes a child
@@ -892,6 +896,7 @@ def _write_research_checks(report: SignalReport, input: MarkReportReadyInput) ->
create_checks_from_specs(
report=report,
specs=specs,
+ checks_snapshot=input.checks_snapshot,
attribution=(
ArtefactAttribution.from_task(input.checks_task_id)
if input.checks_task_id
diff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.py
index 0ac913a3c789..a89b8650705d 100644
--- a/products/signals/backend/test/test_report_checks.py
+++ b/products/signals/backend/test/test_report_checks.py
@@ -12,10 +12,14 @@ from django.utils import timezone
from parameterized import parameterized
from pydantic import ValidationError as PydanticValidationError
from rest_framework import status
+from rest_framework.request import Request
+from rest_framework.test import APIRequestFactory, force_authenticate
from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.constants import AvailableFeature
from posthog.models import PropertyDefinition, Team
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.access_control.backend.facade.contracts import PropertyAccessLevel
from products.access_control.backend.models.property_access_control import PropertyAccessControl
@@ -42,6 +46,7 @@ from products.signals.backend.report_check_authoring import (
arm_pending_checks,
create_check,
create_checks_from_specs,
+ replace_metric_check,
)
from products.signals.backend.report_check_execution import (
CHECK_ERROR_RETRY_AFTER,
@@ -54,6 +59,7 @@ from products.signals.backend.report_check_execution import (
resolve_check_query,
run_due_report_checks,
)
+from products.signals.backend.report_check_research import check_versions
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,
@@ -78,6 +84,8 @@ from products.signals.backend.report_checks import (
parse_check_config,
validate_metric_check_for_write,
)
+from products.signals.backend.report_merge import merge_reports
+from products.signals.backend.report_metric_access import ReportMetricAccessPolicy
from products.signals.backend.report_metric_refresh import MetricMeasurement
from products.signals.backend.scout_harness.tools.checks import (
InvalidCheckResultError,
@@ -149,6 +157,8 @@ class TestCheckComparison(SimpleTestCase):
@parameterized.expand(
[
+ ("null_unit", _threshold_config(unit="m\x00s")),
+ ("surrogate_unit", _threshold_config(unit="m\ud800s")),
("neither_source", {"comparison": {"operator": "lte", "value": 1}}),
("empty_metric_id", {"metric_id": "", "comparison": {"operator": "lte", "value": 1}}),
(
@@ -932,10 +942,15 @@ class TestReportCheckAPI(APIBaseTest):
assert not SignalReportCheck.objects.for_team(self.team.id).exists()
def test_list_then_cancel(self) -> None:
- check_id = str(self._create().id)
+ check = self._create()
+ check_id = str(check.id)
+ finished = self._create()
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=finished.id).update(
+ status=SignalReportCheck.Status.PASSED, created_at=check.created_at + timedelta(minutes=1)
+ )
listed = self.client.get(self.url)
- assert [row["id"] for row in listed.json()["results"]] == [check_id]
+ assert [row["id"] for row in listed.json()["results"]] == [check_id, str(finished.id)]
assert listed.json()["results"][0]["config"]["query"] == _PAGEVIEWS
cancelled = self.client.delete(f"{self.url}{check_id}/")
@@ -944,6 +959,196 @@ class TestReportCheckAPI(APIBaseTest):
already_cancelled = self.client.delete(f"{self.url}{check_id}/")
assert already_cancelled.status_code == status.HTTP_400_BAD_REQUEST
+ assert self.client.post(f"{self.url}{check_id}/approve/").status_code == status.HTTP_400_BAD_REQUEST
+ check.refresh_from_db()
+ assert check.approved_at is None
+
+ def test_approval_is_idempotent_and_does_not_change_the_schedule(self) -> None:
+ check = self._create()
+ approved_at = check.updated_at + timedelta(minutes=1)
+ with time_machine.travel(approved_at, tick=False):
+ first = self.client.post(f"{self.url}{check.id}/approve/")
+ with time_machine.travel(approved_at + timedelta(minutes=1), tick=False):
+ second = self.client.post(f"{self.url}{check.id}/approve/")
+
+ assert first.status_code == status.HTTP_200_OK
+ assert second.status_code == status.HTTP_200_OK
+ check.refresh_from_db()
+ assert check.approved_by_id == self.user.id
+ assert check.approved_at == check.updated_at == approved_at
+ assert datetime.fromisoformat(first.json()["updated_at"]) == approved_at
+ assert first.json()["updated_at"] == second.json()["updated_at"]
+ assert first.json()["next_run_at"] == second.json()["next_run_at"]
+ assert check.status == SignalReportCheck.Status.ACTIVE
+
+ @parameterized.expand(
+ [
+ ("missing_config", {}),
+ ("fractional_count", _threshold_config(value_format="count", comparison={"operator": "lte", "value": 1.5})),
+ (
+ "malformed_hogql",
+ _threshold_config(
+ query=trends_metric_query(
+ series=[{"kind": "EventsNode", "event": "$pageview", "math": "hogql", "math_hogql": "sum("}]
+ )
+ ),
+ ),
+ ]
+ )
+ def test_invalid_metric_replacement_leaves_the_check_and_activity_unchanged(self, _name: str, config: dict) -> None:
+ check = self._create()
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).update(approved_at=timezone.now())
+ original_state = SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).values().get()
+ log_count = SignalReportArtefact.objects.filter(report=self.report).count()
+
+ rejected = self.client.post(
+ f"{self.url}{check.id}/replace/", {"title": "Better metric", "config": config}, format="json"
+ )
+ assert rejected.status_code == status.HTTP_400_BAD_REQUEST
+ assert SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).values().get() == original_state
+ assert SignalReportCheck.objects.for_team(self.team.id).filter(report=self.report).count() == 1
+ assert SignalReportArtefact.objects.filter(report=self.report).count() == log_count
+
+ def test_replacement_keeps_a_check_moved_by_a_report_merge(self) -> None:
+ SignalReport.objects.filter(id=self.report.id).update(status=SignalReport.Status.READY)
+ self.report.refresh_from_db()
+ check = self._create()
+ survivor = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="Surviving fix")
+ merge_reports(
+ team=self.team,
+ survivor=survivor,
+ source_ids=[str(self.report.id)],
+ attribution=ArtefactAttribution.from_user(self.user.id),
+ )
+ original_state = SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).values().get()
+ log_count = SignalReportArtefact.objects.filter(report_id__in=[self.report.id, survivor.id]).count()
+ request = APIRequestFactory().post(self.url)
+ force_authenticate(request, user=self.user)
+
+ with self.assertRaisesRegex(CheckCreationError, "moved to another report"):
+ replace_metric_check(
+ check=check,
+ title="Revised goal",
+ rationale="",
+ config=_threshold_config(),
+ attribution=ArtefactAttribution.from_user(self.user.id),
+ access_policy=ReportMetricAccessPolicy(request=Request(request), team=self.team),
+ )
+
+ assert SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).values().get() == original_state
+ assert original_state["report_id"] == survivor.id
+ assert not SignalReportCheck.objects.for_team(self.team.id).filter(report=self.report).exists()
+ assert SignalReportArtefact.objects.filter(report_id__in=[self.report.id, survivor.id]).count() == log_count
+
+ @parameterized.expand(
+ [
+ ("minute_precision_soak", "-30d", MIN_CHECK_INTERVAL_MINUTES, 3, True),
+ ("zero_soak", "-7d", MIN_CHECK_INTERVAL_MINUTES, 3, True, 0),
+ ("longer_query_window", "-40d", 30 * 24 * 60, 3, False),
+ ("last_run_at_expiry", "-7d", 30 * 24 * 60, 3, False, 30 * 24 * 60),
+ ("fits_near_horizon", "-7d", 30 * 24 * 60, 3, True, 29 * 24 * 60),
+ ("pending_longer_query", "-40d", 30 * 24 * 60, 3, False, 1450, SignalReport.Status.READY),
+ ]
+ )
+ def test_replacement_preserves_only_recurring_schedules_that_fit(
+ self,
+ _name: str,
+ date_from: str,
+ interval: int,
+ runs: int,
+ fits: bool,
+ stored_soak: int = 1450,
+ report_status: str = SignalReport.Status.RESOLVED,
+ ) -> None:
+ now = datetime(2026, 10, 2, 12, tzinfo=UTC)
+ with time_machine.travel(now, tick=False):
+ SignalReport.objects.filter(id=self.report.id).update(status=report_status)
+ self.report.refresh_from_db()
+ check = self._create(
+ config=_threshold_config(
+ query=trends_metric_query(series=[{"kind": "EventsNode", "event": "$pageview"}], date_from="-7d")
+ ),
+ run_interval_minutes=interval,
+ runs_remaining=runs,
+ )
+ SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).update(
+ soak_minutes=stored_soak, approved_at=now, approved_by=self.user
+ )
+ original_state = SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).values().get()
+ log_count = SignalReportArtefact.objects.filter(report=self.report).count()
+ config = _threshold_config(
+ query=trends_metric_query(series=[{"kind": "EventsNode", "event": "$pageview"}], date_from=date_from),
+ comparison={"operator": "lte", "value": 5},
+ )
+ payload: dict[str, object] = {"title": "Revised goal", "config": config}
+ response = self.client.post(f"{self.url}{check.id}/replace/", payload, format="json")
+ check.refresh_from_db()
+ if not fits:
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert "90-day horizon" in response.json()["error"]
+ assert SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).values().get() == original_state
+ assert SignalReportCheck.objects.for_team(self.team.id).filter(report=self.report).count() == 1
+ assert SignalReportArtefact.objects.filter(report=self.report).count() == log_count
+ else:
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ replacement = SignalReportCheck.objects.for_team(self.team.id).get(id=response.json()["id"])
+ assert check.status == SignalReportCheck.Status.CANCELLED
+ assert replacement.soak_minutes == stored_soak
+ assert replacement.run_interval_minutes == interval
+ assert replacement.runs_remaining == runs
+ assert replacement.approved_at is None
+ assert replacement.approved_by_id is None
+ assert replacement.status == SignalReportCheck.Status.ACTIVE
+ last_run_at = replacement.next_run_at + timedelta(minutes=interval * (runs - 1))
+ assert last_run_at < replacement.expires_at <= now + MAX_CHECK_HORIZON
+
+ @parameterized.expand([("direct_query", False), ("metric_reference", True)])
+ def test_replacement_cannot_schedule_queries_hidden_from_the_requester(self, _name: str, reference: bool) -> None:
+ check = self._create()
+ self.report.metrics = [{"metric_id": "pageviews", "query": _PAGEVIEWS}]
+ self.report.save(update_fields=["metrics"])
+ 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: dict[str, object] = {"comparison": {"operator": "lte", "value": 5}}
+ config.update({"metric_id": "pageviews"} if reference else {"query": _PAGEVIEWS})
+ response = self.client.post(
+ f"{self.url}{check.id}/replace/", {"title": "Revised goal", "config": config}, format="json"
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ACTIVE
+ assert SignalReportCheck.objects.for_team(self.team.id).filter(report=self.report).count() == 1
+
+ def test_task_write_key_without_query_access_cannot_replace_a_metric_check(self) -> None:
+ check = self._create()
+ raw_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Task-only test key",
+ user=self.user,
+ secure_value=hash_key_value(raw_key),
+ scopes=["task:write", "task:read"],
+ scoped_teams=[self.team.id],
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {raw_key}")
+ response = self.client.post(
+ f"{self.url}{check.id}/replace/",
+ {"title": "Revised goal", "config": _threshold_config()},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ACTIVE
def test_a_created_check_is_reported_for_adoption(self) -> None:
with patch(_CAPTURE) as capture:
@@ -995,9 +1200,12 @@ class TestReportCheckAPI(APIBaseTest):
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)
+ assert stored.config["metric_kind"] == "occurrences"
+ assert stored.config["value_format"] == "count"
overridden = self._create(config={**config, "metric_kind": "custom", "value_format": "number", "unit": "USD"})
- assert not {"metric_kind", "value_format", "unit"}.intersection(overridden.config)
+ assert overridden.config["metric_kind"] == "occurrences"
+ assert overridden.config["value_format"] == "count"
+ assert overridden.config["unit"] is None
# Rewriting the metric under the same id must not move the check's target.
rewritten = trends_metric_query(series=[{"kind": "EventsNode", "event": "$autocapture"}])
@@ -1734,18 +1942,33 @@ class TestPendingChecks(APIBaseTest):
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:
+ @parameterized.expand(
+ [
+ ("long_query_window", "-365d", 60, None, 1),
+ ("long_recurring_schedule", "-40d", 60, 30 * 24 * 60, 3),
+ ]
+ )
+ def test_measurement_schedule_outside_the_horizon_is_rejected_before_resolution(
+ self, _name: str, date_from: str, soak_minutes: int, interval: int | None, runs: int
+ ) -> None:
+ log_count = SignalReportArtefact.objects.filter(report=self.report).count()
with self.assertRaisesRegex(CheckCreationError, "90-day horizon"):
create_check(
report=self.report,
- title="Yearly metric",
+ title="Unreachable metric",
kind="metric_threshold",
config=_threshold_config(
- query=trends_metric_query(series=[{"kind": "EventsNode", "event": "$pageview"}], date_from="-365d")
+ query=trends_metric_query(
+ series=[{"kind": "EventsNode", "event": "$pageview"}], date_from=date_from
+ )
),
attribution=ArtefactAttribution.system(),
- soak_minutes=60,
+ soak_minutes=soak_minutes,
+ run_interval_minutes=interval,
+ runs_remaining=runs,
)
+ assert not SignalReportCheck.objects.for_team(self.team.id).filter(report=self.report).exists()
+ assert SignalReportArtefact.objects.filter(report=self.report).count() == log_count
def test_invalid_legacy_config_does_not_prevent_other_checks_from_arming(self) -> None:
invalid = self._pending()
@@ -2091,6 +2314,64 @@ class TestResearchAuthoredChecks(APIBaseTest):
assert older[0].status == SignalReportCheck.Status.CANCELLED
assert newer[0].status == SignalReportCheck.Status.PENDING
+ @parameterized.expand(
+ [
+ ("replacement",),
+ ("external_agent",),
+ ("approval",),
+ ("replacement_during_research", True),
+ ("approval_during_research", True),
+ ("task_check_during_research", True),
+ ]
+ )
+ def test_research_preserves_person_selected_pending_checks(
+ self, selection: str, capture_snapshot: bool = False
+ ) -> None:
+ original = create_checks_from_specs(
+ report=self.report,
+ specs=[self._spec()],
+ attribution=ArtefactAttribution.from_agent(self.user.id, "test-client")
+ if selection == "external_agent"
+ else ArtefactAttribution.system(),
+ )[0]
+ snapshot = check_versions([original]) if capture_snapshot else None
+ url = f"/api/projects/{self.team.id}/signals/reports/{self.report.id}/checks/{original.id}/"
+ if selection.startswith("replacement"):
+ response = self.client.post(
+ f"{url}replace/",
+ {"title": "Person-selected goal", "config": self._spec().config},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ elif selection.startswith("approval"):
+ response = self.client.post(f"{url}approve/")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ elif selection == "task_check_during_research":
+ create_check(
+ report=self.report,
+ title="Task-selected goal",
+ rationale="",
+ kind="metric_threshold",
+ config=self._spec().config,
+ attribution=ArtefactAttribution.from_task(
+ str(Task.objects.create(team=self.team, title="Select a check", description="").id)
+ ),
+ soak_minutes=60,
+ )
+ checks = SignalReportCheck.objects.for_team(self.team.id).filter(report=self.report).order_by("id")
+ selected_state = list(checks.values())
+ log_count = SignalReportArtefact.objects.filter(report=self.report).count()
+
+ create_checks_from_specs(
+ report=self.report,
+ specs=[self._spec(title="New research goal")],
+ attribution=ArtefactAttribution.system(),
+ checks_snapshot=snapshot,
+ )
+
+ assert list(checks.values()) == selected_state
+ assert SignalReportArtefact.objects.filter(report=self.report).count() == log_count
+
def test_a_spec_naming_a_metric_the_report_does_not_have_is_dropped(self) -> None:
written = create_checks_from_specs(
report=self.report,
diff --git a/products/signals/backend/test/test_report_metrics.py b/products/signals/backend/test/test_report_metrics.py
index 853f6c74a869..e8879ea720b8 100644
--- a/products/signals/backend/test/test_report_metrics.py
+++ b/products/signals/backend/test/test_report_metrics.py
@@ -388,6 +388,25 @@ class TestReportMetric(SimpleTestCase):
with self.assertRaisesRegex(ValidationError, f"at most {MAX_LIVE_METRIC_QUERY_SERIES} series"):
ReportMetric.model_validate(content)
+ def test_live_query_validates_custom_hogql_aggregation_syntax(self) -> None:
+ for series in ({"kind": "EventsNode", "event": "$pageview"}, {"kind": "ActionsNode", "id": 1}):
+ for math_kind, expression, valid in (
+ ("hogql", "sum(", False),
+ ("hogql", "", False),
+ ("hogql", "count()", True),
+ ("hogql", "sum(properties.amount)", True),
+ ("total", "sum(", True),
+ ):
+ with self.subTest(series=series, math=math_kind, expression=expression):
+ content = _affected_users_metric().model_dump(mode="json")
+ content["kind"] = "custom"
+ content["query"]["source"]["series"] = [{**series, "math": math_kind, "math_hogql": expression}]
+ if valid:
+ assert ReportMetric.model_validate(content).query == content["query"]
+ else:
+ with self.assertRaisesRegex(ValidationError, "math_hogql.*valid HogQL expression"):
+ ReportMetric.model_validate(content)
+
def test_live_query_rejects_formulas_the_trends_runner_cannot_execute(self) -> None:
for description, trends_formula in (
("empty formulas entry", {"formulas": [""]}),
diff --git a/products/signals/backend/test/test_summary_workflow.py b/products/signals/backend/test/test_summary_workflow.py
index 6ad47541dbb5..52ec587a9adc 100644
--- a/products/signals/backend/test/test_summary_workflow.py
+++ b/products/signals/backend/test/test_summary_workflow.py
@@ -181,12 +181,14 @@ class _Recorder:
has_assigned_signals: bool = True,
research_choice: ActionabilityChoice = ActionabilityChoice.NOT_ACTIONABLE,
research_metrics: list[dict[str, object]] | None = None,
+ checks_snapshot: dict[str, str] | None = None,
) -> None:
self.gate_answers = gate_answers or {}
self.fetch_results = fetch_results or [[_signal_data()]]
self.has_assigned_signals = has_assigned_signals
self.research_choice = research_choice
self.research_metrics = research_metrics
+ self.checks_snapshot = checks_snapshot
self.gate_checks: list[str] = []
self.fetches = 0
self.assigned_signal_checks = 0
@@ -230,6 +232,7 @@ def test_legacy_agentic_activity_payload_defaults_metrics_to_preserve() -> None:
assert decoded.metrics is None
assert decoded.charts is None
+ assert decoded.checks_snapshot is None
async def _run_summary_workflow(recorder: _Recorder) -> None:
@@ -275,6 +278,7 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:
already_addressed=False,
repository="owner/repo",
metrics=recorder.research_metrics,
+ checks_snapshot=recorder.checks_snapshot,
)
@activity.defn(name="mark_report_pending_input_activity")
@@ -384,13 +388,16 @@ async def test_open_gates_let_the_run_flow_through():
)
async def test_metric_payload_reaches_the_report_transition(choice, target):
metrics = [{"metric_id": "affected-users", "kind": "affected_users", "value": 12}]
- recorder = _Recorder(research_choice=choice, research_metrics=metrics)
+ snapshot = {"check-1": "2026-10-02T12:00:00+00:00"}
+ recorder = _Recorder(research_choice=choice, research_metrics=metrics, checks_snapshot=snapshot)
await _run_summary_workflow(recorder)
inputs = recorder.pending_inputs if target == "pending" else recorder.ready_inputs
assert len(inputs) == 1
assert inputs[0].metrics == metrics
+ if target == "ready":
+ assert recorder.ready_inputs[0].checks_snapshot == snapshot
# ---------------------------------------------------------------------------
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index e874ed567a87..79d856c89279 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -143,7 +143,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_authoring import cancel_check
+from products.signals.backend.report_check_authoring import (
+ CheckCreationError,
+ CheckQueryAccessError,
+ cancel_check,
+ replace_metric_check,
+)
from products.signals.backend.report_claims import (
actor_owns_claim,
get_active_claim,
@@ -197,6 +202,7 @@ from products.signals.backend.serializers import (
SignalReportArtefactSerializer,
SignalReportArtefactWriteResponseSerializer,
SignalReportArtefactWriteSerializer,
+ SignalReportCheckReplacementSerializer,
SignalReportCheckSerializer,
SignalReportClaimSerializer,
SignalReportListQuerySerializer,
@@ -4796,7 +4802,7 @@ class SignalReportCheckViewSet(
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
- """Checks attached to a signal report: read and cancel.
+ """Checks attached to a signal report: read, approve, replace metrics, and cancel.
There is no create here. A check is authored by a scout run or by the research pipeline, both
through `report_check_authoring.create_check`. An `agent` check puts its author's prose in front
@@ -4804,16 +4810,24 @@ class SignalReportCheckViewSet(
endpoint accepts one. Anyone who can read the report can read its checks, and a person can
still stop one.
- 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 let its author write a new one.
+ There is no in-place update: a check is a claim about the future, and editing its threshold
+ after a result would make the recorded verdict unreadable. Replacing an open metric check
+ cancels the old row and creates a new one in one transaction.
"""
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", "delete", "head", "options"]
+ queryset = SignalReportCheck.objects.unscoped().order_by(
+ Case(
+ When(status__in=SignalReportCheck.OPEN_STATUSES, then=Value(0)),
+ default=Value(1),
+ output_field=IntegerField(),
+ ),
+ "-created_at",
+ )
+ http_method_names = ["get", "post", "delete", "head", "options"]
def _validated_report(self) -> SignalReport:
report_id = self.parents_query_dict["report_id"]
@@ -4845,6 +4859,60 @@ class SignalReportCheckViewSet(
)
return Response(self.get_serializer(check).data)
+ @extend_schema(
+ request=None,
+ responses={200: SignalReportCheckSerializer},
+ summary="Approve a follow-up check",
+ description="Record a person's quality signal. Approval does not affect scheduling or execution.",
+ operation_id="signals_report_checks_approve_create",
+ )
+ @action(detail=True, methods=["post"], url_path="approve", required_scopes=["task:write"])
+ def approve(self, request: Request, *args, **kwargs) -> Response:
+ attribution = resolve_request_attribution(request, self.team.id)
+ if attribution.kind != "user" or not isinstance(request.successful_authenticator, SessionAuthentication):
+ return Response({"error": "A person must approve this check."}, status=status.HTTP_403_FORBIDDEN)
+ check = cast(SignalReportCheck, self.get_object())
+ if check.kind == SignalReportCheck.Kind.METRIC_THRESHOLD and not ReportMetricAccessPolicy(
+ request=request, team=self.team
+ ).may_read_query(check.config):
+ return Response(
+ {"error": "The measurement query is not available to you."}, status=status.HTTP_403_FORBIDDEN
+ )
+ approved_at = timezone.now()
+ SignalReportCheck.objects.for_team(self.team.id).filter(
+ id=check.id, status__in=SignalReportCheck.OPEN_STATUSES, approved_at__isnull=True
+ ).update(approved_at=approved_at, approved_by_id=attribution.user_id, updated_at=approved_at)
+ check.refresh_from_db()
+ if check.status not in SignalReportCheck.OPEN_STATUSES:
+ return Response({"error": "Only open checks can be approved."}, status=status.HTTP_400_BAD_REQUEST)
+ return Response(self.get_serializer(check).data)
+
+ @validated_request(
+ request_serializer=SignalReportCheckReplacementSerializer,
+ responses={200: SignalReportCheckSerializer},
+ summary="Replace a metric follow-up check",
+ description="Atomically replace an open metric check. The old check stays live if the new one is invalid.",
+ operation_id="signals_report_checks_replace_create",
+ )
+ @action(detail=True, methods=["post"], url_path="replace", required_scopes=["task:write", "query:read"])
+ def replace(self, request: ValidatedRequest, *args, **kwargs) -> Response:
+ check = cast(SignalReportCheck, self.get_object())
+ data = request.validated_data
+ try:
+ replacement = replace_metric_check(
+ check=check,
+ title=data["title"],
+ rationale=data.get("rationale", ""),
+ config=data["config"],
+ attribution=resolve_request_attribution(request, self.team.id),
+ access_policy=ReportMetricAccessPolicy(request=request, team=self.team),
+ )
+ except CheckQueryAccessError as error:
+ return Response({"error": str(error)}, status=status.HTTP_403_FORBIDDEN)
+ except CheckCreationError as error:
+ return Response({"error": str(error)}, status=status.HTTP_400_BAD_REQUEST)
+ return Response(self.get_serializer(replacement).data)
+
@extend_schema_view(
list=extend_schema(
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 8e4aabd3d6c2..7fb3f641800a 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -2958,6 +2958,8 @@ export interface SignalReportCheckApi {
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
+ /** @nullable */
+ readonly approved_at: string | null
/** 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
/**
@@ -3006,6 +3008,21 @@ export interface PaginatedSignalReportCheckListApi {
results: SignalReportCheckApi[]
}
+export interface SignalReportCheckReplacementApi {
+ /**
+ * Label for the new metric check.
+ * @maxLength 200
+ */
+ title: string
+ /**
+ * Why this check is better.
+ * @maxLength 2000
+ */
+ rationale?: string
+ /** Metric threshold configuration, including a bounded query and comparison. */
+ config: MetricThresholdConfigApi
+}
+
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 allowed from ready, pending_input, or failed, or from a suppressed report that previously held one of those statuses or resolved. Resolving an already resolved report succeeds. Other statuses return 409 (skipped in bulk). Dismissing or resolving closes the report's open implementation PR, if it has one.
*
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 678993e85927..bfa6559c0c69 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -78,6 +78,7 @@ import type {
SignalReportBulkStateRequestApi,
SignalReportBulkStateResponseApi,
SignalReportCheckApi,
+ SignalReportCheckReplacementApi,
SignalReportClaimApi,
SignalReportDeletionStatusApi,
SignalReportFeedbackRequestApi,
@@ -1058,7 +1059,7 @@ export const getSignalsReportChecksRetrieveUrl = (projectId: string, reportId: s
}
/**
- * Checks attached to a signal report: read and cancel.
+ * Checks attached to a signal report: read, approve, replace metrics, and cancel.
*
* There is no create here. A check is authored by a scout run or by the research pipeline, both
* through `report_check_authoring.create_check`. An `agent` check puts its author's prose in front
@@ -1066,8 +1067,9 @@ export const getSignalsReportChecksRetrieveUrl = (projectId: string, reportId: s
* endpoint accepts one. Anyone who can read the report can read its checks, and a person can
* still stop one.
*
- * 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 let its author write a new one.
+ * There is no in-place update: a check is a claim about the future, and editing its threshold
+ * after a result would make the recorded verdict unreadable. Replacing an open metric check
+ * cancels the old row and creates a new one in one transaction.
* @summary Get a single check
*/
export const signalsReportChecksRetrieve = async (
@@ -1102,6 +1104,49 @@ export const signalsReportChecksDestroy = async (
})
}
+export const getSignalsReportChecksApproveCreateUrl = (projectId: string, reportId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${reportId}/checks/${id}/approve/`
+}
+
+/**
+ * Record a person's quality signal. Approval does not affect scheduling or execution.
+ * @summary Approve a follow-up check
+ */
+export const signalsReportChecksApproveCreate = async (
+ projectId: string,
+ reportId: string,
+ id: string,
+ options?: RequestInit
+): Promise<SignalReportCheckApi> => {
+ return apiMutator<SignalReportCheckApi>(getSignalsReportChecksApproveCreateUrl(projectId, reportId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getSignalsReportChecksReplaceCreateUrl = (projectId: string, reportId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${reportId}/checks/${id}/replace/`
+}
+
+/**
+ * Atomically replace an open metric check. The old check stays live if the new one is invalid.
+ * @summary Replace a metric follow-up check
+ */
+export const signalsReportChecksReplaceCreate = async (
+ projectId: string,
+ reportId: string,
+ id: string,
+ signalReportCheckReplacementApi: SignalReportCheckReplacementApi,
+ options?: RequestInit
+): Promise<SignalReportCheckApi> => {
+ return apiMutator<SignalReportCheckApi>(getSignalsReportChecksReplaceCreateUrl(projectId, reportId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(signalReportCheckReplacementApi),
+ })
+}
+
export const getSignalsReportsAvailableReviewersRetrieveUrl = (
projectId: string,
params?: SignalsReportsAvailableReviewersRetrieveParams
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index ed1cab0432ac..95ea45346c97 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -483,6 +483,94 @@ 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."
)
+/**
+ * Atomically replace an open metric check. The old check stays live if the new one is invalid.
+ * @summary Replace a metric follow-up check
+ */
+export const signalsReportChecksReplaceCreateBodyTitleMax = 200
+
+export const signalsReportChecksReplaceCreateBodyRationaleMax = 2000
+
+export const signalsReportChecksReplaceCreateBodyConfigOneUnitOneMax = 40
+
+export const SignalsReportChecksReplaceCreateBody = /* @__PURE__ */ zod.object({
+ title: zod.string().max(signalsReportChecksReplaceCreateBodyTitleMax).describe('Label for the new metric check.'),
+ rationale: zod
+ .string()
+ .max(signalsReportChecksReplaceCreateBodyRationaleMax)
+ .optional()
+ .describe('Why this check is better.'),
+ 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. `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.'
+ ),
+ 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.'),
+ 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(signalsReportChecksReplaceCreateBodyConfigOneUnitOneMax), 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."
+ )
+ .describe('Metric threshold configuration, including a bounded query and comparison.'),
+})
+
/**
* Transition many reports to a new state in one call.
*
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 14a0b1390614..3fa531035456 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -143,12 +143,34 @@ tools:
list: true
title: List a report's checks
description: >
- List the follow-up checks on one report, newest first. Each row carries the expectation and why it was
- written, its schedule (`next_run_at`, `run_interval_minutes`, `runs_remaining`, `expires_at`), its `status`
- (`pending`, `active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. A
- `pending` check waits for its report to resolve before its clock starts. Checks are written by scout runs
- and by the research pipeline, so this surface reads them and does not create them. `query` and
- `baseline_value` read as null when you cannot read the data they describe.
+ List the follow-up checks on one report, open checks first and newest first within each group. Each row
+ carries the expectation and why it was written, its schedule (`next_run_at`, `run_interval_minutes`,
+ `runs_remaining`, `expires_at`), its `status` (`pending`, `active`, `passed`, `failed`, `errored`,
+ `expired`, or `cancelled`) and its `last_outcome`. A `pending` check waits for its report to resolve before
+ its clock starts. Checks are written by scout runs and by the research pipeline, so this surface reads them
+ and does not create them. `query` and `baseline_value` read as null when you cannot read the data they
+ describe.
+ inbox-report-checks-replace:
+ operation: signals_report_checks_replace_create
+ enabled: true
+ scopes:
+ - task:write
+ - query:read
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Replace a metric follow-up check
+ description: >
+ Replace one open metric check after investigating a better measure or threshold. Read the current check and
+ report first. Supply a bounded live Trends query or a report metric ID, an explicit comparison, and a
+ measured baseline. The old check stays live if the replacement fails validation. A successful replacement
+ starts unapproved and is scheduled independently of human approval. Do not use this to change an agent
+ check. The replacement preserves the existing soak and remaining recurrence. The measurement also requires
+ event_definition:read for event series, action:read for action series, and cohort:read for cohort filters
+ when present.
+ feature_flag: signals-report-checks-replace
+ feature_flag_behavior: enable
inbox-report-checks-retrieve:
operation: signals_report_checks_retrieve
enabled: true
@@ -1203,6 +1225,9 @@ tools:
signals-report-artefacts-diff:
operation: signals_report_artefacts_diff
enabled: false
+ signals-report-checks-approve-create:
+ operation: signals_report_checks_approve_create
+ enabled: false
signals-report-checks-destroy:
operation: signals_report_checks_destroy
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 4cb153508dcc..b5bd08a3f0ab 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6714,7 +6714,7 @@
}
},
"inbox-report-checks-list": {
- "description": "List the follow-up checks on one report, newest first. Each row carries the expectation and why it was written, its schedule (`next_run_at`, `run_interval_minutes`, `runs_remaining`, `expires_at`), its `status` (`pending`, `active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. A `pending` check waits for its report to resolve before its clock starts. Checks are written by scout runs and by the research pipeline, so this surface reads them and does not create them. `query` and `baseline_value` read as null when you cannot read the data they describe.",
+ "description": "List the follow-up checks on one report, open checks first and newest first within each group. Each row carries the expectation and why it was written, its schedule (`next_run_at`, `run_interval_minutes`, `runs_remaining`, `expires_at`), its `status` (`pending`, `active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. A `pending` check waits for its report to resolve before its clock starts. Checks are written by scout runs and by the research pipeline, so this surface reads them and does not create them. `query` and `baseline_value` read as null when you cannot read the data they describe.",
"category": "Signals",
"feature": "signals",
"summary": "List a report's checks",
@@ -6727,6 +6727,22 @@
"readOnlyHint": true
}
},
+ "inbox-report-checks-replace": {
+ "description": "Replace one open metric check after investigating a better measure or threshold. Read the current check and report first. Supply a bounded live Trends query or a report metric ID, an explicit comparison, and a measured baseline. The old check stays live if the replacement fails validation. A successful replacement starts unapproved and is scheduled independently of human approval. Do not use this to change an agent check. The replacement preserves the existing soak and remaining recurrence. The measurement also requires event_definition:read for event series, action:read for action series, and cohort:read for cohort filters when present.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Replace a metric follow-up check",
+ "title": "Replace a metric follow-up check",
+ "required_scopes": ["task:write", "query:read"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "signals-report-checks-replace",
+ "feature_flag_behavior": "enable"
+ },
"inbox-report-checks-retrieve": {
"description": "Get one check on a report by its id, with its full config, schedule, status, and last outcome. The verdicts themselves are `check_result` artefacts on the report, so read those through the artefact list.",
"category": "Signals",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index cf2522c45c8f..ba9de21aa012 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6911,7 +6911,7 @@
}
},
"inbox-report-checks-list": {
- "description": "List the follow-up checks on one report, newest first. Each row carries the expectation and why it was written, its schedule (`next_run_at`, `run_interval_minutes`, `runs_remaining`, `expires_at`), its `status` (`pending`, `active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. A `pending` check waits for its report to resolve before its clock starts. Checks are written by scout runs and by the research pipeline, so this surface reads them and does not create them. `query` and `baseline_value` read as null when you cannot read the data they describe.",
+ "description": "List the follow-up checks on one report, open checks first and newest first within each group. Each row carries the expectation and why it was written, its schedule (`next_run_at`, `run_interval_minutes`, `runs_remaining`, `expires_at`), its `status` (`pending`, `active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. A `pending` check waits for its report to resolve before its clock starts. Checks are written by scout runs and by the research pipeline, so this surface reads them and does not create them. `query` and `baseline_value` read as null when you cannot read the data they describe.",
"category": "Signals",
"feature": "signals",
"summary": "List a report's checks",
@@ -6924,6 +6924,22 @@
"readOnlyHint": true
}
},
+ "inbox-report-checks-replace": {
+ "description": "Replace one open metric check after investigating a better measure or threshold. Read the current check and report first. Supply a bounded live Trends query or a report metric ID, an explicit comparison, and a measured baseline. The old check stays live if the replacement fails validation. A successful replacement starts unapproved and is scheduled independently of human approval. Do not use this to change an agent check. The replacement preserves the existing soak and remaining recurrence. The measurement also requires event_definition:read for event series, action:read for action series, and cohort:read for cohort filters when present.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Replace a metric follow-up check",
+ "title": "Replace a metric follow-up check",
+ "required_scopes": ["task:write", "query:read"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "signals-report-checks-replace",
+ "feature_flag_behavior": "enable"
+ },
"inbox-report-checks-retrieve": {
"description": "Get one check on a report by its id, with its full config, schedule, status, and last outcome. The verdicts themselves are `check_result` artefacts on the report, so read those through the artefact list.",
"category": "Signals",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 99d5f71ec5bc..c8e0d91e8c05 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -69672,6 +69672,8 @@ export namespace Schemas {
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;
+ /** @nullable */
+ readonly approved_at: string | null;
/** 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;
/**
@@ -94462,6 +94464,21 @@ export namespace Schemas {
not_found_count: number;
}
+ export interface SignalReportCheckReplacement {
+ /**
+ * Label for the new metric check.
+ * @maxLength 200
+ */
+ title: string;
+ /**
+ * Why this check is better.
+ * @maxLength 2000
+ */
+ rationale?: string;
+ /** Metric threshold configuration, including a bounded query and comparison. */
+ config: MetricThresholdConfig;
+ }
+
export interface SignalReportClaim {
/** Active claim ID returned by an earlier call. Stale claims are rejected. */
claim_id?: string;
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 5dbe76b8e86c..479262d0f3fc 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 49 enabled ops
+ * PostHog API - MCP 50 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -523,7 +523,7 @@ export const SignalsReportChecksListQueryParams = () => zod.object({
})
/**
- * Checks attached to a signal report: read and cancel.
+ * Checks attached to a signal report: read, approve, replace metrics, and cancel.
*
* There is no create here. A check is authored by a scout run or by the research pipeline, both
* through `report_check_authoring.create_check`. An `agent` check puts its author's prose in front
@@ -531,8 +531,9 @@ export const SignalsReportChecksListQueryParams = () => zod.object({
* endpoint accepts one. Anyone who can read the report can read its checks, and a person can
* still stop one.
*
- * 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 let its author write a new one.
+ * There is no in-place update: a check is a claim about the future, and editing its threshold
+ * after a result would make the recorded verdict unreadable. Replacing an open metric check
+ * cancels the old row and creates a new one in one transaction.
* @summary Get a single check
*/
export const SignalsReportChecksRetrieveParams = () => zod.object({
@@ -549,6 +550,104 @@ export const SignalsReportChecksRetrieveParams = () => zod.object({
),
})
+/**
+ * Atomically replace an open metric check. The old check stays live if the new one is invalid.
+ * @summary Replace a metric follow-up check
+ */
+export const SignalsReportChecksReplaceCreateParams = () => zod.object({
+ id: zod.string().describe('A UUID string identifying this Signal report check.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+ report_id: zod.string(),
+})
+
+export const signalsReportChecksReplaceCreateBodyTitleMax = 200
+
+export const signalsReportChecksReplaceCreateBodyRationaleMax = 2000
+
+export const signalsReportChecksReplaceCreateBodyConfigOneUnitOneMax = 40
+
+export const SignalsReportChecksReplaceCreateBody = () => zod.object({
+ title: zod.string().max(signalsReportChecksReplaceCreateBodyTitleMax).describe('Label for the new metric check.'),
+ rationale: zod
+ .string()
+ .max(signalsReportChecksReplaceCreateBodyRationaleMax)
+ .optional()
+ .describe('Why this check is better.'),
+ 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. `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.'
+ ),
+ 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.'),
+ 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(signalsReportChecksReplaceCreateBodyConfigOneUnitOneMax), 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."
+ )
+ .describe('Metric threshold configuration, including a bounded query and comparison.'),
+})
+
/**
* Transition many reports to a new state in one call.
*
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 2c702eab63b6..c81257c928bc 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -226,6 +226,41 @@ const inboxReportChecksList = (): ToolBase<
},
})
+const InboxReportChecksReplaceSchema = () => {
+ const SignalsReportChecksReplaceCreateBody = orvalSchemas.SignalsReportChecksReplaceCreateBody()
+ const SignalsReportChecksReplaceCreateParams = orvalSchemas.SignalsReportChecksReplaceCreateParams()
+ return SignalsReportChecksReplaceCreateParams.omit({ project_id: true }).extend(
+ SignalsReportChecksReplaceCreateBody.shape
+ )
+}
+
+const inboxReportChecksReplace = (): ToolBase<
+ ReturnType<typeof InboxReportChecksReplaceSchema>,
+ Schemas.SignalReportCheck
+> => ({
+ name: 'inbox-report-checks-replace',
+ schema: InboxReportChecksReplaceSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof InboxReportChecksReplaceSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.title !== undefined) {
+ body['title'] = params.title
+ }
+ if (params.rationale !== undefined) {
+ body['rationale'] = params.rationale
+ }
+ if (params.config !== undefined) {
+ body['config'] = params.config
+ }
+ const result = await context.api.request<Schemas.SignalReportCheck>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/${encodeURIComponent(String(params.report_id))}/checks/${encodeURIComponent(String(params.id))}/replace/`,
+ body,
+ })
+ return result
+ },
+})
+
const InboxReportChecksRetrieveSchema = () => {
const SignalsReportChecksRetrieveParams = orvalSchemas.SignalsReportChecksRetrieveParams()
return SignalsReportChecksRetrieveParams.omit({ project_id: true })
@@ -2429,6 +2464,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'inbox-report-artefacts-update': inboxReportArtefactsUpdate,
'inbox-report-checks-create': inboxReportChecksCreate,
'inbox-report-checks-list': inboxReportChecksList,
+ 'inbox-report-checks-replace': inboxReportChecksReplace,
'inbox-report-checks-retrieve': inboxReportChecksRetrieve,
'inbox-reports-bulk-set-state': inboxReportsBulkSetState,
'inbox-reports-claim': inboxReportsClaim,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-replace.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-replace.json
new file mode 100644
index 000000000000..1d4435ede18a
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-replace.json
@@ -0,0 +1,156 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "config": {
+ "description": "Metric threshold configuration, including a bounded query and comparison.",
+ "properties": {
+ "baseline_value": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The value observed when the check was written, recorded on each result for context."
+ },
+ "comparison": {
+ "description": "What the measured value must satisfy to pass.",
+ "properties": {
+ "bounds": {
+ "anyOf": [
+ {
+ "properties": {
+ "lower": {
+ "type": "number"
+ },
+ "upper": {
+ "type": "number"
+ }
+ },
+ "required": ["lower", "upper"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The inclusive range for `between`; unused by `lte` and `gte`."
+ },
+ "operator": {
+ "description": "`lte`, `gte`, or `between`.",
+ "enum": ["lte", "gte", "between"],
+ "type": "string"
+ },
+ "value": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The bound for `lte` and `gte`; unused by `between`."
+ }
+ },
+ "required": ["operator"],
+ "type": "object"
+ },
+ "metric_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "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."
+ },
+ "metric_kind": {
+ "anyOf": [
+ {
+ "enum": [
+ "affected_users",
+ "affected_sessions",
+ "occurrences",
+ "conversion_rate",
+ "error_rate",
+ "duration",
+ "revenue",
+ "custom"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "How to draw this measurement; copied from a referenced metric."
+ },
+ "query": {
+ "anyOf": [
+ {
+ "additionalProperties": {},
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "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."
+ },
+ "unit": {
+ "anyOf": [
+ {
+ "maxLength": 40,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional value suffix."
+ },
+ "value_format": {
+ "anyOf": [
+ {
+ "enum": ["number", "count", "percentage", "percentage_scaled", "duration", "currency"],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "How to format measured values; copied from a referenced metric."
+ }
+ },
+ "required": ["comparison"],
+ "type": "object"
+ },
+ "id": {
+ "description": "A UUID string identifying this Signal report check.",
+ "type": "string"
+ },
+ "rationale": {
+ "description": "Why this check is better.",
+ "maxLength": 2000,
+ "type": "string"
+ },
+ "report_id": {
+ "type": "string"
+ },
+ "title": {
+ "description": "Label for the new metric check.",
+ "maxLength": 200,
+ "type": "string"
+ }
+ },
+ "required": ["id", "report_id", "title", "config"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/schema.signals-checks.test.ts b/services/mcp/tests/unit/schema.signals-checks.test.ts
new file mode 100644
index 000000000000..8d50524285b3
--- /dev/null
+++ b/services/mcp/tests/unit/schema.signals-checks.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest'
+
+import { SignalsReportChecksReplaceCreateBody } from '@/generated/signals/api'
+
+describe('Signals metric check replacement inputs', () => {
+ it('leaves omitted display fields available for the referenced metric to supply', () => {
+ const result = SignalsReportChecksReplaceCreateBody().parse({
+ title: 'Checkout conversion improves',
+ config: { metric_id: 'checkout-conversion', comparison: { operator: 'gte', value: 0.8 } },
+ })
+ expect(result.config.metric_kind).toBeUndefined()
+ expect(result.config.value_format).toBeUndefined()
+ expect(result.config.unit).toBeUndefined()
+ })
+})
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index d1fb50d1e03e..66175189fde8 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -292,6 +292,22 @@ const createMockContext = (
})
describe('Tool Filtering - API Scopes', () => {
+ it.each([
+ { scopes: ['task:write'], rollout: true, visible: false },
+ { scopes: ['query:read'], rollout: true, visible: false },
+ { scopes: ['task:write', 'query:read'], rollout: true, visible: true },
+ { scopes: ['task:write', 'query:write'], rollout: true, visible: true },
+ { scopes: ['task:write', 'query:read'], rollout: false, visible: false },
+ { scopes: ['task:write', 'query:read'], rollout: undefined, visible: false },
+ ])('metric replacement requires query access and rollout: %j', async ({ scopes, rollout, visible }) => {
+ const featureFlags: EvaluatedFlags = {}
+ if (rollout !== undefined) {
+ featureFlags['signals-report-checks-replace'] = rollout
+ }
+ const tools = await getToolsFromContext(createMockContext(scopes), { featureFlags })
+ expect(tools.some((tool) => tool.name === 'inbox-report-checks-replace')).toBe(visible)
+ })
+
it.each([
{ scopes: ['billing:read'], visible: true },
{ scopes: [], visible: false },
@@ -998,7 +1014,11 @@ describe('Tool Filtering - Feature Flags', () => {
it('getRequiredFeatureFlags should return flags used by current definitions', () => {
const allFlags = getRequiredFeatureFlags()
- const branchFlags = ['self-optimising-workflows', 'business-knowledge-github-repos']
+ const branchFlags = [
+ 'self-optimising-workflows',
+ 'business-knowledge-github-repos',
+ 'signals-report-checks-replace',
+ ]
expect(allFlags).toEqual(expect.arrayContaining(branchFlags))
// The flags branches add are asserted on the line above and held out of the list and
// count below. Those belong to master and move with every flag master adds or drops, so a
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index 2fc70c12c685..14a292995a63 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -102,6 +102,7 @@ describe('Tool schema snapshots', () => {
'agent-platform': true,
'billing-alerts': true,
'experiment-setup-context': true,
+ 'signals-report-checks-replace': true,
}
const tools = [...(await getToolsFromContext(context, { featureFlags }))].sort((a, b) =>
a.name.localeCompare(b.name)