: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
fix(signals): guard report check lifecycle (#114438)
Mikayla Thompson9b6960aef422
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.mdindex f2ed1677d4d3..5265a0735d46 100644--- a/docs/internal/signals-pr-lifecycle.md+++ b/docs/internal/signals-pr-lifecycle.md@@ -7,6 +7,7 @@ Attaching a new open, draft, or unknown PR to a resolved report returns it to reThe shared PR-linking service applies this rule to task outputs and agent attachments.An existing attachment retry does not reopen a report, and importing legacy assignments preserves its status.Suppressed reports remain suppressed when another PR is attached.+A report merged into another report cannot be restored or resolved from the archive; act on the surviving report instead.A report that is `part_of` another report is a step in a plan, and the plan completes from its steps.When every live step of a plan is closed, the plan takes their verdict: resolved if at least one step resolved, suppressed if they all were.@@ -38,6 +39,8 @@ Protected research runs require analytics access before a person can resume or w## Follow-up measurement timing+Reopening or archiving a resolved report immediately parks its active checks and clears their measurement starts and dispatches. It resets both error and inconclusive retry streaks. Delayed resolution callbacks only arm checks while the report is still resolved. Results from an earlier measurement window or dispatch cannot update the current check.+Metric follow-up checks wait until their full trailing query window contains only post-resolution data. The configured soak is an independent minimum wait. Reopening a report clears the measurement anchor; resolving it again starts a new window. Legacy active metric checks without an anchor start their window at the next coordinator tick and recalculate expiry from the remaining schedule, capped at 90 days from that tick. Legacy rows do not distinguish supplied expiries from defaults, so both follow this re-arming policy. Checks with an existing anchor retain their expiry. A window that cannot finish before expiry records an inconclusive result instead of scheduling an unreachable run. Agent checks keep their soak-based schedule.New metric checks validate numeric goals and baselines against their metric kind, format, unit, and query. Existing check configurations remain readable.diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.pyindex 268d7ac6569c..002db5bcca33 100644--- a/products/signals/backend/receivers.py+++ b/products/signals/backend/receivers.py@@ -394,12 +394,17 @@ def arm_pending_checks_when_report_resolved(inbox, and an MCP state write all finish in a ``save``. Plenty of fixes never have a pullrequest to date a window from, which is why the report's own transition is the event."""- if instance.status != SignalReport.Status.RESOLVED:- return+ prior_status = getattr(instance, "_prior_status", None)if not _status_changed_on_this_save(- instance, created=created, update_fields=update_fields, prior_status=getattr(instance, "_prior_status", None)+ instance, created=created, update_fields=update_fields, prior_status=prior_status):return+ if instance.status != SignalReport.Status.RESOLVED:+ if prior_status == SignalReport.Status.RESOLVED:+ from products.signals.backend.report_check_execution import park_report_checks_on_reopen++ park_report_checks_on_reopen(team_id=instance.team_id, report_id=str(instance.id), now=timezone.now())+ returnteam_id = instance.team_idreport_id = str(instance.id)resolved_at = timezone.now()diff --git a/products/signals/backend/report_check_authoring.py b/products/signals/backend/report_check_authoring.pyindex 4db49c2af3cd..c7adaee0c00b 100644--- a/products/signals/backend/report_check_authoring.py+++ b/products/signals/backend/report_check_authoring.py@@ -420,7 +420,7 @@ def cancel_check(return bool(cancelled)-def arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_at: datetime) -> int:+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.Called from the report's `post_save` receiver, so every resolve path reaches it: the pull@@ -464,3 +464,11 @@ def arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_at:))return armed+++def arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_at: datetime) -> int:+ with transaction.atomic():+ report = SignalReport.objects.select_for_update().filter(team_id=team_id, id=report_id).first()+ if report is None or report.status != SignalReport.Status.RESOLVED:+ return 0+ return _arm_pending_checks(team_id=team_id, report_id=report_id, resolved_at=resolved_at)diff --git a/products/signals/backend/report_check_execution.py b/products/signals/backend/report_check_execution.pyindex 971d101a4e32..3c47d79c8776 100644--- a/products/signals/backend/report_check_execution.py+++ b/products/signals/backend/report_check_execution.py@@ -16,6 +16,7 @@ a breach the same way and there is one place where "is this value out of bounds?from __future__ import annotationsimport time+from collections.abc import Iterablefrom datetime import datetime, timedeltafrom functools import partialfrom typing import cast@@ -348,7 +349,11 @@ def record_check_verdict(.filter(id=check.id, status=SignalReportCheck.Status.ACTIVE).first())- if current is None:+ if (+ current is None+ or current.measurement_start_at != check.measurement_start_at+ or current.dispatched_at != check.dispatched_at+ ):returntransition = _next_state(current, verdict, now)current.status = transition.status@@ -565,26 +570,7 @@ def _report_expired_checks(overdue: list[SignalReportCheck]) -> None:logger.exception("signals.report_check.expired_report_failed")-def park_checks_on_unresolved_reports(now: datetime) -> int:- """Move active checks whose report is not resolved back to `pending`. 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- made the report decide, and any write path that skips `create_check`. Such a check must not run- or spend its error budget before a fix is live. As a pending row, the next resolve arms it- through `arm_pending_checks` with a fresh soak, and the expiry sweep retires it if the report- never resolves.-- A dated row keeps the gap its author left as its soak. The error streak and any open dispatch- are cleared, so retry accounting starts again after the next resolve.- """- active = list(- SignalReportCheck.all_teams.filter(status=SignalReportCheck.Status.ACTIVE)- .exclude(report__status=SignalReport.Status.RESOLVED)- .only("id", "team_id", "created_at", "next_run_at", "soak_minutes", "last_run_at", "dispatched_at")[- :MAX_CHECK_PARKS_PER_TICK- ]- )+def _park_checks(active: Iterable[SignalReportCheck], now: datetime) -> int:parked = 0for check in active:soak_minutes = check.soak_minutes@@ -596,7 +582,8 @@ def park_checks_on_unresolved_reports(now: datetime) -> int:else soak_minutes_from_gap(check.next_run_at, check.created_at))parked += (- SignalReportCheck.all_teams.filter(id=check.id, status=SignalReportCheck.Status.ACTIVE)+ SignalReportCheck.objects.for_team(check.team_id)+ .filter(id=check.id, status=SignalReportCheck.Status.ACTIVE).exclude(report__status=SignalReport.Status.RESOLVED).update(status=SignalReportCheck.Status.PENDING,@@ -605,10 +592,42 @@ def park_checks_on_unresolved_reports(now: datetime) -> int:next_run_at=now + timedelta(minutes=soak_minutes),expires_at=now + MAX_CHECK_HORIZON,consecutive_errors=0,+ consecutive_inconclusive=0,dispatched_at=None,updated_at=now,))+ return parked+++def park_report_checks_on_reopen(*, team_id: int, report_id: str, now: datetime) -> int:+ return _park_checks(+ SignalReportCheck.objects.for_team(team_id).filter(report_id=report_id, status=SignalReportCheck.Status.ACTIVE),+ now,+ )+++def park_checks_on_unresolved_reports(now: datetime) -> int:+ """Move active checks whose report is not resolved back to `pending`. 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+ made the report decide, and any write path that skips `create_check`. Such a check must not run+ or spend its error budget before a fix is live. As a pending row, the next resolve arms it+ through `arm_pending_checks` with a fresh soak, and the expiry sweep retires it if the report+ never resolves.++ A dated row keeps the gap its author left as its soak. The error streak and any open dispatch+ are cleared, so retry accounting starts again after the next resolve.+ """+ active = list(+ SignalReportCheck.all_teams.filter(status=SignalReportCheck.Status.ACTIVE)+ .exclude(report__status=SignalReport.Status.RESOLVED)+ .only("id", "team_id", "created_at", "next_run_at", "soak_minutes", "last_run_at", "dispatched_at")[+ :MAX_CHECK_PARKS_PER_TICK+ ]+ )+ parked = _park_checks(active, now)if parked:logger.info("signals.report_check.parked_on_unresolved_report", parked=parked)return parkeddiff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.pyindex 6addd881f270..9edd03ce396d 100644--- a/products/signals/backend/test/test_report_checks.py+++ b/products/signals/backend/test/test_report_checks.py@@ -44,7 +44,6 @@ from products.signals.backend.report_check_agent import ()from products.signals.backend.report_check_authoring import (CheckCreationError,- arm_pending_checks,cancel_check,create_check,create_checks_from_specs,@@ -713,10 +712,21 @@ class TestReportCheckExecution(APIBaseTest):# An active row on an open report: a report that left `resolved`, or a row written before# the create path let the report decide. It must not run, and its old error streak must not# count against the soak that follows the next resolve.- check = self._check(consecutive_errors=MAX_CONSECUTIVE_CHECK_ERRORS - 1)+ check = self._check(+ consecutive_errors=MAX_CONSECUTIVE_CHECK_ERRORS - 1,+ consecutive_inconclusive=len(AWAITING_DATA_RETRY_WAITS),+ dispatched_at=timezone.now(),+ )self.report.status = report_statusself.report.save(update_fields=["status"])+ check.refresh_from_db()+ assert check.status == SignalReportCheck.Status.PENDING+ assert check.consecutive_errors == 0+ assert check.consecutive_inconclusive == 0+ assert check.dispatched_at is None+ assert check.measurement_start_at is None+with patch(_MEASURE) as measure:summary = run_due_report_checks()@@ -748,22 +758,31 @@ class TestReportCheckExecution(APIBaseTest):assert collect_due_checks(timezone.now()) == []- @parameterized.expand([("cancelled",), ("reopened",)])+ @parameterized.expand([("cancelled",), ("reopened",), ("resolved_again",), ("redispatched",)])def test_a_check_invalidated_while_its_query_ran_records_nothing(self, reason: str) -> None:check = self._check()if reason == "cancelled":check.status = SignalReportCheck.Status.CANCELLEDcheck.save(update_fields=["status"])+ elif reason == "redispatched":+ SignalReportCheck.objects.for_team(self.team.id).filter(id=check.id).update(dispatched_at=timezone.now())else:self.report.status = SignalReport.Status.READYself.report.save(update_fields=["status"])+ if reason == "resolved_again":+ with self.captureOnCommitCallbacks(execute=True):+ self.report.save(update_fields=self.report.transition_to(SignalReport.Status.RESOLVED))record_check_verdict(check, CheckVerdict(outcome="passed", explanation="held", observed_value=1.0))check.refresh_from_db()- assert check.status == (- SignalReportCheck.Status.CANCELLED if reason == "cancelled" else SignalReportCheck.Status.ACTIVE- )+ expected_status = {+ "cancelled": SignalReportCheck.Status.CANCELLED,+ "reopened": SignalReportCheck.Status.PENDING,+ "resolved_again": SignalReportCheck.Status.ACTIVE,+ "redispatched": SignalReportCheck.Status.ACTIVE,+ }+ assert check.status == expected_status[reason]assert check.last_run_at is Noneassert self._results() == []@@ -1960,6 +1979,20 @@ 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+ ) -> 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))++ check.refresh_from_db()+ assert check.status == SignalReportCheck.Status.PENDING+ assert check.measurement_start_at is None+ assert collect_due_checks(timezone.now() + timedelta(days=7)) == []+def test_resolving_the_report_waits_for_a_full_query_window_after_the_soak(self) -> None:check = self._pending()before = timezone.now()@@ -2029,7 +2062,8 @@ class TestPendingChecks(APIBaseTest):soak_minutes=24 * 60,)resolved_at = timezone.now()- arm_pending_checks(team_id=self.team.id, report_id=self.report.id, resolved_at=resolved_at)+ with time_machine.travel(resolved_at, tick=False):+ self._resolve()metric.refresh_from_db()agent.refresh_from_db()assert metric.next_run_at == resolved_at + timedelta(days=3)@@ -2698,7 +2732,8 @@ class TestReportCheckLifecycleLog(APIBaseTest):attribution=ArtefactAttribution.system(),)- arm_pending_checks(team_id=self.team.id, report_id=open_report.id, resolved_at=timezone.now())+ with self.captureOnCommitCallbacks(execute=True):+ open_report.save(update_fields=open_report.transition_to(SignalReport.Status.RESOLVED))entries = self._entries(SignalReportArtefact.ArtefactType.CHECK_SCHEDULED, open_report)check.refresh_from_db()diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex dc5af133bb16..8062968ca355 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -3393,8 +3393,15 @@ class TestSignalReportMergeAPI(APIBaseTest):assert survivor.signal_count == 1assert good.status == SignalReport.Status.READY- @parameterized.expand([("straight_after_the_merge", False), ("after_a_later_dismissal", True)])- def test_a_merged_report_cannot_be_restored(self, _name, dismiss_again):+ @parameterized.expand(+ [+ (f"{target}_{bulk}_{dismiss_again}", target, bulk, dismiss_again)+ for target in ["potential", "resolved"]+ for bulk in [False, True]+ for dismiss_again in [False, True]+ ]+ )+ def test_a_merged_report_cannot_be_restored(self, _name: str, target: str, bulk: bool, dismiss_again: bool) -> None:survivor = self._report()source = self._report()assert self._merge(survivor, source).status_code == status.HTTP_200_OK@@ -3411,10 +3418,14 @@ class TestSignalReportMergeAPI(APIBaseTest):)response = self.client.post(- self._state_url(str(source.id)), data=json.dumps({"state": "potential"}), content_type="application/json"+ f"/api/projects/{self.team.id}/signals/reports/bulk-state/" if bulk else self._state_url(str(source.id)),+ data=json.dumps({"state": target, **({"ids": [str(source.id)]} if bulk else {})}),+ content_type="application/json",)- assert response.status_code == status.HTTP_409_CONFLICT, response.json()+ assert response.status_code == (status.HTTP_200_OK if bulk else status.HTTP_409_CONFLICT), response.json()+ if bulk:+ assert response.json()["skipped_count"] == 1source.refresh_from_db()assert source.status == SignalReport.Status.SUPPRESSEDdiff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex d289e9d70f14..e618506eb610 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -3228,6 +3228,20 @@ class SignalReportViewSet():return SignalReportBulkStateOutcome.SKIPPED, "Refunded reports can't be restored."+ # A merged report has no signals of its own left: they moved to the survivor, and+ # so did its work log. Restoring it would put an empty duplicate back in the inbox+ # and start it collecting again alongside the report it was folded into.+ if (+ report.status == SignalReport.Status.SUPPRESSED+ and target_status in {SignalReport.Status.POTENTIAL, SignalReport.Status.RESOLVED}+ and was_merged_away(report)+ ):+ return (+ SignalReportBulkStateOutcome.SKIPPED,+ "This report was merged into another one and can't be restored. Open the report it was "+ "merged into instead.",+ )+# Archiving must not grant a transition the report couldn't make directly. "Any# non-deleted status can be suppressed", so without this a report could be laundered# through the archive into RESOLVED from candidate/in_progress with no title or summary.@@ -3256,15 +3270,6 @@ class SignalReportViewSet(SignalReportBulkStateOutcome.SKIPPED,"This report is archived. Refresh it before continuing.",)- # A merged report has no signals of its own left: they moved to the survivor, and- # so did its work log. Restoring it would put an empty duplicate back in the inbox- # and start it collecting again alongside the report it was folded into.- if was_merged_away(report):- return (- SignalReportBulkStateOutcome.SKIPPED,- "This report was merged into another one and can't be restored. Open the report it was "- "merged into instead.",- )effective_target = report.restore_target_status()effective_snooze_for = snooze_for if target == "potential" else None