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.

feat(data-management): log activity for bulk tag updates (#68893)

jake sciotto3bbf23a7a9c8
diff --git a/posthog/api/event_definition.py b/posthog/api/event_definition.py
index df956e6fe77e..c0e858a1ba15 100644
--- a/posthog/api/event_definition.py
+++ b/posthog/api/event_definition.py
@@ -21,6 +21,7 @@ from posthog.api.event_definition_generators.typescript import TypeScriptGenerat
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import (
+ BulkTagActivityContext,
BulkUpdateTagsUUIDRequestSerializer,
BulkUpdateTagsUUIDResponseSerializer,
TaggedItemSerializerMixin,
@@ -478,7 +479,16 @@ class EventDefinitionViewSet(
found_ids = {obj.id for obj in objects}
skipped = [{"id": obj_id, "reason": "Not found"} for obj_id in validated_ids if obj_id not in found_ids]
- updated = apply_bulk_tag_changes(objects, validated["action"], validated["tags"])
+ activity_context = BulkTagActivityContext(
+ scope="EventDefinition",
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated(request),
+ # The single-object event-definition update path logs under the "changed" verb.
+ activity="changed",
+ )
+ updated = apply_bulk_tag_changes(
+ objects, validated["action"], validated["tags"], activity_context=activity_context
+ )
return response.Response({"updated": updated, "skipped": skipped})
def perform_create(self, serializer):
diff --git a/posthog/api/tagged_item.py b/posthog/api/tagged_item.py
index c69f536ad4d3..4022e347b4b8 100644
--- a/posthog/api/tagged_item.py
+++ b/posthog/api/tagged_item.py
@@ -1,5 +1,6 @@
+import dataclasses
from collections.abc import Sequence
-from typing import Any, cast
+from typing import TYPE_CHECKING, Any, Optional, cast
from django.db import models
from django.db.models import Prefetch, Q, QuerySet, prefetch_related_objects
@@ -10,10 +11,15 @@ from rest_framework.viewsets import GenericViewSet
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
+from posthog.helpers.impersonation import is_impersonated
from posthog.models import Tag, TaggedItem
+from posthog.models.activity_logging.activity_log import Change, Detail, LogActivityEntry, bulk_log_activity
from posthog.models.tag import tagify
from posthog.rbac.user_access_control import access_level_satisfied_for_resource
+if TYPE_CHECKING:
+ from posthog.models.user import User
+
def set_tags_on_object(tags: list[str], obj: Any) -> list[TaggedItem]:
"""Set tags on a taggable object, creating/deleting TaggedItems as needed.
@@ -42,17 +48,45 @@ def cleanup_orphan_tags(team_id: int) -> None:
Tag.objects.filter(Q(team_id=team_id) & Q(tagged_items__isnull=True)).delete()
-def apply_bulk_tag_changes(objects: Sequence, tag_action: str, tags: list[str]) -> list[dict[str, Any]]:
[email protected](frozen=True)
+class BulkTagActivityContext:
+ """Context needed to write an activity-log entry for each object mutated in bulk.
+
+ ``scope`` is the resource's ``ActivityScope`` (e.g. ``"FeatureFlag"``) and ``activity`` is the
+ verb its single-object update path uses ("updated" for flags/insights/dashboards, "changed" for
+ event definitions), so a bulk entry matches what that path already writes. Passing this to
+ ``apply_bulk_tag_changes`` makes the bulk path leave the same audit trail; omitting it preserves
+ the old silent behavior.
+ """
+
+ scope: str
+ user: "User"
+ was_impersonated: bool
+ activity: str
+
+
+def apply_bulk_tag_changes(
+ objects: Sequence,
+ tag_action: str,
+ tags: list[str],
+ *,
+ activity_context: Optional[BulkTagActivityContext] = None,
+) -> list[dict[str, Any]]:
"""Apply an add/remove/set tag mutation to each object and return a per-object result.
Callers are responsible for team-scoping and access-checking ``objects`` first. When a
``prefetched_tags`` attribute is present it is used to avoid a per-object tag query.
Orphaned tags are cleaned up per affected team, since ``objects`` may span multiple teams
when the caller scopes by project (e.g. event definitions across environments).
+
+ When ``activity_context`` is provided, an activity-log entry carrying a ``tags`` diff is
+ recorded for every object whose tags actually change, mirroring the single-object update path
+ so the bulk endpoint leaves the same audit trail.
"""
normalized_tags = {tagify(t) for t in tags}
updated: list[dict[str, Any]] = []
team_ids: set[int] = set()
+ activity_entries: list[LogActivityEntry] = []
for obj in objects:
team_ids.add(obj.team_id)
@@ -73,12 +107,45 @@ def apply_bulk_tag_changes(objects: Sequence, tag_action: str, tags: list[str])
set_tags_on_object(list(new_tags), obj)
updated.append({"id": obj.id, "tags": sorted(new_tags)})
+ if activity_context is not None and current_tags != new_tags:
+ activity_entries.append(
+ _bulk_tag_activity_entry(obj, sorted(current_tags), sorted(new_tags), activity_context)
+ )
+
for team_id in team_ids:
cleanup_orphan_tags(team_id)
+ if activity_entries:
+ bulk_log_activity(activity_entries)
+
return updated
+def _bulk_tag_activity_entry(
+ obj: Any, before: list[str], after: list[str], context: BulkTagActivityContext
+) -> LogActivityEntry:
+ """Build an activity-log entry for a single bulk-tagged object.
+
+ ``organization_id`` is left ``None`` (the team is enough to scope the entry, and ``objects``
+ can span teams within a project), matching the single-object update path.
+ """
+ return LogActivityEntry(
+ organization_id=None,
+ team_id=obj.team_id,
+ user=context.user,
+ was_impersonated=context.was_impersonated,
+ item_id=str(obj.id),
+ scope=context.scope,
+ activity=context.activity,
+ detail=Detail(
+ name=getattr(obj, "name", None) or getattr(obj, "key", None),
+ # short_id is how insights are linked in the activity feed; None (and ignored) elsewhere.
+ short_id=getattr(obj, "short_id", None),
+ changes=[Change(type=context.scope, action="changed", field="tags", before=before, after=after)],
+ ),
+ )
+
+
class TaggedItemSerializerMixin(serializers.Serializer):
"""
Serializer mixin that handles tags for objects.
@@ -210,6 +277,22 @@ def _prefetch_tags_for_instances(instances: Sequence) -> None:
class TaggedItemViewSetMixin(viewsets.GenericViewSet):
+ # Set to the resource's ActivityScope (e.g. "FeatureFlag") to record an activity-log entry per
+ # object whose tags change via ``bulk_update_tags``. Left ``None`` for resources that don't log
+ # bulk tag edits, which leaves their behavior unchanged.
+ bulk_tag_activity_scope: Optional[str] = None
+
+ def _bulk_tag_activity_context(self) -> Optional[BulkTagActivityContext]:
+ if not self.bulk_tag_activity_scope:
+ return None
+ return BulkTagActivityContext(
+ scope=self.bulk_tag_activity_scope,
+ user=cast("User", self.request.user),
+ was_impersonated=is_impersonated(self.request),
+ # Flags, insights, and dashboards log single-object updates under the "updated" verb.
+ activity="updated",
+ )
+
def prefetch_tagged_items_if_available(self, queryset: QuerySet | models.query.RawQuerySet) -> QuerySet:
if isinstance(queryset, models.query.RawQuerySet):
return queryset # type: ignore[return-value] # ty: ignore[invalid-return-type]
@@ -296,7 +379,9 @@ class TaggedItemViewSetMixin(viewsets.GenericViewSet):
if obj_id not in found_ids:
errors.append({"id": obj_id, "reason": "Not found"})
- updated = apply_bulk_tag_changes(editable_objects, tag_action, tags)
+ updated = apply_bulk_tag_changes(
+ editable_objects, tag_action, tags, activity_context=self._bulk_tag_activity_context()
+ )
return response.Response({"updated": updated, "skipped": errors})
diff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.py
index 308a74105c1c..f190f23b2c4c 100644
--- a/posthog/api/test/test_event_definition.py
+++ b/posthog/api/test/test_event_definition.py
@@ -553,6 +553,47 @@ class TestEventDefinitionAPI(APIBaseTest):
assert not Tag.objects.filter(name="orphan_a", team=self.demo_team).exists()
assert not Tag.objects.filter(name="orphan_b", team=other_env).exists()
+ def test_bulk_update_tags_logs_activity_per_event_definition(self):
+ # The single-object update path leaves a tags audit trail; the bulk path must too, or tagging
+ # 50 definitions is silent while tagging one is logged. Guards that the override threads an
+ # activity context through to apply_bulk_tag_changes.
+ ed1 = EventDefinition.objects.create(team=self.demo_team, name="logged_a")
+ ed2 = EventDefinition.objects.create(team=self.demo_team, name="logged_b")
+
+ response = self.client.post(
+ f"/api/projects/{self.demo_team.pk}/event_definitions/bulk_update_tags/",
+ {"ids": [str(ed1.id), str(ed2.id)], "action": "add", "tags": ["pii"]},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ logs = ActivityLog.objects.filter(
+ scope="EventDefinition", activity="changed", item_id__in=[str(ed1.id), str(ed2.id)]
+ )
+ assert {log.item_id for log in logs} == {str(ed1.id), str(ed2.id)}
+ log = logs.get(item_id=str(ed1.id))
+ assert log.detail is not None
+ assert log.detail["changes"] == [
+ {"type": "EventDefinition", "action": "changed", "field": "tags", "before": [], "after": ["pii"]}
+ ]
+
+ def test_bulk_update_tags_noop_does_not_log_activity(self):
+ # Adding a tag a definition already has changes nothing; it must not write an empty activity
+ # entry. Guards the current_tags != new_tags skip in apply_bulk_tag_changes.
+ ed = EventDefinition.objects.create(team=self.demo_team, name="noop_event")
+ self.client.post(
+ f"/api/projects/{self.demo_team.pk}/event_definitions/bulk_update_tags/",
+ {"ids": [str(ed.id)], "action": "set", "tags": ["kept"]},
+ )
+ ActivityLog.objects.filter(scope="EventDefinition").delete()
+
+ response = self.client.post(
+ f"/api/projects/{self.demo_team.pk}/event_definitions/bulk_update_tags/",
+ {"ids": [str(ed.id)], "action": "add", "tags": ["kept"]},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert not ActivityLog.objects.filter(scope="EventDefinition", item_id=str(ed.id)).exists()
+
class TestEventDefinitionExcludeStale(APIBaseTest):
"""Stale filter tests need real wall-clock times so the Postgres NOW() comparison
diff --git a/posthog/api/test/test_tagged_item.py b/posthog/api/test/test_tagged_item.py
index b04a386d7d9c..1ed865597200 100644
--- a/posthog/api/test/test_tagged_item.py
+++ b/posthog/api/test/test_tagged_item.py
@@ -3,7 +3,7 @@ from posthog.test.base import APIBaseTest
from parameterized import parameterized
from rest_framework import status
-from posthog.models import Organization, Tag, Team
+from posthog.models import ActivityLog, Organization, Tag, Team
from posthog.models.tagged_item import TaggedItem
from products.dashboards.backend.models.dashboard import Dashboard
@@ -195,6 +195,33 @@ class TestBulkUpdateTags(APIBaseTest):
assert data["updated"][0]["tags"] == ["existing"]
assert data["skipped"] == []
+ def test_bulk_update_tags_logs_activity(self):
+ # A silent bulk edit was the reported gap: single-object updates log tag changes, the bulk
+ # path didn't. Guards that the shared mixin threads its bulk_tag_activity_scope into an
+ # activity entry (scope + "updated" verb + tags diff) for the resource.
+ dashboard = self._create_dashboard_with_tags("dash", ["existing"])
+
+ response = self.client.post(
+ self._bulk_update_url(),
+ {"ids": [dashboard.id], "action": "add", "tags": ["new"]},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ logs = ActivityLog.objects.filter(scope="Dashboard", activity="updated", item_id=str(dashboard.id))
+ assert logs.count() == 1
+ log = logs.get()
+ assert log.detail is not None
+ assert log.detail["changes"] == [
+ {
+ "type": "Dashboard",
+ "action": "changed",
+ "field": "tags",
+ "before": ["existing"],
+ "after": ["existing", "new"],
+ }
+ ]
+
# --- Validation errors ---
@parameterized.expand(
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 15573fb71d50..96091ecfa53f 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -2072,6 +2072,8 @@ class DashboardsViewSet(
viewsets.ModelViewSet,
):
scope_object = "dashboard"
+ # Record a tags change per dashboard when bulk_update_tags mutates it, matching the single-object path.
+ bulk_tag_activity_scope = "Dashboard"
queryset = Dashboard.objects_including_soft_deleted.order_by("-pinned", "name")
permission_classes = [CanEditDashboard]
renderer_classes = [SafeJSONRenderer, ServerSentEventRenderer]
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 55084d19ab20..66586536c414 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -2683,6 +2683,8 @@ class FeatureFlagViewSet(
"""
scope_object = "feature_flag"
+ # Record a tags change per flag when bulk_update_tags mutates it, matching the single-object path.
+ bulk_tag_activity_scope = "FeatureFlag"
psak_allowed_actions = ["remote_config"]
# Opt the shared TaggedItemViewSetMixin action into feature_flag:write.
# Other inheritors of the mixin don't extend write actions and so still
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 1314f424cdfd..d2617203c89e 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -1427,6 +1427,8 @@ class InsightViewSet(
viewsets.ModelViewSet,
):
scope_object = "insight"
+ # Record a tags change per insight when bulk_update_tags mutates it, matching the single-object path.
+ bulk_tag_activity_scope = "Insight"
serializer_class = InsightSerializer
throttle_classes = [
ClickHouseBurstRateThrottle,