: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(flags): detect stale flag health issues (#95189)
James Gillc34d9b95b5b5
diff --git a/frontend/src/scenes/health/healthCategories.tsx b/frontend/src/scenes/health/healthCategories.tsxindex 35dac7361e92..82e731558243 100644--- a/frontend/src/scenes/health/healthCategories.tsx+++ b/frontend/src/scenes/health/healthCategories.tsx@@ -1,4 +1,13 @@-import { IconBug, IconCode, IconDatabase, IconDecisionTree, IconPulse, IconTrending, IconWarning } from '@posthog/icons'+import {+ IconBug,+ IconCode,+ IconDatabase,+ IconDecisionTree,+ IconPulse,+ IconToggle,+ IconTrending,+ IconWarning,+} from '@posthog/icons'export type HealthIssueCategory =| 'ingestion'@@ -7,6 +16,7 @@ export type HealthIssueCategory =| 'data_modeling'| 'pipelines'| 'error_tracking'+ | 'feature_flags'| 'other'export type HealthIssueKind =@@ -24,6 +34,7 @@ export type HealthIssueKind =| 'materialized_view_failure'| 'external_data_failure'| 'error_tracking_missing_source_maps'+ | 'stale_feature_flags'export interface CategoryConfig {label: string@@ -76,6 +87,13 @@ export const HEALTH_CATEGORY_CONFIG: Record<HealthIssueCategory, CategoryConfig>icon: <IconBug className="size-5" />,showInSummary: true,},+ feature_flags: {+ label: 'Feature flags',+ description: 'Feature flags that may be ready for cleanup',+ healthyDescription: 'No stale flags',+ icon: <IconToggle className="size-5" />,+ showInSummary: true,+ },other: {label: 'Other',description: 'Other health issues',@@ -101,6 +119,9 @@ const KIND_TO_CATEGORY: Record<HealthIssueKind, HealthIssueCategory> = {// Error trackingerror_tracking_missing_source_maps: 'error_tracking',+ // Feature flags+ stale_feature_flags: 'feature_flags',+// Web analyticsno_live_events: 'web_analytics',no_pageleave_events: 'web_analytics',@@ -127,6 +148,7 @@ export const KIND_LABELS: Record<HealthIssueKind, string> = {sdk_outdated: 'SDK outdated',materialized_view_failure: 'Materialized view failure',error_tracking_missing_source_maps: 'Missing source maps',+ stale_feature_flags: 'Stale feature flag',}export const categoryForKind = (kind: string): HealthIssueCategory => {@@ -146,5 +168,6 @@ export const CATEGORY_ORDER: HealthIssueCategory[] = ['data_modeling','pipelines','error_tracking',+ 'feature_flags','other',]diff --git a/posthog/job_owners.py b/posthog/job_owners.pyindex 1edd3eed9f58..7638f44956b3 100644--- a/posthog/job_owners.py+++ b/posthog/job_owners.py@@ -15,6 +15,7 @@ class JobOwners(str, Enum):TEAM_DATA_STACK = "team-data-stack"TEAM_DATA_TOOLS = "team-data-tools"TEAM_ERROR_TRACKING = "team-error-tracking"+ TEAM_FEATURE_FLAGS = "team-feature-flags"TEAM_GROWTH = "team-growth"TEAM_INGESTION = "team-ingestion"TEAM_LOGS = "team-logs"diff --git a/posthog/tasks/health_checks.py b/posthog/tasks/health_checks.pyindex dae5732448aa..686454393d4b 100644--- a/posthog/tasks/health_checks.py+++ b/posthog/tasks/health_checks.py@@ -9,14 +9,9 @@ logger = get_logger(__name__)@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)def evaluate_health_check_for_team(kind: str, team_id: int) -> None:# Deferred: posthog.dags.__init__ calls django.setup() and would re-enter if loaded during boot.- from posthog.temporal.health_checks.processing import _process_batch_detection- from posthog.temporal.health_checks.registry import ensure_registry_loaded, get_detect_fn+ from posthog.temporal.health_checks.processing import run_check_for_team- ensure_registry_loaded()try:- detect_fn = get_detect_fn(kind)+ run_check_for_team(kind, team_id)except KeyError:logger.warning("evaluate_health_check_for_team.unknown_kind", kind=kind, team_id=team_id)- return-- _process_batch_detection(team_ids=[team_id], kind=kind, detect_fn=detect_fn)diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambrindex e5928a492dad..6e516ab0b7b6 100644--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr@@ -242,7 +242,11 @@INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")WHERE (NOT ("posthog_featureflag"."deleted")AND NOT "posthog_featureflag"."deleted"- AND "posthog_team"."project_id" = 99999+ AND "posthog_team"."project_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)AND (jsonb_path_exists(filters, '$.** ? (@.type == "flag")')))'''# ---@@ -1161,7 +1165,11 @@INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")WHERE (NOT ("posthog_featureflag"."deleted")AND NOT "posthog_featureflag"."deleted"- AND "posthog_team"."project_id" = 99999+ AND "posthog_team"."project_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)AND (jsonb_path_exists(filters, '$.** ? (@.type == "flag")')))'''# ---diff --git a/posthog/temporal/health_checks/processing.py b/posthog/temporal/health_checks/processing.pyindex acd0a9f40370..661d722bd8ea 100644--- a/posthog/temporal/health_checks/processing.py+++ b/posthog/temporal/health_checks/processing.py@@ -5,12 +5,30 @@ import structlogfrom posthog.temporal.health_checks.alerts import emit_health_check_alertfrom posthog.temporal.health_checks.db import resolve_stale_issues_with_deltas, upsert_issues_with_deltasfrom posthog.temporal.health_checks.models import BatchDetectFn, BatchResult+from posthog.temporal.health_checks.registry import HEALTH_CHECKS, ensure_registry_loaded, get_detect_fnfrom posthog.temporal.health_checks.signal_emitter import emit_health_check_signalsfrom posthog.temporal.health_checks.validation import _validate_batch_outputlogger = structlog.get_logger(__name__)+def run_check_for_team(kind: str, team_id: int) -> BatchResult:+ """Run one registered check for one team, honoring the check's `dry_run`.++ The one entry point for manual single-team paths (the Health page refresh task, agent+ tools), so no caller can forget to forward the registration's `dry_run` again.++ Raises KeyError for an unregistered kind.+ """+ ensure_registry_loaded()+ return _process_batch_detection(+ team_ids=[team_id],+ kind=kind,+ detect_fn=get_detect_fn(kind),+ dry_run=HEALTH_CHECKS[kind].dry_run,+ )++def _process_batch_detection(team_ids: list[int],kind: str,diff --git a/posthog/temporal/health_checks/registry.py b/posthog/temporal/health_checks/registry.pyindex 3f413f94d7a3..b7365b415d9c 100644--- a/posthog/temporal/health_checks/registry.py+++ b/posthog/temporal/health_checks/registry.py@@ -26,6 +26,7 @@ HEALTH_CHECK_MODULES = ["products.web_analytics.backend.temporal.health_checks.web_vitals","products.web_analytics.backend.temporal.health_checks.path_cleaning_suggestions","products.error_tracking.backend.temporal.health_checks.missing_source_maps",+ "products.feature_flags.backend.temporal.health_checks.stale_flags",]_registry_loaded = Falsediff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex e9f788f67607..11ca54988659 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -573,27 +573,15 @@ def find_dependent_flags_batch(def _get_flag_rollout_info(flag: FeatureFlag, checker: FeatureFlagStatusChecker) -> dict[str, Any]:"""Compute rollout state for a flag to include in bulk delete response.- Thin adapter over ``FeatureFlagStatusChecker.get_rollout_summary`` so the- "fully rolled out" determination has a single source of truth. Maps the- summary to the bulk-delete vocabulary:+ Thin adapter over ``rollout_state_and_variant`` so the "fully rolled out"+ determination has a single source of truth. Maps the summary to the+ bulk-delete vocabulary:- rollout_state: "fully_rolled_out", "not_rolled_out", or "partial"- active_variant: variant key if a multivariate flag is fully rolled out to one variant"""summary = checker.get_rollout_summary(flag)-- if summary.effectively_full_rollout:- active_variant = None- if summary.is_multivariate:- # summary already established full rollout; this only fetches the winning variant key.- # Both calls read the same in-memory flag, so they cannot disagree.- _, active_variant = checker.is_multivariate_flag_fully_rolled_out(flag)- return {"rollout_state": "fully_rolled_out", "active_variant": active_variant}-- # Effectively at 0%: every release condition is at 0 (max across groups is 0).- if summary.max_rollout_percentage == 0:- return {"rollout_state": "not_rolled_out", "active_variant": None}-- return {"rollout_state": "partial", "active_variant": None}+ rollout_state, active_variant = checker.rollout_state_and_variant(flag, summary)+ return {"rollout_state": rollout_state, "active_variant": active_variant}def calculate_filter_size_bytes(filters: dict | None) -> int:@@ -4201,6 +4189,8 @@ class FeatureFlagViewSet(queryset = self.queryset.filter(team__project_id=self.project_id, deleted=False)# Exclude internal flags (same as list/matching_ids endpoints)+ # The stale-flags health check mirrors this guard's reference checks in+ # products/feature_flags/backend/temporal/health_checks/stale_flags.py. Keep the two in step.survey_flag_ids = Survey.get_internal_flag_ids(project_id=self.project_id)product_tour_internal_targeting_flags = ProductTour.all_objects.filter(team__project_id=self.project_id, internal_targeting_flag__isnull=Falsediff --git a/products/feature_flags/backend/flag_status.py b/products/feature_flags/backend/flag_status.pyindex f029fbfda35d..29e9220bc2cd 100644--- a/products/feature_flags/backend/flag_status.py+++ b/products/feature_flags/backend/flag_status.py@@ -46,6 +46,14 @@ class FeatureFlagRolloutSummary:is_multivariate: bool+# Shared rollout-state vocabulary. The bulk-delete API response and the stale-flags+# health check both serve these strings, and the frontend consumes them as an enum,+# so the mapping in `rollout_state_and_variant` is the single place they come from.+ROLLOUT_FULLY_ROLLED_OUT = "fully_rolled_out"+ROLLOUT_NOT_ROLLED_OUT = "not_rolled_out"+ROLLOUT_PARTIAL = "partial"++def exclude_archived_unless_requested(queryset: QuerySet, *, requested: bool) -> QuerySet:"""Hide archived flags unless the caller explicitly asked for them.@@ -297,6 +305,23 @@ class FeatureFlagStatusChecker:is_multivariate=bool(multivariate and multivariate.get("variants")),)+ def rollout_state_and_variant(+ self, flag: FeatureFlag, summary: FeatureFlagRolloutSummary+ ) -> tuple[str, str | None]:+ """Map a rollout summary to a `ROLLOUT_*` state and, when a multivariate flag is+ fully rolled out to one variant, that variant's key."""+ if summary.effectively_full_rollout:+ variant = None+ if summary.is_multivariate:+ # summary already established full rollout; this only fetches the winning variant key.+ # Both calls read the same in-memory flag, so they cannot disagree.+ _, variant = self.is_multivariate_flag_fully_rolled_out(flag)+ return ROLLOUT_FULLY_ROLLED_OUT, variant+ # Effectively at 0%: every release condition is at 0 (max across groups is 0).+ if summary.max_rollout_percentage == 0:+ return ROLLOUT_NOT_ROLLED_OUT, None+ return ROLLOUT_PARTIAL, None+def is_flag_fully_rolled_out(self, flag: FeatureFlag) -> tuple[bool, FeatureFlagStatusReason]:multivariate = (flag.filters or {}).get("multivariate", None)# An empty/missing variant list is treated as boolean, matching the STALE SQL filterdiff --git a/products/feature_flags/backend/flag_version_sync.py b/products/feature_flags/backend/flag_version_sync.pyindex 1138b30c02fd..dec479f46bbd 100644--- a/products/feature_flags/backend/flag_version_sync.py+++ b/products/feature_flags/backend/flag_version_sync.py@@ -28,10 +28,11 @@ pre-bump versions."""from collections import defaultdict+from collections.abc import Collectionfrom typing import Anyfrom django.db import transaction-from django.db.models import Value+from django.db.models import QuerySet, Valuefrom django.db.models.functions import Coalescefrom django.db.models.signals import post_save, pre_savefrom django.dispatch import receiver@@ -249,14 +250,15 @@ def _flag_version_bump_entry(flag: FeatureFlag, old_version: int | None, trigger)-def _direct_flag_dependency_ids(flag: FeatureFlag) -> set[int]:+def direct_flag_dependency_ids(flag: FeatureFlag) -> set[int]:"""Flag ids this flag has a ``flag_evaluates_to`` release condition on.Same parse as ``flags_cache._extract_direct_dependency_ids`` (a dependency is keyed bythe referenced flag's id in ``key``), minus its inactive/deleted short-circuit: adisabled flag still ships in the local-evaluation payload so dependencies can resolveit, so its dependents still need the bump. Tolerant of malformed values so one bad- sibling flag can't break the save that triggered this.+ sibling flag can't break the save that triggered this. Read by the version-bump path+ below and by the stale-flags health check."""dependency_ids: set[int] = set()try:@@ -278,6 +280,19 @@ def _direct_flag_dependency_ids(flag: FeatureFlag) -> set[int]:return dependency_ids+def flags_with_flag_dependencies(project_ids: Collection[int]) -> QuerySet[FeatureFlag]:+ """Non-deleted flags in these projects whose filters hold a flag-type release condition.++ The jsonb predicate is the one assumption about how a flag dependency is stored in+ ``filters``; the version-bump path and the stale-flags health check both build on it,+ so it lives here once.+ """+ # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (static predicate, no user input)+ return FeatureFlag.objects.filter(team__project_id__in=project_ids, deleted=False).extra(+ where=["""jsonb_path_exists(filters, '$.** ? (@.type == "flag")')"""]+ )++def _dependent_flags(sources: list[FeatureFlag], project_id: int) -> list[tuple[FeatureFlag, FeatureFlag]]:"""Non-deleted flags in the project that transitively depend on any source flag.@@ -293,18 +308,15 @@ def _dependent_flags(sources: list[FeatureFlag], project_id: int) -> list[tuple[walk below needs no further round trips."""candidate_flags = list(- # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (static predicate, no user input)- FeatureFlag.objects.filter(team__project_id=project_id, deleted=False)- .extra(where=["""jsonb_path_exists(filters, '$.** ? (@.type == "flag")')"""])# select_related: the activity entry per bumped flag reads flag.team.organization_id.- .select_related("team")+ flags_with_flag_dependencies([project_id]).select_related("team"))if not candidate_flags:return []dependents_of: dict[int, list[FeatureFlag]] = defaultdict(list)for flag in candidate_flags:- for dependency_id in _direct_flag_dependency_ids(flag):+ for dependency_id in direct_flag_dependency_ids(flag):dependents_of[dependency_id].append(flag)dependents: list[tuple[FeatureFlag, FeatureFlag]] = []diff --git a/products/feature_flags/backend/session_recording_links.py b/products/feature_flags/backend/session_recording_links.pyindex 013336b5c318..a50d872448c1 100644--- a/products/feature_flags/backend/session_recording_links.py+++ b/products/feature_flags/backend/session_recording_links.py@@ -59,17 +59,22 @@ def teams_linking_flag_in_project(project_id: int, flag_id: int) -> QuerySet[Teadef replay_linked_flag_ids(project_id: int, flag_ids: Collection[int]) -> set[int]:- """Which of the given flags a team in this project gates session recording on.+ """Single-project form of `replay_linked_flag_ids_for_projects`."""+ return replay_linked_flag_ids_for_projects([project_id], flag_ids)+++def replay_linked_flag_ids_for_projects(project_ids: Collection[int], flag_ids: Collection[int]) -> set[int]:+ """Which of the given flags a team in these projects gates session recording on.The batch equivalent of `teams_linking_flag`, in one query. Matching ids inside jsonb keepsthat check's comparison semantics, so the single-flag and bulk delete guards agree on whatcounts as linked; a malformed value like `{"id": true}` matches no flag, because jsonb neverequates booleans with numbers."""- if not flag_ids:+ if not flag_ids or not project_ids:return set()stored_ids = Team.objects.filter(- project_id=project_id,+ project_id__in=project_ids,session_recording_linked_flag__id__in=flag_ids,).values_list("session_recording_linked_flag__id", flat=True)# jsonb also equates numbers regardless of representation, so a stored float id can match andiff --git a/products/feature_flags/backend/temporal/__init__.py b/products/feature_flags/backend/temporal/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/feature_flags/backend/temporal/health_checks/__init__.py b/products/feature_flags/backend/temporal/health_checks/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/feature_flags/backend/temporal/health_checks/stale_flags.py b/products/feature_flags/backend/temporal/health_checks/stale_flags.pynew file mode 100644index 000000000000..204f21a7d175--- /dev/null+++ b/products/feature_flags/backend/temporal/health_checks/stale_flags.py@@ -0,0 +1,252 @@+from collections.abc import Collection+from datetime import datetime++from django.utils import timezone++import structlog++from posthog.clickhouse.query_tagging import Product+from posthog.job_owners import JobOwners+from posthog.models.health_issue import HealthIssue+from posthog.models.team import Team+from posthog.temporal.health_checks.detectors import HealthExecutionPolicy+from posthog.temporal.health_checks.framework import AlertContent, HealthCheck, Remediation+from posthog.temporal.health_checks.models import HealthCheckResult++from products.early_access_features.backend.models import EarlyAccessFeature+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.flag_status import (+ ROLLOUT_FULLY_ROLLED_OUT,+ ROLLOUT_NOT_ROLLED_OUT,+ ROLLOUT_PARTIAL,+ FeatureFlagStatusChecker,+ filter_stale_flags,+)+from products.feature_flags.backend.flag_version_sync import direct_flag_dependency_ids, flags_with_flag_dependencies+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.session_recording_links import replay_linked_flag_ids_for_projects+from products.product_tours.backend.models import ProductTour+from products.surveys.backend.models import Survey++logger = structlog.get_logger(__name__)++# `last_called_at` exists and predates the stale threshold. The column only records received+# `$feature_flag_called` events, so it says nothing about evaluations that send no event.+EVIDENCE_NOT_CALLED_RECENTLY = "not_called_recently"+# No call evidence at all; the flag is old enough and its configuration serves a fixed+# result. This says nothing about whether SDKs still evaluate the flag.+EVIDENCE_FULLY_ROLLED_OUT_WITHOUT_USAGE_DATA = "fully_rolled_out_without_usage_data"++_ROLLOUT_STATE_TEXT = {+ ROLLOUT_FULLY_ROLLED_OUT: "fully rolled out",+ ROLLOUT_NOT_ROLLED_OUT: "not rolled out",+ ROLLOUT_PARTIAL: "partially rolled out",+}+++class StaleFeatureFlagsCheck(HealthCheck):+ """One INFO issue per user-managed flag that qualifies as a cleanup candidate.++ The evidence layer for proactive stale-flag cleanup: the feature-flags scout reads+ these issues and authors the Inbox reports itself, so this check must not implement+ `render_signal` (the framework default returns None). A stale verdict is evidence for+ investigation, never proof that removal is safe.+ """++ name = "stale_feature_flags"+ kind = "stale_feature_flags"+ owner = JobOwners.TEAM_FEATURE_FLAGS+ product = Product.FEATURE_FLAGS+ schedule = "0 6 * * 1" # weekly, Mondays 06:00 UTC+ # Payloads carry flag keys and names.+ access_controlled_resource = "feature_flag"+ # Postgres-heavy and one issue per stale flag rather than per team, so smaller+ # batches than the default policy.+ policy = HealthExecutionPolicy(batch_size=250, max_concurrent=2)+ # Dry until the feature-flags scout can consume these issues; flipping this is an+ # operational checkpoint, not a code change to make casually.+ dry_run = True+ # dry_run stops the writes, not the detection queries. Sample teams until one batch of+ # this check has a measured cost, because filter_stale_flags has only ever run paginated+ # for a single team.+ rollout_percentage = 0.01+ remediation = Remediation(+ human="""+ Open the flag and confirm the staleness evidence is still current. Check every+ repository and runtime that evaluates the flag for code references, and check linked+ systems: experiments, surveys, early access features, session replay settings, and+ other flags that depend on it. Confirm the rollout intent with the flag's owner.+ Then clean up in this order: remove the code checks first and keep the winning+ behavior, merge and deploy, let the release soak, verify that no runtime still+ evaluates the flag, and only then archive it. Do not delete a flag that is rolled+ out to nobody while deployed code still checks it; the disabled path is still the+ code path in use.+ """,+ agent="""+ Read this issue with `health-issues-get`, then re-read the current flag definition+ with the feature-flag tools before acting; the issue's evidence is a snapshot and+ the flag may have changed since detection. Treat a stale verdict as evidence for+ investigation, not proof that removal is safe. Load the stale-flag cleanup skill if+ one is available. Search the user's repositories for the flag key, and check linked+ systems: experiments, surveys, early access features, session replay settings, and+ dependent flags. The cleanup order is fixed: remove code checks first, merge and+ deploy, observe a release soak, verify all relevant runtimes, and archive last.+ Never archive, disable, or delete the flag as part of health detection.+ """,+ )++ @classmethod+ def render_alert(cls, issue: HealthIssue) -> AlertContent:+ payload = issue.payload+ # Flag keys and names are project data; keep interpolated text bounded.+ flag_key = str(payload.get("flag_key") or "unknown")[:200]+ days = payload.get("days_since_evidence")+ if payload.get("evidence_class") == EVIDENCE_NOT_CALLED_RECENTLY:+ evidence_text = (+ f"PostHog has not received a call for this flag in {days} days"+ if isinstance(days, int)+ else "PostHog has not received a call for this flag recently"+ )+ else:+ evidence_text = "This flag has no usage data and its configuration serves a fixed result"+ rollout_text = _ROLLOUT_STATE_TEXT.get(payload.get("rollout_state"))+ rollout_sentence = f" The flag is {rollout_text}." if rollout_text else ""+ flag_id = payload.get("flag_id")+ return AlertContent(+ title=f"Feature flag '{flag_key}' may be ready for cleanup",+ summary=(+ f"{evidence_text}.{rollout_sentence} "+ "Review code references and linked systems before removing anything."+ ),+ link=f"/feature_flags/{flag_id}" if flag_id is not None else "/feature_flags",+ )++ def detect(self, team_ids: list[int]) -> dict[int, list[HealthCheckResult]]:+ candidates = list(+ filter_stale_flags(+ FeatureFlag.objects.filter(+ team_id__in=team_ids,+ deleted=False,+ archived=False,+ active=True,+ ).exclude(is_remote_configuration=True)+ )+ )+ if not candidates:+ return {}++ excluded_ids = _excluded_flag_ids(candidates)++ now = timezone.now()+ issues: dict[int, list[HealthCheckResult]] = {}+ for flag in candidates:+ if flag.id in excluded_ids:+ continue+ issues.setdefault(flag.team_id, []).append(_build_result(flag, now))++ if issues:+ # Each issue fires its own alert once dry_run flips, so the flip decision needs the+ # worst single team, which the framework's batch-wide dry-run summary does not show.+ issue_counts = [len(team_issues) for team_issues in issues.values()]+ logger.info(+ "stale_feature_flags_detected",+ teams_with_issues=len(issues),+ issue_count=sum(issue_counts),+ max_issues_per_team=max(issue_counts),+ )+ return issues+++def _excluded_flag_ids(candidates: list[FeatureFlag]) -> set[int]:+ """Flag ids that known blockers reference, not limited to the candidate ids.++ Every lookup is scoped by team or project rather than by candidate flag id, so each+ one binds a handful of parameters per batch and can return ids for flags outside it.++ Every lookup is one set-wise query over the batch; the count stays fixed as the+ candidate volume grows. These exclusions remove known blockers only. They do not prove+ the remaining flags are free of repository references or product intent.++ The bulk-delete guard in ``products/feature_flags/backend/api/feature_flag.py`` blocks+ the same references and must stay in step with this list. Where the two differ it is on+ purpose, and this list is the stricter one: the guard blocks only running experiments+ where this excludes every non-deleted one, and the guard's ``find_dependent_flags_batch``+ counts only active dependent flags where this also lets disabled dependents block.++ A survey's user-created ``linked_flag`` is deliberately not excluded, unlike the+ survey flags PostHog generates itself. It is user-managed, bulk delete permits it, and+ the remediation tells the investigator to check surveys. A reported flag is evidence+ to investigate, not a verdict that removal is safe.+ """+ flag_ids = [flag.id for flag in candidates]+ team_ids = {flag.team_id for flag in candidates}+ # Product tours, replay links, and flag dependencies are scoped by project, not by team:+ # another team in the same project can reference a flag this batch's teams own. A product+ # tour stays on the environment that created it, while a flag moves to the project root.+ # Surveys stay on team scope: Survey and FeatureFlag both inherit RootTeamMixin, so both+ # rows always sit on the project root team and their team ids line up.+ project_ids = set(Team.objects.filter(id__in=team_ids).values_list("project_id", flat=True))++ excluded: set[int] = set()+ excluded |= Survey.get_internal_flag_ids(team_ids=team_ids)+ excluded |= set(+ ProductTour.all_objects.filter(+ team__project_id__in=project_ids, internal_targeting_flag__isnull=False+ ).values_list("internal_targeting_flag_id", flat=True)+ )+ excluded |= set(+ Experiment.objects.filter(team_id__in=team_ids, deleted=False).values_list("feature_flag_id", flat=True)+ )+ excluded |= set(+ EarlyAccessFeature.objects.filter(team_id__in=team_ids, feature_flag_id__isnull=False).values_list(+ "feature_flag_id", flat=True+ )+ )+ excluded |= _depended_on_flag_ids(project_ids)+ excluded |= replay_linked_flag_ids_for_projects(project_ids, flag_ids)+ return excluded+++def _depended_on_flag_ids(project_ids: Collection[int]) -> set[int]:+ """Ids of flags that at least one non-deleted flag has a flag-type condition on.++ Matches local-evaluation payload semantics (all non-deleted flags, active or not):+ a disabled dependent still ships in the payload and can be re-enabled, so it must+ keep protecting its dependency from cleanup.+ """+ dependents = flags_with_flag_dependencies(project_ids)+ depended_on: set[int] = set()+ for dependent in dependents:+ depended_on |= direct_flag_dependency_ids(dependent)+ return depended_on+++def _build_result(flag: FeatureFlag, now: datetime) -> HealthCheckResult:+ checker = FeatureFlagStatusChecker(feature_flag=flag)+ summary = checker.get_rollout_summary(flag)+ rollout_state, winning_variant = checker.rollout_state_and_variant(flag, summary)++ if flag.last_called_at is not None:+ evidence_class = EVIDENCE_NOT_CALLED_RECENTLY+ evidence_date = flag.last_called_at+ else:+ evidence_class = EVIDENCE_FULLY_ROLLED_OUT_WITHOUT_USAGE_DATA+ evidence_date = flag.created_at++ return HealthCheckResult(+ severity=HealthIssue.Severity.INFO,+ payload={+ "flag_id": flag.id,+ "flag_key": flag.key,+ "flag_name": (flag.name or "")[:500],+ "evidence_class": evidence_class,+ "evidence_date": evidence_date.isoformat(),+ "days_since_evidence": (now - evidence_date).days,+ "rollout_state": rollout_state,+ "winning_variant": winning_variant,+ "has_targeting_conditions": summary.has_targeting_conditions,+ "max_rollout_percentage": summary.max_rollout_percentage,+ "flag_version": flag.version,+ },+ hash_keys=["flag_id"],+ )diff --git a/products/feature_flags/backend/temporal/health_checks/tests/__init__.py b/products/feature_flags/backend/temporal/health_checks/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py b/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.pynew file mode 100644index 000000000000..1ea2535df330--- /dev/null+++ b/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py@@ -0,0 +1,420 @@+from datetime import timedelta+from typing import Any++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.db import connection+from django.test import SimpleTestCase+from django.test.utils import CaptureQueriesContext+from django.utils import timezone++from parameterized import parameterized++from posthog.clickhouse.query_tagging import Product+from posthog.job_owners import JobOwners+from posthog.models.health_issue import HealthIssue+from posthog.models.team import Team+from posthog.tasks.health_checks import evaluate_health_check_for_team+from posthog.temporal.health_checks.processing import _process_batch_detection+from posthog.temporal.health_checks.registry import HEALTH_CHECKS, ensure_registry_loaded++from products.early_access_features.backend.models import EarlyAccessFeature+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.flag_status import ROLLOUT_FULLY_ROLLED_OUT, ROLLOUT_NOT_ROLLED_OUT, ROLLOUT_PARTIAL+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.temporal.health_checks.stale_flags import (+ EVIDENCE_FULLY_ROLLED_OUT_WITHOUT_USAGE_DATA,+ EVIDENCE_NOT_CALLED_RECENTLY,+ StaleFeatureFlagsCheck,+)+from products.product_tours.backend.models import ProductTour+from products.surveys.backend.models import Survey++FULL_ROLLOUT_FILTERS = {"groups": [{"properties": [], "rollout_percentage": 100}]}+++def stale_by_config() -> dict[str, Any]:+ return {"created_at": timezone.now() - timedelta(days=60), "filters": FULL_ROLLOUT_FILTERS}+++def stale_by_usage() -> dict[str, Any]:+ return {+ "last_called_at": timezone.now() - timedelta(days=45),+ "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},+ }+++class TestStaleFlagsDetect(BaseTest):+ def _create_flag(self, key: str, **kwargs: Any) -> FeatureFlag:+ kwargs.setdefault("active", True)+ return FeatureFlag.objects.create(team=self.team, key=key, created_by=self.user, **kwargs)++ def _detect(self, team_ids: list[int] | None = None) -> dict[int, list]:+ return StaleFeatureFlagsCheck().detect(team_ids or [self.team.id])++ def _create_dependent_flag(self, key: str, dependency: FeatureFlag, **kwargs: Any) -> FeatureFlag:+ return self._create_flag(+ key,+ filters={+ "groups": [+ {+ "properties": [+ {+ "type": "flag",+ "key": str(dependency.id),+ "operator": "flag_evaluates_to",+ "value": True,+ }+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ **kwargs,+ )++ def _link(self, link: str, flag: FeatureFlag) -> None:+ if link == "survey_targeting":+ Survey.objects.create(team=self.team, name="s", type="popover", targeting_flag=flag)+ elif link == "survey_linked":+ Survey.objects.create(team=self.team, name="s", type="popover", linked_flag=flag)+ elif link == "product_tour":+ ProductTour.objects.create(team=self.team, name="t", content={"steps": []}, internal_targeting_flag=flag)+ elif link == "child_environment_product_tour":+ # A tour row keeps the environment it was created on, while the flag belongs to the+ # project root team, so the tour's team id is never a candidate team id.+ child_environment = Team.objects.create(+ organization=self.organization, project=self.project, parent_team=self.team, name="child env"+ )+ ProductTour.objects.create(+ team=child_environment, name="t", content={"steps": []}, internal_targeting_flag=flag+ )+ elif link == "archived_product_tour":+ ProductTour.all_objects.create(+ team=self.team, name="t", content={"steps": []}, internal_targeting_flag=flag, archived=True+ )+ elif link == "experiment":+ Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=flag)+ elif link == "deleted_experiment":+ Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=flag, deleted=True)+ elif link == "early_access_feature":+ EarlyAccessFeature.objects.create(team=self.team, name="f", stage="beta", feature_flag=flag)+ elif link == "dependent_flag":+ self._create_dependent_flag("dependent-on-candidate", flag)+ elif link == "disabled_dependent_flag":+ self._create_dependent_flag("disabled-dependent", flag, active=False)+ elif link == "replay_link":+ # Queryset update instead of save so no Team receivers run in the fixture.+ Team.objects.filter(pk=self.team.pk).update(session_recording_linked_flag={"id": flag.id, "key": flag.key})+ else:+ raise ValueError(link)++ @parameterized.expand(+ [+ ("recently_evaluated", {"last_called_at": timezone.now() - timedelta(days=5)}, None, False),+ ("stale_by_usage", stale_by_usage(), None, True),+ ("stale_by_config", stale_by_config(), None, True),+ ("young_without_usage", {"filters": FULL_ROLLOUT_FILTERS}, None, False),+ ("disabled", {**stale_by_usage(), "active": False}, None, False),+ # The archived_flag_must_be_disabled DB constraint forces active=False here.+ ("archived", {**stale_by_usage(), "archived": True, "active": False}, None, False),+ ("soft_deleted", {**stale_by_usage(), "deleted": True}, None, False),+ ("remote_config", {**stale_by_config(), "is_remote_configuration": True}, None, False),+ # The column is nullable; a NULL row is not remote config and must stay reportable.+ ("remote_config_null_still_reported", {**stale_by_config(), "is_remote_configuration": None}, None, True),+ ("survey_targeting_flag", stale_by_config(), "survey_targeting", False),+ ("survey_user_linked_flag", stale_by_config(), "survey_linked", True),+ ("product_tour_internal_flag", stale_by_config(), "product_tour", False),+ ("archived_product_tour_still_blocks", stale_by_config(), "archived_product_tour", False),+ ("child_environment_product_tour_blocks", stale_by_config(), "child_environment_product_tour", False),+ ("experiment_linked", stale_by_config(), "experiment", False),+ ("deleted_experiment_does_not_block", stale_by_config(), "deleted_experiment", True),+ ("early_access_feature_flag", stale_by_config(), "early_access_feature", False),+ ("depended_on_by_active_flag", stale_by_usage(), "dependent_flag", False),+ # Local-evaluation semantics: a disabled dependent still protects its dependency.+ ("disabled_dependent_still_blocks", stale_by_usage(), "disabled_dependent_flag", False),+ ("replay_linked", stale_by_config(), "replay_link", False),+ ]+ )+ def test_detect_inclusion_and_exclusion(+ self, key: str, flag_kwargs: dict[str, Any], link: str | None, expected_included: bool+ ) -> None:+ flag = self._create_flag(key, **flag_kwargs)+ if link is not None:+ self._link(link, flag)++ results = self._detect()++ included = any(result.payload["flag_id"] == flag.id for result in results.get(self.team.id, []))+ assert included is expected_included++ # (name, flag_kwargs, expected payload subset)+ @parameterized.expand(+ [+ (+ "full_rollout_without_usage_data",+ stale_by_config(),+ {+ "evidence_class": EVIDENCE_FULLY_ROLLED_OUT_WITHOUT_USAGE_DATA,+ "rollout_state": ROLLOUT_FULLY_ROLLED_OUT,+ "days_since_evidence": 60,+ "has_targeting_conditions": False,+ "max_rollout_percentage": 100,+ "winning_variant": None,+ },+ ),+ (+ "not_rolled_out_by_usage",+ {+ "last_called_at": timezone.now() - timedelta(days=45),+ "filters": {"groups": [{"properties": [], "rollout_percentage": 0}]},+ },+ {+ "evidence_class": EVIDENCE_NOT_CALLED_RECENTLY,+ "rollout_state": ROLLOUT_NOT_ROLLED_OUT,+ "days_since_evidence": 45,+ },+ ),+ (+ "partial_by_usage",+ stale_by_usage(),+ {"evidence_class": EVIDENCE_NOT_CALLED_RECENTLY, "rollout_state": ROLLOUT_PARTIAL},+ ),+ (+ "targeted_full_rollout_is_partial",+ {+ "last_called_at": timezone.now() - timedelta(days=45),+ "filters": {+ "groups": [+ {"properties": [{"key": "email", "value": "x"}], "rollout_percentage": 100},+ ]+ },+ },+ {"rollout_state": ROLLOUT_PARTIAL, "has_targeting_conditions": True, "max_rollout_percentage": 100},+ ),+ (+ "multivariate_winning_variant",+ {+ "created_at": timezone.now() - timedelta(days=60),+ "filters": {+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},+ "groups": [{"properties": [], "rollout_percentage": 100}],+ },+ },+ {+ "evidence_class": EVIDENCE_FULLY_ROLLED_OUT_WITHOUT_USAGE_DATA,+ "rollout_state": ROLLOUT_FULLY_ROLLED_OUT,+ "winning_variant": "control",+ },+ ),+ ]+ )+ def test_payload_evidence_and_rollout(+ self, key: str, flag_kwargs: dict[str, Any], expected: dict[str, Any]+ ) -> None:+ flag = self._create_flag(key, name="Flag under test", **flag_kwargs)++ results = self._detect()++ result = next(r for r in results[self.team.id] if r.payload["flag_id"] == flag.id)+ assert result.severity == HealthIssue.Severity.INFO+ assert result.hash_keys == ["flag_id"]+ assert result.payload["flag_key"] == key+ assert result.payload["flag_name"] == "Flag under test"+ assert result.payload["flag_version"] == flag.version+ for field, value in expected.items():+ assert result.payload[field] == value, field++ def test_payload_truncates_flag_name(self) -> None:+ flag = self._create_flag("long-name", name="x" * 600, **stale_by_usage())++ results = self._detect()++ result = next(r for r in results[self.team.id] if r.payload["flag_id"] == flag.id)+ assert result.payload["flag_name"] == "x" * 500++ def test_manual_refresh_task_honors_dry_run(self) -> None:+ self._create_flag("manual-refresh", **stale_by_usage())++ evaluate_health_check_for_team(kind="stale_feature_flags", team_id=self.team.id)++ assert not HealthIssue.objects.filter(team=self.team, kind="stale_feature_flags").exists()++ def test_batches_multiple_teams(self) -> None:+ team_two = Team.objects.create(organization=self.organization, name="two")+ healthy_team = Team.objects.create(organization=self.organization, name="healthy")+ self._create_flag("first", **stale_by_usage())+ self._create_flag("second", **stale_by_config())+ FeatureFlag.objects.create(team=team_two, key="third", created_by=self.user, active=True, **stale_by_usage())+ # A blocker on the second team proves the exclusion lookups cover the whole batch,+ # not just the first team.+ blocked = FeatureFlag.objects.create(+ team=team_two, key="blocked", created_by=self.user, active=True, **stale_by_usage()+ )+ Team.objects.filter(pk=team_two.pk).update(session_recording_linked_flag={"id": blocked.id, "key": blocked.key})++ results = self._detect([self.team.id, team_two.id, healthy_team.id])++ assert set(results) == {self.team.id, team_two.id}+ assert len(results[self.team.id]) == 2+ assert len(results[team_two.id]) == 1+ assert results[team_two.id][0].payload["flag_id"] != blocked.id++ def test_query_count_does_not_grow_with_candidates_or_teams(self) -> None:+ self._create_flag("baseline", **stale_by_usage())+ check = StaleFeatureFlagsCheck()++ with CaptureQueriesContext(connection) as before:+ check.detect([self.team.id])++ FeatureFlag.objects.bulk_create(+ FeatureFlag(+ team=self.team,+ key=f"bulk-stale-{index}",+ active=True,+ created_at=timezone.now() - timedelta(days=60),+ filters=FULL_ROLLOUT_FILTERS,+ created_by=self.user,+ )+ for index in range(20)+ )+ other_team = Team.objects.create(organization=self.organization, name="other")+ FeatureFlag.objects.create(+ team=other_team, key="other-stale", created_by=self.user, active=True, **stale_by_usage()+ )++ with CaptureQueriesContext(connection) as after:+ results = check.detect([self.team.id, other_team.id])++ assert len(results[self.team.id]) == 21+ assert len(results[other_team.id]) == 1+ assert len(after) == len(before)++ @patch("posthog.temporal.health_checks.processing.emit_health_check_alert")+ def test_issue_lifecycle(self, _mock_alert) -> None:+ flag_a = self._create_flag("lifecycle-a", **stale_by_usage())+ flag_b = self._create_flag("lifecycle-b", **stale_by_usage())+ check = StaleFeatureFlagsCheck()++ def run() -> None:+ _process_batch_detection([self.team.id], check.kind, check.detect, dry_run=False)++ def active_issues():+ return HealthIssue.objects.filter(team=self.team, kind=check.kind, status=HealthIssue.Status.ACTIVE)++ run()+ assert active_issues().count() == 2+ issue_a = active_issues().get(payload__flag_id=flag_a.id)++ # Volatile evidence moves but the issue identity holds, so the row updates in place.+ flag_a.last_called_at = timezone.now() - timedelta(days=60)+ flag_a.save()+ run()+ assert active_issues().count() == 2+ refreshed_a = active_issues().get(payload__flag_id=flag_a.id)+ assert refreshed_a.id == issue_a.id+ assert refreshed_a.payload["days_since_evidence"] == 60++ # Flag A gets evaluated again; only its issue resolves.+ flag_a.last_called_at = timezone.now()+ flag_a.save()+ run()+ issue_a.refresh_from_db()+ assert issue_a.status == HealthIssue.Status.RESOLVED+ assert active_issues().get().payload["flag_id"] == flag_b.id++ # Flag A requalifies later; a fresh active issue appears beside the resolved history row.+ flag_a.last_called_at = timezone.now() - timedelta(days=40)+ flag_a.save()+ run()+ assert active_issues().count() == 2+ issue_a.refresh_from_db()+ assert issue_a.status == HealthIssue.Status.RESOLVED+ assert active_issues().get(payload__flag_id=flag_a.id).id != issue_a.id+++class TestStaleFlagsContract(SimpleTestCase):+ def _issue(self, payload: dict[str, Any]) -> HealthIssue:+ return HealthIssue(+ team_id=1,+ kind="stale_feature_flags",+ severity=HealthIssue.Severity.INFO,+ payload=payload,+ unique_hash="h",+ )++ def test_registered_with_dry_run_and_feature_flags_ownership(self) -> None:+ ensure_registry_loaded()+ registration = HEALTH_CHECKS["stale_feature_flags"]+ assert registration.dry_run is True+ assert registration.owner == JobOwners.TEAM_FEATURE_FLAGS+ assert registration.product == Product.FEATURE_FLAGS+ # The weekly cadence and 1% sampling are operational guards like dry_run: the full-batch+ # query cost is unmeasured, so widening either must be a deliberate change.+ assert registration.schedule == "0 6 * * 1"+ assert registration.rollout_percentage == 0.01+ assert registration.remediation is not None+ # Payloads carry flag keys and names, so the Health API must gate them on flag access.+ assert registration.access_controlled_resource == "feature_flag"++ def test_remediation_orders_code_removal_before_archive(self) -> None:+ remediation = StaleFeatureFlagsCheck.remediation+ assert remediation is not None+ for text, code_removal in (+ (remediation.human, "remove the code checks"),+ (remediation.agent, "remove code checks"),+ ):+ assert text.index(code_removal) < text.index("deploy") < text.index("archive")+ assert "Never archive, disable, or delete" in remediation.agent++ def test_render_alert_for_usage_evidence(self) -> None:+ content = StaleFeatureFlagsCheck.render_alert(+ self._issue(+ {+ "flag_id": 42,+ "flag_key": "checkout-v2",+ "evidence_class": EVIDENCE_NOT_CALLED_RECENTLY,+ "days_since_evidence": 45,+ "rollout_state": ROLLOUT_FULLY_ROLLED_OUT,+ }+ )+ )+ assert content.title == "Feature flag 'checkout-v2' may be ready for cleanup"+ assert "PostHog has not received a call for this flag in 45 days" in content.summary+ assert "fully rolled out" in content.summary+ assert "Review code references" in content.summary+ assert content.link == "/feature_flags/42"++ def test_render_alert_truncates_flag_key(self) -> None:+ content = StaleFeatureFlagsCheck.render_alert(+ self._issue(+ {+ "flag_id": 1,+ "flag_key": "k" * 400,+ "evidence_class": EVIDENCE_NOT_CALLED_RECENTLY,+ }+ )+ )+ assert content.title == f"Feature flag '{'k' * 200}' may be ready for cleanup"+ assert "PostHog has not received a call for this flag recently" in content.summary+ assert "The flag is" not in content.summary++ def test_render_alert_for_config_evidence(self) -> None:+ content = StaleFeatureFlagsCheck.render_alert(+ self._issue(+ {+ "flag_id": 7,+ "flag_key": "legacy-toggle",+ "evidence_class": EVIDENCE_FULLY_ROLLED_OUT_WITHOUT_USAGE_DATA,+ "rollout_state": ROLLOUT_NOT_ROLLED_OUT,+ }+ )+ )+ assert "no usage data" in content.summary+ assert "serves a fixed result" in content.summary+ assert content.link == "/feature_flags/7"++ def test_render_signal_returns_none(self) -> None:+ issue = self._issue({"flag_id": 42, "flag_key": "checkout-v2"})+ assert StaleFeatureFlagsCheck.render_signal(issue) is Nonediff --git a/products/surveys/backend/models.py b/products/surveys/backend/models.pyindex 17cb8ec52458..6bcfc38b33ce 100644--- a/products/surveys/backend/models.py+++ b/products/surveys/backend/models.py@@ -1,5 +1,6 @@import jsonimport uuid+from collections.abc import Collectionfrom datetime import timedeltafrom typing import TYPE_CHECKING@@ -313,7 +314,7 @@ class Survey(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):def get_internal_flag_ids(cls,*,- team_id: int | None = None,+ team_ids: Collection[int] | None = None,project_id: int | None = None,using: str = "default",) -> set[int]:@@ -328,19 +329,19 @@ class Survey(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):Note: The user-created `linked_flag` is NOT included since it's user-managed.Args:- team_id: Filter by team ID (use for team-scoped queries)+ team_ids: Filter by a batch of team IDs (use for batched jobs like health checks)project_id: Filter by project ID (use for project-scoped queries)using: Database alias to use (e.g., "default" or "replica")Returns:Set of feature flag IDs linked to surveys"""- if team_id is not None:- queryset = cls.objects.db_manager(using).filter(team_id=team_id)+ if team_ids is not None:+ queryset = cls.objects.db_manager(using).filter(team_id__in=team_ids)elif project_id is not None:queryset = cls.objects.db_manager(using).filter(team__project_id=project_id)else:- raise ValueError("Either team_id or project_id must be provided")+ raise ValueError("Either team_ids or project_id must be provided")return {flag_iddiff --git a/products/web_analytics/backend/max_tools.py b/products/web_analytics/backend/max_tools.pyindex 477503acec5d..bf25f5fc0442 100644--- a/products/web_analytics/backend/max_tools.py+++ b/products/web_analytics/backend/max_tools.py@@ -26,8 +26,8 @@ from posthog.models.health_issue import HealthIssuefrom posthog.scopes import APIScopeObjectfrom posthog.sync import database_sync_to_async, database_sync_to_async_poolfrom posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP-from posthog.temporal.health_checks.processing import _process_batch_detection-from posthog.temporal.health_checks.registry import HEALTH_CHECKS, ensure_registry_loaded, get_detect_fn+from posthog.temporal.health_checks.processing import run_check_for_team+from posthog.temporal.health_checks.registry import HEALTH_CHECKS, ensure_registry_loadedfrom products.access_control.backend.facade.user_access_control import AccessControlLevelfrom products.replay_vision.backend.facade.api import fetch_page_session_observations@@ -328,8 +328,7 @@ class WebAnalyticsDoctorTool(MaxTool):def _reevaluate_one_check(team_id: int, kind: str) -> None:- detect_fn = get_detect_fn(kind)- _process_batch_detection(team_ids=[team_id], kind=kind, detect_fn=detect_fn)+ run_check_for_team(kind=kind, team_id=team_id)def _load_active_web_issues(team_id: int, kinds: list[str]) -> list[HealthIssue]:diff --git a/products/web_analytics/backend/test/test_web_analytics_doctor_tool.py b/products/web_analytics/backend/test/test_web_analytics_doctor_tool.pyindex 0d8d8d221b6c..be97ccb2323d 100644--- a/products/web_analytics/backend/test/test_web_analytics_doctor_tool.py+++ b/products/web_analytics/backend/test/test_web_analytics_doctor_tool.py@@ -20,8 +20,8 @@ class TestWebAnalyticsDoctorTool(APIBaseTest):tool = self._create_tool()assert tool.get_required_resource_access() == [("web_analytics", "viewer")]- @patch("products.web_analytics.backend.max_tools._process_batch_detection")- async def test_reports_healthy_when_no_issues(self, _mock_process):+ @patch("products.web_analytics.backend.max_tools.run_check_for_team")+ async def test_reports_healthy_when_no_issues(self, _mock_run_check):tool = self._create_tool()content, artifact = await tool._arun_impl()@@ -34,8 +34,8 @@ class TestWebAnalyticsDoctorTool(APIBaseTest):assert "partial_proxy" in artifact["ran_kinds"]assert "authorized_urls" in artifact["ran_kinds"]- @patch("products.web_analytics.backend.max_tools._process_batch_detection")- async def test_returns_active_issues_sorted_by_severity(self, _mock_process):+ @patch("products.web_analytics.backend.max_tools.run_check_for_team")+ async def test_returns_active_issues_sorted_by_severity(self, _mock_run_check):await HealthIssue.objects.acreate(team_id=self.team.id,kind="reverse_proxy",@@ -63,8 +63,8 @@ class TestWebAnalyticsDoctorTool(APIBaseTest):kinds = {i["kind"] for i in artifact["issues"]}assert kinds == {"reverse_proxy", "no_live_events"}- @patch("products.web_analytics.backend.max_tools._process_batch_detection")- async def test_renders_partial_proxy_host_lists(self, _mock_process):+ @patch("products.web_analytics.backend.max_tools.run_check_for_team")+ async def test_renders_partial_proxy_host_lists(self, _mock_run_check):await HealthIssue.objects.acreate(team_id=self.team.id,kind="partial_proxy",@@ -83,13 +83,13 @@ class TestWebAnalyticsDoctorTool(APIBaseTest):assert "proxied hosts: app.example.com" in contentassert "unproxied hosts: www.example.com" in content- @patch("products.web_analytics.backend.max_tools._process_batch_detection")- async def test_isolates_per_kind_failures(self, mock_process):- def selective_raiser(*, team_ids, kind, detect_fn):+ @patch("products.web_analytics.backend.max_tools.run_check_for_team")+ async def test_isolates_per_kind_failures(self, mock_run_check):+ def selective_raiser(*, kind, team_id):if kind == "reverse_proxy":raise RuntimeError("clickhouse went away")- mock_process.side_effect = selective_raiser+ mock_run_check.side_effect = selective_raisertool = self._create_tool()content, artifact = await tool._arun_impl()@@ -98,8 +98,8 @@ class TestWebAnalyticsDoctorTool(APIBaseTest):assert "no_live_events" in artifact["ran_kinds"]assert "could not be re-evaluated" in content- @patch("products.web_analytics.backend.max_tools._process_batch_detection")- async def test_ignores_issues_from_other_teams(self, _mock_process):+ @patch("products.web_analytics.backend.max_tools.run_check_for_team")+ async def test_ignores_issues_from_other_teams(self, _mock_run_check):other_team = await self.organization.teams.acreate(name="other team")await HealthIssue.objects.acreate(team_id=other_team.id,@@ -115,8 +115,8 @@ class TestWebAnalyticsDoctorTool(APIBaseTest):assert artifact["issues"] == []assert "looks healthy" in content- @patch("products.web_analytics.backend.max_tools._process_batch_detection")- async def test_ignores_resolved_and_dismissed_issues(self, _mock_process):+ @patch("products.web_analytics.backend.max_tools.run_check_for_team")+ async def test_ignores_resolved_and_dismissed_issues(self, _mock_run_check):await HealthIssue.objects.acreate(team_id=self.team.id,kind="reverse_proxy",