: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): add monitoring period lifecycle (#117189)
Mikayla Thompsonde9518a9a3c6
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.mdindex 88795431638e..395cca431777 100644--- a/docs/internal/signals-pr-lifecycle.md+++ b/docs/internal/signals-pr-lifecycle.md@@ -3,15 +3,23 @@A report completes after all linked implementation PRs are closed or merged.At least one merged PR resolves the report; otherwise all closed PRs suppress it.-The schema reserves `monitoring` and a nullable `monitoring_started_at`, but current report transitions do not enter that state. The organization-level `signals-report-monitoring` gate requires explicit enablement, including in local development, and treats evaluation failures as disabled.+Monitoring means implementation is complete and outcome verification is pending. Resolved means the report is finished. The organization-level `signals-report-monitoring` gate requires explicit enablement, including in local development, and treats missing definitions or evaluation failures as disabled.-When that gate is disabled, report list, detail, evidence, PR checks, and PR comments reads treat stored Monitoring reports as Resolved. Resolved filters and counts include them, status sorting uses the Resolved position, and their work state is done. The Monitoring gate uses local flag evaluation; a missing or unevaluable definition is disabled. The Monitoring status filter remains unavailable. The `feedback_state` endpoint exposes each person's saved rating for a fallback report. The `viewed` and `feedback` endpoints record consumption evidence without changing the stored status. This compatibility covers reads and their consumption records; status-changing actions and background processing require separate support before any production path can enter Monitoring.+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.-Attaching a new open, draft, or unknown PR to a resolved report returns it to ready.+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.++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.++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.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 merged into another report cannot be restored, resolved, or marked Monitoring 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.diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex 38eeaa097fde..edf5fcbc39ed 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -596,7 +596,7 @@ def _duplicate_already_worked_on(*, team_id: int, chain: list[str]) -> str | Nonstatus = statuses.get(candidate)if status is None:continue- if candidate in with_work or status == SignalReport.Status.RESOLVED:+ if candidate in with_work or status in {SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING}:return candidatereturn Nonediff --git a/products/signals/backend/briefing_reports.py b/products/signals/backend/briefing_reports.pyindex 086991c259ae..d7cda247dc16 100644--- a/products/signals/backend/briefing_reports.py+++ b/products/signals/backend/briefing_reports.py@@ -29,6 +29,8 @@ from products.signals.backend.implementation_pr import (from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportAssignmentfrom products.signals.backend.report_charts import ReportChartSnapshot, saved_chartsfrom products.signals.backend.report_claims import reports_with_active_claim+from products.signals.backend.report_content_gates import team_report_monitoring_enabled+from products.signals.backend.report_lifecycle import effective_report_statusfrom products.signals.backend.report_metric_access import ReportMetricAccessPolicyfrom products.signals.backend.report_metrics import ReportMetricSnapshot, saved_metric_snapshotsfrom products.signals.backend.signal_metadata import fetch_source_products_for_reports@@ -454,7 +456,7 @@ def reports_for_briefing(relation=candidate.relation,title=_trimmed(report.title, 200) or "Untitled report",summary=_trimmed(report.summary, _SUMMARY_LIMIT),- status=report.status,+ status=report.effective_status,priority=candidate.priority,has_implementation_pr=report.has_implementation_pr,source_products=source_products.get(candidate.report_id, []),@@ -539,12 +541,17 @@ def report_details(return []reports = list(SignalReport.objects.filter(team_id=team_id, id__in=list(report_ids)).only(- "id", "status", "summary", "metrics", "charts", "signal_count", "updated_at"+ "id", "team_id", "status", "summary", "metrics", "charts", "signal_count", "updated_at"))found_ids = [str(report.id) for report in reports]priorities = _priorities(team_id, found_ids)pull_requests = fetch_implementation_pr_state_for_reports(found_ids, team_id=team_id)+ monitoring_enabled = (+ team_report_monitoring_enabled(team_id)+ if any(report.status == SignalReport.Status.MONITORING for report in reports)+ else None+ )details = []for report in reports:report_id = str(report.id)@@ -552,7 +559,7 @@ def report_details(details.append(BriefingReportDetails(report_id=report_id,- status=report.status,+ status=effective_report_status(report.status, team_id=team_id, monitoring_enabled=monitoring_enabled),priority=priorities.get(report_id),summary=summary_lead(report.summary, SUMMARY_LEAD_LIMIT),pull_request_state=_pull_request_state(pull_request.state, pull_request.merged)diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex c164c5a649bb..a696b399082f 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -473,7 +473,7 @@ def organization_acted_on_report(organization_id: "str | uuid.UUID") -> bool:"""return SignalReport.objects.filter(team__organization_id=organization_id,- status__in=[SignalReport.Status.RESOLVED, SignalReport.Status.SUPPRESSED],+ status__in=[SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING, SignalReport.Status.SUPPRESSED],).exists()diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.pyindex a9e662cbd3ff..d7c888b06028 100644--- a/products/signals/backend/implementation_pr.py+++ b/products/signals/backend/implementation_pr.py@@ -26,6 +26,7 @@ from products.signals.backend.models import (SignalReportPullRequest,SignalReportTask,)+from products.signals.backend.report_lifecycle import report_status_filterfrom products.signals.backend.report_urls import ReportLinkSource, build_report_urlfrom products.signals.backend.task_run_artefacts import (NON_PR_BEARING_TASK_RUN_TYPES,@@ -341,7 +342,7 @@ def implementation_pr_needed_by_another_report(*, team_id: int, report_id: str,),).exclude(id=report_id)- .exclude(status__in=_FINISHED_REPORT_STATUSES)+ .exclude(report_status_filter(_FINISHED_REPORT_STATUSES, team_id=team_id)).exists())diff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 4bfe1834a184..4a2e28ccb6aa 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -490,6 +490,19 @@ class SignalReport(UUIDModel):repository = data.get("repository") if isinstance(data, dict) else Nonereturn repository.strip() if isinstance(repository, str) and repository.strip() else None+ def _monitoring_enabled(self) -> bool:+ from products.signals.backend.report_content_gates import (+ team_report_monitoring_enabled, # noqa: PLC0415 - keeps the flag client off model startup+ )++ return team_report_monitoring_enabled(self.team_id)++ @property+ def effective_status(self) -> "SignalReport.Status":+ if self.status == self.Status.MONITORING and not self._monitoring_enabled():+ return self.Status.RESOLVED+ return self.Status(self.status)+def transition_to(self,new_status: "SignalReport.Status",@@ -500,6 +513,7 @@ class SignalReport(UUIDModel):title: str | None = None,summary: str | None = None,error: str | None = None,+ monitoring_started_at: datetime | None = None,) -> list[str]:"""Validate and apply a status transition with side effects.@@ -510,8 +524,31 @@ class SignalReport(UUIDModel):"""S = self.Statusupdated_fields: set[str] = set()+ current_status = self.effective_status+ if new_status == S.MONITORING and not self._monitoring_enabled():+ raise InvalidStatusTransition(self.status, new_status)++ match (current_status, new_status):+ case (S.READY | S.PENDING_INPUT | S.FAILED, S.MONITORING):+ if monitoring_started_at is None or timezone.is_naive(monitoring_started_at):+ raise ValueError("An aware implementation-complete timestamp is required to enter Monitoring.")+ self.monitoring_started_at = monitoring_started_at+ updated_fields.add("monitoring_started_at")++ case (S.MONITORING, S.MONITORING):+ if self.monitoring_started_at is None:+ raise ValueError("The current Monitoring period has no implementation-complete timestamp.")+ return []++ case (S.SUPPRESSED, S.MONITORING):+ if self.status_before_suppression != S.MONITORING or self.monitoring_started_at is None:+ raise InvalidStatusTransition(self.status, new_status)+ self.status_before_suppression = None+ updated_fields.add("status_before_suppression")++ case (S.MONITORING, S.RESOLVED | S.READY):+ pass- match (self.status, new_status):# Pipeline transitions# - POTENTIAL -> CANDIDATE when the report is selected for summary generation# - READY -> CANDIDATE when new matching signals reopen the report for summary / agentic@@ -561,7 +598,10 @@ class SignalReport(UUIDModel):updated_fields.add("error")# Reset to potential (from in_progress via actionability judge, from suppressed, or by user snooze)- case (S.IN_PROGRESS | S.PENDING_INPUT | S.SUPPRESSED | S.READY | S.RESOLVED | S.FAILED, S.POTENTIAL):+ case (+ S.IN_PROGRESS | S.PENDING_INPUT | S.SUPPRESSED | S.READY | S.MONITORING | S.RESOLVED | S.FAILED,+ S.POTENTIAL,+ ):self.promoted_at = Noneupdated_fields.add("promoted_at")if self.status == S.SUPPRESSED:@@ -594,11 +634,18 @@ class SignalReport(UUIDModel):# Any non-deleted status can be suppressedcase (- S.POTENTIAL | S.CANDIDATE | S.IN_PROGRESS | S.PENDING_INPUT | S.READY | S.RESOLVED | S.FAILED,+ S.POTENTIAL+ | S.CANDIDATE+ | S.IN_PROGRESS+ | S.PENDING_INPUT+ | S.READY+ | S.MONITORING+ | S.RESOLVED+ | S.FAILED,S.SUPPRESSED,):# Remember where it was so "restore" can return it there (see restore_target_status).- self.status_before_suppression = self.status+ self.status_before_suppression = current_statusself.promoted_at = Noneupdated_fields.update(["status_before_suppression", "promoted_at"])@@ -609,6 +656,7 @@ class SignalReport(UUIDModel):| S.IN_PROGRESS| S.PENDING_INPUT| S.READY+ | S.MONITORING| S.RESOLVED| S.FAILED| S.SUPPRESSED,@@ -639,6 +687,9 @@ class SignalReport(UUIDModel):updated_fields.add("first_visible_at")self.status = new_status+ if new_status in (S.POTENTIAL, S.READY) and self.monitoring_started_at is not None:+ self.monitoring_started_at = None+ updated_fields.add("monitoring_started_at")updated_fields.update(["status", "updated_at"])return list(updated_fields)@@ -685,6 +736,8 @@ class SignalReport(UUIDModel):S = self.Statusresearched = {S.READY, S.PENDING_INPUT, S.RESOLVED, S.FAILED}prior = self.status_before_suppression+ if prior == S.MONITORING:+ return S.MONITORING if self._monitoring_enabled() else S.RESOLVEDif prior in {s.value for s in researched}:return S(prior)return S.POTENTIAL@@ -1037,7 +1090,7 @@ class SignalReportAssignment(TeamScopedRootMixin, UUIDModel):@propertydef work_state(self) -> SignalReportWorkState:- if self.report.status == SignalReport.Status.RESOLVED:+ if self.report.status in {SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING}:return SignalReportWorkState.DONEfrom products.signals.backend.implementation_pr import fetch_implementation_prs_for_reports@@ -1918,13 +1971,16 @@ class SignalReportArtefact(UUIDModel):from products.signals.backend.plan_rollup import roll_up_plan_parentstry:- status = (+ report = (SignalReport.objects.using("default").filter(team_id=artefact.team_id, id=artefact.report_id)- .values_list("status", flat=True)+ .only("status", "team_id").first())- if status not in (SignalReport.Status.RESOLVED, SignalReport.Status.SUPPRESSED):+ if report is None or report.effective_status not in (+ SignalReport.Status.RESOLVED,+ SignalReport.Status.SUPPRESSED,+ ):returnroll_up_plan_parents(team_id=artefact.team_id, report_id=str(artefact.report_id))except Exception:diff --git a/products/signals/backend/plan_rollup.py b/products/signals/backend/plan_rollup.pyindex 670cdeaf81f4..92df1c103662 100644--- a/products/signals/backend/plan_rollup.py+++ b/products/signals/backend/plan_rollup.py@@ -9,6 +9,9 @@ every way a step can close reaches it: a merged pull request, a manual resolve ibulk state change, and an MCP state write. Plenty of steps close without a pull request at all."""+from collections.abc import Callable+from functools import cache+from django.db import transactionimport structlog@@ -22,6 +25,8 @@ from products.signals.backend.models import (SignalReportArtefact,SignalReportPullRequest,)+from products.signals.backend.report_content_gates import team_report_monitoring_enabled+from products.signals.backend.report_lifecycle import effective_report_statusfrom products.signals.backend.typed_report_links import incoming_links, outgoing_linkslogger = structlog.get_logger(__name__)@@ -69,7 +74,9 @@ def _own_work_in_flight(team_id: int, report_id: str) -> bool:return any(pr.state in _LIVE_PR_STATES for pr in prs)-def _rolled_up_status(*, team_id: int, parent: SignalReport) -> SignalReport.Status | None:+def _rolled_up_status(+ *, team_id: int, parent: SignalReport, get_monitoring_enabled: Callable[[], bool] | None = None+) -> SignalReport.Status | None:"""The status the plan's steps put it in, or None while they disagree or work remains.Every step resolved (or resolved and archived together, with at least one resolved) resolves@@ -94,6 +101,14 @@ def _rolled_up_status(*, team_id: int, parent: SignalReport) -> SignalReport.Sta)if not statuses:return None+ monitoring_enabled = False+ if SignalReport.Status.MONITORING in statuses:+ monitoring_enabled = (+ get_monitoring_enabled() if get_monitoring_enabled is not None else team_report_monitoring_enabled(team_id)+ )+ statuses = [+ effective_report_status(status, team_id=team_id, monitoring_enabled=monitoring_enabled) for status in statuses+ ]if any(status not in _CLOSED_STATUSES for status in statuses):return Noneif any(status == SignalReport.Status.RESOLVED for status in statuses):@@ -101,15 +116,26 @@ def _rolled_up_status(*, team_id: int, parent: SignalReport) -> SignalReport.Stareturn SignalReport.Status.SUPPRESSED-def _close_parent(*, parent: SignalReport, target: SignalReport.Status) -> bool:+def _close_parent(+ *, parent: SignalReport, target: SignalReport.Status, get_monitoring_enabled: Callable[[], bool] | None = None+) -> bool:"""Apply the rolled-up status to the plan. True when the status actually moved.Archiving a resolved plan is refused for the same reason `_apply_pr_report_state` refuses it:a resolve is a person's verdict, and a later archived step must not undo it."""- if parent.status == target:+ parent_status = effective_report_status(+ parent.status,+ team_id=parent.team_id,+ monitoring_enabled=get_monitoring_enabled()+ if parent.status == SignalReport.Status.MONITORING and get_monitoring_enabled is not None+ else None,+ )+ if parent_status == SignalReport.Status.MONITORING:return False- if target == SignalReport.Status.SUPPRESSED and parent.status == SignalReport.Status.RESOLVED:+ if parent_status == target:+ return False+ if target == SignalReport.Status.SUPPRESSED and parent_status == SignalReport.Status.RESOLVED:return Falsetry:updated_fields = parent.transition_to(target)@@ -142,6 +168,11 @@ def roll_up_plan_parents(*, team_id: int, report_id: str, include_report: bool =Returns the ids of the reports whose status moved, newest ancestor last, which is what thetests assert on."""++ @cache+ def monitoring_enabled() -> bool:+ return team_report_monitoring_enabled(team_id)+frontier = [edge.target_id for edge in outgoing_links(team_id=team_id, report_id=report_id, kinds=(ReportLinkKind.PART_OF,))]@@ -165,7 +196,7 @@ def roll_up_plan_parents(*, team_id: int, report_id: str, include_report: bool =continueif _own_work_in_flight(team_id, parent_id):continue- target = _rolled_up_status(team_id=team_id, parent=parent)+ target = _rolled_up_status(team_id=team_id, parent=parent, get_monitoring_enabled=monitoring_enabled)if target is None:# Undecided now, not undecided forever: a step of this plan may be a plan that# closes later in this same walk. A step can be `part_of` both its plan and@@ -174,9 +205,16 @@ def roll_up_plan_parents(*, team_id: int, report_id: str, include_report: bool =# level bound still bounds the walk.visited.discard(parent_id)continue- if _close_parent(parent=parent, target=target):+ if _close_parent(parent=parent, target=target, get_monitoring_enabled=monitoring_enabled):closed.append(parent_id)- if parent.status not in _CLOSED_STATUSES:+ parent_status = effective_report_status(+ parent.status,+ team_id=team_id,+ monitoring_enabled=monitoring_enabled()+ if parent.status == SignalReport.Status.MONITORING+ else None,+ )+ if parent_status not in _CLOSED_STATUSES:continuenext_frontier.extend(edge.target_iddiff --git a/products/signals/backend/pull_requests.py b/products/signals/backend/pull_requests.pyindex b1cb16d7e935..8d9691c6de55 100644--- a/products/signals/backend/pull_requests.py+++ b/products/signals/backend/pull_requests.py@@ -95,7 +95,7 @@ def link_pull_request(link.save(update_fields=["pull_request"])if (state_source != PullRequestStateSource.LEGACY_ASSIGNMENT- and report.status == SignalReport.Status.RESOLVED+ and report.status in {SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING}and pr.state not in {SignalReportPullRequest.State.MERGED, SignalReportPullRequest.State.CLOSED}):report.save(update_fields=report.transition_to(SignalReport.Status.READY))diff --git a/products/signals/backend/ranking/inventory.py b/products/signals/backend/ranking/inventory.pyindex c7f89a4774fe..f901fa62c7aa 100644--- a/products/signals/backend/ranking/inventory.py+++ b/products/signals/backend/ranking/inventory.py@@ -18,6 +18,7 @@ BORN_VISIBLE_STATUSES = (SignalReport.Status.PENDING_INPUT,SignalReport.Status.IN_PROGRESS,SignalReport.Status.RESOLVED,+ SignalReport.Status.MONITORING,)# Inventory a user can still act on, which the sweep scores. A resolved report stays in the spinediff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.pyindex 086004e24e68..e247d9bcb4d3 100644--- a/products/signals/backend/receivers.py+++ b/products/signals/backend/receivers.py@@ -38,7 +38,9 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)-_SNOOZE_SOURCE_STATUSES = frozenset({SignalReport.Status.READY, SignalReport.Status.RESOLVED})+_SNOOZE_SOURCE_STATUSES = frozenset(+ {SignalReport.Status.READY, SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING}+)# The fields the embedded report document is rendered from. A save touching none of them cannot# change the document, so it skips both the prior-state read and the re-embed.@@ -437,8 +439,8 @@ def arm_pending_checks_when_report_resolved(instance, created=created, update_fields=update_fields, prior_status=prior_status):return- if instance.status != SignalReport.Status.RESOLVED:- if prior_status == SignalReport.Status.RESOLVED:+ if instance.effective_status != SignalReport.Status.RESOLVED:+ if prior_status in {SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING}:from products.signals.backend.report_check_execution import park_report_checks_on_reopenpark_report_checks_on_reopen(team_id=instance.team_id, report_id=str(instance.id), now=timezone.now())@@ -493,7 +495,7 @@ def roll_up_plan_parents_when_report_closes(The roll-up walks the whole ancestor chain itself and marks the reports it moved, so thisreceiver stops on its own writes instead of starting a second walk per level."""- if instance.status not in _PLAN_ROLLUP_CLOSED_STATUSES | _PLAN_ROLLUP_RETRY_STATUSES:+ if instance.effective_status not in _PLAN_ROLLUP_CLOSED_STATUSES | _PLAN_ROLLUP_RETRY_STATUSES:returnif getattr(instance, "_plan_rollup", False):returndiff --git a/products/signals/backend/report_assignments.py b/products/signals/backend/report_assignments.pyindex d254c81cb1e4..d7c2c52a3e8a 100644--- a/products/signals/backend/report_assignments.py+++ b/products/signals/backend/report_assignments.py@@ -316,11 +316,14 @@ def _apply_pr_report_state(report: SignalReport, pr_state: str | None) -> None:target = SignalReport.Status.RESOLVEDelif pr_state == SignalReportAssignment.PrState.CLOSED:target = SignalReport.Status.SUPPRESSED- if target is None or report.status == target:+ if target is None or report.effective_status == target:return# Resolving a report closes its own pull request, and GitHub reports that close as an unmerged# close. Suppressing on it would undo the resolution moments after the person made it.- if target == SignalReport.Status.SUPPRESSED and report.status == SignalReport.Status.RESOLVED:+ if target == SignalReport.Status.SUPPRESSED and report.status in {+ SignalReport.Status.RESOLVED,+ SignalReport.Status.MONITORING,+ }:returntry:updated_fields = report.transition_to(target)@@ -384,7 +387,8 @@ def claim_report(release_claim(assignment, actor)assignment = Noneelse:- if locked_report.status not in CLAIMABLE_REPORT_STATUSES:+ report_status = locked_report.effective_status+ if report_status not in CLAIMABLE_REPORT_STATUSES:existing_prs = set(SignalReportArtefact.objects.filter(team_id=report.team_id, report_id=report.id, pull_request__isnull=False@@ -397,7 +401,7 @@ def claim_report(and all((pr.repository, pr.number) in existing_prs for pr in details)):return assignment- raise ReportClaimConflict(f"Reports with status '{locked_report.status}' cannot be claimed.")+ raise ReportClaimConflict(f"Reports with status '{report_status}' cannot be claimed.")if assignment is not None and not actor_owns_claim(assignment, actor):if not takeover:raise ReportClaimConflict(diff --git a/products/signals/backend/report_check_agent.py b/products/signals/backend/report_check_agent.pyindex c2bd828d1c59..5ef2c3ec1d7c 100644--- a/products/signals/backend/report_check_agent.py+++ b/products/signals/backend/report_check_agent.py@@ -33,6 +33,7 @@ from products.signals.backend.artefact_attribution import ArtefactAttributionfrom products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportCheck, SignalScoutConfigfrom products.signals.backend.report_check_telemetry import capture_report_check_dispatchfrom products.signals.backend.report_checks import AgentCheckConfig, parse_check_config+from products.signals.backend.report_lifecycle import check_monitoring_disabled_organizations, report_status_filterfrom products.signals.backend.scout_harness.run_gates import check_fleet_gates, check_run_in_flight, check_spend_gatesfrom products.signals.backend.scout_harness.team_limits import withheld_skills_for_teamfrom products.skills.backend.models.skills import LLMSkill@@ -181,7 +182,7 @@ def build_check_run_note(check: SignalReportCheck, config: AgentCheckConfig) ->lines.append(f"- Why it was set: {check.rationale.strip()}")lines += [f"- Report: {(check.report.title or 'Untitled')[:MAX_CHECK_NOTE_REPORT_TITLE_LENGTH]} ({check.report_id})",- f"- Report status: {check.report.status}",+ f"- Report status: {check.report.effective_status}",]resolution_note = _latest_resolution_note(check.report)if resolution_note:@@ -296,15 +297,22 @@ def requeue_checks_waiting_on_scout(canonical_team_id: int, skill_name: str, *,if skill_name == FALLBACK_CHECK_SKILL_NAME:lane |= ~Q(config__has_key="skill_name") | Q(config__skill_name=None)team_ids = Team.objects.filter(Q(id=canonical_team_id) | Q(parent_team_id=canonical_team_id)).values("id")- return SignalReportCheck.all_teams.filter(+ candidates = SignalReportCheck.all_teams.filter(lane,team_id__in=team_ids,kind=SignalReportCheck.Kind.AGENT,status=SignalReportCheck.Status.ACTIVE,dispatched_at__isnull=True,- report__status=SignalReport.Status.RESOLVED,next_run_at__gt=now,next_run_at__lte=now + CHECK_DISPATCH_DEFER_AFTER,+ )+ disabled_organizations = check_monitoring_disabled_organizations(candidates)+ return candidates.filter(+ report_status_filter(+ [SignalReport.Status.RESOLVED],+ field="report__status",+ disabled_monitoring_organization_ids=disabled_organizations,+ )).update(next_run_at=now, updated_at=now)@@ -331,10 +339,17 @@ def reactivate_checks_errored_by_scout_pause(status=SignalReportCheck.Status.ERRORED,last_outcome=SignalReportCheck.Outcome.ERRORED,expires_at__gt=now,- report__status=SignalReport.Status.RESOLVED,)if team_id is not None:candidates = candidates.filter(team_id=team_id)+ disabled_organizations = check_monitoring_disabled_organizations(candidates)+ candidates = candidates.filter(+ report_status_filter(+ [SignalReport.Status.RESOLVED],+ field="report__status",+ disabled_monitoring_organization_ids=disabled_organizations,+ )+ )matched: list[SignalReportCheck] = []for check in candidates.only("id", "team_id", "report_id").iterator():@@ -389,7 +404,7 @@ def _claim_for_dispatch(check: SignalReportCheck, now: datetime) -> bool:"""with transaction.atomic():report = SignalReport.objects.select_for_update().filter(id=check.report_id, team_id=check.team_id).first()- if report is None or report.status != SignalReport.Status.RESOLVED:+ if report is None or report.effective_status != SignalReport.Status.RESOLVED:return Falseclaimed = (SignalReportCheck.objects.for_team(check.team_id)diff --git a/products/signals/backend/report_check_authoring.py b/products/signals/backend/report_check_authoring.pyindex 485ed12dd17a..f79a4ce69aff 100644--- a/products/signals/backend/report_check_authoring.py+++ b/products/signals/backend/report_check_authoring.py@@ -48,6 +48,7 @@ from products.signals.backend.report_checks import (soak_minutes_from_gap,validate_metric_check_for_write,)+from products.signals.backend.report_lifecycle import effective_report_statusfrom products.signals.backend.report_metric_access import ReportMetricAccessPolicylogger = structlog.get_logger(__name__)@@ -112,7 +113,7 @@ def create_check(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+ if next_run_at is not None and locked_report.effective_status == SignalReport.Status.RESOLVEDelse now + timedelta(minutes=soak_minutes))metric_ready_at = None@@ -129,7 +130,7 @@ def create_check()if open_checks.count() >= MAX_ACTIVE_CHECKS_PER_REPORT:raise CheckCreationError(f"A report may carry at most {MAX_ACTIVE_CHECKS_PER_REPORT} active checks.")- if locked_report.status == SignalReport.Status.RESOLVED:+ if locked_report.effective_status == SignalReport.Status.RESOLVED:status = SignalReportCheck.Status.ACTIVEnext_run_at = first_run_atif metric_ready_at is not None:@@ -480,7 +481,7 @@ def _arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_at"""pending = list(SignalReportCheck.objects.for_team(team_id)- .filter(report_id=report_id, status=SignalReportCheck.Status.PENDING)+ .filter(report_id=report_id, status=SignalReportCheck.Status.PENDING, expires_at__gt=resolved_at).select_related("report__team"))armed = 0@@ -515,9 +516,19 @@ def _arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_atreturn armed-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,+ monitoring_enabled: bool | 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 report.status != SignalReport.Status.RESOLVED:+ if (+ report is None+ or effective_report_status(report.status, team_id=team_id, monitoring_enabled=monitoring_enabled)+ != SignalReport.Status.RESOLVED+ ):return 0return _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 2101b58c5a13..f8a1994684ff 100644--- a/products/signals/backend/report_check_execution.py+++ b/products/signals/backend/report_check_execution.py@@ -20,9 +20,10 @@ from collections.abc import Iterablefrom datetime import datetime, timedeltafrom functools import partialfrom typing import cast+from uuid import UUIDfrom django.db import transaction-from django.db.models import F, Window+from django.db.models import Exists, F, OuterRef, Q, Windowfrom django.db.models.functions import RowNumberfrom django.utils import timezone@@ -70,6 +71,7 @@ from products.signals.backend.report_checks import (parse_check_config,soak_minutes_from_gap,)+from products.signals.backend.report_lifecycle import check_monitoring_disabled_organizations, report_status_filterfrom products.signals.backend.report_metric_refresh import measure_metricfrom products.signals.backend.report_metrics import validate_live_metric_query@@ -343,7 +345,7 @@ def record_check_verdict(with transaction.atomic():report = SignalReport.objects.select_for_update().filter(id=check.report_id, team_id=check.team_id).first()- if report is None or report.status != SignalReport.Status.RESOLVED:+ if report is None or report.effective_status != SignalReport.Status.RESOLVED:returncurrent = (SignalReportCheck.objects.for_team(check.team_id)@@ -439,7 +441,7 @@ def _should_resurface(check: SignalReportCheck, verdict: CheckVerdict) -> bool:return (verdict.outcome == "failed"and check.kind == SignalReportCheck.Kind.METRIC_THRESHOLD- and check.report.status == SignalReport.Status.RESOLVED+ and check.report.effective_status == SignalReport.Status.RESOLVED)@@ -572,9 +574,17 @@ def _report_expired_checks(overdue: list[SignalReportCheck]) -> None:logger.exception("signals.report_check.expired_report_failed")-def _park_checks(active: Iterable[SignalReportCheck], now: datetime) -> int:+def _park_checks(active: Iterable[SignalReportCheck], now: datetime, *, resolved_status_filter: Q | None = None) -> int:parked = 0+ team_filters: dict[int, Q] = {}for check in active:+ status_filter = resolved_status_filter+ if 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"+ )+ status_filter = team_filters[check.team_id]soak_minutes = check.soak_minutesif soak_minutes is None:# A legacy row's retry or recurring date no longer identifies its initial soak.@@ -586,7 +596,7 @@ def _park_checks(active: Iterable[SignalReportCheck], now: datetime) -> int:parked += (SignalReportCheck.objects.for_team(check.team_id).filter(id=check.id, status=SignalReportCheck.Status.ACTIVE)- .exclude(report__status=SignalReport.Status.RESOLVED)+ .exclude(status_filter).update(status=SignalReportCheck.Status.PENDING,soak_minutes=soak_minutes,@@ -609,7 +619,9 @@ def park_report_checks_on_reopen(*, team_id: int, report_id: str, now: datetime))-def park_checks_on_unresolved_reports(now: datetime) -> int:+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.A check can be active on an unresolved report in three ways: a report that left `resolved`@@ -622,20 +634,31 @@ def park_checks_on_unresolved_reports(now: datetime) -> int:A dated row keeps the gap its author left as its soak. The error streak and any open dispatchare cleared, so retry accounting starts again after the next resolve."""+ candidates = SignalReportCheck.all_teams.filter(status=SignalReportCheck.Status.ACTIVE)+ if disabled_monitoring_organization_ids is None:+ disabled_monitoring_organization_ids = check_monitoring_disabled_organizations(candidates)+ status_filter = report_status_filter(+ [SignalReport.Status.RESOLVED],+ field="report__status",+ disabled_monitoring_organization_ids=disabled_monitoring_organization_ids,+ )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- ]+ candidates.exclude(status_filter).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)+ parked = _park_checks(active, now, resolved_status_filter=status_filter)if parked:logger.info("signals.report_check.parked_on_unresolved_report", parked=parked)return parked-def collect_due_checks(now: datetime, *, limit: int = MAX_CHECK_RUNS_PER_TICK) -> list[SignalReportCheck]:+def collect_due_checks(+ now: datetime,+ *,+ limit: int = MAX_CHECK_RUNS_PER_TICK,+ disabled_monitoring_organization_ids: frozenset[UUID] | None = None,+) -> list[SignalReportCheck]:"""The checks to run this tick, most overdue first and capped per team.The horizon is read here rather than trusted to the expiry sweep. That sweep is bounded per@@ -643,15 +666,21 @@ def collect_due_checks(now: datetime, *, limit: int = MAX_CHECK_RUNS_PER_TICK) -sweep would otherwise let a row measure after the horizon it was supposed to retire at."""+ eligible_checks = SignalReportCheck.all_teams.filter(+ status=SignalReportCheck.Status.ACTIVE, next_run_at__lte=now, expires_at__gt=now+ )+ if disabled_monitoring_organization_ids is None:+ disabled_monitoring_organization_ids = check_monitoring_disabled_organizations(eligible_checks)candidates = (- SignalReportCheck.all_teams.filter(- status=SignalReportCheck.Status.ACTIVE,- next_run_at__lte=now,- expires_at__gt=now,+ eligible_checks.filter(+ report_status_filter(+ [SignalReport.Status.RESOLVED],+ field="report__status",+ disabled_monitoring_organization_ids=disabled_monitoring_organization_ids,+ ),# A check re-measures a fix, so it runs only while its report is resolved. The park step# moves any other active row back to `pending`; this filter keeps a row it has not reached# yet out of the tick.- report__status=SignalReport.Status.RESOLVED,).select_related("report", "report__team", "team__organization")# Rank each team's rows against its own, then read those ranks in order, so every team's@@ -679,6 +708,31 @@ def collect_due_checks(now: datetime, *, limit: int = MAX_CHECK_RUNS_PER_TICK) -return due+def _arm_disabled_monitoring_checks(now: datetime, *, disabled_monitoring_organization_ids: frozenset[UUID]) -> None:+ from products.signals.backend.report_check_authoring import arm_pending_checks++ pending_checks = SignalReportCheck.all_teams.filter(+ team_id=OuterRef("team_id"),+ report_id=OuterRef("id"),+ status=SignalReportCheck.Status.PENDING,+ expires_at__gt=now,+ )+ reports = (+ SignalReport.objects.filter(+ report_status_filter(+ [SignalReport.Status.RESOLVED],+ disabled_monitoring_organization_ids=disabled_monitoring_organization_ids,+ ),+ Exists(pending_checks),+ status=SignalReport.Status.MONITORING,+ )+ .only("id", "status", "team_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)++def run_due_report_checks(*, now: datetime | None = None, limit: int = MAX_CHECK_RUNS_PER_TICK) -> CheckRunSummary:"""Expire what timed out, park what lost its resolve, then advance every due check by one step.@@ -689,7 +743,12 @@ def run_due_report_checks(*, now: datetime | None = None, limit: int = MAX_CHECKnow = now or timezone.now()expired = expire_overdue_checks(now)- park_checks_on_unresolved_reports(now)+ candidate_checks = SignalReportCheck.all_teams.filter(+ Q(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)+ park_checks_on_unresolved_reports(now, disabled_monitoring_organization_ids=disabled_organizations)deadline = time.monotonic() + CHECK_RUN_TIME_BUDGET_SECONDScounts: dict[str, int] = {"passed": 0,@@ -700,7 +759,7 @@ def run_due_report_checks(*, now: datetime | None = None, limit: int = MAX_CHECK"deferred": 0,"cancelled": 0,}- for check in collect_due_checks(now, limit=limit):+ for check in collect_due_checks(now, limit=limit, disabled_monitoring_organization_ids=disabled_organizations):if time.monotonic() >= deadline:breakif check.kind == SignalReportCheck.Kind.AGENT:diff --git a/products/signals/backend/report_lifecycle.py b/products/signals/backend/report_lifecycle.pynew file mode 100644index 000000000000..61694a791967--- /dev/null+++ b/products/signals/backend/report_lifecycle.py@@ -0,0 +1,72 @@+from collections.abc import Collection, Iterable+from typing import TYPE_CHECKING, Literal+from uuid import UUID++from django.db.models import Q++from products.signals.backend.models import SignalReport+from products.signals.backend.report_content_gates import (+ organization_report_monitoring_enabled,+ team_report_monitoring_enabled,+)++if TYPE_CHECKING:+ from django.db.models import QuerySet++ from products.signals.backend.models import SignalReportCheck+++def effective_report_status(status: str, *, team_id: int, monitoring_enabled: bool | None = None) -> str:+ if status != SignalReport.Status.MONITORING:+ return status+ enabled = team_report_monitoring_enabled(team_id) if monitoring_enabled is None else monitoring_enabled+ return status if enabled else SignalReport.Status.RESOLVED+++def disabled_monitoring_organizations(organization_ids: Iterable[UUID]) -> frozenset[UUID]:+ return frozenset(+ organization_id+ for organization_id in set(organization_ids)+ if not organization_report_monitoring_enabled(organization_id)+ )+++def check_monitoring_disabled_organizations(checks: "QuerySet[SignalReportCheck]") -> frozenset[UUID]:+ organization_ids = (+ checks.filter(report__status=SignalReport.Status.MONITORING)+ .order_by()+ .values_list("report__team__organization_id", flat=True)+ .distinct()+ )+ return disabled_monitoring_organizations(organization_ids)+++def report_status_filter(+ statuses: Collection[str],+ *,+ team_id: int | None = None,+ field: Literal["status", "report__status"] = "status",+ disabled_monitoring_organization_ids: Collection[UUID] | None = None,+) -> Q:+ if field == "status":+ result = Q(status__in=statuses)+ monitoring = Q(status=SignalReport.Status.MONITORING)+ elif field == "report__status":+ result = Q(report__status__in=statuses)+ monitoring = Q(report__status=SignalReport.Status.MONITORING)+ else:+ raise ValueError("Unsupported report status field.")+ if SignalReport.Status.RESOLVED not in statuses:+ return result+ if team_id is not None:+ if not team_report_monitoring_enabled(team_id):+ result |= monitoring+ return result+ if disabled_monitoring_organization_ids is None:+ raise ValueError("Cross-team status filters require a scoped Monitoring gate snapshot.")+ organizations = (+ Q(team__organization_id__in=disabled_monitoring_organization_ids)+ if field == "status"+ else Q(report__team__organization_id__in=disabled_monitoring_organization_ids)+ )+ return result | (monitoring & organizations)diff --git a/products/signals/backend/report_merge.py b/products/signals/backend/report_merge.pyindex 2f6fb06aabff..73d6310b5150 100644--- a/products/signals/backend/report_merge.py+++ b/products/signals/backend/report_merge.py@@ -359,9 +359,10 @@ def _requested_source_ids(source_ids: list[str], *, survivor_id: str) -> list[stdef _mergeable_source(report: SignalReport | None, requested_id: str) -> SignalReport:if report is None:raise ReportMergeError(f"Report {requested_id} was not found in this project.")- if report.status not in MERGEABLE_STATUSES:+ report_status = report.effective_status+ if report_status not in MERGEABLE_STATUSES:raise ReportMergeError(- f"Report {requested_id} is {report.status} and cannot be merged. Only a live report can be a source."+ f"Report {requested_id} is {report_status} and cannot be merged. Only a live report can be a source.")# The signal move reads one bounded page and never pages or retries, so a source past the cap# would leave the remainder pointing at itself while the survivor's counters already include@@ -400,9 +401,10 @@ def merge_reports(if str(survivor.id) not in locked:raise ReportMergeError("The report to merge into was not found in this project.")survivor = locked[str(survivor.id)]- if survivor.status not in MERGEABLE_STATUSES:+ survivor_status = survivor.effective_status+ if survivor_status not in MERGEABLE_STATUSES:raise ReportMergeError(- f"The report to merge into is {survivor.status} and cannot take on duplicates. "+ f"The report to merge into is {survivor_status} and cannot take on duplicates. ""Only a live report can be the survivor.")sources = [_mergeable_source(locked.get(source_id), source_id) for source_id in ordered_ids]diff --git a/products/signals/backend/scout_harness/inactivity.py b/products/signals/backend/scout_harness/inactivity.pyindex d0a4beabe02a..03822c2e0555 100644--- a/products/signals/backend/scout_harness/inactivity.py+++ b/products/signals/backend/scout_harness/inactivity.py@@ -130,6 +130,7 @@ _ENGAGEMENT_ARTEFACT_TYPES: frozenset[str] = SignalReportArtefact.LOG_ARTEFACT_T_ENGAGED_REPORT_STATUSES: frozenset[str] = frozenset({SignalReport.Status.RESOLVED,+ SignalReport.Status.MONITORING,SignalReport.Status.DELETED,})diff --git a/products/signals/backend/scout_harness/tools/checks.py b/products/signals/backend/scout_harness/tools/checks.pyindex b4d83c1b1785..adca6bd61508 100644--- a/products/signals/backend/scout_harness/tools/checks.py+++ b/products/signals/backend/scout_harness/tools/checks.py@@ -125,7 +125,7 @@ def _resolve_dispatched_check(team: Team, run: SignalScoutRun, check_id: str) ->raise InvalidCheckResultError(f"check {check_id} is not due until {check.next_run_at.isoformat()}, so it is not yours to close yet")- pause_reason = _pause_reason(check, check.report.status, now)+ pause_reason = _pause_reason(check, check.report.effective_status, now)if pause_reason is not None:raise InvalidCheckResultError(f"check {check_id} is paused because {pause_reason}, so nothing is owed on it"@@ -358,7 +358,7 @@ def create_report_check()except CheckCreationError as error:raise InvalidCheckWriteError(str(error)) from None- return _summarize(check, report.status)+ return _summarize(check, report.effective_status)def list_report_checks(*, team: Team, report_id: str) -> list[ScoutCheckSummary]:@@ -372,7 +372,8 @@ def list_report_checks(*, team: Team, report_id: str) -> list[ScoutCheckSummary])run_ids = _dispatched_run_ids(team.parent_team_id or team.id, checks)now = timezone.now()- return [_summarize(check, report.status, run_ids.get(str(check.id)), now) for check in checks]+ report_status = report.effective_status+ return [_summarize(check, report_status, run_ids.get(str(check.id)), now) for check in checks]def _run_attribution(run: SignalScoutRun) -> ArtefactAttribution:@@ -396,4 +397,4 @@ def cancel_report_check(*, team: Team, run: SignalScoutRun, check_id: str) -> Scraise InvalidCheckWriteError(f"check {check_id} not found")if not cancel_check(check, reason="stopped_by_scout", attribution=_run_attribution(run)):raise InvalidCheckWriteError(f"check {check_id} already finished as `{check.status}` and cannot be cancelled")- return _summarize(check, check.report.status)+ return _summarize(check, check.report.effective_status)diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 1e660c561c66..c930dbe88f57 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -8,6 +8,7 @@ from django.db.models import TextChoicesfrom django.utils import timezoneimport structlog+from drf_spectacular.extensions import OpenApiSerializerExtensionfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field, extend_schema_serializerfrom rest_framework import serializers@@ -49,6 +50,9 @@ from products.warehouse_sources.backend.facade.models import ExternalDataSchemafrom products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatusif TYPE_CHECKING:+ from drf_spectacular.openapi import AutoSchema+ from drf_spectacular.utils import Direction+from products.signals.backend.implementation_pr import ImplementationPrfrom products.signals.backend.report_claims import ReportClaim@@ -1227,7 +1231,26 @@ class SignalReportPriorityUpdateSerializer(serializers.Serializer):)+class SignalReportSerializerExtension(OpenApiSerializerExtension):+ target_class = "products.signals.backend.serializers.SignalReportSerializer"+ match_subclasses = True++ def map_serializer(self, auto_schema: "AutoSchema", direction: "Direction") -> dict[str, object]:+ schema: dict[str, object] = auto_schema._map_serializer(self.target, direction, bypass_extensions=True)+ required = schema.get("required")+ if isinstance(required, list):+ # The disabled rollout omits this timestamp, so responses cannot require it.+ schema["required"] = [name for name in required if name != "monitoring_started_at"]+ return schema++class SignalReportSerializer(serializers.ModelSerializer):+ monitoring_started_at = serializers.DateTimeField(+ read_only=True,+ required=False,+ allow_null=True,+ help_text="Original implementation-complete time for this Monitoring period, null before entry. Present only when Monitoring is enabled.",+ )status = serializers.SerializerMethodField(help_text="Current report status. Monitoring reads as resolved when its rollout is disabled.",)@@ -1397,6 +1420,7 @@ class SignalReportSerializer(serializers.ModelSerializer):"summary","summary_lead","status",+ "monitoring_started_at","total_weight", # Used for priority scoring"signal_count", # Used for occurrence count"signals_at_run", # Snooze threshold: re-promote when signal_count >= this value@@ -1445,14 +1469,23 @@ class SignalReportSerializer(serializers.ModelSerializer):},}- @extend_schema_field(serializers.ChoiceField(choices=SignalReport.Status.choices))- def get_status(self, obj: SignalReport) -> str:- if obj.status != SignalReport.Status.MONITORING:- return obj.status+ def _monitoring_enabled(self, obj: SignalReport) -> bool:enabled_by_team = cast(dict[int, bool], self.context.setdefault("report_monitoring_enabled_by_team", {}))if obj.team_id not in enabled_by_team:enabled_by_team[obj.team_id] = team_report_monitoring_enabled(obj.team_id)- return obj.status if enabled_by_team[obj.team_id] else SignalReport.Status.RESOLVED+ return enabled_by_team[obj.team_id]++ def to_representation(self, instance: SignalReport) -> dict[str, object]:+ representation = super().to_representation(instance)+ if not self._monitoring_enabled(instance):+ representation.pop("monitoring_started_at", None)+ return representation++ @extend_schema_field(serializers.ChoiceField(choices=SignalReport.Status.choices))+ def get_status(self, obj: SignalReport) -> str:+ if obj.status == SignalReport.Status.MONITORING and not self._monitoring_enabled(obj):+ return SignalReport.Status.RESOLVED+ return obj.statusdef _get_actionability_artefact_data(self, obj: SignalReport) -> dict | None:prefetched = getattr(obj, "prefetched_actionability_artefacts", None)@@ -1744,7 +1777,7 @@ class SignalReportSerializer(serializers.ModelSerializer):@extend_schema_field(serializers.ChoiceField(choices=SignalReportWorkState.choices))def get_work_state(self, obj: SignalReport) -> str:- if self.get_status(obj) == SignalReport.Status.RESOLVED:+ if obj.status in {SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING}:return "done"if any(pr.state in {"open", "draft", "unknown"} for pr in self._get_pull_requests(obj)):return "in_review"diff --git a/products/signals/backend/supersession.py b/products/signals/backend/supersession.pyindex 05108d81beea..e475112ccc28 100644--- a/products/signals/backend/supersession.py+++ b/products/signals/backend/supersession.py@@ -413,7 +413,13 @@ def reconcile_replacement(team_id: int, replacement_id: str) -> bool:run = tasks_facade.get_task_run(content.run_id, team_id)claim = get_active_claim(team_id=team_id, report_id=report.id)if (- report.status in {SignalReport.Status.DELETED, SignalReport.Status.SUPPRESSED, SignalReport.Status.RESOLVED}+ report.status+ in {+ SignalReport.Status.DELETED,+ SignalReport.Status.SUPPRESSED,+ SignalReport.Status.RESOLVED,+ SignalReport.Status.MONITORING,+ }or not claimor claim.claim_id != replacement.claim_idor claim.actor_task_id != replacement.task_iddiff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.pyindex d6615519e390..2672b7bc1a1e 100644--- a/products/signals/backend/temporal/agentic/report.py+++ b/products/signals/backend/temporal/agentic/report.py@@ -70,6 +70,7 @@ from products.signals.backend.report_generation.reviewer_telemetry import (capture_suggested_reviewers_unresolved,)from products.signals.backend.report_generation.select_repo import RepoSelectionResult+from products.signals.backend.report_lifecycle import report_status_filterfrom products.signals.backend.report_metrics import REPORT_METRIC_GOAL_FIELDS, ReportMetric, metric_batch_errorfrom products.signals.backend.report_steering import ReportSteering, load_research_steeringfrom products.signals.backend.source_suggestions import unused_suggestable_products@@ -322,18 +323,24 @@ async def _load_resolved_report_context(team_id: int, report_id: str) -> tuple[srelated_ids = recurrence_ids or related_idsif not related_ids:return None, None+ closed_filter = await database_sync_to_async(report_status_filter)(+ [SignalReport.Status.RESOLVED, SignalReport.Status.SUPPRESSED], team_id=team_id+ )async for candidate in (SignalReport.objects.filter(+ closed_filter,id__in=related_ids,team_id=team_id,- status__in=(SignalReport.Status.RESOLVED, SignalReport.Status.SUPPRESSED),).only("title", "summary", "status", "team").order_by("-created_at")):if await database_sync_to_async(_is_safety_suppressed, thread_sensitive=False)(str(candidate.id), team_id):continue- if candidate.status == SignalReport.Status.RESOLVED:+ if (+ await database_sync_to_async(lambda report=candidate: report.effective_status)()+ == SignalReport.Status.RESOLVED+ ):return candidate.title, candidate.summary# Only an archived candidate costs the dismissal read, and the newest match wins, so the# loop stops at the first one rather than reading every link.diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex 66175927d16b..fa4c3c4ac5c2 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -661,7 +661,10 @@ def _has_completed_research(report: SignalReport) -> bool:"""if report.researched_signal_count == 0:return False- return report.signals_researched is not None or report.status == SignalReport.Status.READY+ return report.signals_researched is not None or report.status in {+ SignalReport.Status.READY,+ SignalReport.Status.MONITORING,+ }def _researched_summary(team_id: int, report_id: str) -> str | None:@@ -869,7 +872,7 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As# has), so we start a fresh report and link it to the resolved report via a# `recurrence_of` report link. The research agent is later handed that# resolved report as context (see report.py).- if report.status == SignalReport.Status.RESOLVED or dismissed_as_fixed_at is not None:+ if report.effective_status == SignalReport.Status.RESOLVED or dismissed_as_fixed_at is not None:parent_report = reportinherit_content = not _is_safety_suppressed(str(parent_report.id), input.team_id)report = SignalReport.objects.create(diff --git a/products/signals/backend/test/test_assign_and_emit_signal.py b/products/signals/backend/test/test_assign_and_emit_signal.pyindex a93b68fe7200..df2a2eba36e8 100644--- a/products/signals/backend/test/test_assign_and_emit_signal.py+++ b/products/signals/backend/test/test_assign_and_emit_signal.py@@ -388,13 +388,21 @@ async def test_ready_repromotes_to_candidate_on_a_bucket_regardless_of_weight(at@pytest.mark.asyncio@pytest.mark.django_db-async def test_resolved_match_spawns_new_report_and_leaves_resolved_untouched(ateam):- """A signal that would group into a RESOLVED report must not reopen it. Instead a fresh- POTENTIAL report is created and symmetrically linked to the resolved one via related_to- artefacts, and the resolved report keeps its status and signal count."""+ "report_status,flag_result,recurs",+ [+ (SignalReport.Status.RESOLVED, False, True),+ (SignalReport.Status.MONITORING, False, True),+ (SignalReport.Status.MONITORING, RuntimeError("flag service unavailable"), True),+ (SignalReport.Status.MONITORING, True, False),+ ],+)+async def test_resolved_match_spawns_new_report_and_leaves_resolved_untouched(+ ateam: Team, report_status: str, flag_result: bool | Exception, recurs: bool+) -> None:resolved = await database_sync_to_async(SignalReport.objects.create)(team=ateam,- status=SignalReport.Status.RESOLVED,+ status=report_status,total_weight=1.5,signal_count=2,title="original title",@@ -402,7 +410,21 @@ async def test_resolved_match_spawns_new_report_and_leaves_resolved_untouched(at)input_ = _build_input(ateam.id, _existing_match(str(resolved.id)), weight=WEIGHT_THRESHOLD)- result = await assign_and_emit_signal_activity(input_)+ 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,+ ):+ result = await assign_and_emit_signal_activity(input_)++ if not recurs:+ assert result.report_id == str(resolved.id)+ refreshed = await database_sync_to_async(SignalReport.objects.get)(id=resolved.id)+ assert refreshed.status == SignalReport.Status.MONITORING+ assert refreshed.signal_count == 3+ assert refreshed.title == "original title"+ assert refreshed.summary == "original summary"+ return# A brand-new report was created, not the resolved one.assert result.report_id != str(resolved.id)@@ -422,7 +444,7 @@ async def test_resolved_match_spawns_new_report_and_leaves_resolved_untouched(at# The resolved report is untouched — not reopened, no new signal counted.refreshed_resolved = await database_sync_to_async(SignalReport.objects.get)(id=resolved.id)- assert refreshed_resolved.status == SignalReport.Status.RESOLVED+ assert refreshed_resolved.status == report_statusassert refreshed_resolved.signal_count == 2diff --git a/products/signals/backend/test/test_briefing_reports.py b/products/signals/backend/test/test_briefing_reports.pyindex 234f4f3176c4..40fda307936e 100644--- a/products/signals/backend/test/test_briefing_reports.py+++ b/products/signals/backend/test/test_briefing_reports.py@@ -96,8 +96,24 @@ class TestReportsForBriefing(BaseTest):)SignalReportArtefact.objects.filter(pk=artefact.pk).update(created_at=timezone.now() - age)- def test_report_details_keep_only_metrics_with_a_saved_snapshot(self) -> None:+ @parameterized.expand(+ [+ ("ready", SignalReport.Status.READY, False, "ready"),+ ("monitoring_enabled", SignalReport.Status.MONITORING, True, "monitoring"),+ ("monitoring_disabled", SignalReport.Status.MONITORING, False, "resolved"),+ (+ "monitoring_unavailable",+ SignalReport.Status.MONITORING,+ RuntimeError("flag service unavailable"),+ "resolved",+ ),+ ]+ )+ def test_report_details_keep_only_metrics_with_a_saved_snapshot(+ self, _name: str, status: str, flag_result: bool | Exception, expected_status: str+ ) -> None:report = self._urgent_report("Checkout fails")+ report.status = statusquery = trends_metric_query(series=[{"kind": "EventsNode", "event": "$exception", "math": "dau"}], date_from="-14d")@@ -123,7 +139,10 @@ class TestReportsForBriefing(BaseTest):{"chart_id": "broken"},{"chart_id": "form-errors", "title": "Form errors", "query": query},]- report.save(update_fields=["metrics", "charts", "summary"])+ report.save(update_fields=["status", "metrics", "charts", "summary"])+ other_reports = [self._urgent_report(f"Other report {index}") for index in range(2)]+ SignalReport.objects.filter(id__in=[other.id for other in other_reports]).update(status=status)+ report_ids = [str(item.id) for item in [report, *other_reports]]viewer = ReportMetricAccessPolicy(request=cast(Request, SimpleNamespace(user=self.user, successful_authenticator=None)), team=self.team@@ -137,7 +156,28 @@ class TestReportsForBriefing(BaseTest):)SignalReportArtefact.objects.filter(pk=cross_team.pk).update(created_at=timezone.now() + timedelta(hours=1))- [details] = report_details(team_id=self.team.id, report_ids=[str(report.id)], metric_access=viewer)+ 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,+ CaptureQueriesContext(connection) as queries,+ ):+ results = report_details(team_id=self.team.id, report_ids=report_ids, metric_access=viewer)+ assert len(results) == len(report_ids)+ assert {item.status for item in results} == {expected_status}+ team_gate_reads = [+ query+ for query in queries+ if query["sql"].startswith("SELECT")+ and 'FROM "posthog_team"' in query["sql"]+ and '"organization_id"' in query["sql"]+ ]+ expected_gate_reads = int(status == SignalReport.Status.MONITORING)+ assert evaluate.call_count == expected_gate_reads+ assert len(team_gate_reads) == expected_gate_reads+ details = next(item for item in results if item.report_id == str(report.id))# Without a viewer the policy reads nothing, so the briefing must hide every metric, as the Inbox does.[unreadable] = report_details(team_id=self.team.id,@@ -145,7 +185,7 @@ class TestReportsForBriefing(BaseTest):metric_access=ReportMetricAccessPolicy(request=None, team=self.team),)- assert (details.status, details.priority, details.pull_request_state) == ("ready", "P0", None)+ assert (details.status, details.priority, details.pull_request_state) == (expected_status, "P0", None)assert [(m.metric_id, m.value, m.series, m.query) for m in details.metrics] == [("measured", 17, [3.0, 9.0, 17.0], query)]diff --git a/products/signals/backend/test/test_feedback_scout_notes.py b/products/signals/backend/test/test_feedback_scout_notes.pyindex e8700725d1c0..2f0cfa25a642 100644--- a/products/signals/backend/test/test_feedback_scout_notes.py+++ b/products/signals/backend/test/test_feedback_scout_notes.py@@ -195,7 +195,7 @@ class TestFeedbackScoutNotes(APIBaseTest):("ready", "positive", "negative", SignalReport.Status.READY, False, True),("suppressed", "negative", "positive", SignalReport.Status.SUPPRESSED, False, True),("monitoring_disabled", "positive", "negative", SignalReport.Status.MONITORING, False, True),- ("monitoring_enabled", "positive", "negative", SignalReport.Status.MONITORING, True, False),+ ("monitoring_enabled", "positive", "negative", SignalReport.Status.MONITORING, True, True),])def test_feedback_can_be_read_changed_and_cleared(diff --git a/products/signals/backend/test/test_plan_rollup.py b/products/signals/backend/test/test_plan_rollup.pyindex 7a5566a56b0d..16c8a674869c 100644--- a/products/signals/backend/test/test_plan_rollup.py+++ b/products/signals/backend/test/test_plan_rollup.py@@ -5,6 +5,7 @@ from posthog.test.base import BaseTestfrom unittest.mock import patchfrom django.db import OperationalError, connection, transaction+from django.utils import timezonefrom parameterized import parameterized@@ -43,7 +44,12 @@ class TestPlanRollup(BaseTest):def _close(self, report: SignalReport, status: str) -> None:with self.captureOnCommitCallbacks(execute=True):- report.save(update_fields=report.transition_to(SignalReport.Status(status)))+ report.save(+ update_fields=report.transition_to(+ SignalReport.Status(status),+ monitoring_started_at=timezone.now() if status == SignalReport.Status.MONITORING else None,+ )+ )def _attach_pull_request(self, report: SignalReport, number: int, state: str) -> SignalReportPullRequest:pr = SignalReportPullRequest.objects.create(@@ -68,16 +74,25 @@ class TestPlanRollup(BaseTest):("both_resolved", ["resolved", "resolved"], SignalReport.Status.RESOLVED),("mixed_with_a_resolve", ["resolved", "suppressed"], SignalReport.Status.RESOLVED),("all_suppressed", ["suppressed", "suppressed"], SignalReport.Status.SUPPRESSED),+ (+ "monitoring_parent_needs_manual_verification",+ ["resolved"],+ SignalReport.Status.MONITORING,+ SignalReport.Status.MONITORING,+ ),])- def test_a_plan_takes_the_verdict_of_its_steps(self, _name: str, child_statuses: list[str], expected: str):- parent = self._report("plan")+ def test_a_plan_takes_the_verdict_of_its_steps(+ self, _name: str, child_statuses: list[str], expected: str, parent_status: str = SignalReport.Status.READY+ ) -> None:+ parent = self._report("plan", status=parent_status)children = [self._report(f"step-{index}") for index in range(len(child_statuses))]for child in children:self._part_of(child, parent)- for child, status in zip(children, child_statuses):- self._close(child, status)+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):+ for child, status in zip(children, child_statuses):+ self._close(child, status)parent.refresh_from_db()assert parent.status == expected@@ -93,6 +108,32 @@ class TestPlanRollup(BaseTest):parent.refresh_from_db()assert parent.status == SignalReport.Status.READY+ @parameterized.expand(+ [("enabled", True), ("disabled", False), ("unavailable", RuntimeError("flag service unavailable"))]+ )+ def test_monitoring_steps_only_count_as_resolved_when_the_rollout_is_disabled(+ self, _name: str, flag_result: bool | Exception+ ) -> None:+ parent = self._report("plan")+ children = [self._report(f"step {index}") for index in range(3)]+ for child in children:+ self._part_of(child, parent)+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):+ for child in children:+ self._close(child, SignalReport.Status.MONITORING)+ parent.refresh_from_db()+ assert parent.status == SignalReport.Status.READY+ 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 self.captureOnCommitCallbacks(execute=True):+ roll_up_plan_parents(team_id=self.team.id, report_id=str(children[0].id))+ assert evaluate.call_count == 1+ parent.refresh_from_db()+ assert parent.status == (SignalReport.Status.READY if flag_result is True else SignalReport.Status.RESOLVED)+def test_a_merged_pull_request_on_the_last_step_closes_the_plan(self):parent = self._report("plan")child = self._report("step")diff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.pyindex 82f11b910092..af4f84eb5d07 100644--- a/products/signals/backend/test/test_report_checks.py+++ b/products/signals/backend/test/test_report_checks.py@@ -6,7 +6,9 @@ import time_machinefrom posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, patch+from django.db import connectionfrom django.test import SimpleTestCase+from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom parameterized import parameterized@@ -17,7 +19,7 @@ from rest_framework.test import APIRequestFactory, force_authenticatefrom temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.constants import AvailableFeature-from posthog.models import PropertyDefinition, Team+from posthog.models import Organization, PropertyDefinition, Teamfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value@@ -44,6 +46,7 @@ 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,@@ -56,6 +59,7 @@ from products.signals.backend.report_check_execution import (evaluate_check_value,expire_overdue_checks,measure_check,+ park_report_checks_on_reopen,record_check_verdict,resolve_check_query,run_due_report_checks,@@ -763,6 +767,67 @@ class TestReportCheckExecution(APIBaseTest):assert collect_due_checks(timezone.now()) == []+ def test_a_tick_reuses_gate_discovery_and_ignores_monitoring_without_candidate_checks(self) -> None:+ now = timezone.now()+ unrelated_org = Organization.objects.create(name="Other monitoring organization")+ unrelated_team = Team.objects.create(organization=unrelated_org)+ unrelated_report = SignalReport.objects.create(+ team=unrelated_team, status=SignalReport.Status.MONITORING, title="Other verification"+ )+ SignalReportCheck.objects.for_team(unrelated_team.id).create(+ team=unrelated_team,+ report=unrelated_report,+ title="Cancelled verification",+ kind=SignalReportCheck.Kind.METRIC_THRESHOLD,+ config=_threshold_config(),+ status=SignalReportCheck.Status.CANCELLED,+ next_run_at=now,+ expires_at=now + timedelta(days=30),+ )+ with patch(+ "products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True+ ) as evaluate:+ run_due_report_checks(now=now)+ evaluate.assert_not_called()++ checks = [self._check() for _ in range(3)]+ SignalReport.objects.filter(team_id=self.team.id, id=self.report.id).update(+ status=SignalReport.Status.MONITORING, monitoring_started_at=now+ )+ with (+ patch(+ "products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True+ ) as evaluate,+ patch(_MEASURE) as measure,+ ):+ run_due_report_checks(now=now)+ measure.assert_not_called()+ 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++ def test_parking_a_report_batch_reads_its_team_gate_once(self) -> None:+ checks = [self._check() for _ in range(3)]+ SignalReport.objects.filter(team_id=self.team.id, id=self.report.id).update(status=SignalReport.Status.READY)+ with (+ patch(+ "products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True+ ) as evaluate,+ CaptureQueriesContext(connection) as queries,+ ):+ assert park_report_checks_on_reopen(+ team_id=self.team.id, report_id=str(self.report.id), now=timezone.now()+ ) == len(checks)+ team_reads = [+ query for query in queries if query["sql"].startswith("SELECT") and 'FROM "posthog_team"' in query["sql"]+ ]+ assert len(team_reads) == 1+ assert evaluate.call_count == 1+ for check in checks:+ check.refresh_from_db()+ assert check.status == SignalReportCheck.Status.PENDING+@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()@@ -1884,15 +1949,33 @@ class TestCheckResultTool(APIBaseTest):{"config": {"instructions": "x", "skill_name": _OTHER_SKILL}},True,),+ ("monitoring_disabled", {"dispatched_at": None, "next_run_at": timezone.now()}, False, False),+ (+ "monitoring_unavailable",+ {"dispatched_at": None, "next_run_at": timezone.now()},+ False,+ RuntimeError("flag service unavailable"),+ ),])- def test_a_check_this_run_may_answer_is_recorded(self, _name, overrides, bind_run) -> None:+ def test_a_check_this_run_may_answer_is_recorded(+ self, _name, overrides, bind_run, flag_result: bool | Exception | None = None+ ) -> None:+ if flag_result is not None:+ SignalReport.objects.filter(id=self.report.id).update(status=SignalReport.Status.MONITORING)check = self._check(**overrides)if bind_run:self.scout_run.metadata = {"check_id": str(check.id)}self.scout_run.save(update_fields=["metadata"])- result = self._record(check)+ 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,+ ):+ (listed,) = list_report_checks(team=self.team, report_id=str(self.report.id))+ assert listed.run_state == ("due" if check.dispatched_at is None else "queued")+ result = self._record(check)assert result.check_status == SignalReportCheck.Status.FAILED@@ -1901,6 +1984,7 @@ class TestCheckResultTool(APIBaseTest):("its_report_is_ready", SignalReport.Status.READY, timedelta(days=30)),("its_report_is_suppressed", SignalReport.Status.SUPPRESSED, timedelta(days=30)),("its_horizon_passed", SignalReport.Status.RESOLVED, -timedelta(minutes=1)),+ ("its_report_is_monitoring", SignalReport.Status.MONITORING, timedelta(days=30)),])def test_a_due_check_the_coordinator_would_not_dispatch_is_paused(self, _name, report_status, expires_in) -> None:@@ -1908,10 +1992,11 @@ class TestCheckResultTool(APIBaseTest):now = timezone.now()check = self._check(dispatched_at=None, next_run_at=now - timedelta(hours=1), expires_at=now + expires_in)- (listed,) = list_report_checks(team=self.team, report_id=str(self.report.id))- assert listed.run_state == "paused"- with self.assertRaises(InvalidCheckResultError):- self._record(check)+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):+ (listed,) = list_report_checks(team=self.team, report_id=str(self.report.id))+ assert listed.run_state == "paused"+ with self.assertRaises(InvalidCheckResultError):+ self._record(check)check.refresh_from_db()assert check.status == SignalReportCheck.Status.ACTIVE@@ -1986,9 +2071,9 @@ class TestPendingChecks(APIBaseTest):super().setUp()self.report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="Fix")- def _pending(self, **overrides) -> SignalReportCheck:+ def _pending(self, *, report: SignalReport | None = None, **overrides) -> SignalReportCheck:return create_check(- report=self.report,+ report=report or self.report,title="Checkout errors stay low",kind=SignalReportCheck.Kind.METRIC_THRESHOLD,config=_threshold_config(),@@ -2002,6 +2087,58 @@ class TestPendingChecks(APIBaseTest):self.report.status = SignalReport.Status.RESOLVEDself.report.save(update_fields=["status"])+ @parameterized.expand(+ [("enabled", True), ("disabled", False), ("unavailable", RuntimeError("flag service unavailable"))]+ )+ def test_monitoring_checks_wait_for_manual_finish_or_use_the_resolved_fallback(+ self, _name: str, flag_result: bool | Exception+ ) -> None:+ 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()+ )+ )+ check.refresh_from_db()+ assert check.status == SignalReportCheck.Status.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+ )+ assert pending.measurement_start_at == (None if flag_result is True else now)+ 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 == now+ assert 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)+ }+def test_a_pending_check_is_never_due_while_its_report_is_unresolved(self) -> None:self._pending()@@ -2017,6 +2154,12 @@ class TestPendingChecks(APIBaseTest):self.report.save(update_fields=self.report.transition_to(SignalReport.Status.RESOLVED))self.report.save(update_fields=self.report.transition_to(report_status))+ assert (+ arm_pending_checks(+ team_id=self.team.id, report_id=self.report.id, resolved_at=timezone.now(), monitoring_enabled=False+ )+ == 0+ )check.refresh_from_db()assert check.status == SignalReportCheck.Status.PENDINGassert check.measurement_start_at is None@@ -2139,10 +2282,19 @@ class TestPendingChecks(APIBaseTest):assert valid.measurement_start_at is not Noneassert valid.next_run_at == metric_check_ready_at(_PAGEVIEWS, self.team, valid.measurement_start_at)- def test_a_pending_check_retires_when_its_report_never_resolves(self) -> None:+ @parameterized.expand([("open", False), ("monitoring_disabled", True)])+ def test_a_pending_check_retires_when_its_report_never_resolves(self, _name: str, monitoring: bool) -> None:check = self._pending()+ if monitoring:+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):+ self.report.save(+ update_fields=self.report.transition_to(+ SignalReport.Status.MONITORING, monitoring_started_at=timezone.now()+ )+ )- assert expire_overdue_checks(timezone.now() + MAX_CHECK_HORIZON + timedelta(minutes=1)) == 1+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=False):+ assert run_due_report_checks(now=timezone.now() + MAX_CHECK_HORIZON + timedelta(minutes=1)).expired == 1check.refresh_from_db()assert check.status == SignalReportCheck.Status.EXPIREDdiff --git a/products/signals/backend/test/test_report_content_gates.py b/products/signals/backend/test/test_report_content_gates.pyindex 9ad9e9c07a8b..709d93881328 100644--- a/products/signals/backend/test/test_report_content_gates.py+++ b/products/signals/backend/test/test_report_content_gates.py@@ -7,7 +7,6 @@ from django.test import SimpleTestCase, override_settingsimport posthoganalyticsfrom parameterized import parameterized-from products.signals.backend.models import InvalidStatusTransition, SignalReportfrom products.signals.backend.report_content_gates import (organization_report_metrics_enabled,organization_report_monitoring_enabled,@@ -85,9 +84,3 @@ class TestReportContentGates(SimpleTestCase):team_lookup.assert_not_called()evaluate.assert_not_called()-- def test_the_monitoring_status_has_no_transition_yet(self) -> None:- report = SignalReport(team_id=7, status=SignalReport.Status.READY)-- with self.assertRaises(InvalidStatusTransition):- report.transition_to(SignalReport.Status.MONITORING)diff --git a/products/signals/backend/test/test_report_lifecycle.py b/products/signals/backend/test/test_report_lifecycle.pynew file mode 100644index 000000000000..1cb3b407cd01--- /dev/null+++ b/products/signals/backend/test/test_report_lifecycle.py@@ -0,0 +1,80 @@+from datetime import timedelta+from uuid import UUID++from unittest.mock import patch++from django.test import SimpleTestCase+from django.utils import timezone++from parameterized import parameterized++from products.signals.backend.models import InvalidStatusTransition, SignalReport+++class TestReportMonitoringLifecycle(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ lookup = patch("products.signals.backend.report_content_gates.Team.objects.values_list").start()+ lookup.return_value.get.return_value = UUID("00000000-0000-0000-0000-000000000001")+ self.evaluate = patch(+ "products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True+ ).start()+ self.addCleanup(patch.stopall)++ @parameterized.expand(+ [+ (SignalReport.Status.READY, SignalReport.Status.POTENTIAL),+ (SignalReport.Status.PENDING_INPUT, SignalReport.Status.READY),+ (SignalReport.Status.FAILED, SignalReport.Status.POTENTIAL),+ ]+ )+ def test_implementation_time_anchors_the_period_until_implementation_reopens(+ self, initial_status: str, reopened_status: str+ ) -> None:+ report = SignalReport(team_id=7, status=initial_status, title="Checkout errors", summary="Investigated cause")+ merged_at = timezone.now() - timedelta(days=3)+ report.transition_to(SignalReport.Status.MONITORING, monitoring_started_at=merged_at)+ assert report.status == SignalReport.Status.MONITORING+ assert report.monitoring_started_at == merged_at+ assert report.title == "Checkout errors"+ assert report.summary == "Investigated cause"++ retry_at = timezone.now()+ assert report.transition_to(SignalReport.Status.MONITORING, monitoring_started_at=retry_at) == []+ assert report.monitoring_started_at == merged_at+ report.transition_to(SignalReport.Status.SUPPRESSED)+ assert report.restore_target_status() == SignalReport.Status.MONITORING+ report.transition_to(report.restore_target_status(), monitoring_started_at=retry_at)+ assert report.monitoring_started_at == merged_at++ report.transition_to(SignalReport.Status(reopened_status))+ self.assertIsNone(report.monitoring_started_at)+ if reopened_status == SignalReport.Status.READY:+ report.transition_to(SignalReport.Status.MONITORING, monitoring_started_at=retry_at)+ assert report.monitoring_started_at == retry_at++ @parameterized.expand([("missing", None), ("naive", "naive")])+ def test_entry_requires_an_explicit_aware_implementation_time(self, _name: str, invalid_time: str | None) -> None:+ report = SignalReport(team_id=7, status=SignalReport.Status.READY)+ timestamp = timezone.now().replace(tzinfo=None) if invalid_time == "naive" else None+ with self.assertRaises(ValueError):+ report.transition_to(SignalReport.Status.MONITORING, monitoring_started_at=timestamp)+ assert report.status == SignalReport.Status.READY+ assert report.monitoring_started_at is None++ @parameterized.expand([("disabled", False), ("unavailable", RuntimeError("flag service unavailable"))])+ def test_entry_requires_enablement(self, _name: str, flag_result: bool | Exception) -> None:+ self.evaluate.return_value = False+ self.evaluate.side_effect = flag_result if isinstance(flag_result, Exception) else None+ report = SignalReport(team_id=7, status=SignalReport.Status.READY)+ with self.assertRaises(InvalidStatusTransition):+ report.transition_to(SignalReport.Status.MONITORING, monitoring_started_at=timezone.now())+ assert report.status == SignalReport.Status.READY+ assert report.monitoring_started_at is None++ def test_finishing_verification_preserves_the_implementation_time(self) -> None:+ merged_at = timezone.now() - timedelta(days=3)+ report = SignalReport(team_id=7, status=SignalReport.Status.MONITORING, monitoring_started_at=merged_at)+ report.transition_to(SignalReport.Status.RESOLVED)+ assert report.status == SignalReport.Status.RESOLVED+ assert report.monitoring_started_at == merged_atdiff --git a/products/signals/backend/test/test_scout_inactivity.py b/products/signals/backend/test/test_scout_inactivity.pyindex f745c35a13a1..8def09934bee 100644--- a/products/signals/backend/test/test_scout_inactivity.py+++ b/products/signals/backend/test/test_scout_inactivity.py@@ -214,6 +214,7 @@ class TestScoutInactivitySweep(BaseTest):# `resolved` includes the GitHub webhook's resolve-on-merge, which is how a merged PR# counts as consumption even when the merge never touched the app.("resolved_status", None, SignalReport.Status.RESOLVED, None),+ ("monitoring_status", None, SignalReport.Status.MONITORING, None),# Reading is consumption: a report someone opens (or rates) is not a report nobody# wanted, even when they never resolve or dismiss it.("view_action", None, None, SignalReportAction.ActionType.VIEW),diff --git a/products/signals/backend/test/test_signal_report_actions.py b/products/signals/backend/test/test_signal_report_actions.pyindex 460a0874f73d..717ef5dea138 100644--- a/products/signals/backend/test/test_signal_report_actions.py+++ b/products/signals/backend/test/test_signal_report_actions.py@@ -185,7 +185,7 @@ class TestSignalReportViewedEndpoint(APIBaseTest):[("suppressed", SignalReport.Status.SUPPRESSED, False, True),("monitoring_disabled", SignalReport.Status.MONITORING, False, True),- ("monitoring_enabled", SignalReport.Status.MONITORING, True, False),+ ("monitoring_enabled", SignalReport.Status.MONITORING, True, True),])def test_visible_reports_record_their_views(diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex 65ede3805577..da4cf261f0a1 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -1115,17 +1115,17 @@ class TestSignalReportListAPI(APIBaseTest):ordered = self.client.get(self._list_url(ordering="status,-total_weight"))assert ordered.status_code == status.HTTP_200_OK- expected_order = [str(ready.id), *([] if enabled else [str(monitoring.id)]), str(resolved.id)]+ expected_order = [str(ready.id), str(monitoring.id), str(resolved.id)]assert [row["id"] for row in ordered.json()["results"]] == expected_orderdetail = self.client.get(f"{self._list_url()}{monitoring.id}/")- assert detail.status_code == (status.HTTP_404_NOT_FOUND if enabled else status.HTTP_200_OK)+ assert detail.status_code == status.HTTP_200_OKif not enabled:assert detail.json()["status"] == "resolved"assert detail.json()["work_state"] == "done"assert "monitoring_started_at" not in detail.json()evidence = self.client.get(f"{self._list_url()}{monitoring.id}/signals/")- assert evidence.status_code == (status.HTTP_404_NOT_FOUND if enabled else status.HTTP_200_OK)+ assert evidence.status_code == status.HTTP_200_OKif not enabled:assert evidence.json()["report"]["status"] == "resolved"assert evidence.json()["report"]["work_state"] == "done"@@ -1179,7 +1179,7 @@ class TestSignalReportListAPI(APIBaseTest):other_organization.members.add(self.user)other_team = Team.objects.create(organization=other_organization)monitoring = self._create_report(status=SignalReport.Status.MONITORING)- self._create_report(team=other_team, status=SignalReport.Status.MONITORING)+ other_monitoring = self._create_report(team=other_team, status=SignalReport.Status.MONITORING)def evaluate(flag: str, distinct_id: str, **kwargs: object) -> bool:return distinct_id == str(other_organization.id)@@ -1187,10 +1187,12 @@ class TestSignalReportListAPI(APIBaseTest):with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", side_effect=evaluate):disabled = self.client.get(self._list_url(status="resolved"))enabled = self.client.get(f"/api/projects/{other_team.id}/signals/reports/?status=resolved")+ enabled_detail = self.client.get(f"/api/projects/{other_team.id}/signals/reports/{other_monitoring.id}/")assert disabled.status_code == enabled.status_code == status.HTTP_200_OKassert [row["id"] for row in disabled.json()["results"]] == [str(monitoring.id)]assert enabled.json()["results"] == []+ assert enabled_detail.json()["status"] == "monitoring"@parameterized.expand([@@ -2779,6 +2781,43 @@ class TestAssociatedTaskRunsForReports(APIBaseTest):class TestSignalReportSuppressionAPI(APIBaseTest):+ @parameterized.expand([("disabled", False), ("unavailable", RuntimeError("flag service unavailable"))])+ def test_monitoring_entry_fails_closed_and_existing_rows_use_resolved_actions(+ self, _name: str, flag_result: bool | Exception+ ) -> None:+ report = self._create_report()+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):+ rejected = self.client.post(self._state_url(str(report.id)), {"state": "monitoring"})+ assert rejected.status_code == status.HTTP_400_BAD_REQUEST+ report.save(+ update_fields=report.transition_to(SignalReport.Status.MONITORING, monitoring_started_at=timezone.now())+ )+ report.refresh_from_db()+ original_start = report.monitoring_started_at+ with patch(+ "products.signals.backend.report_content_gates.feature_enabled_or_false",+ return_value=False,+ side_effect=flag_result if isinstance(flag_result, Exception) else None,+ ):+ rejected = self.client.post(self._state_url(str(report.id)), {"state": "monitoring"})+ assert rejected.status_code == status.HTTP_400_BAD_REQUEST+ repeated = self.client.post(self._state_url(str(report.id)), {"state": "resolved"})+ assert repeated.status_code == status.HTTP_200_OK+ assert repeated.json()["status"] == "resolved"+ assert repeated.json()["work_state"] == "done"+ assert "monitoring_started_at" not in repeated.json()+ for target, expected in [+ ("suppressed", "suppressed"),+ ("potential", "resolved"),+ ("potential", "potential"),+ ]:+ response = self.client.post(self._state_url(str(report.id)), {"state": target})+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["status"] == expected+ report.refresh_from_db()+ assert report.monitoring_started_at is None+ assert original_start is not None+def _state_url(self, report_id: str) -> str:return f"/api/projects/{self.team.id}/signals/reports/{report_id}/state/"@@ -3230,6 +3269,7 @@ class TestSignalReportSuppressionAPI(APIBaseTest):"reset_weight": True,"error": "injected","signals_at_run_increment": 999,+ "monitoring_started_at": "2000-01-01T00:00:00Z",}),content_type="application/json",@@ -3241,6 +3281,7 @@ class TestSignalReportSuppressionAPI(APIBaseTest):assert report.total_weight == 9.0assert report.error is Noneassert report.signals_at_run == 0+ assert report.monitoring_started_at is Nonedef test_can_reopen_suppressed_report(self):report = self._create_report(report_status=SignalReport.Status.SUPPRESSED)@@ -3607,6 +3648,7 @@ class TestSignalReportMergeAPI(APIBaseTest):# somewhere the pipeline never looks again while the sources archive for good. A# suppressed one is not visible to this action at all.("resolved", SignalReport.Status.RESOLVED, status.HTTP_409_CONFLICT),+ ("monitoring_disabled", SignalReport.Status.MONITORING, status.HTTP_409_CONFLICT),("suppressed", SignalReport.Status.SUPPRESSED, status.HTTP_404_NOT_FOUND),])@@ -3614,7 +3656,11 @@ class TestSignalReportMergeAPI(APIBaseTest):survivor = self._report(report_status=survivor_status, signal_count=3)source = self._report(signal_count=2)- assert self._merge(survivor, source).status_code == expected_code+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=False):+ response = self._merge(survivor, source)+ assert response.status_code == expected_code+ if survivor_status == SignalReport.Status.MONITORING:+ assert "is resolved" in response.json()["error"]source.refresh_from_db()survivor.refresh_from_db()@@ -3625,6 +3671,7 @@ class TestSignalReportMergeAPI(APIBaseTest):[("self_merge", "self", "cannot be merged into itself"),("resolved_source", SignalReport.Status.RESOLVED, "cannot be merged"),+ ("monitoring_disabled_source", SignalReport.Status.MONITORING, "is resolved"),("suppressed_source", SignalReport.Status.SUPPRESSED, "cannot be merged"),# A research run is writing to an in-progress report, and `SUPPRESSED -> READY` is# legal, so the run would resurrect it after the merge moved its work away.@@ -3645,7 +3692,8 @@ class TestSignalReportMergeAPI(APIBaseTest):else:source = self._report(report_status=source_spec)- response = self._merge(survivor, source)+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=False):+ response = self._merge(survivor, source)assert response.status_code == status.HTTP_409_CONFLICT, response.json()assert expected_error in response.json()["error"]@@ -3974,6 +4022,7 @@ class TestSignalReportBulkStateAPI(APIBaseTest):{"ids": ["00000000-0000-0000-0000-000000000001"], "state": "suppressed", "dismissal_reason": "made_up"},),("invalid_state", {"ids": ["00000000-0000-0000-0000-000000000001"], "state": "ready"}),+ ("monitoring_not_available", {"ids": ["00000000-0000-0000-0000-000000000001"], "state": "monitoring"}),("non_uuid_id", {"ids": ["not-a-uuid"], "state": "suppressed"}),])@@ -4717,7 +4766,7 @@ class TestSignalReportPrEndpoints(APIBaseTest):for visibility, report_status, flag_enabled, expected_status in [("suppressed", SignalReport.Status.SUPPRESSED, False, status.HTTP_200_OK),("monitoring_disabled", SignalReport.Status.MONITORING, False, status.HTTP_200_OK),- ("monitoring_enabled", SignalReport.Status.MONITORING, True, status.HTTP_404_NOT_FOUND),+ ("monitoring_enabled", SignalReport.Status.MONITORING, True, status.HTTP_200_OK),]])diff --git a/products/signals/backend/test/test_signal_report_assignment_api.py b/products/signals/backend/test/test_signal_report_assignment_api.pyindex 122920abebfe..344f212faf00 100644--- a/products/signals/backend/test/test_signal_report_assignment_api.py+++ b/products/signals/backend/test/test_signal_report_assignment_api.py@@ -645,12 +645,28 @@ class TestSignalReportAssignmentAPI(APIBaseTest):assert get_active_claim(team_id=self.team.id, report_id=report.id) is not Noneassert not SignalReportAssignment.all_teams.filter(report=report).exists()- def test_resolved_report_cannot_be_claimed(self):- report = self._create_report(report_status=SignalReport.Status.RESOLVED)+ @parameterized.expand(+ [+ ("resolved", SignalReport.Status.RESOLVED, False, "resolved"),+ ("monitoring_enabled", SignalReport.Status.MONITORING, True, "monitoring"),+ ("monitoring_disabled", SignalReport.Status.MONITORING, False, "resolved"),+ ("monitoring_unavailable", SignalReport.Status.MONITORING, RuntimeError("flag unavailable"), "resolved"),+ ]+ )+ def test_resolved_report_cannot_be_claimed(+ self, _name: str, report_status: str, flag_result: bool | Exception, expected_status: str+ ) -> None:+ report = self._create_report(report_status=report_status)- response = self.client.post(self._claim_url(report), data={}, format="json")+ 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,+ ):+ response = self.client.post(self._claim_url(report), data={}, format="json")assert response.status_code == status.HTTP_409_CONFLICT+ assert f"status '{expected_status}'" in response.json()["detail"]assert not SignalReportAssignment.all_teams.filter(report=report).exists()def test_suppressed_report_cannot_be_claimed(self):diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 1f7791cb1ac2..e18ff23135bc 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -1370,12 +1370,10 @@ class SignalReportViewSet(# Deleted reports are terminal, so `deleted` never reaches any endpoint (detail, list,# actions) and is never a valid filter target either.- # Monitoring has no supported lifecycle yet, so it is excluded from reads too._FILTERABLE_STATUSES = frozenset(SignalReport.Status.values) - {SignalReport.Status.DELETED,SignalReport.Status.MONITORING,}- _DEFAULT_STATUSES = _FILTERABLE_STATUSES - {SignalReport.Status.SUPPRESSED}# Actions that work on many reports at once, so per-row annotations are wasted work there._MULTI_REPORT_ACTIONS = frozenset({"list", "bulk_state", "for_you"})@@ -1418,17 +1416,13 @@ class SignalReportViewSet(SignalReportBulkStateOutcome.NOT_FOUND: "No report with this id is visible to you.",}- _MONITORING_FALLBACK_READ_ACTIONS = frozenset(- {"list", "retrieve", "signals", "viewed", "feedback_state", "feedback", "pr_checks", "pr_comments"}- )-@cached_propertydef _report_monitoring_enabled(self) -> bool:return organization_report_monitoring_enabled(self.organization.id)def _resolved_read_statuses(self) -> frozenset[str]:statuses = frozenset({SignalReport.Status.RESOLVED})- if self.action in self._MONITORING_FALLBACK_READ_ACTIONS and not self._report_monitoring_enabled:+ if not self._report_monitoring_enabled:return statuses | {SignalReport.Status.MONITORING}return statuses@@ -1442,12 +1436,15 @@ class SignalReportViewSet(return queryset.filter(status__in=sorted(statuses))def _visible_statuses(self) -> frozenset[str]:+ filterable_statuses = self._FILTERABLE_STATUSES+ if self._report_monitoring_enabled:+ filterable_statuses |= {SignalReport.Status.MONITORING}status_filter = self.request.query_params.get("status")if status_filter:statuses = [s.strip() for s in status_filter.split(",") if s.strip()]- invalid = [s for s in statuses if s not in self._FILTERABLE_STATUSES]+ invalid = [s for s in statuses if s not in filterable_statuses]if invalid:- accepted = ", ".join(sorted(self._FILTERABLE_STATUSES))+ accepted = ", ".join(sorted(filterable_statuses))raise serializers.ValidationError({"status": f"Invalid status value(s): {', '.join(sorted(set(invalid)))}. Accepted values: {accepted}."@@ -1467,8 +1464,8 @@ class SignalReportViewSet(or self._include_all_statuses_requested()or self.request.query_params.get("view") in {"dismissed", "held_back", "all"}):- return self._FILTERABLE_STATUSES- return self._DEFAULT_STATUSES+ return filterable_statuses+ return filterable_statuses - {SignalReport.Status.SUPPRESSED}def _include_all_statuses_requested(self) -> bool:# List-only: the flag widens the *list* for full-inbox-state scans (agent dedup). By-ID@@ -1594,7 +1591,7 @@ class SignalReportViewSet(return querysethas_review_pr = implementation_pr_report_filter(team_id=self.team.id, active_only=True)is_unclaimed = (- ~Q(status__in=self._resolved_read_statuses())+ ~Q(status__in={SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING})& ~reports_with_active_claim(team_id=self.team_id)& ~has_review_pr)@@ -1783,6 +1780,7 @@ class SignalReportViewSet(if inbox_view == "needs_decision":return queryset.filter(Q(status=SignalReport.Status.FAILED)+ | Q(status__in=[SignalReport.Status.MONITORING] if self._report_monitoring_enabled else [])| (Q(status__in=[SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT],@@ -1826,6 +1824,7 @@ class SignalReportViewSet(When(status=SignalReport.Status.CANDIDATE, then=Value(4)),When(status=SignalReport.Status.POTENTIAL, then=Value(5)),When(status=SignalReport.Status.FAILED, then=Value(6)),+ When(status=SignalReport.Status.MONITORING, then=Value(6 if self._report_monitoring_enabled else 7)),When(status__in=self._resolved_read_statuses(), then=Value(7)),When(status=SignalReport.Status.SUPPRESSED, then=Value(8)),When(status=SignalReport.Status.DELETED, then=Value(9)),@@ -2114,11 +2113,7 @@ class SignalReportViewSet(return {**super().get_serializer_context(),"team": self.team,- **(- {"report_monitoring_enabled_by_team": {self.team_id: self._report_monitoring_enabled}}- if self.action in self._MONITORING_FALLBACK_READ_ACTIONS- else {}- ),+ "report_monitoring_enabled_by_team": {self.team_id: self._report_monitoring_enabled},# For the serializer's refund_ineligibility_reason field — computed once per request,# not per report (the bounds are org-level)."billing_period_bounds": current_billing_period_bounds(self.organization),@@ -3434,7 +3429,10 @@ class SignalReportViewSet(# suppression — and the PR close it triggers — from being undone.if is_refunded and (target_status == SignalReport.Status.POTENTIAL- or (report.status == SignalReport.Status.SUPPRESSED and target_status == SignalReport.Status.RESOLVED)+ or (+ report.status == SignalReport.Status.SUPPRESSED+ and target_status in {SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING}+ )):return SignalReportBulkStateOutcome.SKIPPED, "Refunded reports can't be restored."@@ -3443,7 +3441,8 @@ class SignalReportViewSet(# 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 target_status+ in {SignalReport.Status.POTENTIAL, SignalReport.Status.RESOLVED, SignalReport.Status.MONITORING}and was_merged_away(report)):return (@@ -3462,7 +3461,8 @@ class SignalReportViewSet(if (report.status == SignalReport.Status.SUPPRESSEDand target_status == SignalReport.Status.RESOLVED- and report.status_before_suppression not in _RESOLVABLE_STATUSES_BEFORE_SUPPRESSION+ and report.status_before_suppression+ not in _RESOLVABLE_STATUSES_BEFORE_SUPPRESSION | {SignalReport.Status.MONITORING}):return (SignalReportBulkStateOutcome.SKIPPED,@@ -3488,9 +3488,10 @@ class SignalReportViewSet(# the server once GitHub closes the PR (webhook suppresses the report), and that click# still carries feedback for the agent. Skipping the save keeps every receiver quiet, so# no second PR close is queued. A repeat restore carries no feedback, so it stays a 409.- already_holds_verdict = target_status == report.status and target_status in (+ already_holds_verdict = target_status == report.effective_status and target_status in (SignalReport.Status.SUPPRESSED,SignalReport.Status.RESOLVED,+ SignalReport.Status.MONITORING,)writes_dismissal_feedback = target in ("suppressed", "potential", "resolved") and bool(@@ -3646,7 +3647,9 @@ class SignalReportViewSet(corrected_repository=corrected_repository,snooze_for=snooze_for,)- report_status = report.status if outcome == SignalReportBulkStateOutcome.TRANSITIONED else None+ report_status = (+ report.effective_status if outcome == SignalReportBulkStateOutcome.TRANSITIONED else None+ )if outcome == SignalReportBulkStateOutcome.TRANSITIONED:transitioned.append(report)if getattr(report, "_newly_suppressed", False):@@ -3819,7 +3822,7 @@ class SignalReportViewSet(# leaving it resolved would let the caller keep the implementation work after the refund.# Already-suppressed reports need no transition. The dismissal artefact records the# rationale; the structured truth lives on the refund row.- resolved_via_merged_pr = report.status == SignalReport.Status.RESOLVED and pr_merged+ resolved_via_merged_pr = report.effective_status == SignalReport.Status.RESOLVED and pr_mergedif report.status != SignalReport.Status.SUPPRESSED and not resolved_via_merged_pr:updated_fields = report.transition_to(SignalReport.Status.SUPPRESSED)report._transition_actor = attribution # type: ignore[attr-defined]@@ -4051,7 +4054,7 @@ class SignalReportViewSet(report_ids = [str(report_id)for report_id, report_status in self.get_queryset().filter(id__in=requested_ids).values_list("id", "status")- if report_status not in _PR_CI_STATUS_TERMINAL_REPORT_STATUSES+ if report_status not in _PR_CI_STATUS_TERMINAL_REPORT_STATUSES | self._resolved_read_statuses()]if not report_ids:return self._pr_ci_statuses_response([])diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.pyindex 9a5196aa9f06..a03f597d1a19 100644--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py@@ -539,6 +539,7 @@ class TestSpineInclusion(BaseTest):def test_spine_covers_authored_and_promoted_reports_as_of_the_cutoff(self):promoted = self._report(SignalReport.Status.POTENTIAL, promoted_at=BEFORE_CUTOFF)born_visible = self._report(SignalReport.Status.READY)+ monitoring = self._report(SignalReport.Status.MONITORING)promoted_after_cutoff = self._report(SignalReport.Status.READY, promoted_at=AFTER_SNAPSHOT_END)self._report(SignalReport.Status.POTENTIAL)self._report(SignalReport.Status.SUPPRESSED)@@ -549,7 +550,7 @@ class TestSpineInclusion(BaseTest):for report_id in SignalReport.objects.filter(spine_report_filter(SNAPSHOT_END)).values_list("id", flat=True)}- assert in_spine == {promoted, born_visible}+ assert in_spine == {promoted, born_visible, monitoring}assert promoted_after_cutoff not in in_spineassert created_after_cutoff not in in_spinediff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 705735b8b85f..dec91a1f18e6 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -662,6 +662,11 @@ export interface SignalReportListApi {readonly summary_lead: string/** Current report status. Monitoring reads as resolved when its rollout is disabled. */readonly status: SignalReportStatusEnumApi+ /**+ * Original implementation-complete time for this Monitoring period, null before entry. Present only when Monitoring is enabled.+ * @nullable+ */+ readonly monitoring_started_at?: string | nullreadonly total_weight: numberreadonly signal_count: numberreadonly signals_at_run: number@@ -901,6 +906,11 @@ export interface SignalReportApi {readonly summary_lead: string/** Current report status. Monitoring reads as resolved when its rollout is disabled. */readonly status: SignalReportStatusEnumApi+ /**+ * Original implementation-complete time for this Monitoring period, null before entry. Present only when Monitoring is enabled.+ * @nullable+ */+ readonly monitoring_started_at?: string | nullreadonly total_weight: numberreadonly signal_count: numberreadonly signals_at_run: numberdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fcbae6d5d8f8..d3f5502363de 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -73644,6 +73644,11 @@ export namespace Schemas {readonly summary_lead: string;/** Current report status. Monitoring reads as resolved when its rollout is disabled. */readonly status: SignalReportStatusEnum;+ /**+ * Original implementation-complete time for this Monitoring period, null before entry. Present only when Monitoring is enabled.+ * @nullable+ */+ readonly monitoring_started_at?: string | null;readonly total_weight: number;readonly signal_count: number;readonly signals_at_run: number;@@ -95329,6 +95334,11 @@ export namespace Schemas {readonly summary_lead: string;/** Current report status. Monitoring reads as resolved when its rollout is disabled. */readonly status: SignalReportStatusEnum;+ /**+ * Original implementation-complete time for this Monitoring period, null before entry. Present only when Monitoring is enabled.+ * @nullable+ */+ readonly monitoring_started_at?: string | null;readonly total_weight: number;readonly signal_count: number;readonly signals_at_run: number;