: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): arm checks on monitoring entry (#117363)
Mikayla Thompson9da525550544
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.mdindex 395cca431777..59c7f25bbd90 100644--- a/docs/internal/signals-pr-lifecycle.md+++ b/docs/internal/signals-pr-lifecycle.md@@ -13,7 +13,7 @@ Disabled organizations treat stored Monitoring reports as Resolved across reads,Background check processing discovers rollout decisions only for Monitoring reports with candidate checks and reuses them through each coordinator tick, including pending-check arming. Arming still rechecks the report's stored status under its row lock. Reopened-check batches and briefing details share one decision per team. Plan rollups reuse one decision across their child statuses and ancestor walk.-PR merges still resolve reports. A plan already in Monitoring waits for verification even after its steps close. Existing checks stay pending while Monitoring is enabled and start when the report resolves. If the rollout is disabled, existing Resolved check behavior applies to stored Monitoring reports; pending checks begin at the next coordinator tick, without using the Monitoring start as a measurement anchor. Expired checks stay expired. Monitoring entry, outcome checks, and automatic completion ship separately.+PR merges still resolve reports. A plan already in Monitoring waits for verification even after its steps close. Entering Monitoring with the rollout enabled arms existing, unexpired pending checks from the recorded implementation-complete timestamp. Archive pauses active checks; restoring Monitoring re-arms them from the same period. A delayed callback cannot arm checks after reopening, archiving, or entering a newer period. Coordinator ticks retry missed arming from the stored Monitoring start, including after a failed flag lookup, and preserve armed Monitoring checks. Their execution and result handling are not enabled by this arming change. If the rollout is disabled, existing Resolved check behavior applies to stored Monitoring reports; pending checks begin at the next coordinator tick, without using the Monitoring start as a measurement anchor. Expired checks stay expired. Monitoring entry, check execution, and automatic completion ship separately.Attaching a new open, draft, or unknown PR to a resolved or Monitoring report returns it to ready.The shared PR-linking service applies this rule to task outputs and agent attachments.diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.pyindex e247d9bcb4d3..1e55a2bb1388 100644--- a/products/signals/backend/receivers.py+++ b/products/signals/backend/receivers.py@@ -426,20 +426,14 @@ def arm_pending_checks_when_report_resolved(update_fields: set[str] | None = None,**kwargs: Any,) -> None:- """Start the soak clock on the report's pending checks the moment it resolves.-- A check written during research predates any fix, so it carries a soak duration rather than a- date. The resolve is what it waits for, and hooking the model rather than each caller makes- every resolve path the same clock: a merged pull request's webhook, a manual resolve in the- inbox, and an MCP state write all finish in a ``save``. Plenty of fixes never have a pull- request to date a window from, which is why the report's own transition is the event.- """+ """Use the shared status transition so every implementation path starts the same soak clock."""prior_status = getattr(instance, "_prior_status", None)if not _status_changed_on_this_save(instance, created=created, update_fields=update_fields, prior_status=prior_status):return- if instance.effective_status != SignalReport.Status.RESOLVED:+ effective_status = instance.effective_status+ if effective_status not in {SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING}:if prior_status in {SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING}:from products.signals.backend.report_check_execution import park_report_checks_on_reopen@@ -447,12 +441,21 @@ def arm_pending_checks_when_report_resolved(returnteam_id = instance.team_idreport_id = str(instance.id)- resolved_at = timezone.now()- # After commit, so a rolled-back resolve never arms a check, and best-effort: a report that- # resolved is the outcome that matters, and a failure here leaves the checks pending rather- # than losing them.+ monitoring_started_at = (+ instance.monitoring_started_at if effective_status == SignalReport.Status.MONITORING else None+ )+ if effective_status == SignalReport.Status.MONITORING and monitoring_started_at is None:+ return+ resolved_at = monitoring_started_at or timezone.now()+ # After commit so a rollback cannot start measurement; the callback also verifies the captured period.transaction.on_commit(- partial(_arm_pending_checks_safely, team_id=team_id, report_id=report_id, resolved_at=resolved_at)+ partial(+ _arm_pending_checks_safely,+ team_id=team_id,+ report_id=report_id,+ resolved_at=resolved_at,+ expected_monitoring_started_at=monitoring_started_at,+ ))@@ -526,13 +529,20 @@ def _roll_up_plan_parents_safely(*, team_id: int, report_id: str, include_reportlogger.exception("signals.plan_rollup.failed", report_id=report_id, team_id=team_id)-def _arm_pending_checks_safely(*, team_id: int, report_id: str, resolved_at: datetime) -> None:+def _arm_pending_checks_safely(+ *, team_id: int, report_id: str, resolved_at: datetime, expected_monitoring_started_at: datetime | None = None+) -> None:# Function-local: the authoring module reaches the execution module and from there the alerts# facade, which the startup-import-budget test keeps off django.setup().from products.signals.backend.report_check_authoring import arm_pending_checks # noqa: PLC0415try:- arm_pending_checks(team_id=team_id, report_id=report_id, resolved_at=resolved_at)+ arm_pending_checks(+ team_id=team_id,+ report_id=report_id,+ resolved_at=resolved_at,+ expected_monitoring_started_at=expected_monitoring_started_at,+ )except Exception:logger.exception("signals.report_check.arm_on_resolve_failed", report_id=report_id, team_id=team_id)diff --git a/products/signals/backend/report_check_authoring.py b/products/signals/backend/report_check_authoring.pyindex f79a4ce69aff..343b7924cf17 100644--- a/products/signals/backend/report_check_authoring.py+++ b/products/signals/backend/report_check_authoring.py@@ -470,18 +470,15 @@ def cancel_check(return bool(cancelled)-def _arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_at: datetime) -> int:- """Start the clock on a resolved report's pending checks. Returns how many were armed.+def _arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_at: datetime, armed_at: datetime) -> int:+ """Arm rows individually because each check carries its own soak and schedule.- Called from the report's `post_save` receiver, so every resolve path reaches it: the pull- request merge webhook, a manual resolve in the inbox, and an MCP state write alike.-- Each row is armed individually rather than in one UPDATE, because `next_run_at` and `expires_at`- are derived from the row's own soak and schedule.+ The measurement origin can precede this write when implementation completes before the status update.+ Expiry eligibility and the write timestamp use the arming time instead."""pending = list(SignalReportCheck.objects.for_team(team_id)- .filter(report_id=report_id, status=SignalReportCheck.Status.PENDING, expires_at__gt=resolved_at)+ .filter(report_id=report_id, status=SignalReportCheck.Status.PENDING, expires_at__gt=armed_at).select_related("report__team"))armed = 0@@ -510,7 +507,7 @@ def _arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_atnext_run_at=next_run_at,measurement_start_at=resolved_at if check.kind == SignalReportCheck.Kind.METRIC_THRESHOLD else None,expires_at=expires_at,- updated_at=resolved_at,+ updated_at=armed_at,))return armed@@ -522,13 +519,23 @@ def arm_pending_checks(report_id: str | uuid.UUID,resolved_at: datetime,monitoring_enabled: bool | None = None,+ expected_monitoring_started_at: datetime | None = None,) -> int:with transaction.atomic():report = SignalReport.objects.select_for_update().filter(team_id=team_id, id=report_id).first()- if (- report is None- or effective_report_status(report.status, team_id=team_id, monitoring_enabled=monitoring_enabled)- != SignalReport.Status.RESOLVED- ):+ if report is None:+ return 0+ status = effective_report_status(report.status, team_id=team_id, monitoring_enabled=monitoring_enabled)+ if expected_monitoring_started_at is not None:+ if (+ status != SignalReport.Status.MONITORING+ or report.monitoring_started_at != expected_monitoring_started_at+ ):+ return 0+ resolved_at = expected_monitoring_started_at+ armed_at = timezone.now()+ elif status == SignalReport.Status.RESOLVED:+ armed_at = resolved_at+ else:return 0- return _arm_pending_checks(team_id=team_id, report_id=report_id, resolved_at=resolved_at)+ return _arm_pending_checks(team_id=team_id, report_id=report_id, resolved_at=resolved_at, armed_at=armed_at)diff --git a/products/signals/backend/report_check_execution.py b/products/signals/backend/report_check_execution.pyindex f8a1994684ff..fcb072fd7232 100644--- a/products/signals/backend/report_check_execution.py+++ b/products/signals/backend/report_check_execution.py@@ -582,7 +582,9 @@ def _park_checks(active: Iterable[SignalReportCheck], now: datetime, *, resolvedif status_filter is None:if check.team_id not in team_filters:team_filters[check.team_id] = report_status_filter(- [SignalReport.Status.RESOLVED], team_id=check.team_id, field="report__status"+ [SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING],+ team_id=check.team_id,+ field="report__status",)status_filter = team_filters[check.team_id]soak_minutes = check.soak_minutes@@ -622,7 +624,7 @@ def park_report_checks_on_reopen(*, team_id: int, report_id: str, now: datetime)def park_checks_on_unresolved_reports(now: datetime, *, disabled_monitoring_organization_ids: frozenset[UUID] | None = None) -> int:- """Move active checks whose report is not resolved back to `pending`. Returns how many moved.+ """Park active checks whose report no longer has an implemented fix. Returns how many moved.A check can be active on an unresolved report in three ways: a report that left `resolved`(reopened, archived, or restored somewhere else), a row written active before the create path@@ -638,7 +640,7 @@ def park_checks_on_unresolved_reports(if disabled_monitoring_organization_ids is None:disabled_monitoring_organization_ids = check_monitoring_disabled_organizations(candidates)status_filter = report_status_filter(- [SignalReport.Status.RESOLVED],+ [SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING],field="report__status",disabled_monitoring_organization_ids=disabled_monitoring_organization_ids,)@@ -708,7 +710,7 @@ def collect_due_checks(return due-def _arm_disabled_monitoring_checks(now: datetime, *, disabled_monitoring_organization_ids: frozenset[UUID]) -> None:+def _arm_monitoring_checks(now: datetime, *, disabled_monitoring_organization_ids: frozenset[UUID]) -> None:from products.signals.backend.report_check_authoring import arm_pending_checkspending_checks = SignalReportCheck.all_teams.filter(@@ -719,18 +721,23 @@ def _arm_disabled_monitoring_checks(now: datetime, *, disabled_monitoring_organi)reports = (SignalReport.objects.filter(- report_status_filter(- [SignalReport.Status.RESOLVED],- disabled_monitoring_organization_ids=disabled_monitoring_organization_ids,- ),+ Q(monitoring_started_at__isnull=False) | Q(team__organization_id__in=disabled_monitoring_organization_ids),Exists(pending_checks),status=SignalReport.Status.MONITORING,)- .only("id", "status", "team_id")+ .select_related("team")+ .only("id", "status", "team_id", "monitoring_started_at", "team__organization_id").order_by("id")[:MAX_CHECK_PARKS_PER_TICK])for report in reports:- arm_pending_checks(team_id=report.team_id, report_id=report.id, resolved_at=now, monitoring_enabled=False)+ monitoring_enabled = report.team.organization_id not in disabled_monitoring_organization_ids+ arm_pending_checks(+ team_id=report.team_id,+ report_id=report.id,+ resolved_at=now,+ monitoring_enabled=monitoring_enabled,+ expected_monitoring_started_at=report.monitoring_started_at if monitoring_enabled else None,+ )def run_due_report_checks(*, now: datetime | None = None, limit: int = MAX_CHECK_RUNS_PER_TICK) -> CheckRunSummary:@@ -747,7 +754,7 @@ def run_due_report_checks(*, now: datetime | None = None, limit: int = MAX_CHECKQ(status=SignalReportCheck.Status.ACTIVE) | Q(status=SignalReportCheck.Status.PENDING, expires_at__gt=now))disabled_organizations = check_monitoring_disabled_organizations(candidate_checks)- _arm_disabled_monitoring_checks(now, disabled_monitoring_organization_ids=disabled_organizations)+ _arm_monitoring_checks(now, disabled_monitoring_organization_ids=disabled_organizations)park_checks_on_unresolved_reports(now, disabled_monitoring_organization_ids=disabled_organizations)deadline = time.monotonic() + CHECK_RUN_TIME_BUDGET_SECONDScounts: dict[str, int] = {diff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.pyindex af4f84eb5d07..e76c4a01e3b7 100644--- a/products/signals/backend/test/test_report_checks.py+++ b/products/signals/backend/test/test_report_checks.py@@ -805,7 +805,7 @@ class TestReportCheckExecution(APIBaseTest):assert [call.args[1] for call in evaluate.call_args_list] == [str(self.organization.id)]for check in checks:check.refresh_from_db()- assert check.status == SignalReportCheck.Status.PENDING+ assert check.status == SignalReportCheck.Status.ACTIVEdef test_parking_a_report_batch_reads_its_team_gate_once(self) -> None:checks = [self._check() for _ in range(3)]@@ -2088,56 +2088,176 @@ class TestPendingChecks(APIBaseTest):self.report.save(update_fields=["status"])@parameterized.expand(- [("enabled", True), ("disabled", False), ("unavailable", RuntimeError("flag service unavailable"))]+ [+ (f"{kind}_{name}", kind, result, recovered)+ for kind in [SignalReportCheck.Kind.METRIC_THRESHOLD, SignalReportCheck.Kind.AGENT]+ for name, result, recovered in [+ ("enabled", True, False),+ ("disabled", False, False),+ ("unavailable", RuntimeError("flag unavailable"), False),+ ("recovered", RuntimeError("flag unavailable"), True),+ ]+ ])- def test_monitoring_checks_wait_for_manual_finish_or_use_the_resolved_fallback(- self, _name: str, flag_result: bool | Exception+ def test_monitoring_entry_arms_checks_or_keeps_the_resolved_fallback(+ self, _name: str, kind: str, flag_result: bool | Exception, recovered: bool) -> None:+ now = timezone.now()+ implemented_at = now - timedelta(days=3)+ config = _threshold_config()+ if kind == SignalReportCheck.Kind.AGENT:+ LLMSkill.objects.create(team=self.team, name=FALLBACK_CHECK_SKILL_NAME, is_latest=True, deleted=False)+ SignalScoutConfig.objects.create(team=self.team, skill_name=FALLBACK_CHECK_SKILL_NAME)+ config = {"instructions": "Check whether checkout errors recur."}reports = [self.report] + [SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title=f"Fix {index}")for index in range(2)]- checks = [self._pending(report=report) for report in reports]- check = checks[0]- with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):- with self.captureOnCommitCallbacks(execute=True):- for report in reports:- report.save(- update_fields=report.transition_to(- SignalReport.Status.MONITORING, monitoring_started_at=timezone.now()+ checks = [+ create_check(+ report=report,+ title="Checkout errors stay low",+ kind=kind,+ config=config,+ attribution=ArtefactAttribution.system(),+ soak_minutes=DEFAULT_CHECK_SOAK_HOURS * 60,+ )+ for report in reports+ ]+ with time_machine.travel(now, tick=False):+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):+ with self.captureOnCommitCallbacks(execute=False) as callbacks:+ for report in reports:+ report.save(+ update_fields=report.transition_to(+ SignalReport.Status.MONITORING, monitoring_started_at=implemented_at+ ))+ with patch(+ "products.signals.backend.report_content_gates.feature_enabled_or_false",+ return_value=flag_result if isinstance(flag_result, bool) else False,+ side_effect=flag_result if isinstance(flag_result, Exception) else None,+ ):+ for callback in callbacks:+ callback()+ for check in checks:+ check.refresh_from_db()+ assert check.status == (+ SignalReportCheck.Status.ACTIVE if flag_result is True else SignalReportCheck.Status.PENDING)- check.refresh_from_db()- assert check.status == SignalReportCheck.Status.PENDING+ coordinator_flag = True if recovered else flag_result+ with patch(+ "products.signals.backend.report_content_gates.feature_enabled_or_false",+ return_value=coordinator_flag if isinstance(coordinator_flag, bool) else False,+ side_effect=coordinator_flag if isinstance(coordinator_flag, Exception) else None,+ ) as evaluate:+ with patch(_MEASURE) as measure:+ run_due_report_checks(now=now)+ measure.assert_not_called()+ assert evaluate.call_count == 1+ anchor = implemented_at if coordinator_flag is True else now+ expected_due = anchor + timedelta(hours=DEFAULT_CHECK_SOAK_HOURS)+ if kind == SignalReportCheck.Kind.METRIC_THRESHOLD:+ expected_due = max(expected_due, metric_check_ready_at(_PAGEVIEWS, self.team, anchor))+ for check in checks:+ check.refresh_from_db()+ assert check.status == SignalReportCheck.Status.ACTIVE+ assert check.measurement_start_at == (+ anchor if kind == SignalReportCheck.Kind.METRIC_THRESHOLD else None+ )+ assert check.next_run_at == expected_due+ assert check.updated_at == now+ assert {due.id for due in collect_due_checks(expected_due + timedelta(minutes=1))} == (+ set() if coordinator_flag is True else {check.id for check in checks}+ )+ if coordinator_flag is True:+ with self.captureOnCommitCallbacks(execute=True):+ self.report.save(update_fields=self.report.transition_to(SignalReport.Status.RESOLVED))+ checks[0].refresh_from_db()+ assert checks[0].next_run_at == expected_due+ assert collect_due_checks(expected_due + timedelta(minutes=1)) == [checks[0]]++ def test_a_delayed_monitoring_callback_cannot_arm_a_newer_period(self) -> None:+ check = self._pending()now = timezone.now()- with patch(- "products.signals.backend.report_content_gates.feature_enabled_or_false",- return_value=flag_result if isinstance(flag_result, bool) else False,- side_effect=flag_result if isinstance(flag_result, Exception) else None,- ) as evaluate:- with patch(_MEASURE) as measure:- run_due_report_checks(now=now)- measure.assert_not_called()- assert evaluate.call_count == 1- for pending in checks:- pending.refresh_from_db()- assert pending.status == (- SignalReportCheck.Status.PENDING if flag_result is True else SignalReportCheck.Status.ACTIVE+ old_start = now - timedelta(days=3)+ new_start = now - timedelta(hours=1)+ with (+ time_machine.travel(now, tick=False),+ patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True),+ ):+ with self.captureOnCommitCallbacks(execute=False) as old_callbacks:+ self.report.save(+ update_fields=self.report.transition_to(+ SignalReport.Status.MONITORING, monitoring_started_at=old_start+ ))- assert pending.measurement_start_at == (None if flag_result is True else now)+ self.report.save(update_fields=self.report.transition_to(SignalReport.Status.READY))+ with self.captureOnCommitCallbacks(execute=False) as new_callbacks:+ self.report.save(+ update_fields=self.report.transition_to(+ SignalReport.Status.MONITORING, monitoring_started_at=new_start+ )+ )+ for callback in old_callbacks:+ callback()+ check.refresh_from_db()+ assert check.status == SignalReportCheck.Status.PENDING+ assert check.measurement_start_at is None+ for callback in new_callbacks:+ callback()check.refresh_from_db()- if flag_result is True:- assert check.status == SignalReportCheck.Status.PENDING- assert collect_due_checks(now + timedelta(days=35)) == []- with self.captureOnCommitCallbacks(execute=True):- self.report.save(update_fields=self.report.transition_to(SignalReport.Status.RESOLVED))- check.refresh_from_db()- else:- assert check.measurement_start_at == nowassert check.status == SignalReportCheck.Status.ACTIVE- assert {due.id for due in collect_due_checks(check.next_run_at + timedelta(minutes=1))} == {- pending.id for pending in ([check] if flag_result is True else checks)- }+ assert check.measurement_start_at == new_start++ def test_restoring_monitoring_rearms_checks_from_the_original_period(self) -> None:+ check = self._pending()+ implemented_at = timezone.now() - timedelta(days=3)+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):+ with self.captureOnCommitCallbacks(execute=True):+ self.report.save(+ update_fields=self.report.transition_to(+ SignalReport.Status.MONITORING, monitoring_started_at=implemented_at+ )+ )+ check.refresh_from_db()+ original_due = check.next_run_at+ self.report.save(update_fields=self.report.transition_to(SignalReport.Status.SUPPRESSED))+ check.refresh_from_db()+ assert check.status == SignalReportCheck.Status.PENDING+ assert check.measurement_start_at is None+ with self.captureOnCommitCallbacks(execute=True):+ self.report.save(update_fields=self.report.transition_to(self.report.restore_target_status()))+ check.refresh_from_db()+ assert check.status == SignalReportCheck.Status.ACTIVE+ assert check.measurement_start_at == implemented_at+ assert check.next_run_at == original_due++ @parameterized.expand(+ [+ ("expired", SignalReportCheck.Status.PENDING),+ ("answered", SignalReportCheck.Status.PASSED),+ ]+ )+ def test_monitoring_entry_does_not_arm_expired_or_answered_checks(self, _name: str, check_status: str) -> None:+ check = self._pending()+ now = timezone.now()+ SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).update(+ status=check_status,+ expires_at=now - timedelta(minutes=1)+ if check_status == SignalReportCheck.Status.PENDING+ else now + timedelta(days=1),+ )+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):+ with self.captureOnCommitCallbacks(execute=True):+ self.report.save(+ update_fields=self.report.transition_to(+ SignalReport.Status.MONITORING, monitoring_started_at=now - timedelta(days=3)+ )+ )+ check.refresh_from_db()+ assert check.status == check_status+ assert check.measurement_start_at is Nonedef test_a_pending_check_is_never_due_while_its_report_is_unresolved(self) -> None:self._pending()@@ -2145,14 +2265,25 @@ class TestPendingChecks(APIBaseTest):# Well past the soak, but the clock has not started: the report is still open.assert collect_due_checks(timezone.now() + timedelta(days=7)) == []- @parameterized.expand([("reopened", SignalReport.Status.READY), ("archived", SignalReport.Status.SUPPRESSED)])- def test_a_delayed_resolve_callback_does_not_arm_checks_after_reopening(- self, _name: str, report_status: SignalReport.Status+ @parameterized.expand(+ [+ (f"{initial}_{target}", initial, target)+ for initial in [SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING]+ for target in [SignalReport.Status.READY, SignalReport.Status.SUPPRESSED]+ ]+ )+ def test_a_delayed_arming_callback_does_not_arm_checks_after_reopening(+ self, _name: str, initial_status: SignalReport.Status, report_status: SignalReport.Status) -> None:check = self._pending()- with self.captureOnCommitCallbacks(execute=True):- self.report.save(update_fields=self.report.transition_to(SignalReport.Status.RESOLVED))- self.report.save(update_fields=self.report.transition_to(report_status))+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):+ with self.captureOnCommitCallbacks(execute=True):+ self.report.save(+ update_fields=self.report.transition_to(+ initial_status, monitoring_started_at=timezone.now() - timedelta(days=3)+ )+ )+ self.report.save(update_fields=self.report.transition_to(report_status))assert (arm_pending_checks(