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.

fix(insights): delete subscriptions with their insight (#103898)

Matt Puae758e796261c
diff --git a/frontend/src/scenes/insights/InsightScene.test.tsx b/frontend/src/scenes/insights/InsightScene.test.tsx
new file mode 100644
index 000000000000..3e03642eb036
--- /dev/null
+++ b/frontend/src/scenes/insights/InsightScene.test.tsx
@@ -0,0 +1,32 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { router } from 'kea-router'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { InsightScene } from './InsightScene'
+
+jest.mock('scenes/insights/InsightAsScene', () => ({ InsightAsScene: () => null }))
+jest.mock('products/posthog_ai/frontend/api/logics', () => ({ useAttachedContext: jest.fn() }))
+
+describe('InsightScene', () => {
+ afterEach(cleanup)
+
+ it('replaces the skeleton with not found when a directly opened subscription has no parent insight', async () => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/insights/': { count: 0, results: [] },
+ },
+ })
+ initKeaTests()
+ router.actions.push('/insights/missing1/subscriptions/123')
+
+ render(<InsightScene />)
+
+ expect(screen.getAllByText('Loading…').length).toBeGreaterThan(0)
+ expect(await screen.findByText('Insight not found')).toBeInTheDocument()
+ expect(screen.queryByText('Loading…')).not.toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/scenes/insights/InsightScene.tsx b/frontend/src/scenes/insights/InsightScene.tsx
index d12a33de014f..cd3e76c6f15b 100644
--- a/frontend/src/scenes/insights/InsightScene.tsx
+++ b/frontend/src/scenes/insights/InsightScene.tsx
@@ -15,7 +15,7 @@ import { ItemMode } from '~/types'
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
export function InsightScene(): JSX.Element {
- const { insightId, insight, insightLogicRef, insightMode, dashboardId } = useValues(insightSceneLogic)
+ const { insightId, insight, insightLoading, insightMode, dashboardId } = useValues(insightSceneLogic)
useAttachedContext(
insight?.short_id && insight?.query
@@ -46,7 +46,7 @@ export function InsightScene(): JSX.Element {
return <InsightAsScene insightId={insightId} attachTo={insightSceneLogic} />
}
- if (insightLogicRef?.logic?.values?.insightLoading) {
+ if (insightLoading) {
return <InsightSkeleton />
}
diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsx
index 35092c1c76ba..d7aff910849e 100644
--- a/frontend/src/scenes/insights/insightLogic.tsx
+++ b/frontend/src/scenes/insights/insightLogic.tsx
@@ -1322,7 +1322,8 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
deleteInsight: ({ dashboardId }) => {
LemonDialog.open({
title: 'Delete insight?',
- description: 'Are you sure you want to delete this insight? This action can be undone.',
+ description:
+ 'Are you sure you want to delete this insight? Associated alerts and subscriptions will also be removed. Their removal cannot be undone.',
primaryButton: {
children: 'Delete',
status: 'danger',
diff --git a/frontend/src/scenes/insights/insightSceneLogic.tsx b/frontend/src/scenes/insights/insightSceneLogic.tsx
index 6e6a625cd863..3550a3b5e5e5 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.tsx
+++ b/frontend/src/scenes/insights/insightSceneLogic.tsx
@@ -139,6 +139,7 @@ export interface insightSceneLogicValues {
| ((state: any, props?: InsightLogicProps<QuerySchema> | undefined) => Record<string, any>)
| undefined
insightId: InsightId | null
+ insightLoading: boolean
insightLogicRef: {
logic: BuiltLogic<insightLogicType>
unmount: () => void
@@ -256,6 +257,7 @@ export interface insightSceneLogicMeta {
} | null
) => ((state: any, props?: InsightLogicProps<QuerySchema> | undefined) => Record<string, any>) | undefined
insightData: (arg: Record<string, any> | null | undefined) => Record<string, any> | null | undefined
+ insightLoading: (arg: boolean) => boolean
insightSelector: (
insightLogicRef: {
logic: BuiltLogic<insightLogicType>
@@ -502,6 +504,13 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
],
(insightData: Record<string, any> | null | undefined) => insightData,
],
+ insightLoading: [
+ (s) => [
+ (state, props) =>
+ s.insightLogicRef(state, props)?.logic.selectors.insightLoading(state, props) ?? false,
+ ],
+ (insightLoading: boolean): boolean => insightLoading,
+ ],
insightSelector: [
(s) => [s.insightLogicRef],
(
diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsx
index 193612ac572a..b9763f19c1e0 100644
--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx
+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx
@@ -283,7 +283,7 @@ export function SavedInsights(): JSX.Element {
LemonDialog.open({
title: 'Delete insight?',
description:
- 'Are you sure you want to delete this insight? This action can be undone.',
+ 'Are you sure you want to delete this insight? Associated alerts and subscriptions will also be removed. Their removal cannot be undone.',
primaryButton: {
children: 'Delete',
status: 'danger',
@@ -441,7 +441,7 @@ export function SavedInsights(): JSX.Element {
const noun = count === 1 ? 'insight' : 'insights'
LemonDialog.open({
title: `Delete ${count} ${noun}?`,
- description: `Are you sure you want to delete ${count} ${noun}? This action can be undone.`,
+ description: `Are you sure you want to delete ${count} ${noun}? Associated alerts and subscriptions will also be removed. Their removal cannot be undone.`,
primaryButton: {
children: 'Delete',
status: 'danger',
diff --git a/products/exports/backend/facade/api.py b/products/exports/backend/facade/api.py
index 523700308bdb..708f37d3fdfd 100644
--- a/products/exports/backend/facade/api.py
+++ b/products/exports/backend/facade/api.py
@@ -103,6 +103,11 @@ def save_export_asset_content_from_file(
_save_content_from_file(asset, file_path, max_database_bytes=max_database_bytes)
+def delete_insight_subscriptions(*, project_id: int, insight_ids: Collection[int]) -> None:
+ for subscription in Subscription.objects.filter(team__project_id=project_id, insight_id__in=insight_ids):
+ subscription.delete()
+
+
def insight_ids_with_subscriptions(insight_ids: Collection[int]) -> set[int]:
"""Which of the given insights have a subscription that has not been deleted.
diff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.py
index 29a3ef55cdf3..ef2a9999835f 100644
--- a/products/exports/backend/models/subscription.py
+++ b/products/exports/backend/models/subscription.py
@@ -116,6 +116,8 @@ class Subscription(ModelActivityMixin, models.Model):
Also see https://jakubroztocil.github.io/rrule/ for a helpful visual demonstration
"""
+ activity_logging_on_delete = True
+
class SubscriptionTarget(models.TextChoices):
EMAIL = "email"
SLACK = "slack"
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 18e369ac3784..1a8bee10ae3b 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -160,6 +160,7 @@ from products.dashboards.backend.facade.api import (
update_insight_dashboard_membership,
)
from products.dashboards.backend.facade.enums import PrivilegeLevel, RestrictionLevel
+from products.exports.backend.facade.api import delete_insight_subscriptions
from products.product_analytics.backend.facade.account_filters import plan_test_account_filter_update
from products.product_analytics.backend.facade.api import (
insight_variables_for_team,
@@ -868,17 +869,21 @@ class InsightSerializer(InsightBasicSerializer):
"and this insight is publicly shared."
)
- if validated_data.get("deleted", False):
- hide_tiles_for_insights([instance.id])
- for alert in instance.alertconfiguration_set.all():
- alert.delete()
- else:
- dashboard_ids = validated_data.pop("dashboards", None)
- if dashboard_ids is not None:
- # The membership write runs before the query is saved, so gate on the incoming one.
- self._update_insight_dashboards(dashboard_ids, instance, validated_data.get("query", instance.query))
+ with transaction.atomic():
+ if validated_data.get("deleted", False):
+ delete_insight_subscriptions(project_id=instance.team.project_id, insight_ids=[instance.id])
+ hide_tiles_for_insights([instance.id])
+ for alert in instance.alertconfiguration_set.all():
+ alert.delete()
+ else:
+ dashboard_ids = validated_data.pop("dashboards", None)
+ if dashboard_ids is not None:
+ # The membership write runs before the query is saved, so gate on the incoming one.
+ self._update_insight_dashboards(
+ dashboard_ids, instance, validated_data.get("query", instance.query)
+ )
- updated_insight = super().update(instance, validated_data)
+ updated_insight = super().update(instance, validated_data)
# Delete linked alerts only when the insight can no longer carry any alert. A switch between
# alertable kinds (e.g. trends -> SQL) is left alone: the config type no longer matches, but
# the alert check cycle re-validates against the current query and auto-disables + notifies on
@@ -2365,6 +2370,7 @@ When set, the specified dashboard's filters and date range override will be appl
# Match InsightSerializer.update: hide the insights' tiles and remove linked alerts.
hide_tiles_for_insights(insight_ids)
delete_insight_alerts(insight_ids)
+ delete_insight_subscriptions(project_id=self.team.project_id, insight_ids=insight_ids)
activity_log_entries: list[LogActivityEntry] = []
for insight in insights:
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index 1ce7b442cf22..1c78da2cbcc3 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -54,6 +54,7 @@ from posthog.constants import AvailableFeature
from posthog.exceptions import ClickHouseQueryTimeOut
from posthog.hogql_queries.query_runner import SHARED_FORCE_BLOCKING_STALENESS_WINDOW, ExecutionMode
from posthog.models import Filter, OrganizationMembership, SharingConfiguration, Team, User
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.project import Project
from posthog.query_scan.findings import build_warning
from posthog.query_scan.flag import QueryScanFlag, QueryScanMode
@@ -66,6 +67,7 @@ from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscr
from products.dashboards.backend.facade.access import DashboardAccessMethod
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text
+from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery
from products.product_analytics.backend.facade.models import Insight, InsightVariable
from products.product_analytics.backend.models.insight import InsightViewed
@@ -3073,14 +3075,38 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def test_soft_delete_causes_404(self) -> None:
insight_id, _ = self.dashboard_api.create_insight({"name": "to be deleted"})
self.dashboard_api.get_insight(insight_id=insight_id, expected_status=status.HTTP_200_OK)
+ subscription = Subscription.objects.create(
+ team=self.team, insight_id=insight_id, start_date=timezone.now(), frequency="daily"
+ )
+ unrelated = Subscription.objects.create(team=self.team, start_date=timezone.now(), frequency="daily")
+ deleted_subscription = Subscription.objects.create(
+ team=self.team, insight_id=insight_id, start_date=timezone.now(), frequency="daily", deleted=True
+ )
+ delivery = SubscriptionDelivery.objects.create(
+ team=self.team, subscription=subscription, idempotency_key="insight-delete-test", status="completed"
+ )
update_response = self.client.patch(f"/api/projects/{self.team.id}/insights/{insight_id}", {"deleted": True})
self.assertEqual(update_response.status_code, status.HTTP_200_OK)
self.dashboard_api.get_insight(insight_id=insight_id, expected_status=status.HTTP_404_NOT_FOUND)
+ self.assertFalse(Subscription.objects.filter(pk=subscription.pk).exists())
+ deletion_log = ActivityLog.objects.get(
+ team_id=self.team.id, scope="Subscription", item_id=str(subscription.pk), activity="deleted"
+ )
+ self.assertEqual(deletion_log.user_id, self.user.id)
+ unrelated.refresh_from_db()
+ self.assertFalse(unrelated.deleted)
+
+ self.assertFalse(Subscription.objects.filter(pk=deleted_subscription.pk).exists())
+ self.assertFalse(SubscriptionDelivery.objects.filter(pk=delivery.pk).exists())
+
def test_soft_delete_can_be_reversed_by_patch(self) -> None:
insight_id, _ = self.dashboard_api.create_insight({"name": "an insight"})
+ subscription = Subscription.objects.create(
+ team=self.team, insight_id=insight_id, start_date=timezone.now(), frequency="daily"
+ )
self.client.patch(
f"/api/projects/{self.team.id}/insights/{insight_id}",
@@ -3124,6 +3150,8 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"type": "Insight",
}
+ self.assertFalse(Subscription.objects.filter(pk=subscription.pk).exists())
+
def test_soft_delete_cannot_be_reversed_for_another_team(self) -> None:
other_team = Team.objects.create(organization=self.organization, name="other team")
other_insight = Insight.objects.create(
@@ -4289,6 +4317,10 @@ class TestInsightBulkDelete(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest)
insight = self._create_insight()
tile = DashboardTile.objects.create(insight=insight, dashboard=dashboard)
alert = AlertConfiguration.objects.create(team=self.team, insight=insight, name="alert")
+ subscription = Subscription.objects.create(
+ team=self.team, insight_id=insight.id, start_date=timezone.now(), frequency="daily"
+ )
+ unrelated = Subscription.objects.create(team=self.team, start_date=timezone.now(), frequency="daily")
response = self._bulk_delete([insight.id])
@@ -4296,6 +4328,14 @@ class TestInsightBulkDelete(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest)
self.assertTrue(DashboardTile.objects_including_soft_deleted.get(id=tile.id).deleted)
self.assertFalse(AlertConfiguration.objects.filter(id=alert.id).exists())
+ self.assertFalse(Subscription.objects.filter(pk=subscription.pk).exists())
+ deletion_log = ActivityLog.objects.get(
+ team_id=self.team.id, scope="Subscription", item_id=str(subscription.pk), activity="deleted"
+ )
+ self.assertEqual(deletion_log.user_id, self.user.id)
+ unrelated.refresh_from_db()
+ self.assertFalse(unrelated.deleted)
+
def test_bulk_delete_reports_unknown_ids_as_skipped(self) -> None:
insight = self._create_insight()
diff --git a/tach.toml b/tach.toml
index e41c90a46ba4..e04479451a3f 100644
--- a/tach.toml
+++ b/tach.toml
@@ -715,6 +715,7 @@ depends_on = [
"products.alerts",
"products.dashboards",
"products.event_definitions",
+ "products.exports",
"products.annotations",
"products.warehouse_sources", "products.access_control",
# A trends query filtering on a first-pageview-aware property builds it through