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.

fix(activity-logs): keep internal activity events under the kafka limit (#111955)

posthog[bot]17f5fe5e6086
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index edc8d16bf26c..d4840d6e8b73 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -32,6 +32,11 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
+# Kafka rejects messages above `message.max.bytes` (1 MB by default), so leave room for the event envelope.
+MAX_INTERNAL_EVENT_DETAIL_BYTES = 512 * 1024
+_SUMMARY_DETAIL_KEYS = ("id", "short_id", "type", "name")
+_MAX_SUMMARY_NAME_LENGTH = 1000
+
ACTIVITY_LOG_WRITE_FAILURES = Counter(
"activity_log_write_failures_total",
"Activity log rows that failed to write",
@@ -972,6 +977,13 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"custom_oauth2_integrations",
# Same hazard: the destination set is edited through its own endpoint, not by saving a source.
"destination_links",
+ # The diff reads each reverse relation in full on both sides, after the save, so it never
+ # sees a real before-state. The view prefetches `schemas` without the deleted ones, so the
+ # two lists differ on every save and the entry stores every job and schema twice, which
+ # goes past the Kafka message limit for a source with a long sync history. Schemas log
+ # their own changes under the ExternalDataSchema scope, and jobs are sync runs, not user changes.
+ "jobs",
+ "schemas",
],
"ExternalDataSchema": [
"status",
@@ -1583,6 +1595,38 @@ def load_all_activity(scope_list: list[ActivityScope], team_id: int, limit: int
return get_activity_page(activity_query, limit, page)
+def _json_size(value: Any) -> int:
+ return len(json.dumps(value).encode("utf-8"))
+
+
+def bound_detail_for_internal_event(detail: Any) -> tuple[Any, bool]:
+ """Shrink an activity detail so the internal event stays under the Kafka message limit.
+
+ Returns the detail to send and a flag that tells if it was truncated.
+ """
+ if _json_size(detail) <= MAX_INTERNAL_EVENT_DETAIL_BYTES:
+ return detail, False
+ if not isinstance(detail, dict):
+ return None, True
+
+ # First drop the change values and the free-form fields, but keep which fields changed.
+ bounded: dict[str, Any] = {key: detail.get(key) for key in _SUMMARY_DETAIL_KEYS if key in detail}
+ bounded["changes"] = [
+ {key: change.get(key) for key in ("type", "action", "field")}
+ for change in detail.get("changes") or []
+ if isinstance(change, dict)
+ ]
+ if _json_size(bounded) <= MAX_INTERNAL_EVENT_DETAIL_BYTES:
+ return bounded, True
+
+ summary: dict[str, Any] = {key: detail.get(key) for key in _SUMMARY_DETAIL_KEYS if key in detail}
+ if isinstance(summary.get("name"), str):
+ summary["name"] = summary["name"][:_MAX_SUMMARY_NAME_LENGTH]
+ if _json_size(summary) <= MAX_INTERNAL_EVENT_DETAIL_BYTES:
+ return summary, True
+ return None, True
+
+
@receiver(post_save, sender=ActivityLog)
def activity_log_created(sender, instance: "ActivityLog", created, **kwargs):
from posthog.api.advanced_activity_logs import ActivityLogSerializer
@@ -1607,6 +1651,9 @@ def activity_log_created(sender, instance: "ActivityLog", created, **kwargs):
serialized_data = ActivityLogSerializer(instance).data
# We need to serialize the detail object using the encoder to avoid unsupported types like timedelta
serialized_data["detail"] = json.loads(json.dumps(serialized_data["detail"], cls=ActivityDetailEncoder))
+ serialized_data["detail"], detail_truncated = bound_detail_for_internal_event(serialized_data["detail"])
+ if detail_truncated:
+ serialized_data["detail_truncated"] = True
# TODO: Move this into the producer to support dataclasses
user_data = UserBasicSerializer(instance.user).data if instance.user else None
@@ -1637,6 +1684,15 @@ def activity_log_created(sender, instance: "ActivityLog", created, **kwargs):
)
except Exception as e:
# We don't want to hard fail here.
- logger.exception("Failed to produce internal event", data=serialized_data, error=e)
+ # Identify the entry by ids only: the detail can carry person data and runs to megabytes.
+ logger.exception(
+ "Failed to produce internal event",
+ activity_log_id=str(instance.id),
+ scope=instance.scope,
+ activity=instance.activity,
+ team_id=instance.team_id,
+ organization_id=instance.organization_id,
+ error=e,
+ )
capture_exception(e)
return
diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.py
index 57a423a45c9a..8e74f4d207d0 100644
--- a/posthog/test/activity_logging/test_activity_logging.py
+++ b/posthog/test/activity_logging/test_activity_logging.py
@@ -1,7 +1,9 @@
import hmac
+import json
import time
import hashlib
from datetime import timedelta
+from typing import Any
from uuid import UUID
import pytest
@@ -105,6 +107,38 @@ class TestActivityLogModel(BaseTest):
log: ActivityLog = ActivityLog.objects.latest("id")
self.assertEqual(log.activity, "added_to_clink_expander")
+ @parameterized.expand(
+ [
+ ("small_detail_is_sent_unchanged", "x" * 100, False),
+ ("oversized_detail_drops_change_values", "x" * (2 * 1024 * 1024), True),
+ ]
+ )
+ def test_internal_event_detail_stays_under_kafka_limit(self, _name: str, after: str, truncated: bool) -> None:
+ change = Change(type="FeatureFlag", field="filters", action="changed", before=None, after=after)
+ with (
+ patch("posthog.cdp.internal_events.produce_internal_event") as mock_produce,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=6,
+ scope="FeatureFlag",
+ activity="updated",
+ detail=Detail(name="my flag", changes=[change]),
+ )
+
+ properties = mock_produce.call_args.kwargs["event"].properties
+ assert len(json.dumps(properties).encode("utf-8")) < 1024 * 1024
+ assert properties["detail"]["name"] == "my flag"
+ assert properties.get("detail_truncated", False) is truncated
+ expected_change: dict[str, Any] = {"type": "FeatureFlag", "action": "changed", "field": "filters"}
+ if not truncated:
+ expected_change.update(before=None, after=after)
+ assert properties["detail"]["changes"] == [expected_change]
+
def test_client_is_populated_from_activity_storage(self) -> None:
activity_storage.set_client("posthog-js/1.234.0")
try:
diff --git a/posthog/test/activity_logging/test_external_data_source_activity_logging.py b/posthog/test/activity_logging/test_external_data_source_activity_logging.py
index 0d77a5dc11de..21204dfba6c3 100644
--- a/posthog/test/activity_logging/test_external_data_source_activity_logging.py
+++ b/posthog/test/activity_logging/test_external_data_source_activity_logging.py
@@ -1,6 +1,8 @@
+from django.db.models import Prefetch
+
from posthog.test.activity_log_utils import ActivityLogTestHelper
-from products.warehouse_sources.backend.facade.models import ExternalDataSource
+from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource
class TestExternalDataSourceActivityLogging(ActivityLogTestHelper):
@@ -65,3 +67,23 @@ class TestExternalDataSourceActivityLogging(ActivityLogTestHelper):
self.assertIsNotNone(deleted_change)
assert deleted_change is not None
self.assertEqual(deleted_change["after"], True)
+
+ def test_saving_a_source_does_not_diff_its_jobs_or_schemas(self):
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_id="source", connection_id="connection", status="Completed", source_type="Stripe"
+ )
+ ExternalDataSchema.objects.create(team=self.team, source=source, name="Customer", deleted=True)
+ ExternalDataJob.objects.create(team=self.team, pipeline=source, status="Completed", rows_synced=0)
+ request_copy = (
+ ExternalDataSource.objects.filter(pk=source.pk)
+ .prefetch_related("jobs", Prefetch("schemas", queryset=ExternalDataSchema.objects.exclude(deleted=True)))
+ .get()
+ )
+ ExternalDataJob.objects.create(team=self.team, pipeline=source, status="Running", rows_synced=0)
+ self.clear_activity_logs()
+
+ request_copy.status = "Running"
+ request_copy.save()
+
+ [log_entry] = self.get_activity_logs_for_item("ExternalDataSource", str(source.id))
+ assert [change["field"] for change in log_entry.detail["changes"]] == ["status"]