: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): guard deferred audit write so it stops failing saved requests (#88121)
posthog[bot]c7ab3a6fa93a
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 42fa9b655aa0..62f8d5c074b1 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -15,6 +15,7 @@ from django.dispatch.dispatcher import receiverfrom django.utils import timezoneimport structlog+from prometheus_client import Counterfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.activity_logging.utils import ACTIVITY_LOG_CLIENT_MAX_LENGTH, activity_storage@@ -25,6 +26,12 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)+ACTIVITY_LOG_WRITE_FAILURES = Counter(+ "activity_log_write_failures_total",+ "Activity log rows that failed to write",+ labelnames=["deferred"],+)+ActivityScope = Literal["Cohort","FeatureFlag",@@ -1050,22 +1057,37 @@ def dict_changes_between(return changes+def _report_activity_log_write_failure(e: Exception, error_context: dict, deferred: bool) -> None:+ logger.warn(+ "activity_log.failed_to_write_to_activity_log",+ **error_context,+ exception=e,+ )+ capture_exception(e)+ ACTIVITY_LOG_WRITE_FAILURES.labels(deferred=str(deferred).lower()).inc()++def _handle_activity_log_transaction(create_fn, error_context: dict):try:# Check if we're in a transaction, if yes, defer the activity log creation to the commit signalif not transaction.get_autocommit() and getattr(settings, "ACTIVITY_LOG_TRANSACTION_MANAGEMENT", True):- transaction.on_commit(create_fn)+ # The transaction already committed by the time this callback runs, so its own guard+ # keeps a slow audit write from failing a request whose data is already durable.+ def _deferred_create():+ try:+ create_fn()+ except Exception as e:+ _report_activity_log_write_failure(e, error_context, deferred=True)+ if settings.TEST:+ raise++ transaction.on_commit(_deferred_create)return Noneelse:return create_fn()except Exception as e:- logger.warn(- "activity_log.failed_to_write_to_activity_log",- **error_context,- exception=e,- )- capture_exception(e)+ _report_activity_log_write_failure(e, error_context, deferred=False)if settings.TEST:raisereturn Nonediff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.pyindex 849ae79bbf14..8600cd2d10f5 100644--- a/posthog/test/activity_logging/test_activity_logging.py+++ b/posthog/test/activity_logging/test_activity_logging.py@@ -190,6 +190,31 @@ class TestActivityLogModel(BaseTest):error.exception.args[0],)+ def test_deferred_write_failure_does_not_escape_committed_transaction(self) -> None:+ # A write deferred to transaction.on_commit runs after the transaction commits, so a+ # failure there must not surface as a request error for data that already persisted.+ with patch("posthog.models.activity_logging.activity_log.logger") as mock_logger:+ with self.settings(TEST=False, ACTIVITY_LOG_TRANSACTION_MANAGEMENT=True):+ with patch.object(ActivityLog.objects, "create", side_effect=IntegrityError("write timed out")):+ try:+ with self.captureOnCommitCallbacks(execute=True):+ log_activity(+ organization_id=self.organization.id,+ team_id=self.team.id,+ user=self.user,+ was_impersonated=False,+ item_id="12345",+ scope="FeatureFlag",+ activity="updated",+ detail=Detail(changes=[Change(type="FeatureFlag", field="active", action="created")]),+ )+ except Exception as e:+ raise pytest.fail(f"Deferred write failure should not escape: {e}")++ warning = mock_logger.warn.call_args+ self.assertEqual(warning.args[0], "activity_log.failed_to_write_to_activity_log")+ self.assertIsInstance(warning.kwargs["exception"], IntegrityError)+def test_does_not_throw_if_cannot_log_activity(self) -> None:# Assert on the module logger directly instead of assertLogs: the root logger sits at# ERROR under test settings, so whether the warning reaches a root handler depends on