Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(flags): add command to delete auto-generated flag usage insights (#80029)

Phil Haack15f169767be4
diff --git a/posthog/helpers/dashboard_templates.py b/posthog/helpers/dashboard_templates.py
index 1ed9bfe41b48..c5c16923f722 100644
--- a/posthog/helpers/dashboard_templates.py
+++ b/posthog/helpers/dashboard_templates.py
@@ -702,7 +702,14 @@ def create_dashboard_from_template(
FEATURE_FLAG_TOTAL_VOLUME_INSIGHT_NAME = "Feature Flag Called Total Volume"
-FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME = "Feature Flag calls made by unique users per variant"
+# The unique-calls name embeds the pluralized aggregation entity, so only its ends are fixed.
+FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_PREFIX = "Feature Flag calls made by unique "
+FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_SUFFIX = " per variant"
+FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME = (
+ f"{FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_PREFIX}users{FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_SUFFIX}"
+)
+FEATURE_FLAG_ENRICHED_VIEW_INSIGHT_NAME = f"{ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER} Total Volume"
+FEATURE_FLAG_ENRICHED_INTERACTION_INSIGHT_NAME = "Feature Interaction Total Volume"
def _get_aggregation_entity_labels(feature_flag) -> tuple[str | None, str | None]:
@@ -776,7 +783,7 @@ def _get_feature_flag_unique_calls_insight_name(feature_flag) -> str:
_, plural = _get_aggregation_entity_labels(feature_flag)
if plural is None:
return FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME
- return f"Feature Flag calls made by unique {plural} per variant"
+ return f"{FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_PREFIX}{plural}{FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_SUFFIX}"
# The feature flag Usage tab renders these same charts inline for flags without a usage dashboard —
@@ -1199,7 +1206,7 @@ def add_enriched_insights_to_feature_flag_dashboard(feature_flag, dashboard: Das
# 1 row
_create_tile_for_insight(
dashboard,
- name=f"{ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER} Total Volume",
+ name=FEATURE_FLAG_ENRICHED_VIEW_INSIGHT_NAME,
description="Shows the total number of times this feature was viewed and interacted with",
query={
"kind": "InsightVizNode",
@@ -1247,7 +1254,7 @@ def add_enriched_insights_to_feature_flag_dashboard(feature_flag, dashboard: Das
_create_tile_for_insight(
dashboard,
- name="Feature Interaction Total Volume",
+ name=FEATURE_FLAG_ENRICHED_INTERACTION_INSIGHT_NAME,
description="Shows the total number of times this feature was viewed and interacted with",
query={
"kind": "InsightVizNode",
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 8cb3107f5d4f..e64bda1aca4a 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -1177,7 +1177,15 @@ class LogActivityEntry(TypedDict, total=False):
force_save: bool
-def bulk_log_activity(log_entries: list[LogActivityEntry], batch_size: int = 500) -> list[ActivityLog]:
+def bulk_log_activity(
+ log_entries: list[LogActivityEntry], batch_size: int = 500, *, notify: bool = True
+) -> list[ActivityLog]:
+ """Write activity log rows in bulk.
+
+ Each row created also fires `post_save`, which produces a CDP internal event so customer
+ destinations and workflows can react. Pass `notify=False` for a maintenance sweep, where that
+ fan-out would put one event per affected row onto the internal-events topic.
+ """
if not log_entries:
return []
@@ -1212,8 +1220,9 @@ def bulk_log_activity(log_entries: list[LogActivityEntry], batch_size: int = 500
def _do_bulk_create():
created_logs = ActivityLog.objects.bulk_create(activity_logs, batch_size=batch_size)
- for log in created_logs:
- post_save.send(sender=ActivityLog, instance=log, created=True)
+ if notify:
+ for log in created_logs:
+ post_save.send(sender=ActivityLog, instance=log, created=True)
return created_logs
diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.py
index 2add22858137..c892076e9de2 100644
--- a/products/alerts/backend/facade/api.py
+++ b/products/alerts/backend/facade/api.py
@@ -1,4 +1,5 @@
import uuid
+from collections.abc import Collection
from datetime import datetime, timedelta
from typing import Literal
from zoneinfo import ZoneInfo
@@ -54,6 +55,18 @@ def get_alert_team_id(alert_id: uuid.UUID) -> int | None:
return AlertConfiguration.objects.filter(id=alert_id).values_list("team_id", flat=True).first()
+def insight_ids_with_alerts(insight_ids: Collection[int]) -> set[int]:
+ """Which of the given insights have at least one alert configured.
+
+ Lets callers outside this product treat "an alert points at this insight" as a signal that
+ something depends on it, without importing the model.
+ """
+ # 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(AlertConfiguration.objects.filter(insight_id__in=insight_ids).values_list("insight_id", flat=True))
+
+
def snooze_alert_from_slack(
alert_id: uuid.UUID, *, user: User, duration: str | None = None, until: datetime | None = None
) -> SlackSnoozeOutcome:
@@ -151,6 +164,7 @@ __all__ = [
"build_alert_destination_config",
"create_alert_destination_hog_functions",
"get_alert_team_id",
+ "insight_ids_with_alerts",
"snooze_alert_from_slack",
"soft_delete_alert_destinations",
"soft_delete_all_alert_destinations",
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 5930c1b1fa58..e72351edf78a 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -2264,14 +2264,20 @@ class FeatureFlagSerializer(
return [{"id": exp.id, "name": exp.name, "is_running": exp.is_running} for exp in experiments]
+# Migration 0546 backfilled `creation_mode="template"` onto dashboards matching these, so together
+# they identify a generated usage dashboard even after its flag is gone.
+USAGE_DASHBOARD_NAME_PREFIX = "Generated Dashboard: "
+USAGE_DASHBOARD_DESCRIPTION_PREFIX = "This dashboard was generated by the feature flag with key ("
+
+
def _create_usage_dashboard(feature_flag: FeatureFlag, user):
from posthog.helpers.dashboard_templates import create_feature_flag_dashboard
from products.dashboards.backend.models.dashboard import Dashboard
usage_dashboard = Dashboard.objects.create(
- name="Generated Dashboard: " + feature_flag.key + " Usage",
- description="This dashboard was generated by the feature flag with key (" + feature_flag.key + ")",
+ name=USAGE_DASHBOARD_NAME_PREFIX + feature_flag.key + " Usage",
+ description=USAGE_DASHBOARD_DESCRIPTION_PREFIX + feature_flag.key + ")",
team=feature_flag.team,
created_by=user,
creation_mode="template",
diff --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.py
new file mode 100644
index 000000000000..074ec86a2a26
--- /dev/null
+++ b/products/feature_flags/backend/management/commands/delete_feature_flag_usage_insights.py
@@ -0,0 +1,447 @@
+from __future__ import annotations
+
+import time
+from dataclasses import dataclass, fields
+from typing import Any
+from uuid import UUID, uuid4
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.db import transaction
+from django.db.models import F, Q, QuerySet
+from django.utils.timezone import now
+
+from posthog.helpers.dashboard_templates import (
+ FEATURE_FLAG_ENRICHED_INTERACTION_INSIGHT_NAME,
+ FEATURE_FLAG_ENRICHED_VIEW_INSIGHT_NAME,
+ FEATURE_FLAG_TOTAL_VOLUME_INSIGHT_NAME,
+ FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_PREFIX,
+ FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_SUFFIX,
+)
+from posthog.models.activity_logging.activity_log import Detail, LogActivityEntry, Trigger, bulk_log_activity
+from posthog.models.file_system.constants import DEFAULT_SURFACE, surface_q
+from posthog.models.file_system.file_system import FileSystem
+from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
+from posthog.models.sharing_configuration import SharingConfiguration
+from posthog.utils import friendly_time
+
+from products.alerts.backend.facade.api import insight_ids_with_alerts
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.feature_flags.backend.api.feature_flag import (
+ USAGE_DASHBOARD_DESCRIPTION_PREFIX,
+ USAGE_DASHBOARD_NAME_PREFIX,
+)
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.product_analytics.backend.models.insight import Insight
+
+# Tags each activity-log entry so a sweep's deletions are distinguishable from a user's.
+_JOB_TYPE = "delete_feature_flag_usage_insights"
+
+
+def _classifier_q() -> Q:
+ """Match only the insights auto-generated for feature flag usage dashboards.
+
+ Keys on name and description, not on `is_sample`: every dashboard template sets that, so on its
+ own it would also match billing/usage and onboarding insights. Callers wanting a second signal
+ add it on top of this (see `_delete_orphaned`).
+ Names come from constants in posthog/helpers/dashboard_templates.py, which is what creates them.
+ Descriptions interpolate the flag key, so those are matched by fragment instead.
+ """
+ return (
+ Q(name=FEATURE_FLAG_TOTAL_VOLUME_INSIGHT_NAME)
+ | (
+ Q(name__startswith=FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_PREFIX)
+ & Q(name__endswith=FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_SUFFIX)
+ )
+ | Q(name=FEATURE_FLAG_ENRICHED_VIEW_INSIGHT_NAME)
+ | Q(name=FEATURE_FLAG_ENRICHED_INTERACTION_INSIGHT_NAME)
+ | Q(description__startswith="Shows the number of", description__contains="calls made on feature flag")
+ | Q(description__startswith="Shows the total number of times this feature was viewed")
+ )
+
+
+@dataclass(frozen=True, kw_only=True)
+class _Candidate:
+ """An insight considered for deletion, narrowed to the columns this sweep reads.
+
+ Read as values rather than model instances: `select_related("team")` ignores `TeamManager`'s
+ deferrals and would pull the fat taxonomy columns once per row, while `only()` turns
+ `Insight.__init__`'s read of `query` into a refetch per row.
+ """
+
+ id: int
+ short_id: str
+ name: str | None
+ derived_name: str | None
+ favorited: bool
+ is_sample: bool
+ team_id: int
+ organization_id: UUID
+
+
+# Derived so a new `_Candidate` field can't drift from the columns fetched to populate it.
+_CANDIDATE_FIELDS = tuple(f.name for f in fields(_Candidate))
+
+
+def _candidate_rows(insights: QuerySet[Insight]) -> QuerySet[Insight, dict[str, Any]]:
+ """Narrow an insight queryset to `_Candidate` values, keyed so each row splats into `_Candidate(**row)`."""
+ return insights.annotate(organization_id=F("team__organization_id")).values(*_CANDIDATE_FIELDS)
+
+
+@dataclass(frozen=True, kw_only=True)
+class _SweepOptions:
+ batch_size: int
+ sleep_interval: float
+ team_id: int | None
+ limit: int | None
+ dry_run: bool
+ include_orphaned: bool
+ keep_list_ids: frozenset[int]
+
+
+@dataclass(frozen=False)
+class _SweepStats:
+ deleted: int = 0
+ kept: int = 0
+ flags_nulled: int = 0
+
+
+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."
+ )
+
+ options: _SweepOptions
+ stats: _SweepStats
+ run_id: str
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--batch-size", type=int, default=100, help="Flags (pass 1) or insights (pass 2) per batch")
+ parser.add_argument("--sleep-interval", type=float, default=0.2, help="Sleep time between batches in seconds")
+ parser.add_argument("--team-id", type=int, help="Restrict to a single team")
+ parser.add_argument("--limit", type=int, help="Stop after soft-deleting this many insights (safety cap)")
+ parser.add_argument(
+ "--keep-ids-file",
+ type=str,
+ help=(
+ "Path to a file of insight IDs to keep (one leading integer per line). "
+ "Use this for the usage-based keep-list computed from the warehouse."
+ ),
+ )
+ parser.add_argument(
+ "--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."
+ ),
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Report what would be deleted without changing anything.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ self.options = _SweepOptions(
+ batch_size=options["batch_size"],
+ sleep_interval=options["sleep_interval"],
+ team_id=options["team_id"],
+ limit=options["limit"],
+ dry_run=options["dry_run"],
+ include_orphaned=options["include_orphaned"],
+ keep_list_ids=self._load_keep_ids(options["keep_ids_file"]),
+ )
+ self.stats = _SweepStats()
+ self.run_id = str(uuid4())
+
+ if self.options.dry_run:
+ self.stdout.write(self.style.WARNING("Running in dry-run mode - no changes will be made"))
+ else:
+ self.stdout.write(self.style.SUCCESS("Running in live mode - changes will be made to the database"))
+ self.stdout.write(
+ f"Configuration: batch_size={self.options.batch_size}, sleep_interval={self.options.sleep_interval}, "
+ f"team_id={self.options.team_id}, limit={self.options.limit}, "
+ f"include_orphaned={self.options.include_orphaned}, keep_list={len(self.options.keep_list_ids)}"
+ )
+
+ start_time = time.time()
+
+ self._delete_referential()
+ if self.options.include_orphaned:
+ self._delete_orphaned()
+
+ verb = "Would soft-delete" if self.options.dry_run else "Soft-deleted"
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"{verb} {self.stats.deleted} insights, kept {self.stats.kept} (usage/keep-list), "
+ f"nulled {self.stats.flags_nulled} flag usage_dashboard references "
+ f"in {friendly_time(time.time() - start_time)}"
+ )
+ )
+
+ def _load_keep_ids(self, path: str | None) -> frozenset[int]:
+ if not path:
+ return frozenset()
+ keep_ids: set[int] = set()
+ unparsed = 0
+ try:
+ # utf-8-sig so a BOM from a spreadsheet export doesn't eat the first id.
+ with open(path, encoding="utf-8-sig") as f:
+ for line in f:
+ stripped = line.strip()
+ if not stripped:
+ continue
+ columns = [c.strip().strip('"') for c in stripped.split(",")]
+ if len(columns) > 1 and columns[0].isdecimal() and columns[1].isdecimal():
+ # Two leading numbers means the id is probably not the column being read, as in
+ # a team_id,insight_id export. Guessing here would protect the wrong insights.
+ raise CommandError(
+ f"--keep-ids-file {path} has more than one numeric column on a line: {stripped!r}. "
+ "Expected one insight ID per line, as the first comma-separated value."
+ )
+ # isdecimal, not isdigit: isdigit accepts characters like "²" that int() rejects.
+ if columns[0].isdecimal():
+ keep_ids.add(int(columns[0]))
+ else:
+ unparsed += 1
+ except (OSError, UnicodeDecodeError) as e:
+ raise CommandError(f"Could not read --keep-ids-file {path}: {e}")
+ if unparsed and not keep_ids:
+ # This file is the only thing protecting in-use insights, so a total parse failure has to
+ # stop the run rather than silently sweep with no keep-list.
+ raise CommandError(
+ f"--keep-ids-file {path} yielded no insight IDs from {unparsed} non-blank lines. "
+ "Expected one insight ID per line, as the first comma-separated value."
+ )
+ if unparsed:
+ self.stdout.write(self.style.WARNING(f"Ignored {unparsed} unparsable lines in {path}"))
+ return frozenset(keep_ids)
+
+ @property
+ def _limit_reached(self) -> bool:
+ return self.options.limit is not None and self.stats.deleted >= self.options.limit
+
+ def _throttle(self, *, wrote: bool) -> None:
+ # A dry run issues only reads, so there is no write load to pace. Same for a batch that matched
+ # nothing, which is the common case on a re-run: pacing it only slows the scan down.
+ if self.options.dry_run or not wrote:
+ return
+ if self.options.sleep_interval > 0:
+ 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.
+
+ An insight without `is_sample` is one somebody edited. The generator sets that marker on every
+ insight it creates, and `InsightSerializer.update` clears it on any PATCH, so its absence is
+ the record that a user made this insight their own.
+
+ The keep-list file carries the warehouse-derived usage signals. Postgres does record insight
+ views in `InsightViewed`, but that is not usable as a keep signal here: the flag page embeds
+ the usage dashboard, and loading a dashboard records a view for every tile on it, so opening
+ a flag's Usage tab once marks all of its generated insights as viewed.
+ """
+ ids = [c.id for c in candidates]
+ keep = {c.id for c in candidates if c.favorited or not c.is_sample or c.id in self.options.keep_list_ids}
+ keep |= set(
+ SharingConfiguration.objects.filter(insight_id__in=ids, enabled=True).values_list("insight_id", flat=True)
+ )
+ keep |= insight_ids_with_alerts(ids)
+ return keep
+
+ 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)
+ self.stats.kept += len(keep)
+ deletable = [c for c in candidates if c.id not in keep]
+ if self.options.limit is not None:
+ deletable = deletable[: max(0, self.options.limit - self.stats.deleted)]
+ return deletable
+
+ def _soft_delete(self, insights: list[_Candidate]) -> None:
+ """Mirror InsightViewSet.bulk_delete (products/product_analytics/backend/api/insight.py): soft-delete
+ the insights and their tiles, then log each removal as system activity.
+
+ Three of bulk_delete's steps are deliberately dropped: its alert teardown, because `_keep_ids`
+ excludes alerted insights so none reach here; `last_modified_by`, because there is no acting
+ user; and its `team__project_id` guard, which the candidate query already provides.
+ """
+ insight_ids = [i.id for i in insights]
+ Insight.objects_including_soft_deleted.filter(id__in=insight_ids).update(deleted=True, last_modified_at=now())
+ DashboardTile.objects_including_soft_deleted.filter(insight_id__in=insight_ids).update(deleted=True)
+ self._prune_file_system_rows(insights)
+
+ entries: list[LogActivityEntry] = []
+ for insight in insights:
+ name = insight.name or insight.derived_name
+ if not name:
+ continue
+ entries.append(
+ LogActivityEntry(
+ organization_id=insight.organization_id,
+ team_id=insight.team_id,
+ user=None, # system-attributed (is_system=True)
+ was_impersonated=False,
+ item_id=insight.id,
+ scope="Insight",
+ activity="deleted",
+ detail=Detail(
+ name=name,
+ short_id=insight.short_id,
+ # Without this the customer's activity feed can't tell a maintenance sweep from
+ # someone on their own team deleting the insight.
+ trigger=Trigger(job_type=_JOB_TYPE, job_id=self.run_id, payload={}),
+ ),
+ )
+ )
+ # A sweep must not put one CDP internal event per deleted insight onto the topic.
+ bulk_log_activity(entries, notify=False)
+
+ def _prune_file_system_rows(self, insights: list[_Candidate]) -> None:
+ """Drop the project-tree rows for insights this sweep deleted.
+
+ `FileSystemSyncMixin` prunes these on save, but the soft delete above goes through `.update()`,
+ which fires no signal. Without this the swept insights stay listed under Unfiled/Insights and in
+ Recents, and clicking one lands on "Insight not found".
+ """
+ tree_refs = Q()
+ for insight in insights:
+ tree_refs |= Q(team_id=insight.team_id, ref=insight.short_id)
+ if not tree_refs:
+ return
+ surface = surface_q(DEFAULT_SURFACE)
+ FileSystem.objects.filter(surface, tree_refs, type="insight").delete()
+ FileSystemShortcut.objects.filter(surface, tree_refs, type="insight").delete()
+
+ def _emptied_usage_dashboards(self, dashboard_ids: set[int], deleted_insight_ids: set[int]) -> set[int]:
+ """Of these dashboards, the ones this delete leaves with no live tiles.
+
+ Only dashboards that still had a tile going in can be emptied by us, so a dashboard that was
+ already tile-less is left alone rather than counted as this run's work.
+ """
+ had_tiles: set[int] = set()
+ keeps_a_tile: set[int] = set()
+ for dashboard_id, insight_id in DashboardTile.objects.filter(dashboard_id__in=dashboard_ids).values_list(
+ "dashboard_id", "insight_id"
+ ):
+ had_tiles.add(dashboard_id)
+ if insight_id not in deleted_insight_ids:
+ keeps_a_tile.add(dashboard_id)
+ return had_tiles - keeps_a_tile
+
+ def _unlink_usage_dashboards(self, emptied: set[int]) -> None:
+ """Null usage_dashboard on every flag pointing at one of these dashboards.
+
+ Reports the pairs it severs: unlike the soft deletes, this write keeps no copy of the old
+ value, so its own output is what makes the run reversible.
+ """
+ # 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")
+ )
+ 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)
+ 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)
+ 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")
+
+ self.stdout.write("Pass 1 (referential): scanning feature flags with a usage dashboard")
+ last_id = 0
+ while not self._limit_reached:
+ flag_batch = list(flag_rows.filter(id__gt=last_id)[: self.options.batch_size])
+ if not flag_batch:
+ break
+ last_id = flag_batch[-1][0]
+ dashboard_ids = {dash_id for _, dash_id in flag_batch}
+
+ # Live tiles (default manager excludes deleted tiles and deleted dashboards) on these dashboards.
+ live_tiles = DashboardTile.objects.filter(dashboard_id__in=dashboard_ids, insight__isnull=False)
+ classified = Insight.objects.filter(_classifier_q(), id__in=live_tiles.values("insight_id"))
+ if self.options.team_id is not None:
+ classified = classified.filter(team_id=self.options.team_id)
+ classified = classified.order_by("id")
+ deletable = self._deletable([_Candidate(**row) for row in _candidate_rows(classified)])
+
+ emptied = self._emptied_usage_dashboards(dashboard_ids, {c.id for c in deletable})
+ if self.options.dry_run:
+ if emptied:
+ self._unlink_usage_dashboards(emptied)
+ else:
+ with transaction.atomic():
+ if deletable:
+ self._soft_delete(deletable)
+ if emptied:
+ self._unlink_usage_dashboards(emptied)
+ self.stats.deleted += len(deletable)
+
+ self.stdout.write(
+ f"Pass 1: through flag id {last_id} | deleted {self.stats.deleted} | kept {self.stats.kept} | "
+ f"flags nulled {self.stats.flags_nulled}"
+ )
+ 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)
+ # 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.
+ generated_dashboards = Dashboard.objects.filter(
+ creation_mode="template",
+ name__startswith=USAGE_DASHBOARD_NAME_PREFIX,
+ description__startswith=USAGE_DASHBOARD_DESCRIPTION_PREFIX,
+ )
+ # Requiring the generator's marker keeps rows an edit has already disqualified out of the scan
+ # entirely. `_keep_ids` would spare them anyway, so this only saves fetching them.
+ insights = Insight.objects.filter(
+ _classifier_q(),
+ is_sample=True,
+ id__in=DashboardTile.objects.filter(dashboard_id__in=generated_dashboards.values("id")).values(
+ "insight_id"
+ ),
+ )
+ 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")
+ last_id = 0
+ while not self._limit_reached:
+ batch = [_Candidate(**row) for row in insight_rows.filter(id__gt=last_id)[: self.options.batch_size]]
+ if not batch:
+ break
+ last_id = batch[-1].id
+
+ # Drop any still reachable from a live 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"),
+ ).values_list("insight_id", flat=True)
+ )
+ deletable = self._deletable([c for c in batch if c.id not in reachable])
+
+ if deletable and not self.options.dry_run:
+ with transaction.atomic():
+ self._soft_delete(deletable)
+ self.stats.deleted += len(deletable)
+
+ self.stdout.write(
+ f"Pass 2: through insight id {last_id} | deleted {self.stats.deleted} | kept {self.stats.kept}"
+ )
+ self._throttle(wrote=bool(deletable))
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.py
new file mode 100644
index 000000000000..46ed1776bb0f
--- /dev/null
+++ b/products/feature_flags/backend/management/commands/test/test_delete_feature_flag_usage_insights.py
@@ -0,0 +1,282 @@
+import tempfile
+from io import StringIO
+from pathlib import Path
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from parameterized import parameterized
+
+from posthog.helpers.dashboard_templates import (
+ FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME,
+ add_enriched_insights_to_feature_flag_dashboard,
+)
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.file_system.file_system import FileSystem
+from posthog.models.sharing_configuration import SharingConfiguration
+from posthog.models.team import Team
+from posthog.test.persons import create_group_type_mapping
+
+from products.alerts.backend.models.alert import AlertConfiguration
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.feature_flags.backend.api.feature_flag import _create_usage_dashboard
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.product_analytics.backend.models.insight import Insight
+
+
+class TestDeleteFeatureFlagUsageInsights(BaseTest):
+ def _flag_with_usage_dashboard(
+ self,
+ key: str,
+ enriched: bool = False,
+ aggregation_group_type_index: int | None = None,
+ team: Team | None = None,
+ ) -> FeatureFlag:
+ team = team or self.team
+ filters: dict[str, Any] = {"groups": [{"rollout_percentage": 100}]}
+ if aggregation_group_type_index is not None:
+ create_group_type_mapping(
+ team=team,
+ project_id=team.project_id,
+ group_type="organization",
+ group_type_index=aggregation_group_type_index,
+ )
+ # `FeatureFlag.aggregation_group_type_index` reads through to filters.
+ filters["aggregation_group_type_index"] = aggregation_group_type_index
+ flag = FeatureFlag.objects.create(team=team, created_by=self.user, key=key, filters=filters)
+ # Built through the API's own helper so the dashboard is shaped the way production shapes it.
+ dashboard = _create_usage_dashboard(flag, self.user)
+ if enriched:
+ add_enriched_insights_to_feature_flag_dashboard(flag, dashboard)
+ return flag
+
+ def _run(self, *args: str, team: Team | None = None, stdout: StringIO | None = None) -> None:
+ """Run the command scoped to one team, so a reused test database cannot feed it other rows."""
+ call_command(
+ "delete_feature_flag_usage_insights",
+ "--sleep-interval=0",
+ f"--team-id={(team or self.team).id}",
+ *args,
+ **({"stdout": stdout} if stdout is not None else {}),
+ )
+
+ def _usage_insights(self, flag: FeatureFlag) -> list[Insight]:
+ assert flag.usage_dashboard_id is not None
+ tile_insight_ids = DashboardTile.objects.filter(dashboard_id=flag.usage_dashboard_id).values_list(
+ "insight_id", flat=True
+ )
+ return list(Insight.objects_including_soft_deleted.filter(id__in=tile_insight_ids).order_by("id"))
+
+ @parameterized.expand(
+ [
+ ("user_aggregation", None, FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME),
+ ("group_aggregation", 0, "Feature Flag calls made by unique organizations per variant"),
+ ]
+ )
+ def test_deletes_all_four_generated_insights_and_nulls_usage_dashboard(
+ self, key: str, aggregation_group_type_index: int | None, expected_unique_calls_name: str
+ ) -> None:
+ # All four generated insights must come off the dashboard, so the flag ends up unlinked.
+ # The group case pins the pluralized unique-calls name the generator produces; its description
+ # matches the classifier's description arm too, so this does not isolate the name arms.
+ flag = self._flag_with_usage_dashboard(
+ key, enriched=True, aggregation_group_type_index=aggregation_group_type_index
+ )
+ dashboard_id = flag.usage_dashboard_id
+ assert dashboard_id is not None
+ insights = self._usage_insights(flag)
+ assert len(insights) == 4
+ assert expected_unique_calls_name in {i.name for i in insights}
+
+ self._run()
+
+ assert Insight.objects.filter(id__in=[i.id for i in insights]).count() == 0
+ assert DashboardTile.objects.filter(dashboard_id=dashboard_id).count() == 0
+ flag.refresh_from_db()
+ assert flag.usage_dashboard_id is None
+ # Activity is system-attributed since there is no request user.
+ logged = ActivityLog.objects.filter(scope="Insight", activity="deleted", item_id=str(insights[0].id)).first()
+ assert logged is not None
+ assert logged.is_system is True
+
+ 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.
+ flag = self._flag_with_usage_dashboard("drifted")
+ insights = self._usage_insights(flag)
+ Insight.objects.filter(id__in=[i.id for i in insights]).update(description="")
+
+ self._run()
+
+ assert Insight.objects.filter(id__in=[i.id for i in insights]).count() == 0
+
+ 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.
+ flag = self._flag_with_usage_dashboard("orphan")
+ insights = self._usage_insights(flag)
+ FeatureFlag.objects.filter(id=flag.id).update(usage_dashboard=None)
+
+ self._run()
+ assert Insight.objects.filter(id__in=[i.id for i in insights]).count() == len(insights)
+
+ self._run("--include-orphaned")
+ assert Insight.objects.filter(id__in=[i.id for i in insights]).count() == 0
+
+ def test_orphan_sweep_needs_a_generated_dashboard_not_just_a_matching_name(self) -> None:
+ # Pass 2 has no flag vouching for its candidates, so it anchors on the dashboard the generator
+ # stamps. Drop that anchor and it goes back to sweeping the whole insight table on a name match.
+ dashboard = Dashboard.objects.create(team=self.team, name="Someone's own dashboard")
+ lookalike = Insight.objects.create(
+ team=self.team, name=FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME, is_sample=True, saved=True
+ )
+ DashboardTile.objects.create(dashboard=dashboard, insight=lookalike)
+
+ self._run("--include-orphaned")
+
+ assert Insight.objects.filter(id=lookalike.id).exists()
+
+ def test_limit_caps_how_many_are_deleted(self) -> None:
+ # --limit is the operator's brake, and the truncation is hand-rolled arithmetic against a
+ # running total, so an off-by-one here means a capped run deletes everything.
+ flag = self._flag_with_usage_dashboard("capped")
+ insights = self._usage_insights(flag)
+
+ self._run("--limit=1")
+
+ assert Insight.objects.filter(id__in=[i.id for i in insights]).count() == len(insights) - 1
+ # The surviving insight is still a live tile, so the flag must keep its dashboard. Computing the
+ # emptied set before the limit truncation would unlink a flag whose dashboard still holds one.
+ flag.refresh_from_db()
+ assert flag.usage_dashboard_id is not None
+ assert DashboardTile.objects.filter(dashboard_id=flag.usage_dashboard_id).count() == 1
+
+ def test_team_id_confines_the_sweep_to_one_team(self) -> None:
+ # Losing this filter turns an operator's single-team run into a fleet-wide one.
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ mine = self._usage_insights(self._flag_with_usage_dashboard("mine"))
+ theirs = self._usage_insights(self._flag_with_usage_dashboard("theirs", team=other_team))
+
+ self._run()
+
+ assert Insight.objects.filter(id__in=[i.id for i in mine]).count() == 0
+ assert Insight.objects.filter(id__in=[i.id for i in theirs]).count() == len(theirs)
+
+ def test_leaves_flag_linked_when_its_dashboard_was_already_empty(self) -> None:
+ # Only dashboards this run empties should be unlinked. A dashboard that was already tile-less
+ # (the user cleared it, or it is in the trash) is not this command's to sever.
+ flag = self._flag_with_usage_dashboard("already-empty")
+ assert flag.usage_dashboard_id is not None
+ DashboardTile.objects_including_soft_deleted.filter(dashboard_id=flag.usage_dashboard_id).delete()
+
+ self._run()
+
+ flag.refresh_from_db()
+ assert flag.usage_dashboard_id is not None
+
+ @parameterized.expand(
+ [
+ ("missing_file", "/nonexistent/keep.txt", None),
+ ("nothing_parseable", None, "insight_id\nnot-an-id\n"),
+ # A team_id,insight_id export would otherwise keep the team ids and sweep the insights.
+ ("two_numeric_columns", None, "team_id,insight_id\n2,4567\n"),
+ ]
+ )
+ def test_unusable_keep_list_stops_the_run(self, _name: str, path: str | None, contents: str | None) -> None:
+ # The keep-list is the only thing protecting in-use insights, so it must fail closed rather
+ # than sweep with an empty one.
+ if contents is not None:
+ keep_file = Path(self.enterContext(tempfile.TemporaryDirectory())) / "keep.txt"
+ keep_file.write_text(contents)
+ path = str(keep_file)
+
+ with self.assertRaises(CommandError):
+ self._run(f"--keep-ids-file={path}")
+
+ def test_does_not_delete_unrelated_sample_insight(self) -> None:
+ # The classifier keys on name/description, not is_sample, so other dashboard-template insights
+ # (billing, onboarding) that also carry is_sample must survive.
+ unrelated = Insight.objects.create(
+ team=self.team, name="Billable Event Usage by Library", is_sample=True, saved=True
+ )
+
+ self._run("--include-orphaned")
+
+ assert Insight.objects.filter(id=unrelated.id).exists()
+
+ @parameterized.expand(["favorited", "edited", "sharing", "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)
+ kept, other = insights[0], insights[1]
+
+ extra_args: list[str] = []
+ if signal == "favorited":
+ kept.favorited = True
+ kept.save()
+ elif signal == "edited":
+ # What the insight API leaves behind on any PATCH, so it stands in for a user edit.
+ kept.is_sample = False
+ kept.save()
+ elif signal == "sharing":
+ SharingConfiguration.objects.create(team=self.team, insight=kept, enabled=True)
+ elif signal == "alert":
+ AlertConfiguration.objects.create(team=self.team, insight=kept, created_by=self.user, name="a")
+ elif signal == "keep_list":
+ keep_file = Path(self.enterContext(tempfile.TemporaryDirectory())) / "keep.txt"
+ keep_file.write_text(f"insight_id\n{kept.id}\n")
+ extra_args = [f"--keep-ids-file={keep_file}"]
+
+ self._run(*extra_args)
+
+ assert Insight.objects.filter(id=kept.id).exists()
+ assert not Insight.objects.filter(id=other.id).exists()
+ # A kept insight still lives on the dashboard, so the flag must stay linked to it.
+ 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.
+ flag = self._flag_with_usage_dashboard("quiet")
+ insights = self._usage_insights(flag)
+
+ with patch("posthog.models.activity_logging.activity_log.post_save.send") as mock_post_save:
+ self._run()
+
+ assert ActivityLog.objects.filter(
+ scope="Insight", activity="deleted", item_id__in=[str(i.id) for i in insights]
+ ).count() == len(insights)
+ assert not [call for call in mock_post_save.call_args_list if call.kwargs.get("sender") is ActivityLog]
+
+ def test_prunes_the_project_tree_rows_for_swept_insights(self) -> None:
+ # The soft delete goes through .update(), which fires no signal, so FileSystemSyncMixin never
+ # prunes these. Leaving them makes a swept insight clickable in Recents and the project tree,
+ # landing on "Insight not found".
+ flag = self._flag_with_usage_dashboard("tree")
+ insights = self._usage_insights(flag)
+ refs = [i.short_id for i in insights]
+ assert FileSystem.objects.filter(team=self.team, type="insight", ref__in=refs).exists()
+
+ self._run()
+
+ assert not FileSystem.objects.filter(team=self.team, type="insight", ref__in=refs).exists()
+
+ def test_dry_run_changes_nothing_but_reports_the_flags_it_would_unlink(self) -> None:
+ # A dry run sizes the live run, so it has to account for both mutations. Reporting the
+ # deletes while silently reporting zero unlinks would understate what the live run does.
+ flag = self._flag_with_usage_dashboard("dry")
+ insights = self._usage_insights(flag)
+ out = StringIO()
+
+ self._run("--dry-run", stdout=out)
+
+ 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
+ assert "nulled 1 flag usage_dashboard references" in out.getvalue()
diff --git a/tach.toml b/tach.toml
index eec03a13a902..07e50d9948e1 100644
--- a/tach.toml
+++ b/tach.toml
@@ -426,6 +426,7 @@ depends_on = [
"products.cohorts",
"ee",
"posthog",
+ "products.alerts",
"products.approvals",
"products.dashboards",
"products.early_access_features",