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(conversations): attribute workflow tag changes on tickets (#69244)

Abigaild13e77da4eea
diff --git a/posthog/models/activity_logging/model_activity.py b/posthog/models/activity_logging/model_activity.py
index 053573800301..6f5b42c5f815 100644
--- a/posthog/models/activity_logging/model_activity.py
+++ b/posthog/models/activity_logging/model_activity.py
@@ -14,6 +14,10 @@ def get_current_user():
return activity_storage.get_user()
+def get_current_trigger():
+ return activity_storage.get_trigger()
+
+
def is_impersonated_session(request):
"""Lazy import to avoid circular import issues during Django setup"""
try:
@@ -125,6 +129,37 @@ class ModelActivityMixin(models.Model):
return should_log, before_update
+class ActivityTriggerContext:
+ """Attributes signal-driven activity logging to an automated source (e.g. a workflow).
+
+ Model-signal activity handlers (like TaggedItem's) run deep inside ORM calls where no
+ Trigger can be passed explicitly, so this stashes one in the activity thread-local for
+ handlers to pick up via ``get_current_trigger()``. Always used as a context manager so
+ the trigger cannot leak into unrelated activity on a reused worker thread; a ``None``
+ trigger makes this a no-op.
+ """
+
+ def __init__(self, trigger):
+ self.trigger = trigger
+ self.previous = None
+
+ def __enter__(self):
+ if self.trigger is not None:
+ # Save and restore rather than clear on exit, so a nested context can't
+ # silently erase an enclosing context's attribution.
+ self.previous = activity_storage.get_trigger()
+ activity_storage.set_trigger(self.trigger)
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ if self.trigger is None:
+ return
+ if self.previous is not None:
+ activity_storage.set_trigger(self.previous)
+ else:
+ activity_storage.clear_trigger()
+
+
class ImpersonatedContext:
# This is a context manager that sets the was_impersonated flag in the activity storage
# if the request is impersonated. Use this to call the model's save method with impersonated
diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.py
index 7cee920751e2..ce95e656c342 100644
--- a/posthog/models/activity_logging/signal_handlers.py
+++ b/posthog/models/activity_logging/signal_handlers.py
@@ -33,7 +33,7 @@ from posthog.models.activity_logging.activity_log import (
changes_between,
log_activity,
)
-from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated
+from posthog.models.activity_logging.model_activity import get_current_trigger, get_current_user, get_was_impersonated
from posthog.models.activity_logging.personal_api_key_utils import (
log_personal_api_key_activity,
log_personal_api_key_scope_change,
@@ -598,6 +598,8 @@ def handle_tagged_item_change(
team = tagged_item.tag.team
organization_id = team.organization_id if team else None
team_id = tagged_item.tag.team_id
+ # Set by ActivityTriggerContext when the change comes from an automated source (e.g. a workflow)
+ trigger = get_current_trigger()
log_activity(
organization_id=organization_id,
@@ -611,6 +613,7 @@ def handle_tagged_item_change(
changes=changes_between(scope, previous=before_update, current=after_update),
name=tagged_item.tag.name,
context=context,
+ trigger=trigger,
),
)
@@ -638,6 +641,7 @@ def handle_tagged_item_change(
before=tagged_item.tag.name if activity == "deleted" else None,
)
],
+ trigger=trigger,
),
)
diff --git a/posthog/models/activity_logging/utils.py b/posthog/models/activity_logging/utils.py
index 1aeffface4a7..f4b93b9f1c2a 100644
--- a/posthog/models/activity_logging/utils.py
+++ b/posthog/models/activity_logging/utils.py
@@ -8,7 +8,7 @@ import structlog
from asgiref.local import Local
if TYPE_CHECKING:
- from posthog.models.activity_logging.activity_log import ActivityLog
+ from posthog.models.activity_logging.activity_log import ActivityLog, Trigger
logger = structlog.get_logger(__name__)
@@ -64,11 +64,22 @@ class ActivityLoggingStorage:
if hasattr(self._local, "ip_address"):
delattr(self._local, "ip_address")
+ def set_trigger(self, trigger: Optional["Trigger"]) -> None:
+ self._local.trigger = trigger
+
+ def get_trigger(self) -> Optional["Trigger"]:
+ return getattr(self._local, "trigger", None)
+
+ def clear_trigger(self) -> None:
+ if hasattr(self._local, "trigger"):
+ delattr(self._local, "trigger")
+
def clear_all(self) -> None:
self.clear_user()
self.clear_was_impersonated()
self.clear_client()
self.clear_ip_address()
+ self.clear_trigger()
activity_storage = ActivityLoggingStorage()
diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.py
index db834bff467a..ea545063fe7a 100644
--- a/posthog/test/activity_logging/test_activity_logging.py
+++ b/posthog/test/activity_logging/test_activity_logging.py
@@ -6,7 +6,8 @@ from django.db.utils import IntegrityError
from parameterized import parameterized
from posthog.models import User
-from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, log_activity
+from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, Trigger, log_activity
+from posthog.models.activity_logging.model_activity import ActivityTriggerContext
from posthog.models.activity_logging.utils import activity_storage, activity_visibility_manager
from posthog.models.utils import UUIDT
@@ -330,3 +331,26 @@ class TestActivityLogVisibilityManager(BaseTest):
filtered = activity_visibility_manager.apply_to_queryset(queryset, is_staff=True)
self.assertEqual(filtered.count(), 4)
+
+
+class TestActivityTriggerContext(BaseTest):
+ def tearDown(self):
+ activity_storage.clear_trigger()
+ super().tearDown()
+
+ def test_nested_contexts_restore_the_outer_trigger(self):
+ outer = Trigger(job_type="hog_flow", job_id="outer", payload={})
+ inner = Trigger(job_type="hog_flow", job_id="inner", payload={})
+
+ with ActivityTriggerContext(outer):
+ with ActivityTriggerContext(inner):
+ self.assertEqual(activity_storage.get_trigger(), inner)
+ self.assertEqual(activity_storage.get_trigger(), outer)
+ self.assertIsNone(activity_storage.get_trigger())
+
+ def test_none_trigger_is_a_noop(self):
+ outer = Trigger(job_type="hog_flow", job_id="outer", payload={})
+ with ActivityTriggerContext(outer):
+ with ActivityTriggerContext(None):
+ self.assertEqual(activity_storage.get_trigger(), outer)
+ self.assertEqual(activity_storage.get_trigger(), outer)
diff --git a/products/conversations/backend/api/external.py b/products/conversations/backend/api/external.py
index 334193fde734..febd5ec003fd 100644
--- a/products/conversations/backend/api/external.py
+++ b/products/conversations/backend/api/external.py
@@ -24,6 +24,7 @@ from rest_framework.views import APIView
from posthog.exceptions_capture import capture_exception
from posthog.models import Tag, Team
from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity
+from posthog.models.activity_logging.model_activity import ActivityTriggerContext
from posthog.models.tag import tagify
from products.conversations.backend.api.tickets import assign_ticket
@@ -169,34 +170,6 @@ def _workflow_trigger_from_request(request: Request) -> Trigger | None:
return Trigger(job_type="hog_flow", job_id=hog_flow_id, payload={})
-def _log_ticket_tag_removals(ticket: Ticket, team: Team, removed_tags: set[str], trigger: Trigger | None) -> None:
- """Mirror tag removals onto the ticket's activity stream.
-
- Tag *additions* go through ``TaggedItem`` saves that fire the model activity signal,
- which already logs them to the ticket. Removals use a bulk queryset delete that bypasses
- that signal, so they would otherwise leave no trace — this fills that gap (and, when a
- workflow made the change, attributes it via ``trigger``).
- """
- if not removed_tags:
- return
- changes = [
- Change(type="Ticket", field="tag", action="deleted", before=tag_name) for tag_name in sorted(removed_tags)
- ]
- try:
- log_activity(
- organization_id=team.organization_id,
- team_id=team.id,
- user=None,
- was_impersonated=False,
- item_id=str(ticket.id),
- scope="Ticket",
- activity="updated",
- detail=Detail(name=f"Ticket #{ticket.ticket_number}", changes=changes, trigger=trigger),
- )
- except Exception as e:
- capture_exception(e, {"ticket_id": str(ticket.id)})
-
-
class ExternalTicketView(APIView):
"""
GET /api/conversations/external/ticket/<ticket_id> — Fetch ticket data
@@ -459,36 +432,34 @@ class ExternalTicketView(APIView):
try:
tags_mode = serializer.validated_data.get("tags_mode", "add")
normalized_tags = {tagify(t) for t in serializer.validated_data["tags"]}
- existing_tags = set(ticket.tagged_items.values_list("tag__name", flat=True))
-
- # Additions log themselves via the TaggedItem model activity signal; only bulk
- # deletes bypass it, so we track removals to log them explicitly below.
- removed_tags: set[str] = set()
-
- if tags_mode == "remove":
- removed_tags = existing_tags & normalized_tags
- ticket.tagged_items.filter(tag__name__in=normalized_tags).delete()
- Tag.objects.filter(team_id=team.id, tagged_items__isnull=True).delete()
- elif tags_mode == "set":
- removed_tags = existing_tags - normalized_tags
- for tag_name in normalized_tags:
- tag_instance, _ = Tag.objects.get_or_create(name=tag_name, team_id=team.id)
- ticket.tagged_items.get_or_create(tag_id=tag_instance.id)
- ticket.tagged_items.exclude(tag__name__in=normalized_tags).delete()
- Tag.objects.filter(team_id=team.id, tagged_items__isnull=True).delete()
- else:
- for tag_name in normalized_tags:
- tag_instance, _ = Tag.objects.get_or_create(name=tag_name, team_id=team.id)
- ticket.tagged_items.get_or_create(tag_id=tag_instance.id)
+
+ # Tag adds and removes are both logged by the TaggedItem model activity signal
+ # (to the ticket's timeline and the Tag audit stream). Removals must go through
+ # the per-instance delete() so the signal fires for them too; a bulk queryset
+ # delete would skip it. The trigger context attributes every resulting entry
+ # to the workflow that made the change.
+ with ActivityTriggerContext(workflow_trigger):
+ if tags_mode == "remove":
+ for tagged_item in ticket.tagged_items.filter(tag__name__in=normalized_tags).select_related(
+ "tag__team", "ticket"
+ ):
+ tagged_item.delete()
+ Tag.objects.filter(team_id=team.id, tagged_items__isnull=True).delete()
+ elif tags_mode == "set":
+ for tag_name in normalized_tags:
+ tag_instance, _ = Tag.objects.get_or_create(name=tag_name, team_id=team.id)
+ ticket.tagged_items.get_or_create(tag_id=tag_instance.id)
+ for tagged_item in ticket.tagged_items.exclude(tag__name__in=normalized_tags).select_related(
+ "tag__team", "ticket"
+ ):
+ tagged_item.delete()
+ Tag.objects.filter(team_id=team.id, tagged_items__isnull=True).delete()
+ else:
+ for tag_name in normalized_tags:
+ tag_instance, _ = Tag.objects.get_or_create(name=tag_name, team_id=team.id)
+ ticket.tagged_items.get_or_create(tag_id=tag_instance.id)
except Exception as e:
capture_exception(e, {"ticket_id": str(ticket.id)})
return Response({"error": "Failed to update tags"}, status=status.HTTP_400_BAD_REQUEST)
- _log_ticket_tag_removals(
- ticket=ticket,
- team=team,
- removed_tags=removed_tags,
- trigger=workflow_trigger,
- )
-
return Response({"ok": True})
diff --git a/products/conversations/backend/api/tests/test_external.py b/products/conversations/backend/api/tests/test_external.py
index f8d6b7c3549f..9ceeefca7d0a 100644
--- a/products/conversations/backend/api/tests/test_external.py
+++ b/products/conversations/backend/api/tests/test_external.py
@@ -594,9 +594,17 @@ class TestExternalTicketAPI(BaseTest):
assert activity is not None
self.assertIsNone(activity.detail.get("trigger"))
- def test_patch_tag_remove_logs_activity_with_workflow_trigger(self):
- # Removals use a bulk delete that bypasses the TaggedItem activity signal, so without
- # explicit logging they leave no trace. Assert the gap is filled and workflow-attributed.
+ @parameterized.expand(
+ [
+ ("add", {"tags": ["urgent"], "tags_mode": "add"}, "created", "after", "urgent"),
+ ("remove", {"tags": ["bug"], "tags_mode": "remove"}, "deleted", "before", "bug"),
+ ]
+ )
+ def test_patch_tag_changes_record_workflow_trigger(self, _name, payload, action, direction, tag_name):
+ # Both directions flow through the TaggedItem activity signal: adds fire it on save,
+ # removes only because the endpoint deletes per-instance (a bulk delete would skip it).
+ # The signal picks the workflow trigger up from ActivityTriggerContext; without that,
+ # workflow tag changes render as an anonymous "PostHog" on the ticket timeline.
from posthog.models import Tag
existing_tag = Tag.objects.create(name="bug", team_id=self.team.id)
@@ -604,7 +612,7 @@ class TestExternalTicketAPI(BaseTest):
response = self.client.patch(
self.url,
- {"tags": ["bug"], "tags_mode": "remove"},
+ payload,
content_type="application/json",
**self._workflow_headers(),
)
@@ -614,10 +622,52 @@ class TestExternalTicketAPI(BaseTest):
assert activity is not None
tag_change = next((c for c in activity.detail.get("changes", []) if c["field"] == "tag"), None)
assert tag_change is not None
- self.assertEqual(tag_change["action"], "deleted")
- self.assertEqual(tag_change["before"], "bug")
+ self.assertEqual(tag_change["action"], action)
+ self.assertEqual(tag_change[direction], tag_name)
self.assertEqual(activity.detail["trigger"]["job_type"], "hog_flow")
+ def test_patch_tag_changes_write_tag_audit_entries(self):
+ # Removals used to go through a bulk queryset delete, which skips the TaggedItem signal
+ # and left them out of the global Tag audit stream entirely. Both directions must now
+ # produce a TaggedItem-scope entry, attributed to the workflow.
+ response = self.client.patch(
+ self.url,
+ {"tags": ["urgent"], "tags_mode": "add"},
+ content_type="application/json",
+ **self._workflow_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ response = self.client.patch(
+ self.url,
+ {"tags": ["urgent"], "tags_mode": "remove"},
+ content_type="application/json",
+ **self._workflow_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ audit_activities = {
+ entry.activity: entry for entry in ActivityLog.objects.filter(team_id=self.team.id, scope="TaggedItem")
+ }
+ self.assertIn("created", audit_activities)
+ self.assertIn("deleted", audit_activities)
+ deleted_detail = audit_activities["deleted"].detail
+ assert deleted_detail is not None
+ self.assertEqual(deleted_detail["trigger"]["job_type"], "hog_flow")
+
+ def test_workflow_trigger_does_not_leak_after_request(self):
+ # The trigger thread-local must be cleared by the context manager, or attribution
+ # would bleed into unrelated activity logged later on a reused worker thread.
+ from posthog.models.activity_logging.utils import activity_storage
+
+ response = self.client.patch(
+ self.url,
+ {"tags": ["urgent"], "tags_mode": "add"},
+ content_type="application/json",
+ **self._workflow_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIsNone(activity_storage.get_trigger())
+
def test_patch_assignee_records_workflow_trigger(self):
response = self.client.patch(
self.url,
@@ -630,3 +680,31 @@ class TestExternalTicketAPI(BaseTest):
activity = self._latest_ticket_activity(activity="assigned")
assert activity is not None
self.assertEqual(activity.detail["trigger"]["job_type"], "hog_flow")
+
+ def test_patch_unchanged_assignee_logs_no_activity(self):
+ # Callers send the assignee whenever it's in the payload (the ticket UI always sends the
+ # full form), so a no-op assignment must not write "assigned to unassigned" entries or
+ # fire assignment-triggered workflows on every save.
+ response = self.client.patch(
+ self.url,
+ {"assignee": None},
+ content_type="application/json",
+ **self._auth_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIsNone(self._latest_ticket_activity(activity="assigned"))
+
+ for _ in range(2):
+ response = self.client.patch(
+ self.url,
+ {"assignee": {"type": "user", "id": self.user.id}},
+ content_type="application/json",
+ **self._auth_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ ActivityLog.objects.filter(
+ team_id=self.team.id, scope="Ticket", item_id=str(self.ticket.id), activity="assigned"
+ ).count(),
+ 1,
+ )
diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.py
index ea47e6db8161..25d4de10d053 100644
--- a/products/conversations/backend/api/tickets.py
+++ b/products/conversations/backend/api/tickets.py
@@ -1376,6 +1376,13 @@ def assign_ticket(
assignment_before.delete()
serialized_assignment_after = None
+ # Callers pass the assignee whenever it's present in the payload (the ticket UI always
+ # sends the full form), so skip logging and the assignment event when nothing changed —
+ # otherwise every save writes "assigned to unassigned" and fires assignment-triggered
+ # workflows.
+ if serialized_assignment_before == serialized_assignment_after:
+ return
+
log_activity(
organization_id=organization.id,
team_id=team_id,