:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(subscriptions): gate AI summaries on AI credit budget (#59625)
Vasco de Krijger1430d55cd3de
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex 9a3f28d70b6e..3a06501316a0 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -43,6 +43,7 @@ from posthog.utils import str_to_boolfrom products.product_analytics.backend.models.insight import Insight+from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limitedfrom ee.tasks.subscriptions.auto_disable import validate_re_enablefrom ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNT@@ -293,6 +294,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):# — otherwise PATCHing `deleted=False` on a grandfathered row would# bypass the cap entirely.if self._is_becoming_active_summary(attrs):+ self._validate_summary_credit_budget()organization = self.context["get_organization"]()self._validate_summary_enabled_org_limit(organization)@@ -308,6 +310,16 @@ class SubscriptionSerializer(serializers.ModelSerializer):post_active = post_summary_enabled and not post_deletedreturn post_active and not pre_active+ def _validate_summary_credit_budget(self) -> None:+ # Refuse to turn a summary on while the org is over its AI credit budget,+ # mirroring the chat assistant's gate (ee/api/conversation.py).+ team = self.context["get_team"]()+ if is_team_limited(team.api_token, QuotaResource.AI_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY):+ raise QuotaLimitExceeded(+ "Your organization reached its AI credit usage limit. "+ "Increase the limits in Billing settings, or ask an org admin to do so."+ )+def _validate_summary_enabled_org_limit(self, organization) -> None:# Already-on subscriptions stay on for grandfathered orgs already over# the cap; the becoming-active check in validate() ensures we only getdiff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex 10aeb8e39b73..ad2ee43b26a0 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -674,6 +674,64 @@ class TestSubscriptionTemporal(APILicensedTest):assert response.json()["title"] == "renamed while over the cap"assert response.json()["summary_enabled"] is True+ @parameterized.expand(+ [+ # The credit gate fires only when a summary is being switched on: an over-budget+ # org is blocked when summary_enabled=True but can still create plain subscriptions.+ ("summary_on_over_budget", True, True, status.HTTP_402_PAYMENT_REQUIRED),+ ("summary_on_under_budget", True, False, status.HTTP_201_CREATED),+ ("summary_off_over_budget", False, True, status.HTTP_201_CREATED),+ ]+ )+ def test_create_summary_enabled_respects_ai_credit_budget(+ self,+ _name: str,+ summary_enabled: bool,+ is_limited: bool,+ expected_status: int,+ ) -> None:+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()++ with patch("ee.api.subscription.is_team_limited", return_value=is_limited):+ response = self._create_subscription(summary_enabled=summary_enabled)++ assert response.status_code == expected_status, response.content+ if expected_status == status.HTTP_402_PAYMENT_REQUIRED:+ assert "AI credit usage limit" in response.json()["detail"]++ def test_patch_transition_to_summary_enabled_blocked_when_over_credit_budget(self) -> None:+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ create_response = self._create_subscription(summary_enabled=False)+ sub_id = create_response.json()["id"]++ with patch("ee.api.subscription.is_team_limited", return_value=True):+ patch_response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}",+ {"summary_enabled": True},+ )++ assert patch_response.status_code == status.HTTP_402_PAYMENT_REQUIRED+ assert "AI credit usage limit" in patch_response.json()["detail"]++ def test_patch_unrelated_field_on_already_enabled_summary_when_over_credit_budget(self) -> None:+ # Going over budget mid-month must not trap an org out of editing existing+ # summaries — only transitions *into* an active summary are gated.+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ existing = self._seed_active_summary_subscriptions(1)++ with patch("ee.api.subscription.is_team_limited", return_value=True):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{existing[0].id}",+ {"title": "renamed while over budget"},+ )++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["title"] == "renamed while over budget"+ assert response.json()["summary_enabled"] is True+@parameterized.expand([("under_limit", 3, 10, False),diff --git a/ee/tasks/subscriptions/email_subscriptions.py b/ee/tasks/subscriptions/email_subscriptions.pyindex 1f5d99d13dcf..d35b06bdb354 100644--- a/ee/tasks/subscriptions/email_subscriptions.py+++ b/ee/tasks/subscriptions/email_subscriptions.py@@ -51,6 +51,7 @@ def send_email_subscription_report(total_asset_count: Optional[int] = None,send_async: bool = True,change_summary: Optional[str] = None,+ summary_skipped_over_budget: bool = False,) -> None:utm_tags = f"{UTM_TAGS_BASE}&utm_medium=email"@@ -104,6 +105,8 @@ def send_email_subscription_report("invite_summary": invite_summary,"total_asset_count": total_asset_count,"change_summary": change_summary,+ "summary_skipped_over_budget": summary_skipped_over_budget,+ "billing_url": absolute_uri(f"/organization/billing?{utm_tags}"),},)message.add_recipient(email=email)diff --git a/ee/tasks/subscriptions/slack_subscriptions.py b/ee/tasks/subscriptions/slack_subscriptions.pyindex 7027d02db442..de94ae0235f3 100644--- a/ee/tasks/subscriptions/slack_subscriptions.py+++ b/ee/tasks/subscriptions/slack_subscriptions.py@@ -11,11 +11,22 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.models.exported_asset import ExportedAssetfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.subscription import Subscription+from posthog.utils import absolute_urifrom ee.tasks.subscriptions.subscription_utils import ASSET_GENERATION_FAILED_MESSAGE, UTM_TAGS_BASE, _has_asset_failedlogger = structlog.get_logger(__name__)++# Shown in place of the AI summary when generation was skipped because the org is+# over its AI credit budget. Wording kept in sync with the email template's notice.+def summary_skipped_over_budget_message(billing_url: str) -> str:+ return (+ "_AI summary skipped — your organization has reached its AI credit usage limit. "+ f"Increase the limit in <{billing_url}|Billing settings> to resume summaries._"+ )++# Slack API error codes that indicate transient server-side issues — safe to retry.# These are 5xx-equivalents in Slack's string-coded error model. Permanent errors# (channel_not_found, invalid_auth, etc.) are NOT in this set and should fail fast.@@ -123,6 +134,7 @@ def _prepare_slack_message(total_asset_count: int,is_new_subscription: bool = False,change_summary: str | None = None,+ summary_skipped_over_budget: bool = False,) -> SlackMessageData:"""Prepare Slack message content. Pure function with no side effects."""utm_tags = f"{UTM_TAGS_BASE}&utm_medium=slack"@@ -157,6 +169,14 @@ def _prepare_slack_message(if len(summary_text) > 3000:summary_text = summary_text[:2997] + "..."blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": summary_text}})+ elif summary_skipped_over_budget:+ billing_url = f"{absolute_uri('/organization/billing')}?{utm_tags}"+ blocks.append(+ {+ "type": "context",+ "elements": [{"type": "mrkdwn", "text": summary_skipped_over_budget_message(billing_url)}],+ }+ )blocks.append(_block_for_asset(first_asset, resource_url=resource_info.url))@@ -279,9 +299,15 @@ async def send_slack_message_with_integration_async(total_asset_count: int,is_new_subscription: bool = False,change_summary: str | None = None,+ summary_skipped_over_budget: bool = False,) -> SlackDeliveryResult:message_data = _prepare_slack_message(- subscription, assets, total_asset_count, is_new_subscription, change_summary=change_summary+ subscription,+ assets,+ total_asset_count,+ is_new_subscription,+ change_summary=change_summary,+ summary_skipped_over_budget=summary_skipped_over_budget,)slack_integration = SlackIntegration(integration)diff --git a/ee/tasks/test/subscriptions/test_email_subscriptions.py b/ee/tasks/test/subscriptions/test_email_subscriptions.pyindex 4c96bc7ea25c..6401c032c324 100644--- a/ee/tasks/test/subscriptions/test_email_subscriptions.py+++ b/ee/tasks/test/subscriptions/test_email_subscriptions.py@@ -115,6 +115,36 @@ class TestEmailSubscriptionsTasks(APIBaseTest):assert "You have been subscribed to a PostHog Dashboard" == mocked_email_messages[0].subjectassert f"SHOWING 1 OF 10 DASHBOARD INSIGHTS" in mocked_email_messages[0].html_body+ def test_shows_summary_skipped_notice_when_over_budget(self, MockEmailMessage: MagicMock) -> None:+ mocked_email_messages = mock_ee_email_messages(MockEmailMessage)++ send_email_subscription_report(+ "[email protected]",+ self.subscription,+ [self.asset],+ summary_skipped_over_budget=True,+ )++ assert "AI summary skipped" in mocked_email_messages[0].html_body+ assert "AI credit usage limit" in mocked_email_messages[0].html_body+ # The notice links straight to the billing page so the user can lift the limit.+ assert "/organization/billing" in mocked_email_messages[0].html_body++ def test_no_summary_skipped_notice_when_summary_present(self, MockEmailMessage: MagicMock) -> None:+ # A generated summary renders instead of the skip notice — never both.+ mocked_email_messages = mock_ee_email_messages(MockEmailMessage)++ send_email_subscription_report(+ "[email protected]",+ self.subscription,+ [self.asset],+ change_summary="- Pageviews trending up",+ summary_skipped_over_budget=True,+ )++ assert "AI summary:" in mocked_email_messages[0].html_body+ assert "AI summary skipped" not in mocked_email_messages[0].html_body+def test_same_recipient_gets_distinct_campaign_per_subscription(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_ee_email_messages(MockEmailMessage)diff --git a/ee/tasks/test/subscriptions/test_slack_subscriptions.py b/ee/tasks/test/subscriptions/test_slack_subscriptions.pyindex bf6addd8c7fb..d1bf5238eb28 100644--- a/ee/tasks/test/subscriptions/test_slack_subscriptions.py+++ b/ee/tasks/test/subscriptions/test_slack_subscriptions.py@@ -18,6 +18,7 @@ from products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions.slack_subscriptions import (_block_for_asset,+ _prepare_slack_message,send_slack_message_with_integration_async,send_slack_subscription_report,)@@ -604,3 +605,54 @@ class TestSlackErrorTruncation(APIBaseTest):text = block["text"]["text"]assert "*My Test subscription*" in textassert ASSET_GENERATION_FAILED_MESSAGE in text+++class TestSlackSummaryNotice(APIBaseTest):+ def setUp(self) -> None:+ self.insight = Insight.objects.create(team=self.team, short_id="123456", name="My Test subscription")+ self.asset = ExportedAsset.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ export_format="image/png",+ content_location="s3://bucket/test.png",+ )+ self.subscription = create_subscription(+ team=self.team,+ insight=self.insight,+ created_by=self.user,+ target_type="slack",+ target_value="C12345|#test-channel",+ )++ def _block_texts(self, change_summary: str | None, summary_skipped_over_budget: bool) -> list[str]:+ message = _prepare_slack_message(+ self.subscription,+ [self.asset],+ total_asset_count=1,+ change_summary=change_summary,+ summary_skipped_over_budget=summary_skipped_over_budget,+ )+ return [block.get("text", {}).get("text", "") for block in message.blocks] + [+ element.get("text", "")+ for block in message.blocks+ for element in block.get("elements", [])+ if isinstance(element, dict)+ ]++ def test_shows_over_budget_notice_when_summary_skipped(self) -> None:+ texts = self._block_texts(change_summary=None, summary_skipped_over_budget=True)+ notice = next((t for t in texts if "AI summary skipped" in t), None)+ assert notice is not None+ # "Billing settings" is an inline mrkdwn link (<url|label>) in the notice text itself.+ assert "/organization/billing" in notice+ assert "|Billing settings>" in notice++ def test_no_notice_when_summary_present(self) -> None:+ # A generated summary wins — the over-budget notice never doubles up with it.+ texts = self._block_texts(change_summary="- trending up", summary_skipped_over_budget=True)+ assert any("*AI summary:*" in text for text in texts)+ assert all("AI summary skipped" not in text for text in texts)++ def test_no_notice_when_under_budget_and_no_summary(self) -> None:+ texts = self._block_texts(change_summary=None, summary_skipped_over_budget=False)+ assert all("AI summary skipped" not in text for text in texts)diff --git a/posthog/templates/email/subscription_report.html b/posthog/templates/email/subscription_report.htmlindex 365d1c1f9740..a73ebf7839c5 100644--- a/posthog/templates/email/subscription_report.html+++ b/posthog/templates/email/subscription_report.html@@ -47,6 +47,11 @@<p style="margin: 0 0 8px 0; font-weight: bold;">AI summary:</p><div style="margin: 0;">{{ change_summary|linebreaksbr }}</div></div>+{% elif summary_skipped_over_budget %}+<div style="padding: 16px; background-color: #fff8e6; border: 1px solid #f0e0b0; border-radius: 4px; margin-bottom: 16px;">+ <p style="margin: 0; font-weight: bold;">AI summary skipped</p>+ <p style="margin: 8px 0 0 0;">Your organization has reached its AI credit usage limit, so the AI summary wasn't generated for this report. <a href="{{ billing_url }}">Increase the limit in Billing settings</a> to resume summaries.</p>+</div>{% endif %}{% for asset in asset_data %}diff --git a/posthog/temporal/subscriptions/activities.py b/posthog/temporal/subscriptions/activities.pyindex cbedafaf4ac8..a87b0db43e16 100644--- a/posthog/temporal/subscriptions/activities.py+++ b/posthog/temporal/subscriptions/activities.py@@ -394,6 +394,7 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubstotal_asset_count=inputs.total_insight_count,send_async=False,change_summary=inputs.change_summary,+ summary_skipped_over_budget=inputs.summary_skipped_over_budget,)success_count += 1recipient_results.append(RecipientResult(recipient=email, status="success"))@@ -465,6 +466,7 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubstotal_asset_count=inputs.total_insight_count,is_new_subscription=inputs.is_new_subscription_target,change_summary=inputs.change_summary,+ summary_skipped_over_budget=inputs.summary_skipped_over_budget,)if delivery_result.is_complete_success:diff --git a/posthog/temporal/subscriptions/snapshot_activities.py b/posthog/temporal/subscriptions/snapshot_activities.pyindex 0e8c81af8fc8..4c0af596db4b 100644--- a/posthog/temporal/subscriptions/snapshot_activities.py+++ b/posthog/temporal/subscriptions/snapshot_activities.py@@ -3,6 +3,7 @@ from typing import Anyimport posthoganalyticsimport temporalio.activity+from asgiref.sync import sync_to_asyncfrom prometheus_client import Counterfrom structlog import get_logger@@ -20,6 +21,7 @@ from posthog.temporal.subscriptions.types import SnapshotInsightsInputs, Snapshofrom products.product_analytics.backend.models.insight import Insight+from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limitedfrom ee.models import CoreMemoryLOGGER = get_logger(__name__)@@ -37,6 +39,14 @@ SUBSCRIPTION_SUMMARY_SKIPPED_NO_AI_CONSENT = Counter("posthog_subscription_ai_summary_skipped_no_ai_consent_total","AI summary skipped because the organization has not approved AI data processing",)+SUBSCRIPTION_SUMMARY_SKIPPED_OVER_CREDIT_BUDGET = Counter(+ "posthog_subscription_ai_summary_skipped_over_credit_budget_total",+ "AI summary skipped because the organization is over its AI credit budget",+)+SUBSCRIPTION_SUMMARY_CREDIT_CHECK_FAILED = Counter(+ "posthog_subscription_ai_summary_credit_check_failed_total",+ "AI credit budget lookup errored; the summary was generated (fail-open)",+)SUBSCRIPTION_SUMMARY_IMAGE_SKIPPED = Counter("posthog_subscription_ai_summary_image_skipped_total","AI summary image attachment skipped for an insight",@@ -429,6 +439,31 @@ async def _run_snapshot_subscription_insights(inputs: SnapshotInsightsInputs) ->)return SnapshotInsightsResult()+ # Over budget: skip the summary but still deliver the rest of the subscription —+ # graceful degradation beats failing the whole delivery. Fail open on a quota-lookup+ # error: generate the summary rather than silently dropping it on a transient blip.+ try:+ is_over_credit_budget = await sync_to_async(is_team_limited, thread_sensitive=False)(+ subscription.team.api_token, QuotaResource.AI_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY+ )+ except Exception as e:+ is_over_credit_budget = False+ SUBSCRIPTION_SUMMARY_CREDIT_CHECK_FAILED.inc()+ await LOGGER.awarning(+ "snapshot_subscription_insights.credit_budget_check_failed",+ subscription_id=inputs.subscription_id,+ error=str(e),+ exc_info=True,+ )+ if is_over_credit_budget:+ SUBSCRIPTION_SUMMARY_SKIPPED_OVER_CREDIT_BUDGET.inc()+ await LOGGER.ainfo(+ "snapshot_subscription_insights.skipped_over_credit_budget",+ subscription_id=inputs.subscription_id,+ organization_id=str(subscription.team.organization_id),+ )+ return SnapshotInsightsResult(summary_skipped_over_budget=True)+if not inputs.delivery_id:return SnapshotInsightsResult()diff --git a/posthog/temporal/subscriptions/test_snapshot_ai_consent.py b/posthog/temporal/subscriptions/test_snapshot_ai_consent.pyindex 26a77decbc42..5d8bd5b21a2f 100644--- a/posthog/temporal/subscriptions/test_snapshot_ai_consent.py+++ b/posthog/temporal/subscriptions/test_snapshot_ai_consent.py@@ -98,6 +98,8 @@ async def test_skips_summary_when_org_has_not_approved_ai(team, user):)assert result.summary_text is None+ # No-consent skips carry no user-facing notice — only over-budget skips do.+ assert result.summary_skipped_over_budget is Falseasync def test_runs_summary_when_org_has_approved_ai(team, user, monkeypatch):@@ -139,6 +141,74 @@ async def test_runs_summary_when_org_has_approved_ai(team, user, monkeypatch):assert result.summary_text == "- Pageviews is trending up"+# A named function rather than a lambda because the fail-open param case needs to raise.+def _raise_quota_lookup_error(*args, **kwargs):+ raise RuntimeError("quota cache unavailable")+++ "name,is_team_limited_impl,expect_summary_generated,expect_skipped_over_budget",+ [+ # Over budget: skip the summary entirely (generate is never called) and flag it so+ # the delivered report can show a notice.+ ("over_budget_skips", lambda *a, **kw: True, False, True),+ # Under budget: generate and deliver as normal.+ ("under_budget_runs", lambda *a, **kw: False, True, False),+ # Fail open: a quota-lookup error must not drop the summary — generate and deliver.+ ("credit_check_errors_fails_open", _raise_quota_lookup_error, True, False),+ ],+)+async def test_summary_generation_respects_ai_credit_budget(+ team, user, monkeypatch, name, is_team_limited_impl, expect_summary_generated, expect_skipped_over_budget+):+ subscription = await _create_subscription(team, user)+ await _set_ai_consent(subscription, approved=True)+ delivery = await _create_delivery(+ subscription,+ {+ "insights": [+ {+ "id": subscription.insight_id,+ "name": "Pageviews",+ "query_results": {"result": [{"label": "Pageviews", "data": [1, 2, 3]}]},+ }+ ]+ },+ )++ summary_text = "- Pageviews is trending up"+ called = {}++ def fake_generate(*args, **kwargs):+ called["ran"] = True+ return summary_text++ monkeypatch.setattr(+ "posthog.temporal.subscriptions.snapshot_activities.is_team_limited",+ is_team_limited_impl,+ )+ monkeypatch.setattr(+ "posthog.temporal.subscriptions.snapshot_activities.generate_change_summary",+ fake_generate,+ )++ result = await _run(+ SnapshotInsightsInputs(+ subscription_id=subscription.id,+ team_id=subscription.team_id,+ delivery_id=str(delivery.id),+ )+ )++ if expect_summary_generated:+ assert result.summary_text == summary_text+ assert called.get("ran") is True+ else:+ assert result.summary_text is None+ assert called.get("ran") is None+ assert result.summary_skipped_over_budget is expect_skipped_over_budget++async def test_skips_summary_when_summary_not_enabled(team, user):subscription = await _create_subscription(team, user, summary_enabled=False)await _set_ai_consent(subscription, approved=True)@@ -152,6 +222,8 @@ async def test_skips_summary_when_summary_not_enabled(team, user):)assert result.summary_text is None+ # Summary-disabled skips carry no user-facing notice — only over-budget skips do.+ assert result.summary_skipped_over_budget is Falseasync def test_stored_prompt_guide_is_ignored_when_prompt_guide_flag_is_off(team, user, monkeypatch):diff --git a/posthog/temporal/subscriptions/types.py b/posthog/temporal/subscriptions/types.pyindex d4a7c37e912a..593b7dfe40f3 100644--- a/posthog/temporal/subscriptions/types.py+++ b/posthog/temporal/subscriptions/types.py@@ -88,6 +88,7 @@ class DeliverSubscriptionInputs:previous_value: typing.Optional[str] = Noneinvite_message: typing.Optional[str] = Nonechange_summary: typing.Optional[str] = None+ summary_skipped_over_budget: bool = False@dataclasses.dataclass@@ -185,6 +186,8 @@ class SnapshotInsightsInputs:@dataclasses.dataclassclass SnapshotInsightsResult:summary_text: str | None = None+ # Set only on the over-budget skip — drives the user-facing notice in the report.+ summary_skipped_over_budget: bool = False@dataclasses.dataclassdiff --git a/posthog/temporal/subscriptions/workflows.py b/posthog/temporal/subscriptions/workflows.pyindex 5a15a949f6da..3a13e647a00d 100644--- a/posthog/temporal/subscriptions/workflows.py+++ b/posthog/temporal/subscriptions/workflows.py@@ -179,6 +179,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):# even on early returns (no-assets SKIPPED) or exceptions before the summary# activity runs.change_summary: str | None = None+ summary_skipped_over_budget = Falsetry:# Create delivery history record — uuid4() is deterministic across@@ -302,6 +303,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),)change_summary = snapshot_result.summary_text+ summary_skipped_over_budget = snapshot_result.summary_skipped_over_budgetexcept Exception:temporalio.workflow.logger.warning("process_subscription.snapshot_failed",@@ -325,6 +327,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):previous_value=inputs.previous_value,invite_message=inputs.invite_message,change_summary=change_summary,+ summary_skipped_over_budget=summary_skipped_over_budget,),start_to_close_timeout=dt.timedelta(minutes=5),retry_policy=temporalio.common.RetryPolicy(