: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
fix: auto-disable subscriptions when the creator left or lost access (#123649)
Alex Lider5a487018c2ac
diff --git a/.agents/skills/debugging-table-access-denied/SKILL.md b/.agents/skills/debugging-table-access-denied/SKILL.mdindex 761965004056..4d3e5b84a07b 100644--- a/.agents/skills/debugging-table-access-denied/SKILL.md+++ b/.agents/skills/debugging-table-access-denied/SKILL.md@@ -15,5 +15,5 @@ Hints:- On an HTTP request this is an expected 4xx, never captured. An error tracking issue means it was raised in a background context — figure out which from the event's query tags (`team_id`, `user_id`, `product`, `celery_task_id`, `temporal.*`).- A `system.*` name is a system-table decision; a bare name is a warehouse table/view denial.- No `user_id` on the event usually means a userless `Database.create_for` — it fails closed, and `bypass_warehouse_access_control` does not cover system tables. That's a bug in the calling code.-- Background jobs run as the resource's `created_by`; a creator who left the org is the known benign cause (cache warming, alerts, and exports already suppress capture for it via `creator_access_revoked`).+- Background jobs run as the resource's `created_by`. A creator who left the org is the known benign cause: cache warming suppresses capture for it via `creator_access_revoked`, exports refuse to run with `CreatorLeftOrganizationError`, and subscriptions and alerts auto-disable (look for the `alert auto disabled` event or the subscription's last delivery).- Otherwise it's a real access rule (RBAC or entitlement) — see the readme for how a table's access level resolves, and check the `AccessControl` rows for the table's `access_scope`.diff --git a/posthog/query_creator_access.py b/posthog/query_creator_access.pyindex 1315d2e52d81..f921b314a612 100644--- a/posthog/query_creator_access.py+++ b/posthog/query_creator_access.py@@ -1,10 +1,25 @@from typing import Any, Optional+from django.db.models import Model+from posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.ph_client import ph_scoped_capture+from products.access_control.backend.facade.user_access_control import (+ UserAccessControl,+ UserAccessControlError,+ model_to_resource,+)+++class CreatorLeftOrganizationError(Exception):+ """A background query refused to run because its owner is no longer in the organization."""++ def __init__(self) -> None:+ super().__init__("The owner is no longer in the organization.")+def creator_access_revoked(user: Optional[User], team: Team) -> bool:"""True when `user` no longer has access to `team`: they were deleted (`user is None`),@@ -17,6 +32,29 @@ def creator_access_revoked(user: Optional[User], team: Team) -> bool:return not OrganizationMembership.objects.filter(organization_id=team.organization_id, user=user).exists()+def assert_creator_can_run(user: Optional[User], team: Team, *objects: Model | None) -> None:+ """Raise when `user` can no longer run a background query for `team` as its owner.++ `CreatorLeftOrganizationError` when they were deleted (`user is None`), deactivated, or left the+ team's org. `UserAccessControlError` when they are still in the org but cannot view the project+ or one of `objects`. Background jobs load their dashboard and insight directly, so nothing else+ checks object access for them. Organization admins pass, and a `None` object is skipped.+ """+ if user is None or creator_access_revoked(user, team):+ raise CreatorLeftOrganizationError()+ user_access_control = UserAccessControl(user=user, team=team)+ # Object rules do not consult the project, so a member shut out of a private project is checked first.+ if not user_access_control.has_project_access:+ raise UserAccessControlError("project", "viewer", str(team.pk))+ for obj in objects:+ if obj is None:+ continue+ resource = model_to_resource(obj)+ # A model with no scope has no access rules, so there is nothing to deny.+ if resource is not None and not user_access_control.check_access_level_for_object(obj, "viewer"):+ raise UserAccessControlError(resource, "viewer", str(obj.pk))++def report_creator_access_revoked(*,user: Optional[User],diff --git a/posthog/tasks/exporter.py b/posthog/tasks/exporter.pyindex 892c9e0d07f6..9e7ec15181c1 100644--- a/posthog/tasks/exporter.py+++ b/posthog/tasks/exporter.py@@ -7,6 +7,7 @@ from celery import current_task, shared_taskfrom prometheus_client import Counter, Histogramfrom posthog.event_usage import EventSource, groups+from posthog.query_creator_access import CreatorLeftOrganizationError, assert_creator_can_runfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIMEfrom posthog.tasks.utils import CeleryQueue@@ -121,6 +122,12 @@ def export_asset_direct(export_source = source or EventSource.EXPORTtry:+ if exported_asset.created_by is not None:+ assert_creator_can_run(exported_asset.created_by, team, exported_asset.dashboard, exported_asset.insight)+ elif export_source == EventSource.SUBSCRIPTION:+ # A subscription copies its owner onto every asset, so an ownerless one means the owner's account+ # was deleted. Other exports have no owner on purpose (logs, activity logs, sharing renders).+ raise CreatorLeftOrganizationError()assert_export_authorization(exported_asset)export_handler = get_export_format_handler(export_format=exported_asset.export_format, kind=exported_asset.export_kinddiff --git a/posthog/tasks/test/test_exporter.py b/posthog/tasks/test/test_exporter.pyindex 0507056ef057..877ca4391839 100644--- a/posthog/tasks/test/test_exporter.py+++ b/posthog/tasks/test/test_exporter.py@@ -1,5 +1,6 @@import base64+import pytestfrom posthog.test.base import APIBaseTestfrom unittest import TestCasefrom unittest.mock import MagicMock, patch@@ -10,11 +11,16 @@ from parameterized import parameterizedfrom posthog.hogql.errors import QueryError+from posthog.constants import AvailableFeature+from posthog.event_usage import EventSourcefrom posthog.exceptions import ClickHouseAtCapacity+from posthog.models import OrganizationMembership, Userfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.query_creator_access import CreatorLeftOrganizationErrorfrom posthog.tasks import exporter+from products.access_control.backend.models.access_control import AccessControlfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.exports.backend.facade import exporters as export_handlersfrom products.exports.backend.models.exported_asset import DATASET_EXPORT_KIND, ExportedAsset@@ -123,6 +129,66 @@ class TestExporterTask(APIBaseTest):assert asset.exception_type == "QueryError"assert asset.failure_type == FAILURE_TYPE_USER+ @parameterized.expand(+ [+ ("owner_left_the_organization", False, "CreatorLeftOrganizationError"),+ ("owner_cannot_view_the_dashboard", True, "UserAccessControlError"),+ ]+ )+ @patch("products.exports.backend.tasks.image_exporter.export_image")+ def test_export_does_not_run_when_its_owner_cannot(+ self,+ _label: str,+ owner_is_member: bool,+ expected_exception_type: str,+ mock_export: MagicMock,+ mock_uuid: MagicMock,+ ) -> None:+ if owner_is_member:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ owner = User.objects.create_and_join(+ self.organization, "[email protected]", None, level=OrganizationMembership.Level.MEMBER+ )+ AccessControl.objects.create(+ team=self.team,+ resource="dashboard",+ resource_id=str(self.exported_asset.dashboard_id),+ access_level="none",+ )+ else:+ owner = User.objects.create_user(email="[email protected]", first_name="", password=None)+ asset = ExportedAsset.objects.create(+ team=self.team, dashboard=self.exported_asset.dashboard, export_format="image/png", created_by=owner+ )++ exporter.export_asset(asset.id)++ mock_export.assert_not_called()+ asset.refresh_from_db()+ assert asset.exception_type == expected_exception_type+ assert asset.failure_type == FAILURE_TYPE_USER++ @patch("products.exports.backend.tasks.image_exporter.export_image")+ def test_subscription_export_without_an_owner_means_the_owner_was_deleted(+ self, mock_export: MagicMock, mock_uuid: MagicMock+ ) -> None:+ # The subscription copied a null owner onto the asset, which only a deleted account produces.+ asset = ExportedAsset.objects.create(+ team=self.team, dashboard=self.exported_asset.dashboard, export_format="image/png", created_by=None+ )++ # The direct call re-raises after recording, so the delivery workflow sees the failure.+ with pytest.raises(CreatorLeftOrganizationError):+ exporter.export_asset_direct(asset, source=EventSource.SUBSCRIPTION)++ mock_export.assert_not_called()+ asset.refresh_from_db()+ assert asset.exception_type == "CreatorLeftOrganizationError"+ assert asset.failure_type == FAILURE_TYPE_USER+@patch("products.exports.backend.tasks.image_exporter.export_image")def test_routes_a_registered_format_and_kind_to_its_handler(self, mock_export_image: MagicMock, mock_uuid: MagicMockdiff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex 362327e36226..f3c8f982ab1e 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -24,15 +24,12 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.schema import AlertState-from posthog.hogql.errors import TableAccessDeniedError-from posthog.clickhouse.cancel import cancel_query_on_clusterfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.dataclasses import frozenfrom posthog.email import is_email_availablefrom posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorQueryWasCancelledfrom posthog.exceptions_capture import capture_exception-from posthog.query_creator_access import creator_access_revoked, report_creator_access_revokedfrom posthog.schema_migrations.upgrade_manager import upgrade_insightfrom posthog.sync import database_sync_to_asyncfrom posthog.tasks.alerts.investigation_notifications import run_investigation_notification_safety_net@@ -700,29 +697,6 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe# existing path instead of capturing it as an exception, which would pollute error# tracking with a config problem that recurs on every check until fixed.invalid_configuration = str(err)- except TableAccessDeniedError as err:- logger.exception("Alert failed to evaluate", alert_id=alert.id, exc_info=err)- # A revoked creator's access-denied error is a known limitation - report it as an event- # rather than capturing it, which would recur on every check until the alert is fixed.- if creator_access_revoked(alert.created_by, alert.team):- report_creator_access_revoked(- user=alert.created_by,- team=alert.team,- source="alert",- error=err,- properties={"alert_id": str(alert.id), "insight_id": alert.insight_id},- )- error = {"message": str(err)}- else:- capture_exception(- err,- additional_properties={- "alert_configuration_id": str(alert.id),- "insight_id": alert.insight_id,- "team_id": alert.team_id,- },- )- error = {"message": str(err), "traceback": traceback.format_exc()}except Exception as err:logger.exception("Alert failed to evaluate", alert_id=alert.id, exc_info=err)capture_exception(diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex 3066ab777059..a2601bbe96c7 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -30,6 +30,8 @@ from posthog.schema import (TrendsQuery,)+from posthog.hogql.errors import TableAccessDeniedError+from posthog.clickhouse.query_tagging import get_query_tagsfrom posthog.constants import AvailableFeaturefrom posthog.errors import CHQueryErrorQueryWasCancelled@@ -38,7 +40,7 @@ from posthog.exceptions import (ClickHouseClusterMemoryLimitExceeded,ClickHouseQueryMemoryLimitExceeded,)-from posthog.models import Team, User+from posthog.models import OrganizationMembership, Team, Userfrom posthog.redis import get_clientfrom posthog.slo.types import SloOperation, SloOutcomefrom posthog.tasks.alerts.utils import (@@ -75,7 +77,13 @@ from posthog.temporal.alerts.types import (SkipReason,)-from products.alerts.backend.evaluation.contract import AlertDataUnavailableError, AlertExtractionError+from products.access_control.backend.models.access_control import AccessControl+from products.alerts.backend.evaluation.contract import (+ CREATOR_LEFT_DISABLE_REASON,+ CREATOR_LOST_ACCESS_DISABLE_REASON,+ AlertDataUnavailableError,+ AlertExtractionError,+)from products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGEfrom products.alerts.backend.facade.api import (LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,@@ -144,9 +152,14 @@ async def _create_alert(insight_deleted: bool = False,state: str = AlertState.NOT_FIRING,detector_config: dict | None = None,+ created_by: User | None = None,) -> AlertConfiguration:@sync_to_asyncdef _create() -> AlertConfiguration:+ # Production always writes an owner, and an alert with none counts as one whose owner was deleted.+ owner = created_by or User.objects.create_and_join(+ ateam.organization, f"alert-owner-{uuid.uuid4().hex[:6]}@posthog.com", None+ )insight = Insight.objects.create(team=ateam,name="insight",@@ -174,6 +187,7 @@ async def _create_alert(schedule_start_time=schedule_start_time,state=state,detector_config=detector_config,+ created_by=owner,)return alert@@ -1263,6 +1277,59 @@ class TestEvaluateAlert:await sync_to_async(check.refresh_from_db)()assert check.targets_notified+ @pytest.mark.parametrize(+ "owner_change, expected_message",+ [+ ("left_organization", CREATOR_LEFT_DISABLE_REASON),+ ("lost_table_access", CREATOR_LOST_ACCESS_DISABLE_REASON),+ ("lost_insight_access", CREATOR_LOST_ACCESS_DISABLE_REASON),+ ],+ )+ async def test_evaluate_auto_disables_when_the_owner_can_no_longer_run_the_query(+ self, alert_with_user, aorganization, owner_change, expected_message+ ) -> None:+ owner = await sync_to_async(lambda: alert_with_user.subscribed_users.get())()+ alert_with_user.created_by = owner+ await sync_to_async(alert_with_user.save)(update_fields=["created_by"])+ if owner_change == "left_organization":+ await sync_to_async(+ OrganizationMembership.objects.filter(organization_id=aorganization.id, user=owner).delete+ )()+ if owner_change == "lost_insight_access":+ # The owner is a plain member, so a no-access rule on the insight applies to them.+ aorganization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ await sync_to_async(aorganization.save)()+ await sync_to_async(AccessControl.objects.create)(+ team=alert_with_user.team,+ resource="insight",+ resource_id=str(alert_with_user.insight_id),+ access_level="none",+ )++ with (+ # Patched under the real `check_alert_for_insight`, which turns the denial into the owner reason.+ patch(+ "products.alerts.backend.evaluation.dispatcher._check_alert_for_insight",+ side_effect=TableAccessDeniedError("revenue"),+ ) as mock_check,+ patch("posthog.temporal.alerts.activities.capture_exception") as mock_capture,+ ):+ result = await ActivityEnvironment().run(+ evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert_with_user.id))+ )++ assert result.new_state == AlertState.ERRORED+ mock_capture.assert_not_called()+ # A departed owner's alert must stop even when its query would still run.+ assert mock_check.called is (owner_change == "lost_table_access")+ check = await sync_to_async(AlertCheck.objects.get)(pk=result.alert_check_id)+ # The shared code routes the check to the "alert disabled" email, in-app notice and banner.+ assert check.error == {"message": expected_message, "code": "invalid_configuration"}+ refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=alert_with_user.pk)+ assert refreshed.enabled is False+# Transient CH errors bubble up so Temporal's retry policy handles them.# Capacity errors (codes 202/439) surface as ClickHouseAtCapacity, so that's what we simulate.# A server-wide or per-user memory limit is the same kind of cluster pressure: recording it asdiff --git a/posthog/test/test_query_creator_access.py b/posthog/test/test_query_creator_access.pyindex 23540b43202f..63a687d92fed 100644--- a/posthog/test/test_query_creator_access.py+++ b/posthog/test/test_query_creator_access.py@@ -1,7 +1,11 @@from posthog.test.base import BaseTest+from posthog.constants import AvailableFeaturefrom posthog.models import OrganizationMembership-from posthog.query_creator_access import creator_access_revoked+from posthog.query_creator_access import assert_creator_can_run, creator_access_revoked++from products.access_control.backend.facade.user_access_control import UserAccessControlError+from products.access_control.backend.models.access_control import AccessControlclass TestCreatorAccessRevoked(BaseTest):@@ -19,3 +23,20 @@ class TestCreatorAccessRevoked(BaseTest):def test_owner_removed_from_org_is_revoked(self) -> None:OrganizationMembership.objects.filter(organization=self.organization, user=self.user).delete()assert creator_access_revoked(self.user, self.team) is True++ def test_member_without_project_access_lost_access_rather_than_left(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ # Admins keep access to a private project, so the owner is demoted to a plain member first.+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ AccessControl.objects.create(+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="none"+ )+ # Still in the org, so not "left": the recipients' message must say access, not membership.+ assert creator_access_revoked(self.user, self.team) is False+ with self.assertRaises(UserAccessControlError) as raised:+ assert_creator_can_run(self.user, self.team)+ assert raised.exception.resource == "project"diff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.pyindex 58911d597fa3..463c3ddc2941 100644--- a/products/alerts/backend/evaluation/contract.py+++ b/products/alerts/backend/evaluation/contract.py@@ -102,6 +102,18 @@ class AlertDataUnavailableError(AlertExtractionError):"""This check lacks usable data; keep the alert enabled for future checks."""+class AlertOwnerAccessError(AlertExtractionError):+ """The query runs with the owner's access, and the owner can no longer run it.++ Both evaluation stacks disable the alert for an `AlertExtractionError`, so this subclass only+ lets a test or a log tell the owner case apart.+ """+++CREATOR_LEFT_DISABLE_REASON = "The alert owner is no longer in the organization."+CREATOR_LOST_ACCESS_DISABLE_REASON = "The alert owner no longer has access to some of the data it reads."++def lookback_intervals_for(condition: AlertCondition) -> int:"""How many trailing intervals an extractor must fetch for this condition.diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.pyindex 7a853baf0313..23f2bcbc88e9 100644--- a/products/alerts/backend/evaluation/dispatcher.py+++ b/products/alerts/backend/evaluation/dispatcher.py@@ -9,20 +9,25 @@ from rest_framework.exceptions import ValidationError as DRFValidationErrorfrom posthog.schema import AlertCondition, InsightThreshold, IntervalType, NodeKind-from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.errors import ExposedHogQLError, TableAccessDeniedErrorfrom posthog.api.services.query import ExecutionModefrom posthog.dataclasses import frozenfrom posthog.errors import CH_TRANSIENT_ERRORS, ExposedCHQueryErrorfrom posthog.hogql_queries.validation.validate_query import rule_violation_messagefrom posthog.models.team import Team+from posthog.query_creator_access import CreatorLeftOrganizationError, assert_creator_can_runfrom posthog.schema_migrations.upgrade_manager import upgrade_insightfrom posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResultfrom posthog.utils import get_from_dict_or_attr, relative_date_parse_with_delta_mapping+from products.access_control.backend.facade.user_access_control import UserAccessControlErrorfrom products.alerts.backend.evaluation.comparator import evaluate_thresholdfrom products.alerts.backend.evaluation.contract import (+ CREATOR_LEFT_DISABLE_REASON,+ CREATOR_LOST_ACCESS_DISABLE_REASON,AlertExtractionError,+ AlertOwnerAccessError,ComparableSeries,DetectorExtractor,ExtractionResult,@@ -310,6 +315,22 @@ class PerSeriesEvaluation:truncated: bool = False+@contextmanager+def _owner_can_run(alert: AlertConfiguration) -> Iterator[None]:+ """Turn an owner who can no longer run the alert into the alert's own error, which disables it.++ The query runs with the owner's access, so the owner is checked before it: a query that reads no+ restricted table still succeeds, and the query itself only checks tables and runner resources.+ """+ try:+ assert_creator_can_run(alert.created_by, alert.team, alert.insight)+ yield+ except CreatorLeftOrganizationError as err:+ raise AlertOwnerAccessError(CREATOR_LEFT_DISABLE_REASON) from err+ except (TableAccessDeniedError, UserAccessControlError) as err:+ raise AlertOwnerAccessError(CREATOR_LOST_ACCESS_DISABLE_REASON) from err++def check_alert_per_series(alert: AlertConfiguration, *, query_slot: QuerySlot = nullcontext) -> PerSeriesEvaluation | AlertEvaluationResult:@@ -323,7 +344,7 @@ def check_alert_per_series(if alert.detector_config:raise AlertExtractionError("Per-series evaluation supports threshold alerts only")try:- with _resolved_query(alert) as resolved:+ with _owner_can_run(alert), _resolved_query(alert) as resolved:extracted = _extract_for_threshold(alert, resolved.insight, resolved.query, resolved.kind, query_slot)except DelayedEvaluationUnavailable as err:return AlertEvaluationResult(value=None, breaches=[], skipped_reason=str(err))@@ -354,7 +375,8 @@ def check_alert_for_insight(alert: AlertConfiguration, *, evaluation_id: str | None = None, query_slot: QuerySlot = nullcontext) -> AlertEvaluationResult:try:- return _check_alert_for_insight(alert, evaluation_id=evaluation_id, query_slot=query_slot)+ with _owner_can_run(alert):+ return _check_alert_for_insight(alert, evaluation_id=evaluation_id, query_slot=query_slot)except DelayedEvaluationUnavailable as err:if is_llm_detector_config(alert.detector_config):raise LLMDetectorUnavailableError(str(err)) from errdiff --git a/products/alerts/backend/evaluation/test/test_bucket_freshness_clickhouse.py b/products/alerts/backend/evaluation/test/test_bucket_freshness_clickhouse.pyindex fd158f54dc5f..c6d595750626 100644--- a/products/alerts/backend/evaluation/test/test_bucket_freshness_clickhouse.py+++ b/products/alerts/backend/evaluation/test/test_bucket_freshness_clickhouse.py@@ -39,6 +39,7 @@ class TestHourlyAlertScoresItsOwnWindow(APIBaseTest, ClickhouseDestroyTablesMixialert = AlertConfiguration.objects.create(team=self.team,insight=insight,+ created_by=self.user,name="hourly funnel",condition={"type": "absolute_value"},config={"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": None},diff --git a/products/alerts/backend/evaluation/test/test_dispatcher.py b/products/alerts/backend/evaluation/test/test_dispatcher.pyindex 1a2b51cc28f8..9ba75d0dec94 100644--- a/products/alerts/backend/evaluation/test/test_dispatcher.py+++ b/products/alerts/backend/evaluation/test/test_dispatcher.py@@ -16,9 +16,14 @@ from posthog.caching.insight_result import InsightResultfrom posthog.errors import CHQueryErrorNoCommonType, CHQueryErrorS3FileChangedDuringReadfrom posthog.hogql_queries.query_failure_handling import build_failure_exceptionfrom posthog.query_cache.failures import QueryFailureRecord+from posthog.query_creator_access import CreatorLeftOrganizationError+from products.access_control.backend.facade.user_access_control import UserAccessControlErrorfrom products.alerts.backend.evaluation.contract import (+ CREATOR_LEFT_DISABLE_REASON,+ CREATOR_LOST_ACCESS_DISABLE_REASON,AlertExtractionError,+ AlertOwnerAccessError,ComparableSeries,ExtractionResult,SeriesPoint,@@ -142,6 +147,7 @@ def test_per_series_judges_every_breakdown_value_where_the_alert_stops_at_the_fiquery_slot = MagicMock(return_value=nullcontext())with (patch.dict(EXTRACTORS, {NodeKind.TRENDS_QUERY: extractor}),+ patch("products.alerts.backend.evaluation.dispatcher.assert_creator_can_run"),patch("products.alerts.backend.evaluation.dispatcher.upgrade_insight", return_value=nullcontext()),patch("products.alerts.backend.evaluation.dispatcher.validate_evaluation_delay"),patch("products.alerts.backend.evaluation.dispatcher._resolve_execution_mode", return_value=IF_STALE),@@ -203,6 +209,7 @@ def test_per_series_keys_trends_breakdowns_on_their_raw_values()with (patch("products.alerts.backend.evaluation.trends.calculate_for_query_based_insight", return_value=calculated),+ patch("products.alerts.backend.evaluation.dispatcher.assert_creator_can_run"),patch("products.alerts.backend.evaluation.dispatcher.upgrade_insight", return_value=nullcontext()),):evaluated = check_alert_per_series(alert)@@ -210,3 +217,23 @@ def test_per_series_keys_trends_breakdowns_on_their_raw_values(assert isinstance(evaluated, PerSeriesEvaluation)assert [series.identity for series in evaluated.series] == expected_identitiesassert evaluated.truncated is truncated+++ "denial, expected_message",+ [+ (CreatorLeftOrganizationError(), CREATOR_LEFT_DISABLE_REASON),+ (UserAccessControlError("insight", "viewer", "1"), CREATOR_LOST_ACCESS_DISABLE_REASON),+ ],+)+def test_per_series_refuses_an_owner_who_can_no_longer_run_the_query(denial, expected_message) -> None:+ alert = MagicMock(detector_config=None)+ with (+ patch("products.alerts.backend.evaluation.dispatcher.assert_creator_can_run", side_effect=denial),+ patch("products.alerts.backend.evaluation.dispatcher._resolved_query") as resolve,+ pytest.raises(AlertOwnerAccessError) as raised,+ ):+ check_alert_per_series(alert)++ assert str(raised.value) == expected_message+ resolve.assert_not_called()diff --git a/products/alerts/backend/evaluation/test/test_evaluation_delay.py b/products/alerts/backend/evaluation/test/test_evaluation_delay.pyindex 51e8985515ea..01e0bcf732a7 100644--- a/products/alerts/backend/evaluation/test/test_evaluation_delay.py+++ b/products/alerts/backend/evaluation/test/test_evaluation_delay.py@@ -39,6 +39,10 @@ class TestEvaluationDelay(SimpleTestCase):calculation_interval="every_15_minutes",evaluation_delay_intervals=2,)+ # The owner check needs the database, and these alerts have no owner on purpose.+ owner_check = patch("products.alerts.backend.evaluation.dispatcher.assert_creator_can_run")+ owner_check.start()+ self.addCleanup(owner_check.stop)def evaluate(self, data: list[float | None], dates: list[str], detector: bool = False) -> AlertEvaluationResult:module = "detector" if detector else "trends"diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.pyindex bfc0135d398c..3571fc72adbc 100644--- a/products/alerts/backend/test/test_platform_source_cycle.py+++ b/products/alerts/backend/test/test_platform_source_cycle.py@@ -29,7 +29,11 @@ from posthog.tasks.alerts.utils import AlertEvaluationResult, RenderedInsightChafrom posthog.temporal.alerts.admission import admit_evaluation_slots, inflight_alert_ids, release_evaluation_slotfrom posthog.temporal.alerts.retry_policy import ALERT_EVALUATE_RETRY_POLICY-from products.alerts.backend.evaluation.contract import AlertExtractionError+from products.alerts.backend.evaluation.contract import (+ CREATOR_LEFT_DISABLE_REASON,+ AlertExtractionError,+ AlertOwnerAccessError,+)from products.alerts.backend.evaluation.dispatcher import PerSeriesEvaluation, SeriesEvaluationfrom products.alerts.backend.judge.contract import (LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,@@ -98,7 +102,10 @@ class TestPlatformInsightEvaluation(APIBaseTest):self.organization.save()def _alert(self, **overrides: Any) -> AlertConfiguration:- return create_insight_alert(self.team, **{"next_check_at": CUTOFF - timedelta(minutes=1), **overrides})+ # Production always writes an owner, and an alert with none counts as one whose owner was deleted.+ return create_insight_alert(+ self.team, **{"next_check_at": CUTOFF - timedelta(minutes=1), "created_by": self.user, **overrides}+ )def _copy(self, alert: AlertConfiguration | None, **overrides: Any) -> PlatformConfigurationSnapshot:with team_scope(self.team.id):@@ -711,6 +718,7 @@ class TestPlatformInsightEvaluation(APIBaseTest):[("bad_query_shape", AlertExtractionError("bad query shape")),("ai_consent_withdrawn", LLMDetectorMisconfiguredError("consent withdrawn")),+ ("owner_left_or_lost_access", AlertOwnerAccessError(CREATOR_LEFT_DISABLE_REASON)),])def test_an_alert_production_cannot_evaluate_as_configured_errors_and_is_disabled(diff --git a/products/exports/backend/tasks/failure_handler.py b/products/exports/backend/tasks/failure_handler.pyindex 6906aa100b34..580ee2f03bd7 100644--- a/products/exports/backend/tasks/failure_handler.py+++ b/products/exports/backend/tasks/failure_handler.py@@ -39,6 +39,7 @@ from posthog.exceptions import (ClickHouseQuerySizeExceeded,ClickHouseQueryTimeOut,)+from posthog.query_creator_access import CreatorLeftOrganizationErrorfrom posthog.storage.object_storage import ObjectStorageErrorfrom products.access_control.backend.facade.user_access_control import UserAccessControlError@@ -234,6 +235,7 @@ USER_QUERY_ERRORS = (ExcelColumnLimitExceeded,InvalidExportContext,UserAccessControlError, # The export creator has no access to a resource the query needs+ CreatorLeftOrganizationError,)TIMEOUT_ERRORS = (diff --git a/products/subscriptions/backend/logic/auto_disable.py b/products/subscriptions/backend/logic/auto_disable.pyindex c03b03745f52..6a097e668962 100644--- a/products/subscriptions/backend/logic/auto_disable.py+++ b/products/subscriptions/backend/logic/auto_disable.py@@ -1,13 +1,19 @@import uuid+from collections.abc import Iterablefrom typing import NamedTuplefrom urllib.parse import urlparseimport structlog+from posthog.hogql.errors import TableAccessDeniedError+from posthog.email import EmailMessagefrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import User+from posthog.query_creator_access import CreatorLeftOrganizationError+from products.access_control.backend.facade.contracts import UserNotOrganizationMemberError+from products.access_control.backend.facade.user_access_control import UserAccessControlErrorfrom products.notifications.backend.facade.api import (NotificationData,NotificationType,@@ -58,6 +64,22 @@ SLACK_FILE_UPLOAD_PERMISSION_REVOKED_DISABLE_REASON = DisableReason("Add files:write to a custom Slack app, or reconnect PostHog's Slack app, then try again."),)+CREATOR_LEFT_DISABLE_REASON = DisableReason(+ key="creator_left_organization",+ description="The owner of this subscription is no longer in the organization",+ user_message=(+ "Cannot re-enable {target_type} subscription: its owner is no longer in the organization. "+ "Create a new subscription to keep receiving this report."+ ),+)+CREATOR_LOST_ACCESS_DISABLE_REASON = DisableReason(+ key="creator_lost_access",+ description="The owner of this subscription no longer has access to some of its data",+ user_message=(+ "Cannot re-enable {target_type} subscription until its owner has access to all of its data again. "+ "Ask a project admin for access, or create a new subscription."+ ),+)AI_PROMPT_INVALID_DISABLE_REASON = DisableReason(key="ai_prompt_invalid",description="AI subscription prompt or creator is invalid",@@ -83,6 +105,28 @@ def get_subscription_disable_reason(target_type: str | None, integration_id: intreturn None+# Export failures that mean the owner can no longer run the query, not that the export broke.+# Matched by name because delivery only sees the `exception_type` stored on the asset.+_CREATOR_LEFT_ERROR_NAMES = frozenset({CreatorLeftOrganizationError.__name__, UserNotOrganizationMemberError.__name__})+_CREATOR_LOST_ACCESS_ERROR_NAMES = frozenset({TableAccessDeniedError.__name__, UserAccessControlError.__name__})+++def get_assets_owner_disable_reason(exception_types: Iterable[str | None]) -> DisableReason | None:+ """The reason to disable a subscription after a delivery whose exports failed for its owner.++ An owner who left fails every export, so one such failure is enough. Lost access is judged on the+ whole delivery: a dashboard with one denied tile is still delivered, with that tile showing why.+ """+ names = list(exception_types)+ if not names:+ return None+ if any(name in _CREATOR_LEFT_ERROR_NAMES for name in names):+ return CREATOR_LEFT_DISABLE_REASON+ if all(name in _CREATOR_LOST_ACCESS_ERROR_NAMES for name in names):+ return CREATOR_LOST_ACCESS_DISABLE_REASON+ return None++def target_type_label(target_type: str | None) -> str:if not target_type:return ""@@ -110,7 +154,10 @@ def _get_notification_creator(subscription: Subscription) -> User | None:return creator-def disable_invalid_subscription(subscription: Subscription, reason: DisableReason) -> None:+def disable_invalid_subscription(+ subscription: Subscription, reason: DisableReason, *, notify_owner: bool = True+) -> None:+ """Disable the subscription once. Pass `notify_owner=False` when the delivery itself already told the recipients why."""# Compare-and-swap so only one racing caller sends the disabled-notification# email (UUID4 campaign keys mean MessagingRecord can't dedup the duplicate).rowcount = Subscription.objects.filter(pk=subscription.pk, enabled=True).update(enabled=False)@@ -137,6 +184,8 @@ def disable_invalid_subscription(subscription: Subscription, reason: DisableReas# SELECT — refresh_from_db() would also drop the eagerly-loaded created_by# relation (loaded via select_related at the activity site).subscription.enabled = False+ if not notify_owner:+ returntry:create_subscription_auto_disabled_notification(subscription, reason)diff --git a/products/subscriptions/backend/logic/subscription_utils.py b/products/subscriptions/backend/logic/subscription_utils.pyindex bb39b9bc72ef..cbe07a241c75 100644--- a/products/subscriptions/backend/logic/subscription_utils.py+++ b/products/subscriptions/backend/logic/subscription_utils.py@@ -15,6 +15,7 @@ from posthog.utils import wait_for_parallel_celery_groupfrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.product_analytics.backend.facade.models import Insightfrom products.subscriptions.backend.facade.contracts import SharedInsightImage+from products.subscriptions.backend.logic.auto_disable import get_assets_owner_disable_reasonfrom products.subscriptions.backend.models.subscription import Subscriptionlogger = structlog.get_logger(__name__)@@ -63,6 +64,10 @@ def _is_oom_exception_text(exception_text: str | None) -> bool:def subscription_asset_error_message(asset: ExportedAsset) -> str:# Recipients of scheduled subscriptions didn't author the query, so the OOM advice is# unactionable. Original text stays on asset.exception/exception_type for our own logs.+ # The raw access error ("You don't have access to table ...") reads as if the recipient lacks access.+ owner_reason = get_assets_owner_disable_reason([asset.exception_type])+ if owner_reason is not None:+ return f"{owner_reason.description}."is_oom_exception = asset.exception_type == _OOM_EXCEPTION_TYPE or _is_oom_exception_text(asset.exception)if asset.exception and not is_oom_exception:return asset.exceptiondiff --git a/products/subscriptions/backend/temporal/activities.py b/products/subscriptions/backend/temporal/activities.pyindex 6adb3289fc04..6afc266db986 100644--- a/products/subscriptions/backend/temporal/activities.py+++ b/products/subscriptions/backend/temporal/activities.py@@ -21,6 +21,7 @@ from products.subscriptions.backend.logic import _capture_delivery_failed_eventfrom products.subscriptions.backend.logic.auto_disable import (UNSUPPORTED_TARGET_DISABLE_REASON,disable_invalid_subscription,+ get_assets_owner_disable_reason,get_subscription_disable_reason,)from products.subscriptions.backend.logic.email_subscriptions import send_email_subscription_report@@ -506,6 +507,39 @@ async def _deliver_insight_dashboard_subscription(_capture_delivery_failed_event(subscription, Exception(NO_ASSETS_REASON))return DeliverSubscriptionResult(recipient_results=recipient_results)+ # The failed tiles in this delivery already tell the recipients why, so nobody else gets an email.+ disable_reason = get_assets_owner_disable_reason(asset.exception_type for asset in assets)++ try:+ result = await _send_to_target(subscription, inputs, assets, recipient_results, send_only_to_new_recipients)+ except Exception as error:+ # Temporal retries every failure but a non-retryable one, so the retry delivers the reason+ # and the row stays enabled until it does.+ if not (isinstance(error, ApplicationError) and error.non_retryable):+ disable_reason = None+ raise+ finally:+ if disable_reason is not None:+ await database_sync_to_async(disable_invalid_subscription, thread_sensitive=False)(+ subscription, disable_reason, notify_owner=False+ )++ await LOGGER.ainfo(+ "deliver_subscription.completed",+ subscription_id=inputs.subscription_id,+ target_type=subscription.target_type,+ )+ return result+++async def _send_to_target(+ subscription: Subscription,+ inputs: DeliverSubscriptionInputs,+ assets: list[ExportedAsset],+ recipient_results: list[RecipientResult],+ send_only_to_new_recipients: bool,+) -> DeliverSubscriptionResult:+ """Send the assets over the subscription's channel. Split out so the caller can wrap the one send."""if subscription.target_type == Subscription.SubscriptionTarget.EMAIL:async def _send_email(email: str) -> None:@@ -551,12 +585,6 @@ async def _deliver_insight_dashboard_subscription(f"Subscription delivery reached an unsupported target {subscription.target_type!r}",non_retryable=True,)-- await LOGGER.ainfo(- "deliver_subscription.completed",- subscription_id=inputs.subscription_id,- target_type=subscription.target_type,- )return resultdiff --git a/products/subscriptions/backend/temporal/ai_subscription/delivery.py b/products/subscriptions/backend/temporal/ai_subscription/delivery.pyindex a84eed8cc25f..4bf72ffd9c5e 100644--- a/products/subscriptions/backend/temporal/ai_subscription/delivery.py+++ b/products/subscriptions/backend/temporal/ai_subscription/delivery.py@@ -19,10 +19,12 @@ from posthog.helpers.email_formatting import render_ai_email_htmlfrom posthog.helpers.markdown_safety import is_allowed_link_url, strip_external_links_markdownfrom posthog.integrations import IntegrationRecordfrom posthog.models import Team, User+from posthog.query_creator_access import CreatorLeftOrganizationError, assert_creator_can_runfrom posthog.slack.formatting import channel_id_from_targetfrom posthog.sync import database_sync_to_asyncfrom posthog.utils import absolute_uri+from products.access_control.backend.facade.user_access_control import UserAccessControlErrorfrom products.exports.backend.facade.api import get_delivery_image_urlfrom products.slack_app.backend.facade.api import slack_followup_invitefrom products.subscriptions.backend.facade.contracts import PromptRejectedError, SubscriptionTriggerType@@ -439,9 +441,15 @@ async def build_ai_subscription_report(subscription: Subscription) -> AiReportReteam, user, window, ai_query_plan = await database_sync_to_async(_resolve_subscription_context, thread_sensitive=False)(subscription)- # created_by is FK SET_NULL; the pipeline requires a non-None user- if user is None:- raise PromptRejectedError("AI subscription has no creator (created_by deleted); cannot deliver.")+ # The report's queries run as the creator, so a creator who was deleted, left the organization or+ # lost access to the project ends the subscription the same way a bad prompt does.+ try:+ await database_sync_to_async(assert_creator_can_run, thread_sensitive=False)(user, team)+ except CreatorLeftOrganizationError as error:+ raise PromptRejectedError("The owner of this subscription is no longer in the organization.") from error+ except UserAccessControlError as error:+ raise PromptRejectedError("The owner of this subscription no longer has access.") from error+ assert user is not Noneinclude_images = subscription.includes_delivery_part("include_images")result = await generate_ai_report(diff --git a/products/subscriptions/backend/temporal/ai_subscription/test/test_delivery.py b/products/subscriptions/backend/temporal/ai_subscription/test/test_delivery.pyindex 8f0d52bf99cf..982a7afd794a 100644--- a/products/subscriptions/backend/temporal/ai_subscription/test/test_delivery.py+++ b/products/subscriptions/backend/temporal/ai_subscription/test/test_delivery.py@@ -1,4 +1,5 @@import uuid+from collections.abc import Iteratorfrom datetime import UTC, datetime, timedeltaimport pytest@@ -1053,6 +1054,12 @@ class TestFreezePlanPersistence:window = ReportWindow(start=end - timedelta(days=1), end=end)return MagicMock(), MagicMock(), window, sub.ai_query_plan+ @pytest.fixture(autouse=True)+ def _owner_can_run(self) -> Iterator[None]:+ # The team and user above are mocks, so the owner check would query the database with them.+ with patch(f"{_DELIVERY}.assert_creator_can_run"):+ yield+@parameterized.expand([("legacy_config", {}, True),diff --git a/products/subscriptions/backend/temporal/insight_snapshot.py b/products/subscriptions/backend/temporal/insight_snapshot.pyindex 4612569914e8..07f50da75a6d 100644--- a/products/subscriptions/backend/temporal/insight_snapshot.py+++ b/products/subscriptions/backend/temporal/insight_snapshot.py@@ -25,7 +25,9 @@ from posthog.caching.calculate_results import calculate_cache_key, calculate_forfrom posthog.caching.insight_result import InsightResult, NothingInCacheResultfrom posthog.models import Team, Userfrom posthog.models.utils import strip_null_bytes+from posthog.query_creator_access import CreatorLeftOrganizationError, assert_creator_can_run+from products.access_control.backend.facade.user_access_control import UserAccessControlErrorfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.product_analytics.backend.facade.models import Insight@@ -188,6 +190,16 @@ def _execute_and_serialize_insight_query(query_json: Any,) -> dict[str, Any]:"""Run cache/calculate path and return snapshot fields to merge (``query_*`` / ``cache_key`` only)."""+ # Same rule as the export: no query runs for an owner who left or who cannot view the insight.+ try:+ assert_creator_can_run(user, team, dashboard, insight)+ except (CreatorLeftOrganizationError, UserAccessControlError) as error:+ # Both messages are ours and name no query data, so they are safe to show as they are.+ return {+ "query_results": None,+ "cache_key": None,+ "query_error": {"type": type(error).__name__, "message": str(error), "human_readable_error": str(error)},+ }try:insight_result = calculate_for_query_based_insight(insight,diff --git a/products/subscriptions/backend/tests/logic/test_subscriptions_utils.py b/products/subscriptions/backend/tests/logic/test_subscriptions_utils.pyindex 12dfbaf52bc8..6f794e3acc0c 100644--- a/products/subscriptions/backend/tests/logic/test_subscriptions_utils.py+++ b/products/subscriptions/backend/tests/logic/test_subscriptions_utils.py@@ -131,6 +131,7 @@ class TestSubscriptionAssetErrorMessage(APIBaseTest):export_format="image/png",exception=exception,exception_type=exception_type,+ created_by=self.user,)def setUp(self) -> None:@@ -164,6 +165,18 @@ class TestSubscriptionAssetErrorMessage(APIBaseTest):ASSET_GENERATION_FAILED_MESSAGE,),("falls_back_when_no_exception", None, None, ASSET_GENERATION_FAILED_MESSAGE),+ (+ "explains_an_owner_who_left",+ "The owner is no longer in the organization.",+ "CreatorLeftOrganizationError",+ "The owner of this subscription is no longer in the organization.",+ ),+ (+ "explains_an_owner_who_lost_access",+ "You don't have access to table `revenue`.",+ "TableAccessDeniedError",+ "The owner of this subscription no longer has access to some of its data.",+ ),])def test_subscription_asset_error_message(diff --git a/products/subscriptions/backend/tests/temporal/conftest.py b/products/subscriptions/backend/tests/temporal/conftest.pyindex 15e3f783695b..4096464e27d5 100644--- a/products/subscriptions/backend/tests/temporal/conftest.py+++ b/products/subscriptions/backend/tests/temporal/conftest.py@@ -1,5 +1,8 @@# The workflow tests use core's temporal test fixtures: a team whose organization approved AI data# processing, a live Temporal client, and the logger setup every temporal test runs under.+import pytest++from posthog.models import OrganizationMembershipfrom posthog.temporal.conftest import _restore_structlog_config # noqa: F401from posthog.temporal.tests.conftest import ( # noqa: F401_ignore_sigpipe,@@ -8,3 +11,13 @@ from posthog.temporal.tests.conftest import ( # noqa: F401team,temporal_client,)+++def user(request, base_test_mixin_fixture):+ # The temporal team lives in its own organization, so the shared user is made a member of it.+ # Deliveries run as the subscription's creator and stop when that creator is not a member.+ user = base_test_mixin_fixture.user+ temporal_team = request.getfixturevalue("team")+ OrganizationMembership.objects.get_or_create(organization_id=temporal_team.organization_id, user=user)+ return userdiff --git a/products/subscriptions/backend/tests/temporal/test_subscriptions_workflows.py b/products/subscriptions/backend/tests/temporal/test_subscriptions_workflows.pyindex fa0bec000df4..fe3f698d2273 100644--- a/products/subscriptions/backend/tests/temporal/test_subscriptions_workflows.py+++ b/products/subscriptions/backend/tests/temporal/test_subscriptions_workflows.py@@ -798,6 +798,86 @@ async def test_deliver_subscription_auto_disables_invalid_subscriptions(assert result.recipient_results[0].error == expected_error+ "label, exception_types, send_error, expected_raise, expected_enabled",+ [+ ("owner_left", ["CreatorLeftOrganizationError"], None, None, False),+ ("owner_lost_access_to_every_tile", ["TableAccessDeniedError", "TableAccessDeniedError"], None, None, False),+ # One denied tile still delivers the dashboard, with that tile showing why.+ ("owner_lost_access_to_one_tile", ["TableAccessDeniedError", None], None, None, True),+ # A permanent bounce raises out of the send, and the disable must still happen.+ (+ "owner_left_and_email_bounces",+ ["CreatorLeftOrganizationError"],+ EmailDeliveryError("permanent rejection"),+ ApplicationError,+ False,+ ),+ # A transient failure is retried by Temporal, so the retry delivers the reason before any disable.+ (+ "owner_left_and_send_fails_transiently",+ ["CreatorLeftOrganizationError"],+ ConnectionError("smtp unreachable"),+ ConnectionError,+ True,+ ),+ ],+)+async def test_deliver_subscription_sends_the_reason_then_disables_when_the_owner_cannot_run_it(+ team, user, label, exception_types, send_error, expected_raise, expected_enabled+):+ insight = await sync_to_async(Insight.objects.create)(team=team, short_id=f"own-{label[:5]}", name="owner")+ asset_ids = []+ for index, exception_type in enumerate(exception_types):+ asset = await sync_to_async(ExportedAsset.objects.create)(+ team=team,+ insight=insight,+ export_format="image/png",+ content_location=None if exception_type else f"s3://bucket/{label}-{index}.png",+ exception="denied" if exception_type else None,+ exception_type=exception_type,+ )+ asset_ids.append(asset.id)+ subscription = await sync_to_async(create_subscription)(+ team=team,+ insight=insight,+ created_by=user,+ target_type="email",+ target_value="[email protected]",+ enabled=True,+ )++ with (+ patch(+ "products.subscriptions.backend.temporal.activities.send_email_subscription_report",+ side_effect=send_error,+ ) as send_report,+ patch(+ "products.subscriptions.backend.logic.auto_disable.send_notifications_for_disabled_subscription"+ ) as send_disabled_email,+ patch("products.subscriptions.backend.logic.auto_disable.create_notification") as create_notification,+ ):+ run = ActivityEnvironment().run(+ deliver_subscription,+ DeliverSubscriptionInputs(+ subscription_id=subscription.id, exported_asset_ids=asset_ids, total_insight_count=len(asset_ids)+ ),+ )+ if expected_raise is not None:+ with pytest.raises(expected_raise):+ await run+ else:+ result = await run+ assert result.recipient_results[0].status == "success"++ send_report.assert_called_once()+ send_disabled_email.assert_not_called()+ create_notification.assert_not_called()+ await sync_to_async(subscription.refresh_from_db)()+ assert subscription.enabled is expected_enabled++@pytest.mark.asyncioasync def test_no_assets_does_not_auto_disable(team, user):"""Empty `assets` at delivery time is a transient export-pipeline failure@@ -2536,13 +2616,22 @@ async def test_generate_ai_report_consent_revoked_aborts_and_auto_disables(team,assert sub.enabled is False-async def test_generate_ai_report_prompt_rejected_aborts_and_auto_disables(team, user):[email protected]("creator_left_org", [False, True])+async def test_generate_ai_report_prompt_rejected_aborts_and_auto_disables(team, user, creator_left_org):await _set_ai_consent(team, True)sub = await _create_ai_subscription(team, user)delivery = await _create_ai_delivery(sub)+ if creator_left_org:+ # The real report builder refuses before any LLM call, so the planner below must stay unused.+ await sync_to_async(+ OrganizationMembership.objects.filter(organization_id=team.organization_id, user=user).delete+ )()with (- patch(_GENERATE_REPORT, side_effect=PromptRejectedError("Prompt is empty.")),+ patch(+ "products.subscriptions.backend.temporal.ai_subscription.delivery.generate_ai_report",+ side_effect=PromptRejectedError("Prompt is empty."),+ ) as generate_report,patch("products.subscriptions.backend.logic.auto_disable.send_notifications_for_disabled_subscription"),):result = await ActivityEnvironment().run(@@ -2550,6 +2639,7 @@ async def test_generate_ai_report_prompt_rejected_aborts_and_auto_disables(team,)assert result.aborted is True+ assert generate_report.called is (not creator_left_org)# The PromptRejectedError detail must reach the delivery record, not be swallowed.assert any(r.error and r.error.get("type") == "PromptRejectedError" for r in result.recipient_results), ("prompt-rejected abort must carry the rejection detail in recipient_results"