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): snapshot monitoring attempt checks (#122185)

Mikayla Thompsonab11db897bc1
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 03b3bfade471..d738ef13efc5 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -387,6 +387,7 @@ rules:
|SignalReportAction
|SignalReportArtefact
|SignalReportCheck
+ |SignalReportMonitoringAttempt
|SignalReportGithubComment
|SignalReportPullRequest
|SignalReportAssignment
@@ -857,6 +858,7 @@ rules:
|SignalReportAction
|SignalReportArtefact
|SignalReportCheck
+ |SignalReportMonitoringAttempt
|SignalReportGithubComment
|SignalReportPullRequest
|SignalReportAssignment
@@ -1199,6 +1201,7 @@ rules:
|SignalReport
|SignalReportArtefact
|SignalReportCheck
+ |SignalReportMonitoringAttempt
|SignalReportSlackThread
|SignalReportTask
|SignalSourceConfig
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index 9c1663b65c33..3736438ef68d 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -14,6 +14,8 @@ Monitoring means implementation is complete and outcome verification is pending.
A Monitoring period begins with an explicit, timezone-aware implementation-complete timestamp supplied by the server. Merge-driven entry can use the linked PR's recorded `merged_at`, even when its webhook arrives later. The lifecycle never substitutes receipt time for a missing implementation timestamp. Repeated entry preserves the original period; archive and restore preserve it too. Reopening implementation clears the start so a later implementation creates a new period. Resolving after verification keeps the implementation timestamp for history.
+The backend `complete_implementation` service records a durable attempt and freezes this report's pending or active, unexpired check IDs and authored-definition versions in the same transaction as Monitoring entry. Kind, approval, missing configuration, and missing or zero soak do not remove a check from this selection. Stale checks receive expiry records before selection. No applicable checks, or a disabled Monitoring flag, resolve directly without a verification attempt. Carried-over checks lose their earlier evidence and dispatch claims while keeping their remaining runs. Duplicate completion and archive/restore retain the snapshot; reopening creates a new attempt when implementation completes again. Existing state APIs and PR-merge handlers do not call this service yet.
+
Monitoring keeps the researched report available for verification and new matching signals, without starting another implementation. Enabled responses expose the server-owned start time, and implementation work is done while the report itself remains unfinished. A Monitoring child keeps its parent plan open, and child rollups cannot finish a Monitoring parent. The single and bulk state APIs still accept only suppressed, potential, and resolved targets; neither manual entry controls nor automatic PR-merge entry are available.
Disabled organizations treat stored Monitoring reports as Resolved across reads, filters, counts, sorting, actions, recurrence handling, work state, plan rollups, and background checks. Responses omit the Monitoring start field and the inbox offers no Monitoring controls. Monitoring entry is refused. Restoring a report archived from Monitoring returns it to Resolved while disabled. Reads preserve the stored status.
diff --git a/products/signals/backend/migrations/0194_report_monitoring_attempt.py b/products/signals/backend/migrations/0194_report_monitoring_attempt.py
new file mode 100644
index 000000000000..e1720d8062cd
--- /dev/null
+++ b/products/signals/backend/migrations/0194_report_monitoring_attempt.py
@@ -0,0 +1,58 @@
+# Generated by Django 5.2.18 on 2026-10-21 21:31
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1407_scimprovisioneduser_scimrequestlog"),
+ ("signals", "0193_useractivitysummary_consecutive_skips"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="SignalReportMonitoringAttempt",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("monitoring_started_at", models.DateTimeField()),
+ ("check_versions", models.JSONField(default=dict)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "report",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="monitoring_attempts",
+ to="signals.signalreport",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("report", "monitoring_started_at"),
+ name="signals_attempt_period_uniq",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 7c2c7306e5de..5631ca866075 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0193_useractivitysummary_consecutive_skips
+0194_report_monitoring_attempt
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 7643d1ff9857..74cdf9196213 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -2585,6 +2585,22 @@ class SignalReportCheck(UUIDModel):
return self.status not in self.OPEN_STATUSES
+class SignalReportMonitoringAttempt(UUIDModel):
+ # Attempt evidence belongs to the report's environment, not its canonical project.
+ objects = EnvironmentScopedManager()
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ report = models.ForeignKey(SignalReport, on_delete=models.CASCADE, related_name="monitoring_attempts")
+ monitoring_started_at = models.DateTimeField()
+ check_versions = models.JSONField(default=dict)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["report", "monitoring_started_at"], name="signals_attempt_period_uniq")
+ ]
+
+
# ── Signals scout (headless cross-source explorer) ──────────────────────────────
#
# Core tables backing the Signals scout:
diff --git a/products/signals/backend/report_check_artefacts.py b/products/signals/backend/report_check_artefacts.py
index 31f71a87d174..7b2321c5e92e 100644
--- a/products/signals/backend/report_check_artefacts.py
+++ b/products/signals/backend/report_check_artefacts.py
@@ -2,8 +2,8 @@
Every writer lives here rather than at its call site, because a lifecycle entry is written from
four places — the shared authoring path, the expiry sweep, and the cancel paths — and they have to
-agree on what an entry says. Each is best-effort: the transition has already happened, and losing
-its log entry must not fail it.
+agree on what an entry says. Writers are best-effort unless their caller requires the log to
+commit with its transition.
"""
from __future__ import annotations
@@ -24,6 +24,8 @@ def _write(
check: SignalReportCheck,
content: CheckScheduled | CheckExpired | CheckCancelled,
attribution: ArtefactAttribution,
+ *,
+ raise_on_error: bool = False,
) -> None:
try:
SignalReportArtefact.add_log(
@@ -33,6 +35,8 @@ def _write(
attribution=attribution,
)
except Exception:
+ if raise_on_error:
+ raise
logger.exception(
"signals.report_check.lifecycle_artefact_failed",
check_id=str(check.id),
@@ -76,7 +80,7 @@ def write_check_scheduled(check: SignalReportCheck, attribution: ArtefactAttribu
)
-def write_check_expired(check: SignalReportCheck, expired_at: datetime) -> None:
+def write_check_expired(check: SignalReportCheck, expired_at: datetime, *, raise_on_error: bool = False) -> None:
"""Record that a check reached its horizon without settling.
Attributed to the system, because no author chose this: the sweep retires the row when its
@@ -92,6 +96,7 @@ def write_check_expired(check: SignalReportCheck, expired_at: datetime) -> None:
last_run_at=check.last_run_at.isoformat() if check.last_run_at else None,
),
ArtefactAttribution.system(),
+ raise_on_error=raise_on_error,
)
diff --git a/products/signals/backend/report_monitoring_attempts.py b/products/signals/backend/report_monitoring_attempts.py
new file mode 100644
index 000000000000..b547835bf9e7
--- /dev/null
+++ b/products/signals/backend/report_monitoring_attempts.py
@@ -0,0 +1,137 @@
+from __future__ import annotations
+
+import json
+import hashlib
+from datetime import datetime
+from typing import TYPE_CHECKING
+from uuid import UUID
+
+from django.db import transaction
+from django.utils import timezone
+
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.models import (
+ InvalidStatusTransition,
+ SignalReport,
+ SignalReportCheck,
+ SignalReportMonitoringAttempt,
+)
+from products.signals.backend.report_check_artefacts import write_check_expired
+from products.signals.backend.report_content_gates import team_report_monitoring_enabled
+
+if TYPE_CHECKING:
+ from posthog.models import User
+
+
+def check_definition_version(check: SignalReportCheck) -> str:
+ definition = {
+ "title": check.title,
+ "rationale": check.rationale,
+ "kind": check.kind,
+ "config": check.config,
+ "soak_minutes": check.soak_minutes,
+ "run_interval_minutes": check.run_interval_minutes,
+ }
+ return hashlib.sha256(json.dumps(definition, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+
+
+def current_monitoring_attempt(report: SignalReport) -> SignalReportMonitoringAttempt | None:
+ if report.monitoring_started_at is None:
+ return None
+ return (
+ SignalReportMonitoringAttempt.objects.for_team(report.team_id)
+ .filter(report_id=report.id, monitoring_started_at=report.monitoring_started_at)
+ .first()
+ )
+
+
+def complete_implementation(
+ *,
+ team_id: int,
+ report_id: UUID | str,
+ monitoring_started_at: datetime,
+ attribution: ArtefactAttribution | None = None,
+ actor_user: User | None = None,
+ close_pr_on_resolve: bool = False,
+) -> SignalReportMonitoringAttempt | None:
+ if timezone.is_naive(monitoring_started_at):
+ raise ValueError("An aware implementation-complete timestamp is required.")
+ if monitoring_started_at > timezone.now():
+ raise ValueError("Implementation cannot complete in the future.")
+
+ with transaction.atomic():
+ # Check cancellation can write an artefact FK while entry waits for the check row.
+ report = SignalReport.objects.select_for_update(no_key=True).get(team_id=team_id, id=report_id)
+ report._transition_actor = attribution # type: ignore[attr-defined]
+ report._transition_actor_user = actor_user # type: ignore[attr-defined]
+ if report.status == SignalReport.Status.RESOLVED:
+ return None
+ enabled = team_report_monitoring_enabled(team_id)
+ if report.status == SignalReport.Status.MONITORING:
+ if not enabled:
+ return None
+ attempt = current_monitoring_attempt(report)
+ if attempt is None:
+ raise ValueError("The Monitoring period has no check snapshot.")
+ return attempt
+ if report.status not in {
+ SignalReport.Status.READY,
+ SignalReport.Status.PENDING_INPUT,
+ SignalReport.Status.FAILED,
+ }:
+ raise InvalidStatusTransition(report.status, SignalReport.Status.MONITORING)
+ if not enabled:
+ report._close_pr_on_resolve = close_pr_on_resolve # type: ignore[attr-defined]
+ report.save(update_fields=report.transition_to(SignalReport.Status.RESOLVED))
+ return None
+ if (
+ SignalReportMonitoringAttempt.objects.for_team(team_id)
+ .filter(report_id=report.id, monitoring_started_at__gte=monitoring_started_at)
+ .exists()
+ ):
+ raise ValueError("Implementation must complete after the report's earlier Monitoring periods.")
+
+ checks = list(
+ SignalReportCheck.objects.for_team(team_id)
+ .select_for_update()
+ .filter(report_id=report.id, status__in=SignalReportCheck.OPEN_STATUSES)
+ .order_by("id")
+ )
+ now = timezone.now()
+ applicable: list[SignalReportCheck] = []
+ for check in checks:
+ if check.expires_at <= now:
+ check.status = SignalReportCheck.Status.EXPIRED
+ check.save(update_fields=["status", "updated_at"])
+ write_check_expired(check, now, raise_on_error=True)
+ else:
+ applicable.append(check)
+ if not applicable:
+ report._close_pr_on_resolve = close_pr_on_resolve # type: ignore[attr-defined]
+ report.save(update_fields=report.transition_to(SignalReport.Status.RESOLVED))
+ return None
+
+ attempt = SignalReportMonitoringAttempt.objects.for_team(team_id).create(
+ team_id=team_id,
+ report=report,
+ monitoring_started_at=monitoring_started_at,
+ check_versions={str(check.id): check_definition_version(check) for check in applicable},
+ )
+ SignalReportCheck.objects.for_team(team_id).filter(id__in=[check.id for check in applicable]).update(
+ status=SignalReportCheck.Status.PENDING,
+ measurement_start_at=None,
+ last_run_at=None,
+ last_outcome=None,
+ last_outcome_reason=None,
+ dispatched_at=None,
+ consecutive_errors=0,
+ consecutive_inconclusive=0,
+ monitoring_fallback_expires_at=None,
+ updated_at=now,
+ )
+ report.save(
+ update_fields=report.transition_to(
+ SignalReport.Status.MONITORING, monitoring_started_at=monitoring_started_at
+ )
+ )
+ return attempt
diff --git a/products/signals/backend/test/test_report_check_concurrency.py b/products/signals/backend/test/test_report_check_concurrency.py
index f01da9f3d991..604fbb1c1f71 100644
--- a/products/signals/backend/test/test_report_check_concurrency.py
+++ b/products/signals/backend/test/test_report_check_concurrency.py
@@ -15,11 +15,17 @@ from parameterized import parameterized
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import CheckObservation
-from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportCheck
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportCheck,
+ SignalReportMonitoringAttempt,
+)
from products.signals.backend.report_check_authoring import cancel_check
from products.signals.backend.report_check_execution import expire_overdue_checks, run_due_report_checks
from products.signals.backend.report_check_monitoring import MONITORING_ERROR_RETRY_AFTER, record_monitoring_observation
from products.signals.backend.report_checks import MAX_CHECK_HORIZON
+from products.signals.backend.report_monitoring_attempts import complete_implementation
from products.signals.backend.test.report_metric_test_fixtures import trends_metric_query
@@ -104,6 +110,48 @@ class TestReportCheckConcurrency(NonAtomicBaseTest):
team_id=self.team.id, report=self.report, type=SignalReportArtefact.ArtefactType.CHECK_EXPIRED
).exists()
+ @parameterized.expand([("cancelled",), ("expired",)])
+ def test_monitoring_entry_rechecks_eligibility_after_a_lock_wait(self, outcome: str) -> None:
+ now = timezone.now()
+ SignalReport.objects.filter(id=self.report.id, team_id=self.team.id).update(status=SignalReport.Status.READY)
+ checks = SignalReportCheck.objects.for_team(self.team.id).filter(id=self.check.id)
+ checks.update(expires_at=now + timedelta(days=1))
+ with (
+ patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True),
+ ThreadPoolExecutor(max_workers=1) as executor,
+ time_machine.travel(now, tick=False) as clock,
+ ):
+ with transaction.atomic():
+ checks.select_for_update().get()
+ future = self._start_write(
+ executor,
+ lambda: complete_implementation(
+ team_id=self.team.id, report_id=self.report.id, monitoring_started_at=now
+ ),
+ )
+ self._assert_write_waits(future)
+ if outcome == "cancelled":
+ assert cancel_check(
+ self.check, reason="stopped_by_person", attribution=ArtefactAttribution.system()
+ )
+ else:
+ clock.shift(timedelta(days=2))
+ assert future.result(timeout=10) is None
+ self.report.refresh_from_db()
+ self.check.refresh_from_db()
+ assert self.report.status == SignalReport.Status.RESOLVED
+ assert self.check.status == (
+ SignalReportCheck.Status.CANCELLED if outcome == "cancelled" else SignalReportCheck.Status.EXPIRED
+ )
+ assert not SignalReportMonitoringAttempt.objects.for_team(self.team.id).filter(report=self.report).exists()
+ assert SignalReportArtefact.objects.filter(
+ team_id=self.team.id,
+ report=self.report,
+ type=SignalReportArtefact.ArtefactType.CHECK_CANCELLED
+ if outcome == "cancelled"
+ else SignalReportArtefact.ArtefactType.CHECK_EXPIRED,
+ ).exists()
+
@parameterized.expand([("enabled", True), ("disabled", False)])
def test_schedule_repair_preserves_a_concurrent_observation(self, _name: str, flag: bool) -> None:
now = timezone.now()
diff --git a/products/signals/backend/test/test_report_monitoring_attempts.py b/products/signals/backend/test/test_report_monitoring_attempts.py
new file mode 100644
index 000000000000..8a1961af0fed
--- /dev/null
+++ b/products/signals/backend/test/test_report_monitoring_attempts.py
@@ -0,0 +1,379 @@
+import json
+from datetime import timedelta
+
+import time_machine
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.models import (
+ InvalidStatusTransition,
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportCheck,
+ SignalReportMonitoringAttempt,
+)
+from products.signals.backend.report_monitoring_attempts import (
+ check_definition_version,
+ complete_implementation,
+ current_monitoring_attempt,
+)
+
+_FLAG_CLIENT = "products.signals.backend.report_content_gates.feature_enabled_or_false"
+
+
+class TestMonitoringAttemptDefinitionVersion(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("title", "Verify deployment", True),
+ ("rationale", "Check the implemented change", True),
+ ("kind", SignalReportCheck.Kind.METRIC_THRESHOLD, True),
+ ("config", {"instructions": "Verify the new behavior"}, True),
+ ("soak_minutes", 0, True),
+ ("run_interval_minutes", 120, True),
+ ("runs_remaining", 2, False),
+ ("last_outcome", SignalReportCheck.Outcome.PASSED, False),
+ ("status", SignalReportCheck.Status.ACTIVE, False),
+ ]
+ )
+ def test_definition_versions_track_authorship_without_changing_after_execution(
+ self, field: str, value: object, changes_version: bool
+ ) -> None:
+ check = SignalReportCheck(
+ title="Verify fix",
+ rationale="Confirm recovery",
+ kind=SignalReportCheck.Kind.AGENT,
+ config={"instructions": "Verify the behavior", "skill_name": "verification"},
+ soak_minutes=60,
+ run_interval_minutes=None,
+ runs_remaining=3,
+ status=SignalReportCheck.Status.PENDING,
+ )
+ before = check_definition_version(check)
+ check.config = {"skill_name": "verification", "instructions": "Verify the behavior"}
+ assert check_definition_version(check) == before
+ setattr(check, field, value)
+ assert (check_definition_version(check) != before) == changes_version
+
+
+class TestReportMonitoringAttempts(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.now = timezone.now()
+ self.enterContext(time_machine.travel(self.now, tick=False))
+ self.flag = self.enterContext(patch(_FLAG_CLIENT, return_value=True))
+ self.report = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, title="Fix checkout"
+ )
+
+ def _check(
+ self,
+ *,
+ report: SignalReport | None = None,
+ kind: str = SignalReportCheck.Kind.AGENT,
+ status: str = SignalReportCheck.Status.PENDING,
+ soak_minutes: int | None = 60,
+ ) -> SignalReportCheck:
+ report = report or self.report
+ return SignalReportCheck.objects.for_team(report.team_id).create(
+ team_id=report.team_id,
+ report=report,
+ title="Verify checkout",
+ kind=kind,
+ config={},
+ soak_minutes=soak_minutes,
+ status=status,
+ next_run_at=self.now + timedelta(hours=1),
+ expires_at=self.now + timedelta(days=30),
+ )
+
+ @parameterized.expand(
+ [
+ ("pending_agent_missing_soak", SignalReportCheck.Kind.AGENT, SignalReportCheck.Status.PENDING, None),
+ ("active_agent_zero_soak", SignalReportCheck.Kind.AGENT, SignalReportCheck.Status.ACTIVE, 0),
+ (
+ "pending_metric_missing_definition",
+ SignalReportCheck.Kind.METRIC_THRESHOLD,
+ SignalReportCheck.Status.PENDING,
+ 60,
+ ),
+ (
+ "active_metric_missing_soak",
+ SignalReportCheck.Kind.METRIC_THRESHOLD,
+ SignalReportCheck.Status.ACTIVE,
+ None,
+ ),
+ ]
+ )
+ def test_open_checks_qualify_without_approval_configuration_or_positive_soak(
+ self, _name: str, kind: str, status: str, soak_minutes: int | None
+ ) -> None:
+ check = self._check(kind=kind, status=status, soak_minutes=soak_minutes)
+ start = self.now - timedelta(minutes=5)
+
+ attempt = complete_implementation(team_id=self.team.id, report_id=self.report.id, monitoring_started_at=start)
+
+ assert attempt is not None
+ assert attempt.check_versions == {str(check.id): check_definition_version(check)}
+ assert attempt.monitoring_started_at == start
+ self.report.refresh_from_db()
+ assert self.report.status == SignalReport.Status.MONITORING
+ assert self.report.monitoring_started_at == start
+
+ def test_expired_terminal_and_other_reports_checks_cannot_require_monitoring(self) -> None:
+ stale = self._check(status=SignalReportCheck.Status.ACTIVE)
+ stale.expires_at = self.now
+ stale.save(update_fields=["expires_at"])
+ terminal = self._check(status=SignalReportCheck.Status.PASSED)
+ other_report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY)
+ other_check = self._check(report=other_report)
+
+ assert (
+ complete_implementation(team_id=self.team.id, report_id=self.report.id, monitoring_started_at=self.now)
+ is None
+ )
+
+ self.report.refresh_from_db()
+ assert self.report.status == SignalReport.Status.RESOLVED
+ assert not SignalReportMonitoringAttempt.objects.for_team(self.team.id).filter(report=self.report).exists()
+ stale.refresh_from_db()
+ terminal.refresh_from_db()
+ other_check.refresh_from_db()
+ assert stale.status == SignalReportCheck.Status.EXPIRED
+ assert terminal.status == SignalReportCheck.Status.PASSED
+ assert other_check.status == SignalReportCheck.Status.PENDING
+ expired_log = SignalReportArtefact.objects.get(
+ team=self.team, report=self.report, type=SignalReportArtefact.ArtefactType.CHECK_EXPIRED
+ )
+ assert json.loads(expired_log.content)["check_id"] == str(stale.id)
+ assert (
+ complete_implementation(team_id=self.team.id, report_id=self.report.id, monitoring_started_at=self.now)
+ is None
+ )
+ assert (
+ SignalReportArtefact.objects.filter(
+ report=self.report, type=SignalReportArtefact.ArtefactType.CHECK_EXPIRED
+ ).count()
+ == 1
+ )
+
+ def test_expiry_log_failure_rolls_back_entry_and_check_changes(self) -> None:
+ stale = self._check(status=SignalReportCheck.Status.ACTIVE)
+ stale.expires_at = self.now
+ stale.save(update_fields=["expires_at"])
+ applicable = self._check(status=SignalReportCheck.Status.ACTIVE)
+ with (
+ patch.object(SignalReportArtefact, "add_log", side_effect=RuntimeError("Artefact storage unavailable")),
+ self.assertRaisesRegex(RuntimeError, "Artefact storage unavailable"),
+ ):
+ complete_implementation(team_id=self.team.id, report_id=self.report.id, monitoring_started_at=self.now)
+ self.report.refresh_from_db()
+ stale.refresh_from_db()
+ applicable.refresh_from_db()
+ assert self.report.status == SignalReport.Status.READY
+ assert stale.status == SignalReportCheck.Status.ACTIVE
+ assert applicable.status == SignalReportCheck.Status.ACTIVE
+ assert not SignalReportMonitoringAttempt.objects.for_team(self.team.id).exists()
+
+ def test_child_environment_attempts_use_the_literal_team_id(self) -> None:
+ child = Team.objects.create(
+ organization=self.organization, parent_team=self.team, name="Verification environment"
+ )
+ child_report = SignalReport.objects.create(team=child, status=SignalReport.Status.READY)
+ child_check = self._check(report=child_report)
+ self._check()
+
+ with self.assertRaises(SignalReport.DoesNotExist):
+ complete_implementation(team_id=self.team.id, report_id=child_report.id, monitoring_started_at=self.now)
+ attempt = complete_implementation(team_id=child.id, report_id=child_report.id, monitoring_started_at=self.now)
+
+ assert attempt is not None
+ assert attempt.team_id == child.id
+ assert attempt.check_versions == {str(child_check.id): check_definition_version(child_check)}
+ assert not SignalReportMonitoringAttempt.objects.for_team(self.team.id).exists()
+ self.report.refresh_from_db()
+ assert self.report.status == SignalReport.Status.READY
+
+ def test_entry_rolls_back_if_monitoring_is_disabled_before_the_transition(self) -> None:
+ stale = self._check(status=SignalReportCheck.Status.ACTIVE)
+ stale.expires_at = self.now
+ stale.save(update_fields=["expires_at"])
+ applicable = self._check(status=SignalReportCheck.Status.ACTIVE)
+ self.flag.side_effect = [True, False]
+ with self.assertRaises(InvalidStatusTransition):
+ complete_implementation(team_id=self.team.id, report_id=self.report.id, monitoring_started_at=self.now)
+ self.report.refresh_from_db()
+ stale.refresh_from_db()
+ applicable.refresh_from_db()
+ assert self.report.status == SignalReport.Status.READY
+ assert stale.status == SignalReportCheck.Status.ACTIVE
+ assert applicable.status == SignalReportCheck.Status.ACTIVE
+ assert not SignalReportMonitoringAttempt.objects.for_team(self.team.id).exists()
+ assert not SignalReportArtefact.objects.filter(
+ report=self.report, type=SignalReportArtefact.ArtefactType.CHECK_EXPIRED
+ ).exists()
+
+ @parameterized.expand([("disabled", False), ("unavailable", RuntimeError("flag service unavailable"))])
+ def test_disabled_or_unavailable_flag_resolves_without_creating_an_attempt(
+ self, _name: str, flag_result: bool | Exception
+ ) -> None:
+ check = self._check()
+ if isinstance(flag_result, Exception):
+ self.flag.side_effect = flag_result
+ else:
+ self.flag.return_value = flag_result
+
+ assert (
+ complete_implementation(team_id=self.team.id, report_id=self.report.id, monitoring_started_at=self.now)
+ is None
+ )
+
+ self.report.refresh_from_db()
+ check.refresh_from_db()
+ assert self.report.status == SignalReport.Status.RESOLVED
+ assert self.report.monitoring_started_at is None
+ assert not SignalReportMonitoringAttempt.objects.for_team(self.team.id).exists()
+ assert check.status == SignalReportCheck.Status.PENDING
+
+ @parameterized.expand(
+ [("monitoring", True, True), ("manual_resolution", False, True), ("resolution", False, False)]
+ )
+ def test_entry_preserves_attribution_and_only_manual_resolution_closes_the_pr(
+ self, _name: str, has_checks: bool, close_pr_on_resolve: bool
+ ) -> None:
+ if has_checks:
+ self._check()
+ with (
+ patch("products.signals.backend.receivers.posthoganalytics.capture") as capture,
+ patch("products.signals.backend.tasks.close_dismissed_report_pr.delay") as close_pr,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ complete_implementation(
+ team_id=self.team.id,
+ report_id=self.report.id,
+ monitoring_started_at=self.now,
+ attribution=ArtefactAttribution.from_user(self.user.id),
+ actor_user=self.user,
+ close_pr_on_resolve=close_pr_on_resolve,
+ )
+ properties = capture.call_args.kwargs["properties"]
+ assert properties["actor_kind"] == "user"
+ assert properties["actor_user_uuid"] == str(self.user.uuid)
+ assert properties["actor_distinct_id"] == self.user.distinct_id
+ if close_pr_on_resolve and not has_checks:
+ close_pr.assert_called_once_with(
+ report_id=str(self.report.id), team_id=self.team.id, reason="resolved", actor_user_id=self.user.id
+ )
+ else:
+ close_pr.assert_not_called()
+
+ def test_carried_over_check_requires_fresh_evidence_and_arms_after_commit(self) -> None:
+ check = self._check(status=SignalReportCheck.Status.ACTIVE)
+ old_start = self.now - timedelta(days=2)
+ check.measurement_start_at = old_start
+ check.last_run_at = self.now - timedelta(hours=1)
+ check.last_outcome = SignalReportCheck.Outcome.INCONCLUSIVE
+ check.last_outcome_reason = SignalReportCheck.InconclusiveReason.AWAITING_DATA
+ check.dispatched_at = self.now - timedelta(minutes=30)
+ check.consecutive_errors = 2
+ check.consecutive_inconclusive = 3
+ check.monitoring_fallback_expires_at = self.now + timedelta(days=5)
+ check.run_interval_minutes = 120
+ check.runs_remaining = 3
+ check.save()
+ expected_version = check_definition_version(check)
+
+ with self.captureOnCommitCallbacks(execute=True):
+ attempt = complete_implementation(
+ team_id=self.team.id, report_id=self.report.id, monitoring_started_at=self.now
+ )
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.PENDING
+ self.assertIsNone(check.measurement_start_at)
+ self.assertIsNone(check.last_run_at)
+ self.assertIsNone(check.last_outcome)
+ self.assertIsNone(check.last_outcome_reason)
+ self.assertIsNone(check.dispatched_at)
+ assert check.consecutive_errors == 0
+ assert check.consecutive_inconclusive == 0
+ self.assertIsNone(check.monitoring_fallback_expires_at)
+ assert check.runs_remaining == 3
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ACTIVE
+ assert check.next_run_at == self.now + timedelta(hours=1)
+ assert attempt is not None
+ assert attempt.check_versions == {str(check.id): expected_version}
+
+ def test_retries_and_archive_preserve_membership_but_reopening_creates_a_new_attempt(self) -> None:
+ check = self._check()
+ first = complete_implementation(team_id=self.team.id, report_id=self.report.id, monitoring_started_at=self.now)
+ assert first is not None
+ original_versions = first.check_versions.copy()
+ check.status = SignalReportCheck.Status.CANCELLED
+ check.save(update_fields=["status"])
+ replacement = self._check()
+ retry = complete_implementation(
+ team_id=self.team.id, report_id=self.report.id, monitoring_started_at=self.now - timedelta(minutes=1)
+ )
+ assert retry is not None
+ assert retry.id == first.id
+ assert retry.check_versions == original_versions
+ self.report.refresh_from_db()
+ self.report.save(update_fields=self.report.transition_to(SignalReport.Status.SUPPRESSED))
+ archived = current_monitoring_attempt(self.report)
+ assert archived is not None
+ assert archived.id == first.id
+ self.report.save(update_fields=self.report.transition_to(SignalReport.Status.MONITORING))
+ restored = current_monitoring_attempt(self.report)
+ assert restored is not None
+ assert restored.id == first.id
+ self.report.save(update_fields=self.report.transition_to(SignalReport.Status.READY))
+ assert current_monitoring_attempt(self.report) is None
+
+ with time_machine.travel(self.now + timedelta(hours=1), tick=False):
+ second = complete_implementation(
+ team_id=self.team.id,
+ report_id=self.report.id,
+ monitoring_started_at=self.now + timedelta(hours=1),
+ )
+ assert second is not None
+ assert second.id != first.id
+ assert second.check_versions == {str(replacement.id): check_definition_version(replacement)}
+ first.refresh_from_db()
+ assert first.check_versions == original_versions
+
+ @parameterized.expand([("naive",), ("future",), ("reused",), ("older",)])
+ def test_invalid_period_start_cannot_create_an_attempt_or_change_checks(self, kind: str) -> None:
+ check = self._check()
+ start = self.now
+ if kind == "naive":
+ start = timezone.make_naive(self.now)
+ elif kind == "future":
+ start += timedelta(seconds=1)
+ else:
+ SignalReportMonitoringAttempt.objects.for_team(self.team.id).create(
+ team=self.team,
+ report=self.report,
+ monitoring_started_at=start,
+ check_versions={str(check.id): check_definition_version(check)},
+ )
+ if kind == "older":
+ start -= timedelta(seconds=1)
+
+ with self.assertRaises(ValueError):
+ complete_implementation(team_id=self.team.id, report_id=self.report.id, monitoring_started_at=start)
+
+ self.report.refresh_from_db()
+ check.refresh_from_db()
+ assert self.report.status == SignalReport.Status.READY
+ assert check.status == SignalReportCheck.Status.PENDING
+ assert SignalReportMonitoringAttempt.objects.for_team(self.team.id).count() == (
+ 1 if kind in {"reused", "older"} else 0
+ )