: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(billing): write billing activity messages to the activity log (#68513)
Yasen03f25cc2aee5
diff --git a/ee/billing/queue/BillingConsumer.py b/ee/billing/queue/BillingConsumer.pyindex 97d679eaaec0..d063679b90fd 100644--- a/ee/billing/queue/BillingConsumer.py+++ b/ee/billing/queue/BillingConsumer.py@@ -7,7 +7,9 @@ from django.db import close_old_connectionsfrom posthog.cloud_utils import get_cached_instance_licensefrom posthog.exceptions_capture import capture_exception+from posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.organization import Organization+from posthog.models.user import Userfrom products.customer_analytics.backend.facade.api import notify_managers_of_usage_spike@@ -52,6 +54,8 @@ class BillingConsumer(SQSConsumer):self._process_billing_customer_update(body)elif message_type == "usage_spike_detected":self._process_usage_spike_detected(body)+ elif message_type == "billing_activity":+ self._process_billing_activity(body)# Add more message types as needed# elif message_type == "invoice_created":# self._process_invoice_created(body)@@ -174,3 +178,88 @@ class BillingConsumer(SQSConsumer):stripe_customer_id=data.get("stripe_customer_id"),detected_at=data.get("detected_at"),)++ def _process_billing_activity(self, body: dict[str, Any]) -> None:+ """+ Write a billing-originated change (spend limits, addons/products) to the+ organization's activity log.++ The actor is resolved from the distinct_id the billing service carries in+ the message; when it is absent (system-origin changes such as Stripe+ webhooks or dunning) the row is written as a system activity.+ """+ organization_id = body.get("organization_id")+ if not organization_id:+ logger.error("Billing activity is missing organization_id")+ capture_exception(Exception("Billing activity is missing organization_id"))+ return++ try:+ organization = Organization.objects.get(id=organization_id)+ except Organization.DoesNotExist:+ logger.exception(f"Organization {organization_id} does not exist")+ capture_exception(+ Exception("Organization being consumed does not exist"),+ {"organization_id": organization_id},+ )+ return++ distinct_id = body.get("distinct_id")+ # Constrain the actor to a member of this organization: distinct_id is globally+ # unique, so an unconstrained lookup could attribute the change to (and expose in+ # the org's audit log) a user from a different organization.+ user = (+ User.objects.filter(+ distinct_id=distinct_id,+ organization_membership__organization=organization,+ ).first()+ if distinct_id+ else None+ )+ if distinct_id and user is None:+ logger.warning(+ "billing_activity.distinct_id_not_found",+ extra={"distinct_id": distinct_id, "organization_id": organization_id},+ )++ detail_data = body.get("detail") or {}+ changes = [+ Change(+ type=change.get("type", "Billing"),+ action=change.get("action", "changed"),+ field=change.get("field"),+ before=change.get("before"),+ after=change.get("after"),+ )+ for change in (detail_data.get("changes") or [])+ ]++ activity = body.get("activity") or "updated"++ # An "updated" activity with no changes is a no-op that log_activity intentionally+ # drops. Retrying can never make changes appear, so ack the message instead of+ # treating the None return below as a transient failure and looping forever.+ if activity == "updated" and not changes:+ logger.warning(+ "billing_activity.no_changes_to_log",+ extra={"organization_id": organization_id},+ )+ return++ written = log_activity(+ organization_id=organization.id,+ team_id=None,+ user=user,+ was_impersonated=False,+ item_id=body.get("item_id") or str(organization.id),+ scope="Billing",+ activity=activity,+ detail=Detail(name=detail_data.get("name"), changes=changes),+ )++ # This SQS message exists only to create the audit row. log_activity swallows write+ # errors and returns None in production, so a None here means the write failed: raise+ # so process_message leaves the message on the queue for SQS to redeliver rather than+ # deleting it and silently dropping the audit entry.+ if written is None:+ raise Exception("Failed to write billing activity to the activity log")diff --git a/ee/billing/test/test_billing_consumer.py b/ee/billing/test/test_billing_consumer.pyindex 56da4b384189..307e6a8aecc4 100644--- a/ee/billing/test/test_billing_consumer.py+++ b/ee/billing/test/test_billing_consumer.py@@ -1,6 +1,9 @@from posthog.test.base import BaseTestfrom unittest.mock import patch+from posthog.models import Organization, User+from posthog.models.activity_logging.activity_log import ActivityLog+from ee.billing.queue.BillingConsumer import POSTHOG_SELF_TEAM_ID, BillingConsumerCONSUMER = "ee.billing.queue.BillingConsumer"@@ -40,3 +43,91 @@ class TestBillingConsumerUsageSpike(BaseTest):self._build_consumer()._process_usage_spike_detected({"data": {"organization_id": "org-1"}})mock_notify.assert_not_called()mock_capture.assert_called_once()+++class TestBillingConsumerBillingActivity(BaseTest):+ def _build_consumer(self) -> BillingConsumer:+ with patch("ee.sqs.SQSConsumer.boto3"):+ return BillingConsumer(queue_url="http://example/queue", region_name="us-east-1")++ def _message(self, **overrides):+ message = {+ "type": "billing_activity",+ "organization_id": str(self.organization.id),+ "distinct_id": self.user.distinct_id,+ "activity": "updated",+ "item_id": str(self.organization.id),+ "detail": {+ "name": "Billing spend limits",+ "changes": [+ {+ "type": "Billing",+ "action": "changed",+ "field": "product_analytics",+ "before": None,+ "after": 1000,+ }+ ],+ },+ "event_id": "evt-1",+ }+ message.update(overrides)+ return message++ def test_writes_org_scoped_activity_log_attributed_to_actor(self):+ self._build_consumer()._process_billing_activity(self._message())++ log = ActivityLog.objects.get(scope="Billing")+ assert log.organization_id == self.organization.id+ assert log.team_id is None+ assert log.user_id == self.user.id+ assert log.is_system is False+ assert log.item_id == str(self.organization.id)+ assert log.activity == "updated"+ assert log.detail is not None+ assert log.detail["changes"][0]["field"] == "product_analytics"+ assert log.detail["changes"][0]["after"] == 1000++ def test_writes_system_activity_when_distinct_id_absent(self):+ # System-origin changes (Stripe webhooks, dunning) carry no actor.+ self._build_consumer()._process_billing_activity(self._message(distinct_id=None))++ log = ActivityLog.objects.get(scope="Billing")+ assert log.user_id is None+ assert log.is_system is True++ def test_does_not_attribute_distinct_id_from_another_organization(self):+ # distinct_id is globally unique; a user outside this org must never be+ # attributed to (or exposed in) this org's audit log.+ other_org = Organization.objects.create(name="Other org")+ other_user = User.objects.create_and_join(other_org, "[email protected]", None)++ self._build_consumer()._process_billing_activity(self._message(distinct_id=other_user.distinct_id))++ log = ActivityLog.objects.get(scope="Billing")+ assert log.user_id is None+ assert log.is_system is True++ @patch(f"{CONSUMER}.capture_exception")+ def test_missing_organization_id_skips_and_captures(self, mock_capture):+ self._build_consumer()._process_billing_activity(self._message(organization_id=None))++ assert not ActivityLog.objects.filter(scope="Billing").exists()+ mock_capture.assert_called_once()++ def test_acks_updated_activity_with_no_changes(self):+ # An "updated" message with nothing to record must be acked (no write, no raise) so it+ # is not retried forever; otherwise the raise-on-failure path below would loop on it.+ message = self._message()+ message["detail"] = {"name": "Billing spend limits", "changes": []}++ self._build_consumer()._process_billing_activity(message)++ assert not ActivityLog.objects.filter(scope="Billing").exists()++ @patch(f"{CONSUMER}.log_activity", return_value=None)+ def test_raises_when_write_fails_so_message_is_retried(self, _mock_log_activity):+ # log_activity returns None on write failure in production; the consumer must raise so+ # process_message leaves the message for SQS to redeliver instead of dropping the audit.+ with self.assertRaises(Exception):+ self._build_consumer()._process_billing_activity(self._message())