: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(alerts): log activity on platform alert edits (#120012)
Jimmy Zhuac98dd4c6b06
diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 0eb7cbe5c973..835f2d53e6ce 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6193,6 +6193,7 @@ export enum ActivityScope {LLM_TRACE = 'LLMTrace',LOG = 'Log',LOGS_ALERT_CONFIGURATION = 'LogsAlertConfiguration',+ PLATFORM_ALERT_CONFIGURATION = 'PlatformAlertConfiguration',PRODUCT_TOUR = 'ProductTour',TICKET = 'Ticket',KNOWLEDGE_SOURCE = 'KnowledgeSource',diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 1d1047ef5cec..0c4d1bf5e298 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -117,6 +117,7 @@ ActivityScope = Literal["CustomerProfileConfig","Log","LogsAlertConfiguration",+ "PlatformAlertConfiguration","LogsExclusionRule","LogsRetentionRule","TracesRetentionRule",@@ -562,6 +563,18 @@ vision_alert_machine_fields = ["updated_at",]+# Written by checks, ownership handovers and the logs route's snooze, never by a settings edit.+platform_alert_runtime_fields = [+ "next_check_at",+ "snooze_until",+ "consecutive_failures",+ "check_status",+ "owner",+ "owner_changed_at",+ "switched_off_at",+ "updated_at",+]+# Fields that prevent activity signal triggering entirely when only these fields changesignal_exclusions: dict[ActivityScope, list[str]] = {"DataQualityCheckSchedule": ["next_run_at", "last_run_at", "last_suite_run", "updated_at"],@@ -582,6 +595,7 @@ signal_exclusions: dict[ActivityScope, list[str]] = {"consecutive_failures","state",],+ "PlatformAlertConfiguration": platform_alert_runtime_fields,"PersonalAPIKey": ["last_used_at",],@@ -720,6 +734,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {"alerts",],"VisionAlertConfiguration": [*vision_alert_machine_fields, "events", "matches"],+ # The reverse relations hold runtime state per group and per notification thread.+ "PlatformAlertConfiguration": [*platform_alert_runtime_fields, "alerts", "threads", "delivery_paths"],"DataQualityCheckSchedule": ["subject_type", "subject_uuid", "next_run_at", "last_run_at", "last_suite_run"],# The pointer names the tagged object, which a row never changes, and content_type and team# are model objects the diff cannot serialize.diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex d0fd4cedd677..1ba7b5aff833 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -24,6 +24,7 @@ model_activity:products.ai_observability.backend.activity_logging.handle_llm_promodel_activity:products.alerts.backend.activity_logging.handle_alert_configuration_changemodel_activity:products.alerts.backend.activity_logging.handle_alert_subscription_changemodel_activity:products.alerts.backend.activity_logging.handle_threshold_change+model_activity:products.alerts_platform.backend.activity_logging.handle_platform_alert_configuration_activitymodel_activity:products.annotations.backend.activity_logging.handle_annotation_changemodel_activity:products.batch_exports.backend.activity_logging.handle_batch_export_changemodel_activity:products.business_knowledge.backend.signals.handle_knowledge_library_changediff --git a/products/alerts_platform/backend/activity_logging.py b/products/alerts_platform/backend/activity_logging.pynew file mode 100644index 000000000000..69c7607fb0c3--- /dev/null+++ b/products/alerts_platform/backend/activity_logging.py@@ -0,0 +1,43 @@+"""Activity-log receiver for platform alert configurations.++Kept free of API and query-runner imports, because `ready()` connects it in every process.+"""++from typing import Any, cast++from posthog.models.activity_logging.activity_log import ActivityScope, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver+from posthog.models.user import User++from products.alerts_platform.backend.facade.enums import PlatformAlertOwner+from products.alerts_platform.backend.models import PlatformAlertConfiguration+++@mutable_receiver(model_activity_signal, sender=PlatformAlertConfiguration)+def handle_platform_alert_configuration_activity(+ sender: Any,+ scope: str,+ before_update: PlatformAlertConfiguration | None,+ after_update: PlatformAlertConfiguration | None,+ activity: str,+ user: User | None,+ was_impersonated: bool = False,+ **kwargs: Any,+) -> None:+ instance = after_update or before_update+ # A copy its source owns repeats the source's row, which the source logs on its own scope.+ if instance is None or instance.owner != PlatformAlertOwner.PLATFORM:+ return+ log_activity(+ organization_id=instance.team.organization_id,+ team_id=instance.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=instance.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(cast(ActivityScope, scope), previous=before_update, current=after_update),+ name=instance.name,+ ),+ )diff --git a/products/alerts_platform/backend/apps.py b/products/alerts_platform/backend/apps.pyindex b9f08a725137..925e0b5deb76 100644--- a/products/alerts_platform/backend/apps.py+++ b/products/alerts_platform/backend/apps.py@@ -6,3 +6,8 @@ from django.apps import AppConfigclass AlertsPlatformConfig(AppConfig):name = "products.alerts_platform.backend"label = "alerts_platform"++ def ready(self) -> None:+ # Connects the activity-log receiver in every process, because checks, commands and the API+ # all write configurations.+ from products.alerts_platform.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.pyindex f4544a801f8c..c3a38bd1d3c9 100644--- a/products/alerts_platform/backend/models/platform_alert.py+++ b/products/alerts_platform/backend/models/platform_alert.py@@ -8,8 +8,11 @@ configuration already holds in this app. The prefix names what the rows are for:source configures on the shared platform, rather than one product's own table."""+from typing import Any+from django.db import models+from posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import UUIDModel@@ -34,7 +37,7 @@ def source_kind_choices() -> list[tuple[str, str]]:return PlatformAlertConfigurationSourceKind.choices-class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):+class PlatformAlertConfiguration(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):"""What to evaluate, how often, and against what bound.Evaluation-level state lives here rather than on `PlatformAlert`, because a failed check@@ -106,6 +109,13 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):)owner_changed_at = models.DateTimeField(null=True, blank=True)+ def _should_log_activity_for_update(self, **kwargs: Any) -> tuple[bool, Any]:+ # A copy its source owns is not logged, so its writes skip the read of the row before the update.+ # Backfills and source edits write those copies one row at a time.+ if self.owner != PlatformAlertOwner.PLATFORM:+ return False, None+ return super()._should_log_activity_for_update(**kwargs)+class Meta:# Pinned: the name predates this app, and removing this renames a live table.db_table = "alerts_platformalertconfiguration"diff --git a/products/alerts_platform/backend/tests/api/test_platform_alert.py b/products/alerts_platform/backend/tests/api/test_platform_alert.pyindex 23dbf461817b..22f8606f9fe9 100644--- a/products/alerts_platform/backend/tests/api/test_platform_alert.py+++ b/products/alerts_platform/backend/tests/api/test_platform_alert.py@@ -13,7 +13,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.constants import AvailableFeature-from posthog.models import OrganizationMembership, User+from posthog.models import ActivityLog, OrganizationMembership, Userfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.scoping import team_scopefrom posthog.models.team import Team@@ -392,6 +392,29 @@ class TestPlatformAlertAPI(APIBaseTest):assert (configuration.check_status, configuration.consecutive_failures) == ("ok", 0)assert configuration.next_check_at is not None+ def test_an_edit_logs_the_settings_it_changed_and_runtime_writes_log_nothing(self) -> None:+ self._set_flag(True)+ self._create_configuration(self.team, "Seed copy")+ configuration = self._create_configuration(self.team, "API errors", owner="platform")+ with team_scope(self.team.id):+ configuration.next_check_at = datetime(2026, 10, 1, tzinfo=UTC)+ configuration.consecutive_failures = 3+ configuration.save(update_fields=["next_check_at", "consecutive_failures"])++ response = self.client.patch(self._edit_url(configuration), {"name": "Renamed"}, format="json")++ assert response.status_code == status.HTTP_200_OK, response.json()+ logged = ActivityLog.objects.filter(team_id=self.team.id, scope="PlatformAlertConfiguration")+ assert [(row.item_id, row.activity) for row in logged.order_by("created_at")] == [+ (str(configuration.id), "created"),+ (str(configuration.id), "updated"),+ ]+ edit = logged.get(activity="updated")+ assert edit.user == self.user and edit.detail is not None+ assert [(change["field"], change["before"], change["after"]) for change in edit.detail["changes"]] == [+ ("name", "API errors", "Renamed")+ ]+def _grouped_configuration(self, owner: str = "platform") -> PlatformAlertConfiguration:configuration = self._create_configuration(self.team, "API errors", owner=owner)with team_scope(self.team.id):diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex aae97f8ad0d9..2e22c5803beb 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1462,6 +1462,7 @@ export type ActivityLogListParams = {* * `CustomerProfileConfig` - CustomerProfileConfig* * `Log` - Log* * `LogsAlertConfiguration` - LogsAlertConfiguration+ * * `PlatformAlertConfiguration` - PlatformAlertConfiguration* * `LogsExclusionRule` - LogsExclusionRule* * `LogsRetentionRule` - LogsRetentionRule* * `TracesRetentionRule` - TracesRetentionRule@@ -1572,6 +1573,7 @@ export const ActivityLogListScope = {CustomerProfileConfig: 'CustomerProfileConfig',Log: 'Log',LogsAlertConfiguration: 'LogsAlertConfiguration',+ PlatformAlertConfiguration: 'PlatformAlertConfiguration',LogsExclusionRule: 'LogsExclusionRule',LogsRetentionRule: 'LogsRetentionRule',TracesRetentionRule: 'TracesRetentionRule',@@ -1669,6 +1671,7 @@ export const ActivityLogListScope = {* * `CustomerProfileConfig` - CustomerProfileConfig* * `Log` - Log* * `LogsAlertConfiguration` - LogsAlertConfiguration+ * * `PlatformAlertConfiguration` - PlatformAlertConfiguration* * `LogsExclusionRule` - LogsExclusionRule* * `LogsRetentionRule` - LogsRetentionRule* * `TracesRetentionRule` - TracesRetentionRule@@ -1767,6 +1770,7 @@ export const ActivityLogListScopesItem = {CustomerProfileConfig: 'CustomerProfileConfig',Log: 'Log',LogsAlertConfiguration: 'LogsAlertConfiguration',+ PlatformAlertConfiguration: 'PlatformAlertConfiguration',LogsExclusionRule: 'LogsExclusionRule',LogsRetentionRule: 'LogsRetentionRule',TracesRetentionRule: 'TracesRetentionRule',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8b9ac004ad98..95b02818a8a9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -121986,6 +121986,7 @@ export namespace Schemas {* * `CustomerProfileConfig` - CustomerProfileConfig* * `Log` - Log* * `LogsAlertConfiguration` - LogsAlertConfiguration+ * * `PlatformAlertConfiguration` - PlatformAlertConfiguration* * `LogsExclusionRule` - LogsExclusionRule* * `LogsRetentionRule` - LogsRetentionRule* * `TracesRetentionRule` - TracesRetentionRule@@ -122097,6 +122098,7 @@ export namespace Schemas {CustomerProfileConfig: 'CustomerProfileConfig',Log: 'Log',LogsAlertConfiguration: 'LogsAlertConfiguration',+ PlatformAlertConfiguration: 'PlatformAlertConfiguration',LogsExclusionRule: 'LogsExclusionRule',LogsRetentionRule: 'LogsRetentionRule',TracesRetentionRule: 'TracesRetentionRule',@@ -122194,6 +122196,7 @@ export namespace Schemas {* * `CustomerProfileConfig` - CustomerProfileConfig* * `Log` - Log* * `LogsAlertConfiguration` - LogsAlertConfiguration+ * * `PlatformAlertConfiguration` - PlatformAlertConfiguration* * `LogsExclusionRule` - LogsExclusionRule* * `LogsRetentionRule` - LogsRetentionRule* * `TracesRetentionRule` - TracesRetentionRule@@ -122293,6 +122296,7 @@ export namespace Schemas {CustomerProfileConfig: 'CustomerProfileConfig',Log: 'Log',LogsAlertConfiguration: 'LogsAlertConfiguration',+ PlatformAlertConfiguration: 'PlatformAlertConfiguration',LogsExclusionRule: 'LogsExclusionRule',LogsRetentionRule: 'LogsRetentionRule',TracesRetentionRule: 'TracesRetentionRule',