: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
fix(activity-log): stop dropping deferred audit log rows (#117038)
Yasenef4da97f05b6
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.mdindex 8494a405b472..3cc51a83093e 100644--- a/docs/internal/activity-logging.md+++ b/docs/internal/activity-logging.md@@ -53,6 +53,7 @@ model.save()The actor is not passed down this chain.`ActivityLoggingMiddleware` (`posthog/middleware.py`) stores the request user and the impersonation flag in a thread-local (`activity_storage`), and the mixin reads them back.Outside a request the user is `None`, and the row is stored with `is_system=True`.+A deferred insert runs after the commit. If the transaction deleted the acting user, for example when users delete their own account, the row is stored with `user=None` and `is_system=False`.The receiver is the only part a product writes.The mixin, the signal, and `log_activity` are core, and they work the same for every model.@@ -127,6 +128,10 @@ Four registries in `activity_log.py` tune it per scope:Exclude relations that hold execution results or storage bookkeeping, such as a notebook's widget snapshots.Reading their fail-closed managers can require team context that background writes do not have.+A relation field stores the related object as `{"id": <pk>}`.+To store more, such as a name for the describer to show, add a branch for the model to `ActivityDetailEncoder` in `posthog/models/utils.py`.+Never put a credential field in that branch.+Destination activity logs record changes to `mappings` without their values.For `inputs` they keep each key and record only whether its value changed, so the history can name the changed input.Rows written before a field joined `field_with_masked_contents` still store its values.diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 0b4b2f338ace..fecf916fed07 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -1,15 +1,17 @@import jsonimport dataclasses+from collections.abc import Callablefrom typing import TYPE_CHECKING, Any, Literal, Optional, Required, TypedDict, Union, castfrom uuid import UUIDfrom django.conf import settings+from django.contrib.auth import get_user_modelfrom django.contrib.auth.models import AnonymousUserfrom django.contrib.contenttypes.fields import GenericRelationfrom django.contrib.postgres.indexes import GinIndexfrom django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExistfrom django.core.paginator import EmptyPage, Paginator-from django.db import models, transaction+from django.db import models, router, transactionfrom django.db.models import QuerySetfrom django.db.models.signals import post_savefrom django.dispatch.dispatcher import receiver@@ -1323,7 +1325,26 @@ def _report_activity_log_write_failure(e: Exception, error_context: dict, deferrACTIVITY_LOG_WRITE_FAILURES.labels(deferred=str(deferred).lower()).inc()-def _handle_activity_log_transaction(create_fn, error_context: dict, *, using: str | None = None, strict: bool = False):+def _deleted_user_ids(user_ids: set[int]) -> set[int]:+ if not user_ids:+ return set()+ user_model = get_user_model()+ # The insert checks the foreign key on the writer. A lagging replica can miss a user that the+ # committed transaction created, or still hold one that it deleted.+ existing = user_model.objects.using(router.db_for_write(user_model)).filter(pk__in=user_ids)+ return user_ids - set(existing.values_list("pk", flat=True))+++def _handle_activity_log_transaction(+ create_fn: Callable[[bool], Any], error_context: dict, *, using: str | None = None, strict: bool = False+):+ """Call `create_fn(deferred)`.++ A deferred write runs after the commit, so the transaction can delete the acting user first.+ A user who deletes their own account is the actor of the rows that the cascade logs.+ `on_delete=SET_NULL` covers only rows that exist. When `deferred` is true, `create_fn` must+ unset a deleted user, or the insert breaks the foreign key.+ """try:# Check if we're in a transaction, if yes, defer the activity log creation to the commit signalif (@@ -1335,7 +1356,7 @@ def _handle_activity_log_transaction(create_fn, error_context: dict, *, using: s# keeps a slow audit write from failing a request whose data is already durable.def _deferred_create():try:- create_fn()+ create_fn(True)except Exception as e:_report_activity_log_write_failure(e, error_context, deferred=True)if settings.TEST:@@ -1344,7 +1365,7 @@ def _handle_activity_log_transaction(create_fn, error_context: dict, *, using: stransaction.on_commit(_deferred_create, using=using)return Noneelse:- return create_fn()+ return create_fn(False)except Exception as e:if strict:@@ -1457,7 +1478,12 @@ def log_activity("impersonated_by_id": credential.impersonated_by_id if credential else None,}- def _do_log_activity():+ # Read the id now. When the transaction deletes this same instance, `delete()` sets its pk to None.+ user_id = user.pk if user is not None else None++ def _do_log_activity(deferred: bool) -> ActivityLog:+ if deferred and user_id is not None and _deleted_user_ids({user_id}):+ return ActivityLog.objects.create(**{**fields, "user": None})return ActivityLog.objects.create(**fields)if instance_only:@@ -1578,7 +1604,13 @@ def bulk_log_activity(if not activity_logs:return []- def _do_bulk_create():+ def _do_bulk_create(deferred: bool) -> list[ActivityLog]:+ if deferred:+ deleted_user_ids = _deleted_user_ids({log.user_id for log in activity_logs if log.user_id is not None})+ for log in activity_logs:+ if log.user_id in deleted_user_ids:+ log.user = None+created_logs = ActivityLog.objects.bulk_create(activity_logs, batch_size=batch_size)if notify:diff --git a/posthog/models/test/test_activity_logging.py b/posthog/models/test/test_activity_logging.pyindex f6f6cc559caa..7060cf994a1b 100644--- a/posthog/models/test/test_activity_logging.py+++ b/posthog/models/test/test_activity_logging.py@@ -1,14 +1,45 @@-from typing import cast+import json+from typing import Any, cast+from uuid import UUID+from django.db import modelsfrom django.test import SimpleTestCase+from parameterized import parameterized++from posthog.models import DataColorTheme, Organization, Userfrom posthog.models.activity_logging.activity_log import AuditableScope, Change, describe_change, dict_changes_between+from posthog.models.utils import ActivityDetailEncoderfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTileclass TeatActivityLog(SimpleTestCase):+ @parameterized.expand(+ [+ ("model_without_a_branch", DataColorTheme(id=7), {"id": 7}),+ (+ "uuid_primary_key",+ Organization(id=UUID("01890000-0000-0000-0000-000000000001")),+ {"id": "01890000-0000-0000-0000-000000000001"},+ ),+ (+ "model_with_a_branch",+ User(id=3, first_name="Ada", email="[email protected]"),+ {"first_name": "Ada", "email": "[email protected]"},+ ),+ ]+ )+ def test_encoder_serializes_related_model_instances(+ self, _name: str, instance: models.Model, expected: Any+ ) -> None:+ change = Change(type="Dashboard", field="related", action="changed", before=None, after=instance)++ encoded = json.loads(json.dumps(change, cls=ActivityDetailEncoder))++ assert encoded["after"] == expected+def test_dict_changes_between(self):changes = dict_changes_between(model_type="Plugin",diff --git a/posthog/models/utils.py b/posthog/models/utils.pyindex eba85999c983..3ab832c353fa 100644--- a/posthog/models/utils.py+++ b/posthog/models/utils.py@@ -575,4 +575,10 @@ class ActivityDetailEncoder(json.JSONEncoder):"model": obj.model,"provider_key_id": str(obj.provider_key_id) if obj.provider_key_id else None,}+ if isinstance(obj, models.Model):+ # `changes_between` puts the related instance of a relation field into the change.+ # Without this fallback each model with no branch above makes the write raise, and the+ # deferred writer drops the row. The id identifies the instance and copies none of its+ # fields, which can hold credentials.+ return {"id": obj.pk}return json.JSONEncoder.default(self, obj)diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.pyindex 809b7e87d063..1ed4071c9a23 100644--- a/posthog/test/activity_logging/test_activity_logging.py+++ b/posthog/test/activity_logging/test_activity_logging.py@@ -10,6 +10,7 @@ import pytestfrom posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import patch+from django.conf import settingsfrom django.db import transactionfrom django.db.utils import IntegrityErrorfrom django.http import HttpRequest@@ -39,6 +40,7 @@ from posthog.models.activity_logging.activity_log import (ActivityLog,Change,Detail,+ LogActivityEntry,Trigger,bulk_log_activity,log_activity,@@ -62,6 +64,13 @@ from products.dashboards.backend.models.dashboard_widget import DashboardWidgetfrom products.exports.backend.models.exported_asset import ExportedAsset+class _UserReadsFromReplicaRouter:+ """Sends user reads to an alias that does not exist, which fails any read that is not pinned to the writer."""++ def db_for_read(self, model: type, **hints: Any) -> str | None:+ return "unavailable_replica" if model is User else None++class TestActivityLogModel(BaseTest):def test_can_save_a_model_changed_activity_log(self) -> None:change = Change(@@ -457,6 +466,49 @@ class TestActivityLogModel(BaseTest):self.assertEqual(warning.args[0], "activity_log.failed_to_write_to_activity_log")self.assertIsInstance(warning.kwargs["exception"], IntegrityError)+ @parameterized.expand(+ [+ ("single_live_user", "single", None),+ ("single_same_instance_deleted", "single", "same"),+ ("single_other_instance_deleted", "single", "other"),+ ("bulk_live_user", "bulk", None),+ ("bulk_same_instance_deleted", "bulk", "same"),+ ("bulk_other_instance_deleted", "bulk", "other"),+ ]+ )+ def test_deferred_write_keeps_only_a_user_that_still_exists(+ self, _name: str, path: str, deleted_instance: str | None+ ) -> None:+ user = User.objects.create_and_join(self.organization, "[email protected]", None)+ user_id = user.pk+ entry: LogActivityEntry = {+ "organization_id": self.organization.id,+ "team_id": self.team.id,+ "user": user,+ "was_impersonated": False,+ "item_id": "12345",+ "scope": "PersonalAPIKey",+ "activity": "deleted",+ "detail": Detail(),+ }++ with self.settings(ACTIVITY_LOG_TRANSACTION_MANAGEMENT=True):+ with self.captureOnCommitCallbacks() as callbacks:+ if path == "single":+ log_activity(**entry)+ else:+ bulk_log_activity([entry])+ if deleted_instance is not None:+ (user if deleted_instance == "same" else User.objects.get(pk=user_id)).delete()++ with self.settings(DATABASE_ROUTERS=[_UserReadsFromReplicaRouter(), *settings.DATABASE_ROUTERS]):+ for callback in callbacks:+ callback()++ row = ActivityLog.objects.get(team_id=self.team.id, scope="PersonalAPIKey", item_id="12345")+ expected_user_id = None if deleted_instance is not None else user_id+ assert (row.user_id, row.is_system) == (expected_user_id, False)+def test_strict_write_failure_escapes_active_transaction(self) -> None:with self.settings(TEST=False, ACTIVITY_LOG_TRANSACTION_MANAGEMENT=True):with patch.object(ActivityLog.objects, "create", side_effect=IntegrityError("write timed out")):