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(subscriptions): gate AI subscriptions on AI credit budget (#59634)

Vasco de Krijger3c916232f4e3
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.py
index 80dfd539ea9e..7b24f4cfaf35 100644
--- a/ee/billing/quota_limiting.py
+++ b/ee/billing/quota_limiting.py
@@ -226,6 +226,13 @@ def dispatch_recordings_remote_config_sync(team_ids: Iterable[int]) -> None:
capture_exception(e, {"team_id": team_id})
+def is_team_over_ai_credit_budget(team_api_token: str) -> bool:
+ """Single AI-credit quota signal for LLM-spending paths to share — one resource + cache-key
+ pair. On a cache miss this issues a synchronous Redis read, so async callers must wrap it in
+ sync_to_async."""
+ return is_team_limited(team_api_token, QuotaResource.AI_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)
+
+
# -------------------------------------------------------------------------------------------------
# MAIN FUNCTIONS
# -------------------------------------------------------------------------------------------------
diff --git a/posthog/templates/email/ai_subscription_credit_limited.html b/posthog/templates/email/ai_subscription_credit_limited.html
new file mode 100644
index 000000000000..6752afbab54e
--- /dev/null
+++ b/posthog/templates/email/ai_subscription_credit_limited.html
@@ -0,0 +1,20 @@
+{% extends "email/base.html" %} {% load posthog_assets %} {% block section %}
+ <p>
+ Your prompt subscription <strong>{{ title }}</strong> didn't run this cycle because your
+ organization reached its <strong>AI credit limit</strong>.
+ </p>
+ <p>
+ No action is needed — it resumes automatically with the next scheduled report once your
+ AI credits reset on <strong>{{ resume_date|date:"F j, Y" }}</strong>.
+ </p>
+ <p>
+ To give future reports more headroom before they hit the limit, raise your AI credit
+ billing limit.
+ </p>
+ <div class="mb mt text-center">
+ <a class="button primary" href="{{ billing_url }}">Manage AI credits</a>
+ </div>
+ <div class="mb text-center">
+ <a href="{{ subscription_url }}">View subscription</a>
+ </div>
+{% endblock %}
diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.py
index d752e03b7497..dde74c60026c 100644
--- a/posthog/temporal/tests/test_subscriptions_workflows.py
+++ b/posthog/temporal/tests/test_subscriptions_workflows.py
@@ -1,7 +1,7 @@
import uuid
from collections.abc import Callable, Sequence
from concurrent.futures import ThreadPoolExecutor
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Any, cast
from zoneinfo import ZoneInfo
@@ -10,6 +10,7 @@ from freezegun import freeze_time
from unittest.mock import AsyncMock, MagicMock, patch
from django.conf import settings
+from django.utils import timezone
import pytest_asyncio
from asgiref.sync import sync_to_async
@@ -22,6 +23,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.hogql.errors import QueryError
from posthog.errors import CHQueryErrorS3Error
+from posthog.models import OrganizationMembership
from posthog.models.instance_setting import set_instance_setting
from posthog.models.integration import Integration
from posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcome
@@ -42,7 +44,12 @@ from products.exports.backend.temporal.subscriptions.activities import (
update_delivery_record,
validate_subscription_for_delivery,
)
-from products.exports.backend.temporal.subscriptions.ai_subscription.activities import generate_ai_subscription_report
+from products.exports.backend.temporal.subscriptions.ai_subscription.activities import (
+ _CREDIT_RESET_FALLBACK_DAYS,
+ _ai_credit_reset_date,
+ _skip_ai_delivery_over_credit_limit_sync,
+ generate_ai_subscription_report,
+)
from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import PromptRejectedError
from products.exports.backend.temporal.subscriptions.types import (
CreateDeliveryRecordInputs,
@@ -74,6 +81,10 @@ pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]
_GENERATE_MARKDOWN = (
"products.exports.backend.temporal.subscriptions.ai_subscription.activities.generate_ai_subscription_markdown"
)
+_IS_OVER_BUDGET = (
+ "products.exports.backend.temporal.subscriptions.ai_subscription.activities.is_team_over_ai_credit_budget"
+)
+_CREDIT_LIMITED_EMAIL = "products.exports.backend.temporal.subscriptions.ai_subscription.delivery.EmailMessage"
SUBSCRIPTION_SCHEDULE_ACTIVITIES: Sequence[Callable[..., Any]] = cast(
Sequence[Callable[..., Any]],
@@ -2003,6 +2014,9 @@ async def test_deliver_subscription_emits_success_slo_when_disabling(
@sync_to_async
def _create_ai_subscription(team, user, *, target_type="email", target_value="[email protected]") -> Subscription:
+ # The creator is a member of the team's org when they make the subscription — the credit-limit
+ # notice is gated on that membership, so tests asserting the email send need it to hold.
+ OrganizationMembership.objects.get_or_create(organization_id=team.organization_id, user=user)
return create_subscription(
team=team,
created_by=user,
@@ -2034,6 +2048,13 @@ def _set_ai_consent(team, approved: bool) -> None:
org.save(update_fields=["is_ai_data_processing_approved"])
+@sync_to_async
+def _set_org_usage(team, usage) -> None:
+ org = team.organization
+ org.usage = usage
+ org.save(update_fields=["usage"])
+
+
def _ai_delivery_inputs(subscription_id: int, delivery_id) -> DeliverSubscriptionInputs:
return DeliverSubscriptionInputs(
subscription_id=subscription_id, exported_asset_ids=[], total_insight_count=0, delivery_id=delivery_id
@@ -2167,6 +2188,239 @@ async def test_generate_ai_report_skips_regeneration_when_already_persisted(team
mock_generate.assert_not_called()
+async def test_generate_ai_report_skips_when_over_credit_budget(team, user):
+ # Over budget on a cache miss → skip generation (no LLM spend), reschedule, notify once.
+ # Far-future period end so the synced-period reschedule is exercised regardless of when this runs.
+ await _set_ai_consent(team, True)
+ await _set_org_usage(team, {"period": ["2025-01-01T00:00:00Z", "2099-02-01T00:00:00Z"]})
+ sub = await _create_ai_subscription(team, user)
+ delivery = await _create_ai_delivery(sub)
+
+ with (
+ patch(_IS_OVER_BUDGET, return_value=True),
+ patch(_GENERATE_MARKDOWN) as mock_generate,
+ patch(_CREDIT_LIMITED_EMAIL) as mock_email,
+ ):
+ result = await ActivityEnvironment().run(
+ generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
+ )
+
+ assert result.skipped is True
+ assert result.aborted is False
+ mock_generate.assert_not_called() # no LLM tokens spent while over budget
+ mock_email.return_value.send.assert_called_once() # owner notified once
+ await sync_to_async(sub.refresh_from_db)()
+ assert sub.enabled is True, "an over-budget sub stays enabled — it resumes when credits reset"
+ assert sub.next_delivery_date == datetime(2099, 2, 1, tzinfo=ZoneInfo("UTC"))
+
+
+async def test_generate_ai_report_credit_check_fails_open(team, user):
+ # A quota-lookup error must not drop a deliverable report — fail open and generate.
+ await _set_ai_consent(team, True)
+ sub = await _create_ai_subscription(team, user)
+ delivery = await _create_ai_delivery(sub)
+
+ with (
+ patch(_IS_OVER_BUDGET, side_effect=RuntimeError("quota cache unavailable")),
+ patch(_GENERATE_MARKDOWN, return_value="# Report") as mock_generate,
+ ):
+ result = await ActivityEnvironment().run(
+ generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
+ )
+
+ assert result.skipped is False and result.aborted is False
+ mock_generate.assert_called_once()
+ refreshed = await sync_to_async(SubscriptionDelivery.objects.get)(pk=delivery.id)
+ assert refreshed.content_snapshot["ai_report"] == "# Report"
+
+
+async def test_generate_ai_report_already_generated_bypasses_credit_gate(team, user):
+ # A report already on the row (tokens spent on a prior attempt) ships even when over budget —
+ # the idempotency check returns before the gate, so the budget is never consulted.
+ await _set_ai_consent(team, True)
+ sub = await _create_ai_subscription(team, user)
+ delivery = await _create_ai_delivery(sub, report="# Cached")
+
+ with (
+ patch(_IS_OVER_BUDGET, return_value=True) as mock_over_budget,
+ patch(_GENERATE_MARKDOWN) as mock_generate,
+ ):
+ result = await ActivityEnvironment().run(
+ generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
+ )
+
+ assert result.aborted is False and result.skipped is False
+ mock_generate.assert_not_called() # idempotency: no re-bill
+ mock_over_budget.assert_not_called() # gate bypassed entirely on an already-generated report
+
+
+ "usage",
+ [
+ None,
+ {"period": []},
+ {"period": ["2025-01-01T00:00:00Z", None]},
+ {"period": ["2025-01-01T00:00:00Z", "not-a-date"]},
+ ],
+)
+async def test_ai_credit_reset_date_falls_back_on_bad_billing_period(team, user, usage):
+ await _set_org_usage(team, usage)
+ sub = await _create_ai_subscription(team, user)
+
+ reset_date = await sync_to_async(_ai_credit_reset_date)(sub)
+
+ # Bad/missing period → fallback reschedules ~one billing cycle out, not just "some future date".
+ expected = timezone.now() + timedelta(days=_CREDIT_RESET_FALLBACK_DAYS)
+ assert abs((reset_date - expected).total_seconds()) < 60
+
+
+async def test_ai_credit_reset_date_uses_synced_period_end_not_fallback(team, user):
+ # A real synced period ending in 10 days postpones to that cycle end — we wait only until
+ # credits actually reset, never the full 31-day fallback when the true reset is sooner.
+ period_end = timezone.now() + timedelta(days=10)
+ await _set_org_usage(team, {"period": ["2025-01-01T00:00:00Z", period_end.isoformat()]})
+ sub = await _create_ai_subscription(team, user)
+
+ reset_date = await sync_to_async(_ai_credit_reset_date)(sub)
+
+ assert reset_date == period_end
+ assert reset_date < timezone.now() + timedelta(days=_CREDIT_RESET_FALLBACK_DAYS)
+
+
+async def test_ai_credit_reset_date_falls_back_when_period_already_elapsed(team, user):
+ # A rolled-over-but-not-yet-synced period leaves period[1] in the past; promising a reset "on a
+ # past date" would re-fire every tick and email stale dates, so we fall back to ~one cycle out.
+ await _set_org_usage(team, {"period": ["2024-01-01T00:00:00Z", "2024-02-01T00:00:00Z"]})
+ sub = await _create_ai_subscription(team, user)
+
+ reset_date = await sync_to_async(_ai_credit_reset_date)(sub)
+
+ expected = timezone.now() + timedelta(days=_CREDIT_RESET_FALLBACK_DAYS)
+ assert reset_date > timezone.now()
+ assert abs((reset_date - expected).total_seconds()) < 60
+
+
+async def test_skip_helper_reschedules_past_credit_reset_and_emails_owner(team, user):
+ # Far-future period end so the synced-period path is exercised regardless of when this runs.
+ await _set_org_usage(team, {"period": ["2025-01-01T00:00:00Z", "2099-02-01T00:00:00Z"]})
+ sub = await _create_ai_subscription(team, user)
+
+ with patch(_CREDIT_LIMITED_EMAIL) as mock_email:
+ reset_date = await sync_to_async(_skip_ai_delivery_over_credit_limit_sync)(sub)
+
+ assert reset_date == datetime(2099, 2, 1, tzinfo=ZoneInfo("UTC"))
+ await sync_to_async(sub.refresh_from_db)()
+ assert sub.next_delivery_date == datetime(2099, 2, 1, tzinfo=ZoneInfo("UTC"))
+ assert sub.enabled, "an over-limit sub stays enabled — it resumes when credits reset"
+ mock_email.return_value.send.assert_called_once()
+ # campaign_key carries sub id + billing-period date so MessagingRecord dedups to one notice per cycle.
+ campaign_key = mock_email.call_args.kwargs["campaign_key"]
+ assert str(sub.id) in campaign_key
+ assert "2099-02-01" in campaign_key
+
+
+async def test_skip_helper_no_owner_reschedules_without_emailing(team, user):
+ await _set_org_usage(team, {"period": ["2025-01-01T00:00:00Z", "2099-02-01T00:00:00Z"]})
+ sub = await _create_ai_subscription(team, user)
+ sub.created_by = None
+ await sync_to_async(sub.save)(update_fields=["created_by"])
+
+ with patch(_CREDIT_LIMITED_EMAIL) as mock_email:
+ reset_date = await sync_to_async(_skip_ai_delivery_over_credit_limit_sync)(sub)
+
+ assert reset_date == datetime(2099, 2, 1, tzinfo=ZoneInfo("UTC"))
+ await sync_to_async(sub.refresh_from_db)()
+ assert sub.next_delivery_date == datetime(2099, 2, 1, tzinfo=ZoneInfo("UTC"))
+ mock_email.assert_not_called()
+
+
+async def test_skip_helper_no_email_when_creator_left_org(team, user):
+ # The creator was removed from the org after making the sub — don't email a former member their
+ # old org's billing status (it leaks outside the org). Still reschedules; org learns via billing.
+ await _set_org_usage(team, {"period": ["2025-01-01T00:00:00Z", "2099-02-01T00:00:00Z"]})
+ sub = await _create_ai_subscription(team, user)
+ await sync_to_async(OrganizationMembership.objects.filter(organization_id=team.organization_id, user=user).delete)()
+
+ with patch(_CREDIT_LIMITED_EMAIL) as mock_email:
+ reset_date = await sync_to_async(_skip_ai_delivery_over_credit_limit_sync)(sub)
+
+ assert reset_date == datetime(2099, 2, 1, tzinfo=ZoneInfo("UTC"))
+ await sync_to_async(sub.refresh_from_db)()
+ assert sub.next_delivery_date == datetime(2099, 2, 1, tzinfo=ZoneInfo("UTC")), "still reschedules past reset"
+ mock_email.assert_not_called()
+
+
+async def test_skip_helper_falls_back_when_billing_period_unsynced(team, user):
+ # No synced usage → reschedule roughly a cycle out so the sub still moves forward.
+ await _set_org_usage(team, None)
+ sub = await _create_ai_subscription(team, user)
+
+ with patch(_CREDIT_LIMITED_EMAIL) as mock_email:
+ reset_date = await sync_to_async(_skip_ai_delivery_over_credit_limit_sync)(sub)
+
+ assert reset_date > timezone.now()
+ await sync_to_async(sub.refresh_from_db)()
+ assert sub.next_delivery_date is not None and sub.next_delivery_date > timezone.now()
+ # Owner still gets the one-per-cycle notice on the fallback path, keyed on the fallback date.
+ mock_email.return_value.send.assert_called_once()
+ assert reset_date.date().isoformat() in mock_email.call_args.kwargs["campaign_key"]
+
+
+@patch("posthog.slo.events.posthoganalytics")
+@patch("ee.tasks.subscriptions.get_metric_meter")
+@patch(_CREDIT_LIMITED_EMAIL)
+@patch("products.exports.backend.temporal.subscriptions.ai_subscription.activities.send_email_ai_subscription_report")
+@patch(_GENERATE_MARKDOWN)
+@patch(_IS_OVER_BUDGET, return_value=True)
+@freeze_time("2022-02-02T08:55:00.000Z")
+async def test_schedule_ai_subscription_over_credit_budget_lands_skipped(
+ mock_over_budget: MagicMock,
+ mock_generate: MagicMock,
+ mock_send_report: MagicMock,
+ mock_credit_email: MagicMock,
+ mock_metric_meter: MagicMock,
+ mock_analytics: MagicMock,
+ temporal_client: Client,
+ team,
+ user,
+):
+ # End-to-end: an over-budget AI sub lands SKIPPED (not FAILED — it isn't broken) without
+ # spending LLM tokens, and stays enabled so it resumes when credits reset. Proves the
+ # generate-phase skip signal wires through to the workflow's SKIPPED status.
+ await _set_ai_consent(team, True)
+ await _set_org_usage(team, {"period": ["2022-01-01T00:00:00Z", "2099-02-01T00:00:00Z"]})
+ sub = await _create_ai_subscription(team, user)
+ await sync_to_async(Subscription.objects.filter(pk=sub.id).update)(
+ next_delivery_date=datetime(2022, 2, 2, 8, 0, tzinfo=ZoneInfo("UTC"))
+ )
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=settings.TEMPORAL_TASK_QUEUE,
+ workflows=[ScheduleAllSubscriptionsWorkflow, ProcessSubscriptionWorkflow, ProcessAISubscriptionWorkflow],
+ activities=SUBSCRIPTION_SCHEDULE_ACTIVITIES,
+ interceptors=[SloInterceptor()],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ activity_executor=ThreadPoolExecutor(max_workers=50),
+ debug_mode=True,
+ ):
+ await env.client.execute_workflow(
+ ScheduleAllSubscriptionsWorkflow.run,
+ ScheduleAllSubscriptionsWorkflowInputs(),
+ id=str(uuid.uuid4()),
+ task_queue=settings.TEMPORAL_TASK_QUEUE,
+ )
+
+ mock_generate.assert_not_called() # no LLM spend while over budget
+ mock_send_report.assert_not_called() # delivery skipped
+ delivery = await sync_to_async(SubscriptionDelivery.objects.filter(subscription=sub).latest)("created_at")
+ assert delivery.status == SubscriptionDelivery.Status.SKIPPED
+ await sync_to_async(sub.refresh_from_db)()
+ assert sub.enabled is True
+
+
@patch("posthog.slo.events.posthoganalytics")
@patch("ee.tasks.subscriptions.get_metric_meter")
@patch("products.exports.backend.temporal.subscriptions.ai_subscription.activities.send_email_ai_subscription_report")
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
index 5605d5fc23c1..af3a88f7863e 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
@@ -1,14 +1,23 @@
import uuid
+import datetime as dt
+from datetime import datetime
+from django.utils import timezone as tz
+
+import dateutil.parser
import temporalio.activity
+from asgiref.sync import sync_to_async
from structlog import get_logger
from temporalio.exceptions import ApplicationError
+from posthog.models import OrganizationMembership
+from posthog.ph_client import ph_scoped_capture
from posthog.sync import database_sync_to_async
from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery
from products.exports.backend.temporal.subscriptions.ai_subscription.delivery import (
generate_ai_subscription_markdown,
+ send_email_ai_subscription_credit_limited,
send_email_ai_subscription_report,
send_slack_ai_subscription_report,
)
@@ -26,6 +35,7 @@ from products.exports.backend.temporal.subscriptions.types import (
RecipientResult,
)
+from ee.billing.quota_limiting import is_team_over_ai_credit_budget
from ee.tasks.subscriptions import _capture_delivery_failed_event
from ee.tasks.subscriptions.auto_disable import AI_CONSENT_REVOKED_DISABLE_REASON, AI_PROMPT_INVALID_DISABLE_REASON
@@ -37,6 +47,10 @@ LOGGER = get_logger(__name__)
# than on the wire — the same pattern insight snapshots use.
AI_REPORT_SNAPSHOT_KEY = "ai_report"
+# If the org's AI-credit balance isn't synced yet, reschedule roughly a billing cycle out so a
+# skipped sub still moves forward instead of re-firing every tick.
+_CREDIT_RESET_FALLBACK_DAYS = 31
+
async def _load_ai_report(delivery_id: uuid.UUID) -> str | None:
@database_sync_to_async(thread_sensitive=False)
@@ -66,6 +80,86 @@ async def _persist_ai_report(delivery_id: uuid.UUID, markdown: str) -> None:
await _write()
+def _capture_ai_credit_event(
+ subscription: Subscription, event: str, properties: dict[str, object] | None = None
+) -> None:
+ try:
+ distinct_id = (
+ subscription.created_by.distinct_id
+ if subscription.created_by and subscription.created_by.distinct_id
+ else f"team_{subscription.team_id}"
+ )
+ with ph_scoped_capture() as capture:
+ capture(
+ distinct_id=distinct_id,
+ event=event,
+ properties={
+ "subscription_id": subscription.id,
+ "team_id": subscription.team_id,
+ "$process_person_profile": False,
+ **(properties or {}),
+ },
+ groups={"organization": str(subscription.team.organization_id)},
+ )
+ except Exception:
+ LOGGER.warning(f"{event}.capture_failed", subscription_id=subscription.id, exc_info=True)
+
+
+def _ai_credit_reset_date(subscription: Subscription) -> datetime:
+ usage = subscription.team.organization.usage
+ # usage["period"] is [current_period_start, current_period_end] as ISO strings (set in
+ # billing_manager.py); index 1 — the period end — is when AI credits reset. isinstance guard:
+ # a non-dict `usage` would raise AttributeError on .get, which the parse except below misses.
+ period = usage.get("period") if isinstance(usage, dict) else None
+ if period and len(period) == 2 and period[1]:
+ try:
+ reset_date = dateutil.parser.isoparse(period[1])
+ # A rolled-over-but-not-yet-synced period leaves period[1] in the past, which would
+ # resume "on a past date" and re-fire every tick — fall through to the fallback instead.
+ if reset_date > tz.now():
+ return reset_date
+ except (ValueError, TypeError):
+ pass
+ return tz.now() + dt.timedelta(days=_CREDIT_RESET_FALLBACK_DAYS)
+
+
+def _skip_ai_delivery_over_credit_limit_sync(subscription: Subscription) -> datetime:
+ """Reschedule the over-limit subscription past the credit reset and notify the owner once.
+ Runs entirely sync (DB + email) — call via `database_sync_to_async`.
+
+ Persists `next_delivery_date = reset_date` so the always-runs `advance_next_delivery_date`
+ activity recomputes from it (`rrule.after(reset_date)`) — otherwise the next slot could fall
+ before the reset and re-fire while still over-limit.
+ """
+ reset_date = _ai_credit_reset_date(subscription)
+ subscription.next_delivery_date = reset_date
+ subscription.save(update_fields=["next_delivery_date"])
+
+ creator = subscription.created_by
+ # Skip the notice if the creator has left the org: they can no longer act on the credit limit,
+ # and emailing them their former org's billing status leaks it outside the org. The org still
+ # learns it's over budget through the normal billing/quota path.
+ creator_is_org_member = (
+ creator is not None
+ and OrganizationMembership.objects.filter(
+ organization_id=subscription.team.organization_id, user=creator
+ ).exists()
+ )
+ if creator and creator.email and creator_is_org_member:
+ send_email_ai_subscription_credit_limited(
+ email=creator.email,
+ subscription=subscription,
+ resume_date=reset_date,
+ # Stable within a billing period (reset_date is the period end), so MessagingRecord
+ # dedups to one notice per credit-reset cycle.
+ billing_period_key=reset_date.date().isoformat(),
+ )
+ _capture_ai_credit_event(
+ subscription, "ai_subscription_skipped_over_credit_budget", {"resumes_at": reset_date.isoformat()}
+ )
+ return reset_date
+
+
@temporalio.activity.defn
async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> GenerateAIReportResult:
# The "decide what to send" phase, split from delivery so the LLM runs once up front with
@@ -89,6 +183,43 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Gen
aborted = await auto_disable_and_return(subscription, AI_CONSENT_REVOKED_DISABLE_REASON, [])
return GenerateAIReportResult(aborted=True, recipient_results=aborted.recipient_results)
+ # Gate on AI credits before any LLM cost — but only past the idempotency check above, so an
+ # already-generated report (its tokens already spent) still ships. The interactive Max path
+ # enforces this same limit in ee/api/conversation.py; scheduled reports need their own check
+ # or they'd keep spending against an exhausted balance. Fail open: a transient quota-lookup
+ # error shouldn't drop a deliverable report. The check reads Redis (not the DB), so
+ # sync_to_async — but the reschedule below writes the row, so that stays database_sync_to_async.
+ try:
+ over_credit_budget = await sync_to_async(is_team_over_ai_credit_budget, thread_sensitive=False)(
+ subscription.team.api_token
+ )
+ except Exception as exc:
+ over_credit_budget = False
+ LOGGER.warning(
+ "generate_ai_subscription_report.ai_credit_budget_check_failed",
+ subscription_id=subscription.id,
+ error=str(exc),
+ exc_info=True,
+ )
+ # Fail-open is invisible to alerting otherwise — the report ships while billing against a
+ # possibly-exhausted balance, the exact failure mode this gate exists to prevent.
+ await sync_to_async(_capture_ai_credit_event, thread_sensitive=False)(
+ subscription, "ai_subscription_credit_check_failed", {"error": str(exc)}
+ )
+ if over_credit_budget:
+ reset_date = await database_sync_to_async(_skip_ai_delivery_over_credit_limit_sync, thread_sensitive=False)(
+ subscription
+ )
+ LOGGER.warning(
+ "generate_ai_subscription_report.ai_skipped_over_credit_limit",
+ subscription_id=subscription.id,
+ team_id=subscription.team_id,
+ resumes_at=reset_date.isoformat(),
+ )
+ # skipped=True → the workflow records SKIPPED (not FAILED — the sub isn't broken) and skips
+ # delivery; the sub stays enabled and advance_next_delivery_date recomputes from the reset.
+ return GenerateAIReportResult(skipped=True)
+
try:
markdown = await generate_ai_subscription_markdown(subscription)
except PromptRejectedError as exc:
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
index 067812a9d300..5aa6b72edad6 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
@@ -1,4 +1,5 @@
import re
+from datetime import datetime
from urllib.parse import urlparse
import nh3
@@ -208,6 +209,38 @@ def send_email_ai_subscription_report(
message.send(send_async=False)
+def send_email_ai_subscription_credit_limited(
+ *,
+ email: str,
+ subscription: Subscription,
+ resume_date: datetime,
+ billing_period_key: str,
+) -> None:
+ """Notify the owner that a scheduled AI report was skipped for lack of AI credits.
+ `billing_period_key` keys the campaign so MessagingRecord dedups to one notice per
+ credit-reset cycle even if the skip path runs more than once."""
+ utm_tags = f"{UTM_TAGS_BASE}&utm_medium=email"
+ title = subscription.title or "Your PostHog AI report"
+ subscription_url = subscription.url or absolute_uri(
+ f"/project/{subscription.team_id}/subscriptions/{subscription.id}"
+ )
+ billing_url = absolute_uri("/organization/billing")
+
+ message = EmailMessage(
+ campaign_key=f"ai_subscription_credit_limited_{subscription.id}_{billing_period_key}",
+ subject=f"PostHog AI report skipped - {title}",
+ template_name="ai_subscription_credit_limited",
+ template_context={
+ "title": title,
+ "resume_date": resume_date,
+ "subscription_url": f"{subscription_url}?{utm_tags}",
+ "billing_url": f"{billing_url}?{utm_tags}",
+ },
+ )
+ message.add_recipient(email=email)
+ message.send(send_async=False)
+
+
def _build_ai_slack_message(subscription: Subscription, markdown: str) -> SlackMessageData:
utm_tags = f"{UTM_TAGS_BASE}&utm_medium=slack"
channel = subscription.target_value.split("|")[0]
diff --git a/products/exports/backend/temporal/subscriptions/snapshot_activities.py b/products/exports/backend/temporal/subscriptions/snapshot_activities.py
index bfb37767db0c..cad00cf9af4b 100644
--- a/products/exports/backend/temporal/subscriptions/snapshot_activities.py
+++ b/products/exports/backend/temporal/subscriptions/snapshot_activities.py
@@ -22,7 +22,7 @@ from products.exports.backend.temporal.subscriptions.types import SnapshotInsigh
from products.posthog_ai.backend.models.assistant import CoreMemory
from products.product_analytics.backend.models.insight import Insight
-from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited
+from ee.billing.quota_limiting import is_team_over_ai_credit_budget
LOGGER = get_logger(__name__)
@@ -443,8 +443,8 @@ async def _run_snapshot_subscription_insights(inputs: SnapshotInsightsInputs) ->
# 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
+ is_over_credit_budget = await sync_to_async(is_team_over_ai_credit_budget, thread_sensitive=False)(
+ subscription.team.api_token
)
except Exception as e:
is_over_credit_budget = False
diff --git a/products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.py b/products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.py
index 548b6f0395b0..a1d1f431e2e9 100644
--- a/products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.py
+++ b/products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.py
@@ -145,7 +145,7 @@ def _raise_quota_lookup_error(*args, **kwargs):
@pytest.mark.parametrize(
- "name,is_team_limited_impl,expect_summary_generated,expect_skipped_over_budget",
+ "name,is_over_budget_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.
@@ -157,7 +157,7 @@ def _raise_quota_lookup_error(*args, **kwargs):
],
)
async def test_summary_generation_respects_ai_credit_budget(
- team, user, monkeypatch, name, is_team_limited_impl, expect_summary_generated, expect_skipped_over_budget
+ team, user, monkeypatch, name, is_over_budget_impl, expect_summary_generated, expect_skipped_over_budget
):
subscription = await _create_subscription(team, user)
await _set_ai_consent(subscription, approved=True)
@@ -182,8 +182,8 @@ async def test_summary_generation_respects_ai_credit_budget(
return summary_text
monkeypatch.setattr(
- "products.exports.backend.temporal.subscriptions.snapshot_activities.is_team_limited",
- is_team_limited_impl,
+ "products.exports.backend.temporal.subscriptions.snapshot_activities.is_team_over_ai_credit_budget",
+ is_over_budget_impl,
)
monkeypatch.setattr(
"products.exports.backend.temporal.subscriptions.snapshot_activities.generate_change_summary",
diff --git a/products/exports/backend/temporal/subscriptions/types.py b/products/exports/backend/temporal/subscriptions/types.py
index 62b1af2f3834..703fe038327e 100644
--- a/products/exports/backend/temporal/subscriptions/types.py
+++ b/products/exports/backend/temporal/subscriptions/types.py
@@ -164,9 +164,13 @@ class GenerateAIReportInputs:
class GenerateAIReportResult:
"""Outcome of the generation phase. `aborted` signals a terminal pre-delivery
failure (consent revoked, prompt invalid) that already auto-disabled the
- subscription; the workflow records `recipient_results` as FAILED and skips delivery."""
+ subscription; the workflow records `recipient_results` as FAILED and skips delivery.
+ `skipped` signals an over-AI-credit-budget skip: generation rescheduled the sub past
+ the credit reset and notified the owner — the workflow records SKIPPED (not FAILED,
+ the sub isn't broken) and skips delivery."""
aborted: bool = False
+ skipped: bool = False
recipient_results: list[RecipientResult] = dataclasses.field(default_factory=list)
diff --git a/products/exports/backend/temporal/subscriptions/workflows.py b/products/exports/backend/temporal/subscriptions/workflows.py
index e46fa6af480e..c0db06c39e7b 100644
--- a/products/exports/backend/temporal/subscriptions/workflows.py
+++ b/products/exports/backend/temporal/subscriptions/workflows.py
@@ -503,6 +503,13 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):
final_status = DeliveryStatus.FAILED
return
+ if generate_result.skipped:
+ # Over AI-credit budget — generation rescheduled the sub past the credit reset and
+ # notified the owner. SKIPPED (not FAILED): the sub isn't broken, it resumes when
+ # credits reset; advance_next_delivery_date (finally) recomputes from the reschedule.
+ final_status = DeliveryStatus.SKIPPED
+ return
+
# Phase 2: ship the persisted report. is_new only for target-change triggers.
is_new = inputs.trigger_type == SubscriptionTriggerType.TARGET_CHANGE
deliver_result = await temporalio.workflow.execute_activity(