: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): sweep soft-deleted flags' usage dashboards by default (#82239)
Phil Haack624441fc016f
diff --git a/products/exports/backend/facade/api.py b/products/exports/backend/facade/api.pyindex 36b841d7526a..368c6e5bad36 100644--- a/products/exports/backend/facade/api.py+++ b/products/exports/backend/facade/api.py@@ -1,5 +1,6 @@"""Public Python interface for creating and retrieving one-off exports."""+from collections.abc import Collectionfrom datetime import timedeltafrom django.conf import settings@@ -21,6 +22,7 @@ from products.exports.backend.models.exported_asset import (get_content_response,save_content_from_file as _save_content_from_file,)+from products.exports.backend.models.subscription import Subscriptionfrom products.exports.backend.tasks.failure_handler import (InvalidExportContext as InvalidExportContext,RetryableExportError as RetryableExportError,@@ -99,6 +101,36 @@ def save_export_asset_content_from_file(_save_content_from_file(asset, file_path, max_database_bytes=max_database_bytes)+def insight_ids_with_subscriptions(insight_ids: Collection[int]) -> set[int]:+ """Which of the given insights have a subscription that has not been deleted.++ Paused subscriptions (enabled=False) count: disabling delivery does not withdraw the intent+ to deliver this insight again.+ """+ # Caller-supplied ids that are already team-scoped by the caller's own query; this only maps+ # ids to ids and returns no row data.+ # nosemgrep: idor-lookup-without-team+ return set(+ Subscription.objects.filter(insight_id__in=insight_ids, deleted=False).values_list("insight_id", flat=True)+ )+++def dashboard_ids_with_subscriptions(dashboard_ids: Collection[int]) -> set[int]:+ """Which of the given dashboards have a subscription that has not been deleted.++ Paused subscriptions (enabled=False) count: disabling delivery does not withdraw the intent+ to deliver this dashboard again.+ """+ # Caller-supplied ids that are already team-scoped by the caller's own query; this only maps+ # ids to ids and returns no row data.+ # nosemgrep: idor-lookup-without-team+ return set(+ Subscription.objects.filter(dashboard_id__in=dashboard_ids, deleted=False).values_list(+ "dashboard_id", flat=True+ )+ )++def _validate_adhoc_export_context(export_context: dict) -> None:"""The ad-hoc render pipeline (viewport sizing, the exporter page's Query dispatch)assumes an InsightVizNode-wrapped source; anything else renders a JSON dump insteaddiff --git a/products/feature_flags/backend/management/commands/delete_feature_flag_usage_insights.py b/products/feature_flags/backend/management/commands/delete_feature_flag_usage_insights.pyindex 074ec86a2a26..9923543f570e 100644--- a/products/feature_flags/backend/management/commands/delete_feature_flag_usage_insights.py+++ b/products/feature_flags/backend/management/commands/delete_feature_flag_usage_insights.py@@ -27,6 +27,7 @@ from posthog.utils import friendly_timefrom products.alerts.backend.facade.api import insight_ids_with_alertsfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.exports.backend.facade.api import dashboard_ids_with_subscriptions, insight_ids_with_subscriptionsfrom products.feature_flags.backend.api.feature_flag import (USAGE_DASHBOARD_DESCRIPTION_PREFIX,USAGE_DASHBOARD_NAME_PREFIX,@@ -108,9 +109,10 @@ class _SweepStats:class Command(BaseCommand):help = (- "Soft-delete the insights PostHog auto-generates on feature flag usage dashboards. "- "Mirrors the insight bulk_delete side effects (tiles, activity log) and nulls "- "FeatureFlag.usage_dashboard for any flag whose usage dashboard ends up empty."+ "Soft-delete the insights PostHog auto-generates on feature flag usage dashboards, whether "+ "the owning flag is live or soft-deleted. Mirrors the insight bulk_delete side effects "+ "(tiles, activity log) and nulls FeatureFlag.usage_dashboard for any flag whose usage "+ "dashboard ends up empty.")options: _SweepOptions@@ -134,10 +136,10 @@ class Command(BaseCommand):"--include-orphaned",action="store_true",help=(- "Also sweep classified insights not reachable from any live FeatureFlag.usage_dashboard "- "(e.g. left behind when a flag was deleted). Off by default, so only insights on a "- "live flag usage dashboard are removed. Scans the whole insight table, so run it "- "off-peak."+ "Also sweep classified insights on generated dashboards that no flag row references, "+ "e.g. when a soft-deleted flag is hard-deleted to free its key for reuse. "+ "Off by default, so only insights a flag row (live or soft-deleted) still points at "+ "are removed. Scans the whole insight table, so run it off-peak."),)parser.add_argument(@@ -235,7 +237,8 @@ class Command(BaseCommand):time.sleep(self.options.sleep_interval)def _keep_ids(self, candidates: list[_Candidate]) -> set[int]:- """Candidates to keep: edited, favorited, alerted, publicly shared, or on the keep-list file.+ """Candidates to keep: edited, favorited, alerted, publicly shared, subscribed to, on a+ dashboard that is itself shared or subscribed to, or on the keep-list file.An insight without `is_sample` is one somebody edited. The generator sets that marker on everyinsight it creates, and `InsightSerializer.update` clears it on any PATCH, so its absence is@@ -251,9 +254,31 @@ class Command(BaseCommand):keep |= set(SharingConfiguration.objects.filter(insight_id__in=ids, enabled=True).values_list("insight_id", flat=True))+ keep |= insight_ids_with_subscriptions(ids)keep |= insight_ids_with_alerts(ids)+ keep |= self._ids_on_dashboards_in_use(ids)return keep+ def _ids_on_dashboards_in_use(self, insight_ids: list[int]) -> set[int]:+ """Insights with a live tile on a dashboard that is itself shared or subscribed to.++ A dashboard-level share link or scheduled delivery serves every tile on the dashboard, so+ sweeping any of them would blank a surface someone still reads. The insight-level checks in+ `_keep_ids` cannot see these: a dashboard's SharingConfiguration and Subscription rows carry+ no insight id.+ """+ tiles = list(DashboardTile.objects.filter(insight_id__in=insight_ids).values_list("insight_id", "dashboard_id"))+ dashboard_ids = {dashboard_id for _, dashboard_id in tiles}+ if not dashboard_ids:+ return set()+ in_use = set(+ SharingConfiguration.objects.filter(dashboard_id__in=dashboard_ids, enabled=True).values_list(+ "dashboard_id", flat=True+ )+ )+ in_use |= dashboard_ids_with_subscriptions(dashboard_ids)+ return {insight_id for insight_id, dashboard_id in tiles if dashboard_id in in_use}+def _deletable(self, candidates: list[_Candidate]) -> list[_Candidate]:"""Candidates with no keep signal, truncated to what --limit still allows. Records the kept count."""keep = self._keep_ids(candidates)@@ -335,7 +360,10 @@ class Command(BaseCommand):return had_tiles - keeps_a_tiledef _unlink_usage_dashboards(self, emptied: set[int]) -> None:- """Null usage_dashboard on every flag pointing at one of these dashboards.+ """Null usage_dashboard on every flag pointing at one of these dashboards, soft-deleted flags+ included: FeatureFlagViewSet.dashboard regenerates only when the FK is null or its dashboard+ row is deleted, and this sweep leaves the dashboard alive, so a flag restored while still+ linked would reopen its emptied dashboard instead.Reports the pairs it severs: unlike the soft deletes, this write keeps no copy of the oldvalue, so its own output is what makes the run reversible.@@ -343,21 +371,33 @@ class Command(BaseCommand):# Read the pairs once and write against those ids, so the lines an operator would replay from# are the rows actually written.severed = list(- FeatureFlag.objects.filter(usage_dashboard_id__in=emptied).values_list("id", "usage_dashboard_id")+ FeatureFlag.objects_including_soft_deleted.filter(usage_dashboard_id__in=emptied).values_list(+ "id", "usage_dashboard_id"+ ))for flag_id, dashboard_id in severed:self.stdout.write(f" unlink flag_id={flag_id} usage_dashboard_id={dashboard_id}")if not self.options.dry_run:- FeatureFlag.objects.filter(id__in=[flag_id for flag_id, _ in severed]).update(usage_dashboard=None)+ FeatureFlag.objects_including_soft_deleted.filter(id__in=[flag_id for flag_id, _ in severed]).update(+ usage_dashboard=None+ )self.stats.flags_nulled += len(severed)- def _delete_referential(self) -> None:- """Pass 1: the authoritative set, meaning insights on a live FeatureFlag.usage_dashboard that- match the classifier."""- flags = FeatureFlag.objects.filter(usage_dashboard_id__isnull=False)+ def _usage_dashboard_flags(self) -> QuerySet[FeatureFlag]:+ """Every flag row that vouches for a usage dashboard, soft-deleted rows included: deleting+ a flag never touches usage_dashboard, so the row still proves PostHog generated whatever+ the dashboard holds. Pass 1 scans it and pass 2 excludes it, so both passes must read flags+ through this one queryset.+ """+ flags = FeatureFlag.objects_including_soft_deleted.filter(usage_dashboard_id__isnull=False)if self.options.team_id is not None:flags = flags.filter(team_id=self.options.team_id)- flag_rows = flags.order_by("id").values_list("id", "usage_dashboard_id")+ return flags++ def _delete_referential(self) -> None:+ """Pass 1: the authoritative set, meaning insights on any FeatureFlag.usage_dashboard that+ match the classifier."""+ flag_rows = self._usage_dashboard_flags().order_by("id").values_list("id", "usage_dashboard_id")self.stdout.write("Pass 1 (referential): scanning feature flags with a usage dashboard")last_id = 0@@ -395,11 +435,12 @@ class Command(BaseCommand):self._throttle(wrote=bool(deletable or emptied))def _delete_orphaned(self) -> None:- """Pass 2 (opt-in): generated insights left on a generated dashboard no live flag points at."""- live_usage_dashboards = FeatureFlag.objects.filter(usage_dashboard_id__isnull=False)+ """Pass 2 (opt-in): generated insights left on a generated dashboard no flag row points at."""# Anchor on the dashboard the generator stamps, so a name match is never the only evidence that- # PostHog created the insight. Deleting a flag leaves its dashboard behind, which is what keeps- # the orphans reachable; ones whose dashboard was deleted outright stay out of scope.+ # PostHog created the insight. Pass 1 owns every dashboard a flag row still references, so this+ # pass exists for dashboards with no flag row at all (hard-deleted rows, see+ # _free_key_held_by_soft_deleted_flags in products/feature_flags/backend/api/feature_flag.py);+ # ones whose dashboard was deleted outright stay out of scope.generated_dashboards = Dashboard.objects.filter(creation_mode="template",name__startswith=USAGE_DASHBOARD_NAME_PREFIX,@@ -415,11 +456,10 @@ class Command(BaseCommand):),)if self.options.team_id is not None:- live_usage_dashboards = live_usage_dashboards.filter(team_id=self.options.team_id)insights = insights.filter(team_id=self.options.team_id)insight_rows = _candidate_rows(insights.order_by("id"))- self.stdout.write("Pass 2 (orphaned): scanning generated dashboards no live flag points at")+ self.stdout.write("Pass 2 (orphaned): scanning generated dashboards no flag row points at")last_id = 0while not self._limit_reached:batch = [_Candidate(**row) for row in insight_rows.filter(id__gt=last_id)[: self.options.batch_size]]@@ -427,11 +467,11 @@ class Command(BaseCommand):breaklast_id = batch[-1].id- # Drop any still reachable from a live usage dashboard, since pass 1 owns those.+ # Drop any still reachable from a flag's usage dashboard, since pass 1 owns those.reachable = set(DashboardTile.objects.filter(insight_id__in=[c.id for c in batch],- dashboard_id__in=live_usage_dashboards.values("usage_dashboard_id"),+ dashboard_id__in=self._usage_dashboard_flags().values("usage_dashboard_id"),).values_list("insight_id", flat=True))deletable = self._deletable([c for c in batch if c.id not in reachable])diff --git a/products/feature_flags/backend/management/commands/test/test_delete_feature_flag_usage_insights.py b/products/feature_flags/backend/management/commands/test/test_delete_feature_flag_usage_insights.pyindex 46ed1776bb0f..fcd079e82ada 100644--- a/products/feature_flags/backend/management/commands/test/test_delete_feature_flag_usage_insights.py+++ b/products/feature_flags/backend/management/commands/test/test_delete_feature_flag_usage_insights.py@@ -28,6 +28,8 @@ from products.feature_flags.backend.api.feature_flag import _create_usage_dashbofrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.models.insight import Insight+from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription+class TestDeleteFeatureFlagUsageInsights(BaseTest):def _flag_with_usage_dashboard(@@ -104,6 +106,19 @@ class TestDeleteFeatureFlagUsageInsights(BaseTest):assert logged is not Noneassert logged.is_system is True+ def test_sweeps_a_soft_deleted_flags_insights_by_default_and_nulls_its_usage_dashboard(self) -> None:+ # A default run must reach a soft-deleted flag's dashboard without --include-orphaned, and+ # must still sever the FK on the soft-deleted row itself, not just on live flags.+ flag = self._flag_with_usage_dashboard("soft-deleted")+ insights = self._usage_insights(flag)+ FeatureFlag.objects.filter(pk=flag.pk).update(deleted=True)++ self._run()++ assert Insight.objects.filter(id__in=[i.id for i in insights]).count() == 0+ flag.refresh_from_db()+ assert flag.usage_dashboard_id is None+def test_matches_generated_names_when_descriptions_have_drifted(self) -> None:# The name arms are the classifier's only reach once description wording changes, and the# descriptions are prose that a copy edit can reword. Clearing them isolates the name arms.@@ -117,7 +132,9 @@ class TestDeleteFeatureFlagUsageInsights(BaseTest):def test_orphaned_insights_are_swept_only_with_the_opt_in(self) -> None:# Guards the opt-in gate in both directions: a default run must leave orphans alone, and- # --include-orphaned must actually delete them.+ # --include-orphaned must actually delete them. Nulling usage_dashboard rather than deleting+ # the row models a hard-deleted flag: a dashboard is orphaned only when no flag row, live or+ # soft-deleted, points at it, and this update produces exactly that.flag = self._flag_with_usage_dashboard("orphan")insights = self._usage_insights(flag)FeatureFlag.objects.filter(id=flag.id).update(usage_dashboard=None)@@ -209,7 +226,9 @@ class TestDeleteFeatureFlagUsageInsights(BaseTest):assert Insight.objects.filter(id=unrelated.id).exists()- @parameterized.expand(["favorited", "edited", "sharing", "alert", "keep_list"])+ @parameterized.expand(+ ["favorited", "edited", "sharing", "subscription", "subscription_paused", "alert", "keep_list"]+ )def test_keeps_insight_with_usage_signal_and_leaves_dashboard_linked(self, signal: str) -> None:flag = self._flag_with_usage_dashboard(f"flag-{signal}")insights = self._usage_insights(flag)@@ -225,6 +244,8 @@ class TestDeleteFeatureFlagUsageInsights(BaseTest):kept.save()elif signal == "sharing":SharingConfiguration.objects.create(team=self.team, insight=kept, enabled=True)+ elif signal in ("subscription", "subscription_paused"):+ create_subscription(team=self.team, insight=kept, enabled=signal != "subscription_paused")elif signal == "alert":AlertConfiguration.objects.create(team=self.team, insight=kept, created_by=self.user, name="a")elif signal == "keep_list":@@ -240,6 +261,27 @@ class TestDeleteFeatureFlagUsageInsights(BaseTest):flag.refresh_from_db()assert flag.usage_dashboard_id is not None+ @parameterized.expand(["shared", "subscribed", "subscribed_paused"])+ def test_keeps_every_insight_on_a_dashboard_someone_shared_or_subscribed_to(self, signal: str) -> None:+ # A dashboard-level share link or scheduled delivery serves every tile, so no insight on such+ # a dashboard may be swept even though no insight-level signal marks any of them. The+ # insight-level cases above cannot catch a regression here: a dashboard's sharing and+ # subscription rows carry no insight id.+ flag = self._flag_with_usage_dashboard(f"dashboard-{signal}")+ insights = self._usage_insights(flag)+ if signal == "shared":+ SharingConfiguration.objects.create(team=self.team, dashboard_id=flag.usage_dashboard_id, enabled=True)+ else:+ create_subscription(+ team=self.team, dashboard_id=flag.usage_dashboard_id, enabled=signal != "subscribed_paused"+ )++ self._run()++ assert Insight.objects.filter(id__in=[i.id for i in insights]).count() == len(insights)+ flag.refresh_from_db()+ assert flag.usage_dashboard_id is not None+def test_writes_activity_rows_without_emitting_events(self) -> None:# The rows are the audit trail, but each one also emits a CDP event that can fire a customer's# webhooks and Slack destinations. A sweep must write the rows and emit nothing.diff --git a/tach.toml b/tach.tomlindex 0b4765ac5784..481b7f0b477a 100644--- a/tach.toml+++ b/tach.toml@@ -431,6 +431,7 @@ depends_on = ["products.dashboards","products.early_access_features","products.experiments",+ "products.exports","products.product_analytics","products.product_tours","products.surveys",