: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): add request analytics context to subscription saves (#66192)
Matt Puadee710a5fd16
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex 6625ff3eadd6..cb7faf2a2eea 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -32,7 +32,7 @@ from posthog.constants import (SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY,SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY,)-from posthog.event_usage import groups+from posthog.event_usage import get_request_analytics_properties, groupsfrom posthog.exceptions import QuotaLimitExceededfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import Integration@@ -43,7 +43,12 @@ from posthog.slo.types import SloArea, SloOperationfrom posthog.temporal.common.client import sync_connectfrom posthog.utils import str_to_bool-from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery, unsubscribe_using_token+from products.exports.backend.models.subscription import (+ Subscription,+ SubscriptionDelivery,+ attribute_subscription_saves,+ unsubscribe_using_token,+)from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (PROMPT_MAX_LENGTH as AI_PROMPT_MAX_LENGTH,PromptRejectedError,@@ -605,7 +610,8 @@ class SubscriptionSerializer(serializers.ModelSerializer):invite_message = validated_data.pop("invite_message", "")dashboard_export_insight_ids = validated_data.pop("dashboard_export_insights", [])- instance: Subscription = super().create(validated_data)+ with attribute_subscription_saves(get_request_analytics_properties(request)):+ instance: Subscription = super().create(validated_data)# Bust the org-wide active-summary count cache so the next quota# fetch reflects this row, regardless of summary_enabled — over-busting@@ -675,6 +681,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):is_delete = not instance.deleted and validated_data.get("deleted") is Trueinvite_message = validated_data.pop("invite_message", "")dashboard_export_insight_ids = validated_data.pop("dashboard_export_insights", [])+ analytics_props = get_request_analytics_properties(request)if is_delete:with slo_operation(@@ -692,11 +699,13 @@ class SubscriptionSerializer(serializers.ModelSerializer):"resource_type": instance.resource_type,},):- instance = super().update(instance, validated_data)+ with attribute_subscription_saves(analytics_props):+ instance = super().update(instance, validated_data)_invalidate_summary_quota_cache(instance.team.organization_id)return instance- instance = super().update(instance, validated_data)+ with attribute_subscription_saves(analytics_props):+ instance = super().update(instance, validated_data)_invalidate_summary_quota_cache(instance.team.organization_id)if dashboard_export_insight_ids:@@ -1001,6 +1010,7 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mdistinct_id=str(request.user.distinct_id),event="subscription_test_delivery_scheduled",properties={+ **get_request_analytics_properties(request),"subscription_id": subscription.id,"team_id": subscription.team_id,"target_type": subscription.target_type,diff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.pyindex 8cca604ca861..2adbad939c34 100644--- a/products/exports/backend/models/subscription.py+++ b/products/exports/backend/models/subscription.py@@ -1,4 +1,7 @@import sys+from collections.abc import Iterator+from contextlib import contextmanager+from contextvars import ContextVarfrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, Literal, Optional, cast@@ -21,6 +24,7 @@ from posthog.models.utils import UUIDModelfrom posthog.utils import absolute_uriif TYPE_CHECKING:+ from posthog.event_usage import AnalyticsPropsfrom posthog.models.organization import Organization# Resolved lazily via __getattr__ below; declared here so consumers type-check as int.@@ -28,6 +32,23 @@ if TYPE_CHECKING:UNSUBSCRIBE_TOKEN_EXP_DAYS = 30+# Carries request-derived analytics props (source, referer, ...) into the post_save signal,+# which has no request context. Set by the API layer around request-originated saves so the+# canonical "<kind> subscription created/updated" events get source attribution; stays None+# for system saves (Temporal, management commands), which then report without a source.+subscription_request_analytics_props: ContextVar[Optional["AnalyticsProps"]] = ContextVar(+ "subscription_request_analytics_props", default=None+)+++@contextmanager+def attribute_subscription_saves(analytics_props: "AnalyticsProps") -> Iterator[None]:+ token = subscription_request_analytics_props.set(analytics_props)+ try:+ yield+ finally:+ subscription_request_analytics_props.reset(token)+# Single source of truth shared with the frontend create gate via generated schema# (SubscriptionFreeTierLimit.COUNT). Resolved lazily via PEP 562 so posthog.schema (the@@ -391,9 +412,21 @@ class Subscription(ModelActivityMixin, models.Model):def subscription_saved(sender, instance, created, raw, using, **kwargs):from posthog.event_usage import report_user_action+ # Partial-field saves are internal bookkeeping (e.g. next_delivery_date rescheduling), not a+ # user create/update — a real API save writes the whole row. Skip them so re-enabling or the+ # scheduler doesn't emit a second "<kind> subscription updated" event.+ if kwargs.get("update_fields"):+ return+if instance.created_by and instance.resource_info:event_name: str = f"{instance.resource_info.kind.lower()} subscription {'created' if created else 'updated'}"- report_user_action(instance.created_by, event_name, instance.get_analytics_metadata())+ report_user_action(+ instance.created_by,+ event_name,+ instance.get_analytics_metadata(),+ team=instance.team,+ analytics_props=subscription_request_analytics_props.get(),+ )@mutable_receiver(model_activity_signal, sender=Subscription)