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): sync warehouse custom properties on workflow account create (#75585)

Arthur Moreira de Deus80cca6024d32
diff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.md
index c142a52e477e..2aa5908fe1ba 100644
--- a/products/customer_analytics/backend/COMPROMISES.md
+++ b/products/customer_analytics/backend/COMPROMISES.md
@@ -32,6 +32,18 @@ Shortcuts taken to ship the first version. Revisit when they bite.
- **Initial sync is best-effort.** Saving an enabled source enqueues a sync on commit so values
populate without waiting for the next materialization. If the broker is down the save still
succeeds and the enqueue is dropped (logged to error tracking) — the next materialization recovers.
+- **Create-path sync is synchronous, best-effort, and workflow-only.** When the external create
+ endpoint is called by a workflow "Create account" step (the `X-PostHog-Hog-Flow-Id` header),
+ it syncs warehouse-backed custom properties for the new account inline — scoped to its external
+ id, materialized views only — so the next workflow step can read the values. Creates without the
+ header skip the sync, which keeps the per-request warehouse fan-out off the general create path;
+ the header is caller-supplied, so a token holder can opt in by faking it — same trust level as
+ the existing workflow attribution. Failures are captured and swallowed: creation never fails,
+ and no sync outcome is recorded (streaks and `last_synced_at` belong to the scheduled full
+ sync). Values are as fresh as the last materialization. All enabled sources sync, not just
+ properties the workflow references — read-side usage isn't indexed, and one filtered query per
+ view is cheap. If the added request latency bites, narrow to workflow-referenced properties or
+ make the step poll.
- **v2 materialization only.** v1 `run_workflow.py` is frozen and does not dispatch the sync; v1
teams get it after migrating to v2.
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 89a157063232..a647276ee53e 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -62,6 +62,7 @@ from products.customer_analytics.backend.logic.custom_property_definitions impor
coerce_is_big_number,
normalize_options,
)
+from products.customer_analytics.backend.logic.custom_property_sync import sync_custom_properties_for_account
from products.customer_analytics.backend.logic.event_stream_destination import (
archive_event_stream_destination,
send_test_slack_message as send_test_slack_message,
@@ -409,6 +410,8 @@ def create_external_account(
whether it was created; an existing account is returned untouched. The name comes from the
matching group's ``name`` property (fallback: the external id). Attribution goes to the
originating workflow (activity-log trigger) — there is no acting user on this path.
+ On workflow-originated creates, warehouse-backed custom properties are synced inline
+ (best-effort) so the response already carries them.
Raises ``AccountPropertiesValidationError`` / ``AccountConflictError`` (concurrent create)."""
existing = _get_external_account_by_external_id(team.pk, external_id)
if existing is not None:
@@ -417,6 +420,11 @@ def create_external_account(
account = create_account(
team=team, name=_account_name_from_group(team, external_id), external_id=external_id, trigger=trigger
)
+ if workflow_id is not None:
+ # Synchronous so the workflow can read the values in its next step; best-effort inside —
+ # a sync failure never fails the creation. Workflow-only to keep the per-request warehouse
+ # fan-out off the general create path.
+ sync_custom_properties_for_account(team_id=team.pk, external_id=external_id)
return _to_external_account(account), True
diff --git a/products/customer_analytics/backend/logic/custom_property_sync.py b/products/customer_analytics/backend/logic/custom_property_sync.py
index 8e0d4586a33e..b1995692d92e 100644
--- a/products/customer_analytics/backend/logic/custom_property_sync.py
+++ b/products/customer_analytics/backend/logic/custom_property_sync.py
@@ -4,6 +4,8 @@ Reads a configured view via HogQL, matches each row to an account by external_id
selected column as that account's custom property value (through set_custom_property_value).
`run_custom_property_sync` is the entrypoint the Celery task calls: it runs the sync and persists
the outcome (success/failure, auto-disable) onto the sources.
+A sync can be scoped to a single account via ``external_id`` — used by the external create path to
+populate a new account synchronously.
"""
import dataclasses
@@ -50,7 +52,9 @@ class SyncResult:
source_errors: dict[str, str] = dataclasses.field(default_factory=dict)
-def sync_custom_property_values(*, team_id: int, saved_query_id: str | UUID) -> SyncResult:
+def sync_custom_property_values(
+ *, team_id: int, saved_query_id: str | UUID, external_id: str | None = None
+) -> SyncResult:
sources = list(
CustomPropertySource.objects.for_team(team_id)
.filter(saved_query_id=saved_query_id, is_enabled=True)
@@ -82,7 +86,7 @@ def sync_custom_property_values(*, team_id: int, saved_query_id: str | UUID) ->
ordered = sorted(selected_columns)
column_index = {column: position for position, column in enumerate(ordered)}
- account_ids_by_external_id = _get_account_ids_by_external_id(team_id)
+ account_ids_by_external_id = _get_account_ids_by_external_id(team_id, external_id=external_id)
external_ids = sorted(account_ids_by_external_id)
team = Team.objects.get(id=team_id)
rows_by_key_column = {
@@ -114,8 +118,10 @@ def sync_custom_property_values(*, team_id: int, saved_query_id: str | UUID) ->
return result
-def _get_account_ids_by_external_id(team_id: int) -> dict[str, UUID]:
+def _get_account_ids_by_external_id(team_id: int, external_id: str | None = None) -> dict[str, UUID]:
accounts = Account.objects.for_team(team_id).exclude(external_id=None).exclude(external_id="")
+ if external_id is not None:
+ accounts = accounts.filter(external_id=external_id)
return {
external_id: account_id for external_id, account_id in accounts.values_list("external_id", "id") if external_id
}
@@ -243,3 +249,30 @@ def run_custom_property_sync(*, team_id: int, saved_query_id: str | UUID) -> Syn
source_errors=len(result.source_errors),
)
return result
+
+
+def sync_custom_properties_for_account(*, team_id: int, external_id: str) -> None:
+ """Best-effort synchronous population of warehouse-backed custom properties for one account.
+
+ Runs on the external create path so a workflow that creates an account can read the values
+ in its next step. Only materialized views are read — an unmaterialized view would run its raw
+ query inside the request. No sync outcome is recorded: failure streaks, auto-disable and
+ last_synced_at belong to the scheduled full sync.
+ """
+ # enrichment must never break account creation — the outer try also covers source discovery,
+ # which the queryset's laziness would otherwise let escape
+ try:
+ saved_query_ids = (
+ CustomPropertySource.objects.for_team(team_id)
+ .filter(is_enabled=True, source_column__isnull=False, saved_query__table__isnull=False)
+ .exclude(saved_query__deleted=True)
+ .values_list("saved_query_id", flat=True)
+ .distinct()
+ )
+ for saved_query_id in saved_query_ids:
+ try:
+ sync_custom_property_values(team_id=team_id, saved_query_id=saved_query_id, external_id=external_id)
+ except Exception as e:
+ capture_exception(e)
+ except Exception as e:
+ capture_exception(e)
diff --git a/products/customer_analytics/backend/logic/custom_property_sync_test.py b/products/customer_analytics/backend/logic/custom_property_sync_test.py
index 93ab9b3db613..1da3ff513cc4 100644
--- a/products/customer_analytics/backend/logic/custom_property_sync_test.py
+++ b/products/customer_analytics/backend/logic/custom_property_sync_test.py
@@ -11,6 +11,7 @@ from products.customer_analytics.backend.logic.custom_property_sync import (
_read_view,
record_sync_outcome,
run_custom_property_sync,
+ sync_custom_properties_for_account,
sync_custom_property_values,
)
from products.customer_analytics.backend.models import (
@@ -115,6 +116,28 @@ class CustomPropertySyncTest(TeamScopedTestMixin, BaseTest):
assert result.written == 0
assert result.unmatched_keys == 0
+ def test_external_id_scope_only_syncs_that_account(self):
+ self._source(self.mrr_def, "mrr")
+ # selected columns are sorted: mrr, org_id
+ with patch(_EXECUTE, return_value=_Response([(100.0, "acme")])):
+ result = sync_custom_property_values(team_id=self.team.id, saved_query_id=self.view.id, external_id="acme")
+
+ assert result.accounts_total == 1
+ assert result.written == 1
+ assert self._active(self.acme, self.mrr_def).value_num == 100.0
+ assert not CustomPropertyValue.objects.filter(account=self.globex).exists()
+
+ def test_external_id_scope_with_no_matching_account_writes_nothing(self):
+ self._source(self.mrr_def, "mrr")
+ with patch(_EXECUTE, return_value=_Response([])) as execute:
+ result = sync_custom_property_values(
+ team_id=self.team.id, saved_query_id=self.view.id, external_id="nobody"
+ )
+
+ assert result.accounts_total == 0
+ assert result.written == 0
+ execute.assert_not_called() # empty key set -> zero batches -> no ClickHouse query
+
def test_run_sync_records_success_outcome(self):
source = self._source(self.mrr_def, "mrr")
with patch(_EXECUTE, return_value=_Response([(100.0, "acme")])):
@@ -146,6 +169,66 @@ class CustomPropertySyncTest(TeamScopedTestMixin, BaseTest):
assert rows == [(100.0, "acme"), (200.0, "globex")]
+class SyncCustomPropertiesForAccountTest(TeamScopedTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ DataWarehouseTable = apps.get_model("warehouse_sources", "DataWarehouseTable")
+ self.table = DataWarehouseTable.objects.create(team=self.team, name="billing_view_mat", columns={})
+ self.view = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="billing_view", columns={"org_id": {}, "mrr": {}}, table=self.table
+ )
+ self.acme = Account.objects.create(team=self.team, name="Acme", external_id="acme")
+ self.mrr_def = CustomPropertyDefinition.objects.create(
+ team=self.team, name="MRR", display_type=DisplayType.NUMBER
+ )
+ self.source = CustomPropertySource.objects.create(
+ team=self.team,
+ definition=self.mrr_def,
+ saved_query=self.view,
+ source_column="mrr",
+ key_column="org_id",
+ )
+
+ def test_writes_values_for_the_account(self):
+ # selected columns are sorted: mrr, org_id
+ with patch(_EXECUTE, return_value=_Response([(100.0, "acme")])):
+ sync_custom_properties_for_account(team_id=self.team.id, external_id="acme")
+
+ value = CustomPropertyValue.objects.get(account=self.acme, definition=self.mrr_def, is_deleted=False)
+ assert value.value_num == 100.0
+
+ def test_skips_unmaterialized_views(self):
+ self.view.table = None
+ self.view.save()
+ with patch(_EXECUTE) as execute:
+ sync_custom_properties_for_account(team_id=self.team.id, external_id="acme")
+
+ execute.assert_not_called()
+
+ def test_skips_disabled_sources(self):
+ self.source.is_enabled = False
+ self.source.save()
+ with patch(_EXECUTE) as execute:
+ sync_custom_properties_for_account(team_id=self.team.id, external_id="acme")
+
+ execute.assert_not_called()
+
+ def test_swallows_source_discovery_errors(self):
+ discovery = "products.customer_analytics.backend.logic.custom_property_sync.CustomPropertySource"
+ with patch(discovery) as source_model:
+ source_model.objects.for_team.side_effect = Exception("db down")
+ sync_custom_properties_for_account(team_id=self.team.id, external_id="acme")
+
+ def test_swallows_errors_and_records_no_sync_outcome(self):
+ with patch(_EXECUTE, side_effect=Exception("clickhouse down")):
+ sync_custom_properties_for_account(team_id=self.team.id, external_id="acme")
+
+ self.source.refresh_from_db()
+ assert self.source.last_synced_at is None
+ assert self.source.consecutive_failures == 0
+ assert self.source.is_enabled is True
+
+
@patch("posthoganalytics.feature_enabled", new=Mock(return_value=True))
class ReadViewAccessControlTest(ClickhouseTestMixin, TeamScopedTestMixin, BaseTest):
def test_userless_sync_reads_view_despite_warehouse_access_control(self):
diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.py
index 4dcabea5e51d..79503d395c4c 100644
--- a/products/customer_analytics/backend/test/test_external.py
+++ b/products/customer_analytics/backend/test/test_external.py
@@ -4,6 +4,8 @@ from uuid import uuid4
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.apps import apps
+
from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
@@ -17,12 +19,20 @@ from products.customer_analytics.backend.models import (
Account,
AccountRelationship,
AccountRelationshipDefinition,
+ CustomPropertySource,
CustomPropertyValue,
DisplayType,
)
from products.customer_analytics.backend.models.account import AccountProperties
from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
+_SYNC_EXECUTE = "products.customer_analytics.backend.logic.custom_property_sync.execute_hogql_query"
+
+
+class _SyncResponse:
+ def __init__(self, results):
+ self.results = results
+
class TestExternalAccountAPI(APIBaseTest):
def setUp(self):
@@ -403,6 +413,53 @@ class TestExternalAccountAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Account.objects.for_team(self.team.id).get(external_id="shared-key").name, "shared-key")
+ def _create_warehouse_backed_property(self):
+ DataWarehouseTable = apps.get_model("warehouse_sources", "DataWarehouseTable")
+ DataWarehouseSavedQuery = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
+ table = DataWarehouseTable.objects.create(team=self.team, name="billing_view_mat", columns={})
+ view = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="billing_view", columns={"org_id": {}, "mrr": {}}, table=table
+ )
+ definition = create_custom_property_definition(
+ team_id=self.team.id, name="MRR", display_type=DisplayType.NUMBER
+ )
+ return CustomPropertySource.objects.unscoped().create(
+ team=self.team, definition=definition, saved_query=view, source_column="mrr", key_column="org_id"
+ )
+
+ def test_post_from_workflow_returns_warehouse_custom_properties_synced_on_create(self):
+ self._create_warehouse_backed_property()
+ # selected columns are sorted: mrr, org_id
+ with patch(_SYNC_EXECUTE, return_value=_SyncResponse([(100.0, "new-1")])):
+ response = self._post({"external_id": "new-1"}, HTTP_X_POSTHOG_HOG_FLOW_ID=str(uuid4()))
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["custom_properties"]["MRR"], 100.0)
+
+ def test_post_succeeds_when_property_sync_fails(self):
+ self._create_warehouse_backed_property()
+ with patch(_SYNC_EXECUTE, side_effect=Exception("clickhouse down")):
+ response = self._post({"external_id": "new-1"}, HTTP_X_POSTHOG_HOG_FLOW_ID=str(uuid4()))
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertIsNone(response.json()["custom_properties"]["MRR"])
+
+ def test_post_without_workflow_header_does_not_sync(self):
+ self._create_warehouse_backed_property()
+ with patch(_SYNC_EXECUTE) as execute:
+ response = self._post({"external_id": "new-1"})
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ execute.assert_not_called()
+
+ def test_post_existing_account_does_not_sync(self):
+ self._create_warehouse_backed_property()
+ with patch(_SYNC_EXECUTE) as execute:
+ response = self._post({"external_id": "acme-1"}, HTTP_X_POSTHOG_HOG_FLOW_ID=str(uuid4()))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ execute.assert_not_called()
+
class TestExternalAccountCustomPropertiesAPI(APIBaseTest):
def setUp(self):