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(customer-analytics): emit $account_custom_property_changed event (#73330)

Arthur Moreira de Deusf08dc2f4239f
diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.ts
index 74774e108746..638d5b447ac3 100644
--- a/nodejs/src/cdp/async-functions/customer_analytics.ts
+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts
@@ -147,15 +147,22 @@ registerAsyncFunction('postHogSetAccountProperties', {
const team = await getTeamWithSecretToken(context, 'postHogSetAccountProperties')
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${team.secret_api_token}`,
+ }
+
+ const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow
+ if (hogFlow?.id) {
+ headers['X-PostHog-Hog-Flow-Id'] = hogFlow.id
+ }
+
result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({
type: 'fetch',
url: `${context.siteUrl}/api/customer_analytics/external/account/custom_property_values`,
method: 'PATCH',
body: JSON.stringify({ external_id: externalId, properties }),
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${team.secret_api_token}`,
- },
+ headers,
})
},
diff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.md
index 5f0208405051..5267db81c9e6 100644
--- a/products/customer_analytics/backend/COMPROMISES.md
+++ b/products/customer_analytics/backend/COMPROMISES.md
@@ -91,6 +91,32 @@ Cutover checklist — when done, the sync and this section are deleted:
(members are deactivated or removed from the org, not deleted); if it bites, archive the
destinations explicitly in the user-deletion flow rather than reintroducing a signal.
+## Account custom property changed workflow trigger
+
+- **Volatile synced columns can flood workflows.** A view column that genuinely changes for many
+ accounts each sync emits one `$account_custom_property_changed` event — and starts one workflow
+ run — per account per sync run. No cap and no emission-volume observability. Acceptable while the
+ product is internal-only; before external exposure add emission counts to `SyncResult` and
+ guidance to trigger on stable columns.
+- **Multi-property triggers fan out.** One event per changed property, so one run per property,
+ never one per batch write. The trigger UI warns; routing logic is the workflow author's job.
+- **Cross-workflow loops are damped, not prevented.** Same-value writes never emit and frequency
+ masking caps rate, but value-flapping loops (workflow A sets X→1, triggering B which sets X→2, …)
+ depend on runtime values and cannot be detected statically. The save-time cycle advisory is
+ best-effort — static tag/property references only, never a save blocker.
+- **Frequency options are account-keyed because account events carry no person.** The generic event
+ trigger's frequency options hash on `{person.id}`, which resolves empty on person-less events and
+ would mask globally across accounts. CA triggers ship account-keyed options; the generic event
+ trigger keeps its person-keyed options and retains this gap for person-less events.
+- **current/previous are event properties, not workflow variables.** Same `{event.properties.*}`
+ templating access everywhere; auto-populated variables would need executor and trigger-schema
+ changes. Revisit only if variable semantics (mutation, Variables taxonomic category) are needed.
+ The values land as analytics events in the team's own project (the established pattern —
+ conversation events carry old/new status and truncated message content the same way), so they
+ are visible to anyone with project access, like the rest of the account's data.
+- **No unset/delete emission.** No value-delete path exists; if one is added, its author decides
+ whether removal counts as a change.
+
## Tech debt
- **Account property writes have no single choke point.** `Account._properties` is mutated from four
diff --git a/products/customer_analytics/backend/events.py b/products/customer_analytics/backend/events.py
index 7a769b1dcc25..2197f8e9faae 100644
--- a/products/customer_analytics/backend/events.py
+++ b/products/customer_analytics/backend/events.py
@@ -6,6 +6,7 @@ to an account, notify its CSM"). Events are sent to the customer's PostHog
project via their team's API token.
"""
+from datetime import datetime
from typing import Any
from posthog.api.capture import capture_batch_internal
@@ -13,7 +14,7 @@ from posthog.models.group_type_mapping import get_group_types_for_project
from posthog.models.tag import Tag
from posthog.models.user import User
-from products.customer_analytics.backend.models import Account
+from products.customer_analytics.backend.models import Account, CustomPropertyDefinition
EVENT_SOURCE = "customer_analytics_events"
@@ -36,12 +37,7 @@ def _account_groups(account: Account) -> dict[str, str] | None:
return None
-def emit_account_tags_added(
- account: Account, tags: list[Tag], actor: User | None, workflow_id: str | None = None
-) -> None:
- if not tags:
- return
-
+def _base_event_properties(account: Account, actor: User | None, workflow_id: str | None) -> dict[str, Any]:
properties: dict[str, Any] = {
"account_id": str(account.id),
"account_external_id": account.external_id,
@@ -54,13 +50,29 @@ def emit_account_tags_added(
groups = _account_groups(account)
if groups:
properties["$groups"] = groups
+ return properties
+
+
+def _event_distinct_id(account: Account, actor: User | None) -> str:
+ return actor.distinct_id if actor and actor.distinct_id else f"account:{account.id}"
+
+
+def _json_value(value: Any) -> Any:
+ return value.isoformat() if isinstance(value, datetime) else value
+
+
+def emit_account_tags_added(
+ account: Account, tags: list[Tag], actor: User | None, workflow_id: str | None = None
+) -> None:
+ if not tags:
+ return
- distinct_id = actor.distinct_id if actor and actor.distinct_id else f"account:{account.id}"
+ properties = _base_event_properties(account, actor, workflow_id)
capture_batch_internal(
events=[
{
"event": "$account_tag_added",
- "distinct_id": distinct_id,
+ "distinct_id": _event_distinct_id(account, actor),
"properties": {**properties, "tag": tag.name, "tag_id": str(tag.id)},
}
for tag in tags
@@ -68,3 +80,31 @@ def emit_account_tags_added(
token=account.team.api_token,
event_source=EVENT_SOURCE,
).raise_for_status()
+
+
+def emit_account_custom_property_changed(
+ account: Account,
+ definition: CustomPropertyDefinition,
+ previous_value: Any,
+ current_value: Any,
+ actor: User | None,
+ workflow_id: str | None = None,
+) -> None:
+ capture_batch_internal(
+ events=[
+ {
+ "event": "$account_custom_property_changed",
+ "distinct_id": _event_distinct_id(account, actor),
+ "properties": {
+ **_base_event_properties(account, actor, workflow_id),
+ "property_id": str(definition.id),
+ "property_name": definition.name,
+ "data_type": definition.data_type.value,
+ "previous_value": _json_value(previous_value),
+ "current_value": _json_value(current_value),
+ },
+ }
+ ],
+ token=account.team.api_token,
+ event_source=EVENT_SOURCE,
+ ).raise_for_status()
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index f8c3ade7e209..37c89abe353e 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -566,6 +566,7 @@ def set_external_account_custom_properties(
*,
properties: dict[str, Any],
created_by_id: int | None = None,
+ workflow_id: str | None = None,
) -> contracts.ExternalAccountCustomPropertiesResult:
"""Set custom property values on an account by definition id, for the external API.
@@ -594,6 +595,7 @@ def set_external_account_custom_properties(
account_id=account.id,
properties=properties,
created_by_id=created_by_id,
+ workflow_id=workflow_id,
)
except _custom_property_values_logic.CustomPropertyDefinitionNotFound as exc:
return contracts.ExternalAccountCustomPropertiesResult(
@@ -2392,7 +2394,7 @@ def set_custom_property_value(
definition_id: str | UUID,
value: Any,
*,
- created_by_id: int | None = None,
+ actor: "User | None" = None,
) -> contracts.CustomPropertyValue:
if _source_backed_definition_ids(team_id, [definition_id]):
raise CustomPropertyValueSourceManaged(
@@ -2403,7 +2405,8 @@ def set_custom_property_value(
account_id=account_id,
definition_id=definition_id,
value=value,
- created_by_id=created_by_id,
+ created_by_id=actor.id if actor else None,
+ actor=actor,
)
return _to_custom_property_value(row)
diff --git a/products/customer_analytics/backend/logic/custom_property_values.py b/products/customer_analytics/backend/logic/custom_property_values.py
index 179361616adc..c3a82da61ceb 100644
--- a/products/customer_analytics/backend/logic/custom_property_values.py
+++ b/products/customer_analytics/backend/logic/custom_property_values.py
@@ -15,6 +15,10 @@ from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.utils import timezone
+from posthog.exceptions_capture import capture_exception
+from posthog.models.user import User
+
+from products.customer_analytics.backend.events import emit_account_custom_property_changed
from products.customer_analytics.backend.models import (
Account,
CustomPropertyDefinition,
@@ -65,6 +69,8 @@ def set_custom_property_value(
definition_id: str | UUID,
value: Any,
created_by_id: int | None = None,
+ actor: User | None = None,
+ workflow_id: str | None = None,
) -> CustomPropertyValue:
"""Set an account's value for a custom property, preserving history.
@@ -82,7 +88,13 @@ def set_custom_property_value(
raise CustomPropertyDefinitionNotFound(definition_id) from exc
_assert_account_in_team(team_id=team_id, account_id=account_id)
return _set_value(
- team_id=team_id, account_id=account_id, definition=definition, value=value, created_by_id=created_by_id
+ team_id=team_id,
+ account_id=account_id,
+ definition=definition,
+ value=value,
+ created_by_id=created_by_id,
+ actor=actor,
+ workflow_id=workflow_id,
)
@@ -92,6 +104,8 @@ def set_account_custom_properties_by_id(
account_id: str | UUID,
properties: dict[str, Any],
created_by_id: int | None = None,
+ actor: User | None = None,
+ workflow_id: str | None = None,
) -> list[CustomPropertyValue]:
"""Set several of an account's custom property values, addressing each by definition id.
@@ -112,7 +126,13 @@ def set_account_custom_properties_by_id(
raise CustomPropertyDefinitionNotFound(definition_id) from exc
try:
row = _set_value(
- team_id=team_id, account_id=account_id, definition=definition, value=value, created_by_id=created_by_id
+ team_id=team_id,
+ account_id=account_id,
+ definition=definition,
+ value=value,
+ created_by_id=created_by_id,
+ actor=actor,
+ workflow_id=workflow_id,
)
except InvalidCustomPropertyValue as exc:
exc.field = str(definition_id)
@@ -128,14 +148,18 @@ def _set_value(
definition: CustomPropertyDefinition,
value: Any,
created_by_id: int | None,
+ actor: User | None = None,
+ workflow_id: str | None = None,
) -> CustomPropertyValue:
"""Coerce `value` and atomically supersede the account's active row for `definition`."""
column, coerced = _coerce_to_column(definition, value)
try:
with transaction.atomic():
- CustomPropertyValue.objects.for_team(team_id).filter(
+ active_rows = CustomPropertyValue.objects.for_team(team_id).filter(
account_id=account_id, definition_id=definition.id, is_deleted=False
- ).update(is_deleted=True)
+ )
+ previous_row = active_rows.first()
+ active_rows.update(is_deleted=True)
row = CustomPropertyValue.objects.for_team(team_id).create(
team_id=team_id,
account_id=account_id,
@@ -143,6 +167,15 @@ def _set_value(
created_by_id=created_by_id,
**{column: coerced},
)
+ _schedule_value_changed_event(
+ team_id=team_id,
+ account_id=account_id,
+ definition=definition,
+ previous_row=previous_row,
+ current_value=coerced,
+ actor=actor,
+ workflow_id=workflow_id,
+ )
except IntegrityError as exc:
if _is_active_value_conflict(exc):
raise CustomPropertyValueConflict(
@@ -155,6 +188,46 @@ def _set_value(
return row
+def _schedule_value_changed_event(
+ *,
+ team_id: int,
+ account_id: str | UUID,
+ definition: CustomPropertyDefinition,
+ previous_row: CustomPropertyValue | None,
+ current_value: CoercedValue,
+ actor: User | None,
+ workflow_id: str | None,
+) -> None:
+ """Emit $account_custom_property_changed post-commit when the stored value actually changes.
+
+ A first set emits with a null previous_value. Rewriting the same value stays silent: the view
+ sync rewrites every value each run, and a workflow re-setting the same value must not
+ retrigger itself.
+ """
+ previous_value: CoercedValue | None = None
+ if previous_row is not None:
+ previous_row.definition = definition
+ previous_value = value_of(previous_row)
+ if previous_value == current_value:
+ return
+ account = Account.objects.for_team(team_id).select_related("team").get(id=account_id)
+
+ def emit() -> None:
+ try:
+ emit_account_custom_property_changed(
+ account=account,
+ definition=definition,
+ previous_value=previous_value,
+ current_value=current_value,
+ actor=actor,
+ workflow_id=workflow_id,
+ )
+ except Exception as e:
+ capture_exception(e)
+
+ transaction.on_commit(emit)
+
+
def _is_active_value_conflict(exc: IntegrityError) -> bool:
return ACTIVE_VALUE_CONSTRAINT_NAME in str(exc)
diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.py
index b226358f28dc..5cc8f04c2a27 100644
--- a/products/customer_analytics/backend/presentation/views/external.py
+++ b/products/customer_analytics/backend/presentation/views/external.py
@@ -550,7 +550,9 @@ class ExternalAccountCustomPropertiesView(APIView):
if not external_id:
return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)
- result = facade.set_external_account_custom_properties(team.id, external_id, properties=data["properties"])
+ result = facade.set_external_account_custom_properties(
+ team.id, external_id, properties=data["properties"], workflow_id=_workflow_id_from_request(request)
+ )
if result.values is None:
return _custom_properties_error_response(result)
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index fc1c9e8399ee..84e961eb7bce 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -1318,7 +1318,7 @@ class CustomPropertyValueViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
account_id=account_id,
definition_id=write.validated_data["definition"],
value=write.validated_data["value"],
- created_by_id=request.user.id,
+ actor=cast(User, request.user),
)
except api.Account_DoesNotExist:
# The account passed the access pre-check but was deleted before the write committed.
diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.py
index 37fbe875f2e1..3f66314e4e13 100644
--- a/products/customer_analytics/backend/test/test_custom_property_values.py
+++ b/products/customer_analytics/backend/test/test_custom_property_values.py
@@ -378,9 +378,7 @@ class TestCustomPropertyValueFacade(BaseTest):
def test_set_returns_a_contract_with_the_typed_value(self, _name, display_type, value, expected_value):
definition = create_custom_property_definition(team_id=self.team.id, name=_name, display_type=display_type)
- result = facade.set_custom_property_value(
- self.team.id, self.account.id, definition.id, value, created_by_id=self.user.id
- )
+ result = facade.set_custom_property_value(self.team.id, self.account.id, definition.id, value, actor=self.user)
assert isinstance(result, contracts.CustomPropertyValue)
assert result.value == expected_value
diff --git a/products/customer_analytics/backend/test/test_events.py b/products/customer_analytics/backend/test/test_events.py
index f15140e35e2c..7b8a06a8b9f0 100644
--- a/products/customer_analytics/backend/test/test_events.py
+++ b/products/customer_analytics/backend/test/test_events.py
@@ -3,6 +3,8 @@ from unittest.mock import patch
from django.db import transaction
+from parameterized import parameterized
+
from posthog.api.capture import CaptureInternalResult
from posthog.rbac.user_access_control import UserAccessControl
from posthog.test.persons import create_group_type_mapping
@@ -11,7 +13,7 @@ from products.customer_analytics.backend.facade import (
api as facade,
contracts,
)
-from products.customer_analytics.backend.test.factories import create_account
+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
@patch("products.customer_analytics.backend.events.capture_batch_internal")
@@ -112,3 +114,161 @@ class TestAccountTagAddedEvent(BaseTest):
self._add_tags(["enterprise"])
mock_capture_exception.assert_called_once()
+
+
+WORKFLOW_ID = "123e4567-e89b-12d3-a456-426614174000"
+
+
+@patch("products.customer_analytics.backend.events.capture_batch_internal")
+class TestAccountCustomPropertyChangedEvent(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")
+ create_group_type_mapping(team=self.team, project=self.team.project, group_type="account", group_type_index=1)
+ config = self.team.customer_analytics_config
+ config.account_group_type_index = 1
+ config.save()
+
+ def _set_value(self, definition, value, **kwargs):
+ with self.captureOnCommitCallbacks(execute=True):
+ facade.set_custom_property_value(
+ team_id=self.team.id,
+ account_id=str(self.account.id),
+ definition_id=str(definition.id),
+ value=value,
+ **kwargs,
+ )
+
+ @parameterized.expand(
+ [
+ ("text", "silver", "gold", "silver", "gold", "string"),
+ ("number", 1.5, 2.5, 1.5, 2.5, "numeric"),
+ ("boolean", True, False, True, False, "boolean"),
+ (
+ "datetime",
+ "2026-01-01T00:00:00Z",
+ "2026-02-01T00:00:00Z",
+ "2026-01-01T00:00:00+00:00",
+ "2026-02-01T00:00:00+00:00",
+ "datetime",
+ ),
+ ]
+ )
+ def test_change_emits_event_with_previous_and_current(
+ self, mock_capture, display_type, initial, changed, expected_previous, expected_current, expected_data_type
+ ):
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan", display_type=display_type)
+ self._set_value(definition, initial)
+ mock_capture.reset_mock()
+
+ self._set_value(definition, changed)
+
+ 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_custom_property_changed"
+ assert event["distinct_id"] == f"account:{self.account.id}"
+ properties = event["properties"]
+ assert properties["property_id"] == str(definition.id)
+ assert properties["property_name"] == "Plan"
+ assert properties["data_type"] == expected_data_type
+ assert properties["previous_value"] == expected_previous
+ assert properties["current_value"] == expected_current
+ 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"
+ assert properties["$groups"] == {"account": "acme-1"}
+
+ def test_first_set_emits_with_null_previous_value(self, mock_capture):
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+
+ self._set_value(definition, "gold")
+
+ mock_capture.assert_called_once()
+ (event,) = mock_capture.call_args.kwargs["events"]
+ assert event["event"] == "$account_custom_property_changed"
+ assert event["properties"]["previous_value"] is None
+ assert event["properties"]["current_value"] == "gold"
+
+ @parameterized.expand(
+ [
+ ("text", "gold"),
+ ("number", 1.5),
+ ("boolean", True),
+ ("datetime", "2026-01-01T00:00:00Z"),
+ ]
+ )
+ def test_same_value_write_emits_nothing(self, mock_capture, display_type, value):
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan", display_type=display_type)
+ self._set_value(definition, value)
+ mock_capture.reset_mock()
+
+ self._set_value(definition, value)
+
+ mock_capture.assert_not_called()
+
+ def test_no_event_when_transaction_rolls_back(self, mock_capture):
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ self._set_value(definition, "silver")
+ mock_capture.reset_mock()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ try:
+ with transaction.atomic():
+ facade.set_custom_property_value(
+ team_id=self.team.id,
+ account_id=str(self.account.id),
+ definition_id=str(definition.id),
+ value="gold",
+ )
+ raise RuntimeError("boom")
+ except RuntimeError:
+ pass
+
+ mock_capture.assert_not_called()
+
+ def test_capture_failure_is_reported_not_raised(self, mock_capture):
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ self._set_value(definition, "silver")
+ mock_capture.reset_mock()
+ mock_capture.return_value = CaptureInternalResult(status_code=503, error={"error": "transport_error"})
+
+ with patch(
+ "products.customer_analytics.backend.logic.custom_property_values.capture_exception"
+ ) as mock_capture_exception:
+ self._set_value(definition, "gold")
+
+ mock_capture_exception.assert_called_once()
+ (value,) = facade.list_active_custom_property_values(self.team.id, str(self.account.id))
+ assert value.value == "gold"
+
+ def test_workflow_write_sets_workflow_actor(self, mock_capture):
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ self._set_value(definition, "silver")
+ mock_capture.reset_mock()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ result = facade.set_external_account_custom_properties(
+ self.team.id, "acme-1", properties={str(definition.id): "gold"}, workflow_id=WORKFLOW_ID
+ )
+ assert result.error is None
+
+ mock_capture.assert_called_once()
+ (event,) = mock_capture.call_args.kwargs["events"]
+ assert event["properties"]["actor_type"] == "workflow"
+ assert event["properties"]["workflow_id"] == WORKFLOW_ID
+
+ def test_user_actor_populates_actor_fields(self, mock_capture):
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ self._set_value(definition, "silver")
+ mock_capture.reset_mock()
+
+ self._set_value(definition, "gold", actor=self.user)
+
+ mock_capture.assert_called_once()
+ (event,) = mock_capture.call_args.kwargs["events"]
+ assert event["distinct_id"] == self.user.distinct_id
+ assert event["properties"]["actor_type"] == "user"
+ assert event["properties"]["actor_email"] == self.user.email