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(customer-analytics): emit account tag removal events (#88828)

Arthur Moreira de Deus4c1e4034b91b
diff --git a/COMPROMISES.md b/COMPROMISES.md
index c2bec5a859b0..caf1e4000920 100644
--- a/COMPROMISES.md
+++ b/COMPROMISES.md
@@ -13,6 +13,6 @@ Events already carry the attribution a guard needs (`actor_type: "workflow"` + `
## Account tag events: emission blocks the request thread post-commit
-`$account_tag_added` is emitted synchronously inside `transaction.on_commit` (`_schedule_account_tags_added` in `facade/api.py`): one batched `capture_batch_internal` HTTP call per tag write, after the group-type lookup (Redis-cached). Happy path is single-digit ms; the degraded case (capture-rs slow or down) blocks the request for up to the 2s timeout times retries. A Celery offload was tried and reverted (`b6c62469ee9`) as too much overhead for this volume — tag adds are low-frequency, and this matches how conversation ticket events already emit.
+`$account_tag_added` and `$account_tag_removed` are emitted synchronously inside `transaction.on_commit` in `facade/api.py`. Each event type uses one batched `capture_batch_internal` HTTP call after the group-type lookup, which Redis caches. The degraded case blocks the request for up to the two-second timeout times retries when capture-rs is slow or down. A Celery offload was tried and reverted (`b6c62469ee9`) because tag changes are infrequent and conversation ticket events use the same pattern.
Revisit if account tagging becomes bulk/high-frequency (e.g. CRM syncs tagging thousands of accounts). Cheapest fixes then: cap the worst case (`timeout=1, max_attempts=1` — drops instead of retries during a blip), or prebuild the payload in-request and POST from a small module-level thread pool so no ORM touches the worker thread.
diff --git a/products/customer_analytics/backend/events.py b/products/customer_analytics/backend/events.py
index 3ec04698067e..53faca654a78 100644
--- a/products/customer_analytics/backend/events.py
+++ b/products/customer_analytics/backend/events.py
@@ -82,6 +82,27 @@ def emit_account_tags_added(
).raise_for_status()
+def emit_account_tags_removed(
+ account: Account, tags: list[Tag], actor: User | None, workflow_id: str | None = None
+) -> None:
+ if not tags:
+ return
+
+ properties = _base_event_properties(account, actor, workflow_id)
+ capture_batch_internal(
+ events=[
+ {
+ "event": "$account_tag_removed",
+ "distinct_id": _event_distinct_id(account, actor),
+ "properties": {**properties, "tag": tag.name, "tag_id": str(tag.id)},
+ }
+ for tag in tags
+ ],
+ token=account.team.api_token,
+ event_source=EVENT_SOURCE,
+ ).raise_for_status()
+
+
def emit_account_custom_property_changed(
account: Account,
definition: CustomPropertyDefinition,
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 9f89b9356390..d87b0626eefd 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -90,7 +90,7 @@ from products.conversations.backend.facade.api import (
trigger_immediate_channel_summary,
)
from products.customer_analytics.backend.account_urls import build_account_deeplink as build_account_deeplink
-from products.customer_analytics.backend.events import emit_account_tags_added
+from products.customer_analytics.backend.events import emit_account_tags_added, emit_account_tags_removed
from products.customer_analytics.backend.facade.contracts import (
InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,
)
@@ -613,7 +613,12 @@ def list_external_accounts(
def _apply_external_tags(account: Account, tags: list[str], mode: str, workflow_id: str | None = None) -> None:
normalized = list({tagify(t) for t in tags})
if mode == "remove":
+ removed_tags = [
+ tagged_item.tag
+ for tagged_item in account.tagged_items.filter(tag__name__in=normalized).select_related("tag")
+ ]
account.tagged_items.filter(tag__name__in=normalized).delete()
+ _schedule_account_tags_removed(account, removed_tags, actor=None, workflow_id=workflow_id)
elif mode == "set":
_set_tags(normalized, account, workflow_id=workflow_id)
else:
@@ -900,18 +905,23 @@ def _set_tags(
tagged_item_objects.append(tagged_item_instance)
if created:
added_tags.append(tag_instance)
- for tagged_item in account.tagged_items.exclude(tag__name__in=deduped_tags):
+ removed_tags: list[Tag] = []
+ for tagged_item in account.tagged_items.exclude(tag__name__in=deduped_tags).select_related("tag"):
+ removed_tags.append(tagged_item.tag)
tagged_item.delete()
Tag.objects.filter(Q(team_id=account.team_id) & Q(tagged_items__isnull=True)).delete()
account.prefetched_tags = tagged_item_objects # type: ignore[attr-defined]
_schedule_account_tags_added(account, added_tags, actor, workflow_id=workflow_id)
+ _schedule_account_tags_removed(account, removed_tags, actor, workflow_id=workflow_id)
def _schedule_account_tags_added(
account: Account, tags: list[Tag], actor: "User | None", workflow_id: str | None = None
) -> None:
- """Single emission point for $account_tag_added: post-commit, newly created rows only —
- so a workflow re-adding its own trigger tag fires nothing."""
+ """Emit $account_tag_added after commit for newly created rows only.
+
+ A workflow that adds its trigger tag again must not emit another event.
+ """
if not tags:
return
@@ -924,6 +934,22 @@ def _schedule_account_tags_added(
transaction.on_commit(emit)
+def _schedule_account_tags_removed(
+ account: Account, tags: list[Tag], actor: "User | None", workflow_id: str | None = None
+) -> None:
+ """Emit $account_tag_removed after commit for deleted rows only."""
+ if not tags:
+ return
+
+ def emit() -> None:
+ try:
+ emit_account_tags_removed(account, tags, actor, workflow_id=workflow_id)
+ except Exception as e:
+ capture_exception(e)
+
+ transaction.on_commit(emit)
+
+
def _log_activity_swallowing(
*,
instance,
diff --git a/products/customer_analytics/backend/test/test_events.py b/products/customer_analytics/backend/test/test_events.py
index 7b5c355371b2..eede186181d2 100644
--- a/products/customer_analytics/backend/test/test_events.py
+++ b/products/customer_analytics/backend/test/test_events.py
@@ -18,12 +18,12 @@ from products.customer_analytics.backend.test.factories import create_account, c
@patch("products.customer_analytics.backend.events.capture_batch_internal")
-class TestAccountTagAddedEvent(BaseTest):
+class TestAccountTagEvent(BaseTest):
def setUp(self):
super().setUp()
self.account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")
- def _add_tags(self, tags, tags_mode="add"):
+ def _update_tags(self, tags, tags_mode="add"):
with self.captureOnCommitCallbacks(execute=True):
result = facade.update_external_account(
self.team.id, "acme-1", relationship_assignments={}, tags=tags, tags_mode=tags_mode
@@ -36,7 +36,7 @@ class TestAccountTagAddedEvent(BaseTest):
config.account_group_type_index = 1
config.save()
- self._add_tags(["enterprise"])
+ self._update_tags(["enterprise"])
mock_capture.assert_called_once()
kwargs = mock_capture.call_args.kwargs
@@ -52,23 +52,50 @@ class TestAccountTagAddedEvent(BaseTest):
assert properties["actor_type"] == "system"
assert properties["$groups"] == {"account": "acme-1"}
+ def test_external_tag_remove_emits_one_event(self, mock_capture):
+ self._update_tags(["enterprise"])
+ mock_capture.reset_mock()
+
+ self._update_tags(["enterprise"], tags_mode="remove")
+
+ mock_capture.assert_called_once()
+ kwargs = mock_capture.call_args.kwargs
+ assert kwargs["token"] == self.team.api_token
+ (event,) = kwargs["events"]
+ assert event["event"] == "$account_tag_removed"
+ assert event["distinct_id"] == f"account:{self.account.id}"
+ properties = event["properties"]
+ assert properties["tag"] == "enterprise"
+ assert properties["account_id"] == str(self.account.id)
+ assert properties["account_external_id"] == "acme-1"
+ assert properties["account_name"] == "Acme Corp"
+ assert properties["actor_type"] == "system"
+
def test_re_adding_existing_tag_emits_nothing(self, mock_capture):
- self._add_tags(["enterprise"])
+ self._update_tags(["enterprise"])
mock_capture.reset_mock()
- self._add_tags(["enterprise"])
+ self._update_tags(["enterprise"])
mock_capture.assert_not_called()
- def test_set_mode_emits_only_newly_added_tags(self, mock_capture):
- self._add_tags(["old"])
+ def test_removing_missing_tag_emits_nothing(self, mock_capture):
+ self._update_tags(["enterprise"], tags_mode="remove")
+
+ mock_capture.assert_not_called()
+
+ def test_set_mode_emits_added_and_removed_events(self, mock_capture):
+ self._update_tags(["old"])
mock_capture.reset_mock()
- self._add_tags(["old", "new"], tags_mode="set")
+ self._update_tags(["new"], tags_mode="set")
- mock_capture.assert_called_once()
- (event,) = mock_capture.call_args.kwargs["events"]
- assert event["properties"]["tag"] == "new"
+ assert mock_capture.call_count == 2
+ events = [call.kwargs["events"][0] for call in mock_capture.call_args_list]
+ assert [(event["event"], event["properties"]["tag"]) for event in events] == [
+ ("$account_tag_added", "new"),
+ ("$account_tag_removed", "old"),
+ ]
def test_view_update_emits_with_user_actor(self, mock_capture):
with self.captureOnCommitCallbacks(execute=True):
@@ -88,8 +115,30 @@ class TestAccountTagAddedEvent(BaseTest):
assert event["properties"]["actor_type"] == "user"
assert event["properties"]["actor_email"] == self.user.email
+ def test_view_removal_emits_with_user_actor(self, mock_capture):
+ self._update_tags(["enterprise"])
+ mock_capture.reset_mock()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ facade.update_account_for_view(
+ team_id=self.team.id,
+ account_id=str(self.account.id),
+ input=contracts.UpdateAccountInput(tags=[]),
+ user_access_control=UserAccessControl(user=self.user, team=self.team),
+ required_level="editor",
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ mock_capture.assert_called_once()
+ (event,) = mock_capture.call_args.kwargs["events"]
+ assert event["event"] == "$account_tag_removed"
+ assert event["properties"]["actor_type"] == "user"
+ assert event["properties"]["actor_email"] == self.user.email
+
def test_event_without_account_group_type_has_no_groups(self, mock_capture):
- self._add_tags(["enterprise"])
+ self._update_tags(["enterprise"])
mock_capture.assert_called_once()
(event,) = mock_capture.call_args.kwargs["events"]
@@ -112,7 +161,7 @@ class TestAccountTagAddedEvent(BaseTest):
mock_capture.return_value = CaptureInternalResult(status_code=503, error={"error": "transport_error"})
with patch("products.customer_analytics.backend.facade.api.capture_exception") as mock_capture_exception:
- self._add_tags(["enterprise"])
+ self._update_tags(["enterprise"])
mock_capture_exception.assert_called_once()