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 custom-property values on view materialization (#67177)

Arthur Moreira de Deusc55742f175ad
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 73e75a4ea5fe..32ced233e5e5 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -51,6 +51,7 @@ class Product(StrEnum):
BATCH_EXPORT = "batch_export"
COHORTS = "cohorts"
CONVERSATIONS = "conversations"
+ CUSTOMER_ANALYTICS = "customer_analytics"
ENDPOINTS = "endpoints"
ENGINEERING_ANALYTICS = "engineering_analytics"
ERROR_TRACKING = "error_tracking"
@@ -89,6 +90,7 @@ class Product(StrEnum):
class Feature(StrEnum):
+ ACCOUNTS = "accounts"
ALERTING = "alerting"
BACKFILL = "backfill"
BEHAVIORAL_COHORTS = "behavioral_cohorts"
diff --git a/posthog/temporal/data_modeling/activities/succeed_materialization.py b/posthog/temporal/data_modeling/activities/succeed_materialization.py
index 9dd34d462538..c7dc7a5c9755 100644
--- a/posthog/temporal/data_modeling/activities/succeed_materialization.py
+++ b/posthog/temporal/data_modeling/activities/succeed_materialization.py
@@ -1,10 +1,14 @@
import datetime as dt
import dataclasses
+from django.db import transaction
+
+from celery import current_app
from structlog import get_logger
from structlog.contextvars import bind_contextvars
from temporalio import activity
+from posthog.exceptions_capture import capture_exception
from posthog.sync import database_sync_to_async_pool
from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobStatus, Node
@@ -51,9 +55,25 @@ def _succeed_node_and_data_modeling_job(inputs: SucceedMaterializationInputs):
job.last_run_at = dt.datetime.now(dt.UTC)
job.error = None
job.save()
+
+ if node is not None and node.saved_query_id is not None:
+ saved_query_id = str(node.saved_query_id)
+ team_id = inputs.team_id
+ transaction.on_commit(lambda: _enqueue_custom_property_sync(team_id, saved_query_id))
return node, job
+def _enqueue_custom_property_sync(team_id: int, saved_query_id: str) -> None:
+ try:
+ current_app.send_task(
+ "customer_analytics.process_custom_property_sync",
+ kwargs={"team_id": team_id, "saved_query_id": saved_query_id},
+ )
+ except Exception as e:
+ LOGGER.exception("custom_property_sync_enqueue_failed", team_id=team_id, saved_query_id=saved_query_id)
+ capture_exception(e)
+
+
@activity.defn
async def succeed_materialization_activity(inputs: SucceedMaterializationInputs) -> None:
bind_contextvars(team_id=inputs.team_id)
diff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.md
new file mode 100644
index 000000000000..afd28ae0ec5d
--- /dev/null
+++ b/products/customer_analytics/backend/COMPROMISES.md
@@ -0,0 +1,28 @@
+# Customer analytics — v1 compromises
+
+Shortcuts taken to ship the first version. Revisit when they bite.
+
+## Custom property view sync
+
+- **Celery, not Temporal.** The sync runs in a Celery task, not a dedicated Temporal workflow. No
+ durable retries and no run-level UI inspection — failures surface via `last_sync_error` on the
+ source + error tracking. Move to Temporal if we need durable retries, long-running syncs, or
+ per-run inspection.
+- **No retries.** A failed run is not retried; it records the failure (advancing the auto-disable
+ streak) and waits for the next materialization. Only transient write conflicts retry, in-logic.
+- **Direct dispatch by task name, not a signal.** Core (`succeed_materialization_activity`) enqueues
+ this product's sync task by name via `send_task`. A generic core signal the product subscribes to
+ would keep core ignorant of the consumer, but for a single consumer that isn't worth the wiring (a
+ signal definition + a receiver + an app-ready hook). By-name dispatch also keeps the product and
+ HogQL out of the data-modeling worker's process, since core imports nothing from here. Trade-off:
+ core hardcodes this consumer's task name. If a second consumer ever needs the materialization event,
+ switch to a core-owned signal (inversion of control) rather than adding another direct dispatch.
+- **No save-time column validation.** Creating/updating a source does not check that `source_column`
+ / `key_column` exist in the view's schema. A bad column surfaces as a per-source sync error (and
+ advances the auto-disable streak) on the next run, not as a 400 on save. Validate against the saved
+ query's `columns` at write time if the delayed feedback bites.
+- **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.
+- **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 732f23983a88..f2c6fbf8b89c 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -15,13 +15,16 @@ Do NOT:
- Import DRF, serializers, or HTTP concerns
"""
+from collections.abc import Iterable
from typing import TYPE_CHECKING, Any, Optional, cast
from uuid import UUID
+from django.apps import apps
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import Prefetch, Q
+from celery import current_app
from pydantic import ValidationError as PydanticValidationError
from posthog.api.tagged_item import set_tags_on_object
@@ -43,6 +46,7 @@ from products.customer_analytics.backend.models import (
CustomerJourney,
CustomerProfileConfig,
CustomPropertyDefinition,
+ CustomPropertySource,
)
from products.customer_analytics.backend.models.account import AccountProperties as _ModelAccountProperties
from products.notebooks.backend.facade import (
@@ -378,6 +382,13 @@ def set_external_account_custom_properties(
error=contracts.ExternalAccountCustomPropertiesError.ACCOUNT_NOT_FOUND
)
+ source_backed = _source_backed_definition_ids(team_id, list(properties.keys()))
+ if source_backed:
+ return contracts.ExternalAccountCustomPropertiesResult(
+ error=contracts.ExternalAccountCustomPropertiesError.SOURCE_MANAGED,
+ error_field=str(next(iter(source_backed))),
+ )
+
try:
with transaction.atomic():
rows = _custom_property_values_logic.set_account_custom_properties_by_id(
@@ -672,6 +683,7 @@ def _to_custom_property_definition_view(
created_by=definition.created_by_id,
updated_at=definition.updated_at,
references=references or [],
+ source=_definition_source_view(definition),
)
@@ -703,6 +715,16 @@ def _custom_property_references_by_definition_id(
}
+def _definition_source_view(definition: CustomPropertyDefinition) -> contracts.CustomPropertySourceView | None:
+ """The source bound to this definition (reverse one-to-one ``source``), or None. List reads
+ ``select_related("source")`` so this stays a cache hit; detail reads pay one extra query."""
+ try:
+ source = definition.source # type: ignore[attr-defined]
+ except CustomPropertySource.DoesNotExist:
+ return None
+ return _to_custom_property_source_view(source)
+
+
def list_custom_property_definitions(
team_id: int, offset: int, limit: int, *, user_access_control: "UserAccessControl"
) -> tuple[list[contracts.CustomPropertyDefinitionView], int]:
@@ -710,7 +732,7 @@ def list_custom_property_definitions(
``references`` (the workflows referencing each definition) is included only when the caller can
read workflows — see ``_can_read_workflow_references``."""
- queryset = CustomPropertyDefinition.objects.filter(team_id=team_id).order_by("name")
+ queryset = CustomPropertyDefinition.objects.filter(team_id=team_id).select_related("source").order_by("name")
total_count = queryset.count()
page = queryset[offset : offset + limit]
references = (
@@ -834,6 +856,138 @@ def delete_custom_property_definition(
return True
+# --- CustomPropertySource ---
+
+
+class CustomPropertySourceValidationError(Exception):
+ """Raised when a source's saved_query isn't a usable view for the team, or the definition is
+ already source-backed (→ 400)."""
+
+
+def _to_custom_property_source_view(source: CustomPropertySource) -> contracts.CustomPropertySourceView:
+ return contracts.CustomPropertySourceView(
+ id=source.id,
+ definition=source.definition_id,
+ saved_query=source.saved_query_id,
+ source_column=source.source_column,
+ key_column=source.key_column,
+ is_enabled=source.is_enabled,
+ consecutive_failures=source.consecutive_failures,
+ last_synced_at=source.last_synced_at,
+ last_sync_error=source.last_sync_error,
+ created_at=source.created_at,
+ created_by=source.created_by_id,
+ updated_at=source.updated_at,
+ )
+
+
+def _saved_query_belongs_to_team(team_id: int, saved_query_id) -> bool:
+ """Whether the saved query exists for this team and isn't soft-deleted. Uses ``apps.get_model`` so
+ customer_analytics never imports data_modeling (which isn't a dependency)."""
+ saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
+ return saved_query_model.objects.filter(id=saved_query_id, team_id=team_id).exclude(deleted=True).exists()
+
+
+def _enqueue_custom_property_sync(team_id: int, saved_query_id: str) -> None:
+ """Dispatch the sync task by name. Enqueue failure must not fail the originating write, so it's swallowed."""
+ try:
+ current_app.send_task(
+ "customer_analytics.process_custom_property_sync",
+ kwargs={"team_id": team_id, "saved_query_id": saved_query_id},
+ )
+ except Exception as e:
+ capture_exception(e)
+
+
+def _enqueue_sync_if_enabled(source: CustomPropertySource) -> None:
+ """Run an initial sync after the source is saved so its values populate immediately rather than
+ waiting for the next materialization. Skips disabled sources and ones whose view was deleted."""
+ if not source.is_enabled or source.saved_query_id is None:
+ return
+ team_id, saved_query_id = source.team_id, str(source.saved_query_id)
+ transaction.on_commit(lambda: _enqueue_custom_property_sync(team_id, saved_query_id))
+
+
+def list_custom_property_sources(
+ team_id: int, offset: int, limit: int
+) -> tuple[list[contracts.CustomPropertySourceView], int]:
+ """Custom-property sources for the team, newest first. Returns ``(page, total_count)``."""
+ queryset = CustomPropertySource.objects.for_team(team_id).order_by("-created_at")
+ total_count = queryset.count()
+ page = queryset[offset : offset + limit]
+ return [_to_custom_property_source_view(s) for s in page], total_count
+
+
+def get_custom_property_source(team_id: int, source_id: str) -> contracts.CustomPropertySourceView | None:
+ source = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).first()
+ return _to_custom_property_source_view(source) if source is not None else None
+
+
+def create_custom_property_source(
+ *,
+ team_id: int,
+ definition_id: str | UUID,
+ saved_query_id: str | UUID,
+ source_column: str,
+ key_column: str,
+ is_enabled: bool,
+ user: "User",
+) -> contracts.CustomPropertySourceView:
+ if not _saved_query_belongs_to_team(team_id, saved_query_id):
+ raise CustomPropertySourceValidationError("Saved query not found for this team.")
+ if _get_team_scoped(CustomPropertyDefinition, team_id, definition_id) is None:
+ raise CustomPropertySourceValidationError("Custom property definition not found for this team.")
+ try:
+ source = CustomPropertySource.objects.for_team(team_id).create(
+ team_id=team_id,
+ created_by=user,
+ definition_id=definition_id,
+ saved_query_id=saved_query_id,
+ source_column=source_column,
+ key_column=key_column,
+ is_enabled=is_enabled,
+ )
+ except IntegrityError as exc:
+ # Both FKs are team-validated above, so the only expected violation is the definition's
+ # one-to-one uniqueness; re-raise anything else instead of mislabeling it as a duplicate.
+ if "unique" not in str(exc).lower() and "duplicate" not in str(exc).lower():
+ raise
+ raise CustomPropertySourceValidationError("This custom property already has a source.")
+ _enqueue_sync_if_enabled(source)
+ return _to_custom_property_source_view(source)
+
+
+def update_custom_property_source(
+ *, team_id: int, source_id: str, fields: dict[str, Any]
+) -> contracts.CustomPropertySourceView | None:
+ """Apply ``fields`` (source_column / key_column / is_enabled) to a team-scoped source. Re-enabling
+ (is_enabled False→True) resets the failure streak and clears the last error. Returns None (→ 404)
+ when no source matches."""
+ source = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).first()
+ if source is None:
+ return None
+ reenabling = fields.get("is_enabled") is True and not source.is_enabled
+ columns_changed = any(
+ attr in fields and fields[attr] != getattr(source, attr) for attr in ("source_column", "key_column")
+ )
+ for attr, value in fields.items():
+ setattr(source, attr, value)
+ if reenabling:
+ source.consecutive_failures = 0
+ source.last_sync_error = None
+ source.save()
+ # Only re-sync on a change that affects what gets written — not on every (possibly no-op) PATCH.
+ if reenabling or columns_changed:
+ _enqueue_sync_if_enabled(source)
+ return _to_custom_property_source_view(source)
+
+
+def delete_custom_property_source(*, team_id: int, source_id: str) -> bool:
+ """Delete a team-scoped source. Returns False when none matched (→ 404)."""
+ deleted, _ = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).delete()
+ return deleted > 0
+
+
# --- CustomerJourney ---
@@ -1350,7 +1504,7 @@ def delete_account_notebook(
# --- shared resolution / access helpers for the CRUD paths ---
-def _get_team_scoped(model, team_id: int, pk: str):
+def _get_team_scoped(model, team_id: int, pk: str | UUID):
"""Fetch a team-scoped row by pk, or None (malformed/absent). Used by the
profile-config path, whose old viewset returned 404 for both."""
try:
@@ -1392,6 +1546,23 @@ CustomPropertyValueConflict = _custom_property_values_logic.CustomPropertyValueC
InvalidCustomPropertyValue = _custom_property_values_logic.InvalidCustomPropertyValue
+def _source_backed_definition_ids(team_id: int, definition_ids: Iterable[str | UUID]) -> set[UUID]:
+ """Definition ids from ``definition_ids`` that are backed by a view sync. Manual writes to these
+ are closed at the API layer (the sync writes them through the logic directly), so callers can't
+ fight the sync over the value."""
+ return set(
+ CustomPropertySource.objects.for_team(team_id)
+ .filter(definition_id__in=definition_ids)
+ .values_list("definition_id", flat=True)
+ )
+
+
+class CustomPropertyValueSourceManaged(Exception):
+ """Raised when a manual write targets a source-backed definition. The view sync writes such
+ definitions through the logic layer directly; the manual API path is closed so the two can't
+ fight over the value (→ 400)."""
+
+
def _to_custom_property_value(row: "CustomPropertyValue") -> contracts.CustomPropertyValue:
return contracts.CustomPropertyValue(
id=row.id,
@@ -1411,6 +1582,10 @@ def set_custom_property_value(
*,
created_by_id: int | None = None,
) -> contracts.CustomPropertyValue:
+ if _source_backed_definition_ids(team_id, [definition_id]):
+ raise CustomPropertyValueSourceManaged(
+ "This custom property is managed by a data warehouse source and can't be set manually."
+ )
row = _custom_property_values_logic.set_custom_property_value(
team_id=team_id,
account_id=account_id,
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index fb4debfdfa04..96748eba1c49 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -257,7 +257,8 @@ class CustomPropertyDefinitionView:
Defaults exist so the wrapping serializer can parse partial request bodies (see
:class:`AccountView`). ``created_by`` is the creator's user id (or ``None``), matching
the old model serializer's ``PrimaryKeyRelatedField`` output. ``references`` lists where the
- property is used (workflows), resolved by definition id.
+ property is used (workflows), resolved by definition id. ``source`` is the read-only
+ view-sync binding when one is configured for this definition, else ``None``.
"""
id: UUID | None = None
@@ -269,6 +270,32 @@ class CustomPropertyDefinitionView:
created_by: int | None = None
updated_at: datetime | None = None
references: list[CustomPropertyReference] = field(default_factory=list)
+ source: "CustomPropertySourceView | None" = None
+
+
+@stdlib_dataclass(frozen=True)
+class CustomPropertySourceView:
+ """A custom-property source: binds a materialized view's column to a definition, feeding its
+ values on each materialization.
+
+ ``definition`` / ``saved_query`` are ids (the definition this feeds, and the data-warehouse
+ saved query read from). ``last_sync_error`` is null when the last run succeeded or hasn't run.
+ Defaults exist so the wrapping serializer can parse partial request bodies (see
+ :class:`AccountView`).
+ """
+
+ id: UUID | None = None
+ definition: UUID | None = None
+ saved_query: UUID | None = None
+ source_column: str = ""
+ key_column: str = ""
+ is_enabled: bool = True
+ consecutive_failures: int = 0
+ last_synced_at: datetime | None = None
+ last_sync_error: str | None = None
+ created_at: datetime | None = None
+ created_by: int | None = None
+ updated_at: datetime | None = None
@stdlib_dataclass(frozen=True)
@@ -363,6 +390,7 @@ class ExternalAccountCustomPropertiesError(Enum):
INVALID_VALUE = "invalid_value"
CONFLICT = "conflict"
UPDATE_FAILED = "update_failed"
+ SOURCE_MANAGED = "source_managed"
@dataclass(frozen=True)
@@ -371,7 +399,8 @@ class ExternalAccountCustomPropertiesResult:
case to its exact HTTP status and error string without holding write logic.
Exactly one of ``values`` / ``error`` is set. ``error_field`` carries the offending
- property name for ``DEFINITION_NOT_FOUND`` / ``INVALID_VALUE`` failures; it is None otherwise.
+ property name for ``DEFINITION_NOT_FOUND`` / ``INVALID_VALUE`` / ``SOURCE_MANAGED`` failures;
+ it is None otherwise.
"""
values: list[CustomPropertyValue] | None = None
diff --git a/products/customer_analytics/backend/logic/custom_property_sync.py b/products/customer_analytics/backend/logic/custom_property_sync.py
new file mode 100644
index 000000000000..5eabc45e4081
--- /dev/null
+++ b/products/customer_analytics/backend/logic/custom_property_sync.py
@@ -0,0 +1,190 @@
+"""Bulk sync of materialized-view columns into account custom property values.
+
+Reads a configured view via HogQL, matches each row to an account by external_id, and writes the
+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.
+"""
+
+import dataclasses
+from typing import Any
+from uuid import UUID
+
+from django.db import transaction
+from django.utils import timezone
+
+from posthog.hogql import ast
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Team
+
+from products.customer_analytics.backend.logic.custom_property_values import (
+ CustomPropertyValueConflict,
+ InvalidCustomPropertyValue,
+ set_custom_property_value,
+)
+from products.customer_analytics.backend.models import Account, CustomPropertySource
+
+_WRITE_CONFLICT_RETRIES = 3
+
+# Mirrors data_modeling's CONSECUTIVE_TIMEOUTS_TO_PAUSE: auto-disable a source that keeps failing.
+MAX_CONSECUTIVE_SYNC_FAILURES = 5
+_MAX_ERROR_LENGTH = 500
+
+
+class SyncResult:
+ view_found: bool
+ written: int = 0
+ unmatched_keys: int = 0
+ source_errors: dict[str, str] = dataclasses.field(default_factory=dict)
+
+
+def sync_custom_property_values(*, team_id: int, saved_query_id: str | UUID) -> SyncResult:
+ sources = list(
+ CustomPropertySource.objects.for_team(team_id)
+ .filter(saved_query_id=saved_query_id, is_enabled=True)
+ .select_related("definition", "saved_query")
+ )
+ if not sources:
+ return SyncResult(view_found=True)
+
+ saved_query = sources[0].saved_query # every source for this view points at the same one
+ if saved_query is None or saved_query.deleted:
+ return SyncResult(view_found=False)
+
+ available_columns = set((saved_query.columns or {}).keys())
+ result = SyncResult(view_found=True)
+ usable: list[CustomPropertySource] = []
+ selected_columns: set[str] = set()
+ for source in sources:
+ missing = [column for column in (source.key_column, source.source_column) if column not in available_columns]
+ if missing:
+ result.source_errors[str(source.id)] = f"View {saved_query.name} has no column(s): {', '.join(missing)}"
+ continue
+ usable.append(source)
+ selected_columns.update((source.key_column, source.source_column))
+ if not usable:
+ return result
+
+ ordered = sorted(selected_columns)
+ column_index = {column: position for position, column in enumerate(ordered)}
+ rows = _read_view(Team.objects.get(id=team_id), saved_query.name, ordered)
+ accounts = _accounts_by_external_id(team_id, rows, column_index, usable)
+
+ unmatched: set[Any] = set()
+ for source in usable:
+ key_index, value_index = column_index[source.key_column], column_index[source.source_column]
+ for row in rows:
+ key = row[key_index]
+ if key is None:
+ continue
+ account = accounts.get(str(key))
+ if account is None:
+ unmatched.add(key)
+ continue
+ if row[value_index] is None:
+ continue
+ if _write(team_id=team_id, account_id=account.id, source=source, value=row[value_index], result=result):
+ result.written += 1
+ result.unmatched_keys = len(unmatched)
+ return result
+
+
+def _accounts_by_external_id(
+ team_id: int, rows: list, column_index: dict[str, int], sources: list[CustomPropertySource]
+) -> dict[str | None, Account]:
+ keys = {row[column_index[source.key_column]] for source in sources for row in rows}
+ external_ids = [str(key) for key in keys if key is not None]
+ return {a.external_id: a for a in Account.objects.for_team(team_id).filter(external_id__in=external_ids)}
+
+
+def _write(*, team_id: int, account_id: Any, source: CustomPropertySource, value: Any, result: SyncResult) -> bool:
+ last_conflict: CustomPropertyValueConflict | None = None
+ for _ in range(_WRITE_CONFLICT_RETRIES):
+ try:
+ set_custom_property_value(
+ team_id=team_id, account_id=account_id, definition_id=source.definition_id, value=value
+ )
+ return True
+ except CustomPropertyValueConflict as exc:
+ last_conflict = exc # transient active-value race — the retry soft-deletes the winner's row first
+ continue
+ except InvalidCustomPropertyValue as exc:
+ result.source_errors[str(source.id)] = str(exc)
+ return False
+ # Retries exhausted on a transient conflict — the value re-syncs next run. Deliberately not
+ # recorded as a source error (that would auto-disable a healthy source over an environmental
+ # race), but captured so the exhausted-retry case stays visible.
+ if last_conflict is not None:
+ capture_exception(last_conflict)
+ return False
+
+
+def _read_view(team: Team, view_name: str, columns: list[str]) -> list:
+ query = ast.SelectQuery(
+ select=[ast.Field(chain=[column]) for column in columns],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[view_name])),
+ )
+ with tags_context(product=Product.CUSTOMER_ANALYTICS, feature=Feature.ACCOUNTS, team_id=team.pk):
+ return execute_hogql_query(query, team=team).results or []
+
+
+def record_sync_outcome(
+ *,
+ team_id: int,
+ saved_query_id: str | UUID,
+ view_found: bool = True,
+ run_failed: bool = False,
+ run_error: str | None = None,
+ source_errors: dict[str, str] | None = None,
+) -> None:
+ """Persist a sync run's outcome onto every enabled source for the view.
+
+ Clean success resets the failure streak; a missing view disables immediately; a whole-run
+ failure or a per-source column error increments the streak and auto-disables at the cap.
+ """
+ source_errors = source_errors or {}
+ sources = CustomPropertySource.objects.for_team(team_id).filter(saved_query_id=saved_query_id, is_enabled=True)
+ now = timezone.now()
+ with transaction.atomic():
+ for source in sources:
+ source.last_synced_at = now
+ if not view_found:
+ source.last_sync_error = "View not found"
+ source.is_enabled = False
+ source.consecutive_failures = 0
+ elif run_failed or str(source.id) in source_errors:
+ error = run_error if run_failed else source_errors[str(source.id)]
+ source.last_sync_error = (error or "Sync failed")[:_MAX_ERROR_LENGTH]
+ source.consecutive_failures += 1
+ if source.consecutive_failures >= MAX_CONSECUTIVE_SYNC_FAILURES:
+ source.is_enabled = False
+ else:
+ source.last_sync_error = None
+ source.consecutive_failures = 0
+ source.save()
+
+
+def run_custom_property_sync(*, team_id: int, saved_query_id: str | UUID) -> SyncResult:
+ """Run one sync and persist its outcome. The Celery task's entrypoint.
+
+ On a hard failure the outcome is recorded (so the failure streak/auto-disable still advance)
+ and the error is captured, then re-raised so the run shows as failed.
+ """
+ try:
+ result = sync_custom_property_values(team_id=team_id, saved_query_id=saved_query_id)
+ except Exception as e:
+ record_sync_outcome(team_id=team_id, saved_query_id=saved_query_id, run_failed=True, run_error=str(e))
+ capture_exception(e)
+ raise
+
+ record_sync_outcome(
+ team_id=team_id,
+ saved_query_id=saved_query_id,
+ view_found=result.view_found,
+ source_errors=result.source_errors,
+ )
+ return result
diff --git a/products/customer_analytics/backend/logic/custom_property_sync_test.py b/products/customer_analytics/backend/logic/custom_property_sync_test.py
new file mode 100644
index 000000000000..e281f714015f
--- /dev/null
+++ b/products/customer_analytics/backend/logic/custom_property_sync_test.py
@@ -0,0 +1,215 @@
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.apps import apps
+
+from parameterized import parameterized
+
+from products.customer_analytics.backend.logic.custom_property_sync import (
+ MAX_CONSECUTIVE_SYNC_FAILURES,
+ record_sync_outcome,
+ run_custom_property_sync,
+ sync_custom_property_values,
+)
+from products.customer_analytics.backend.models import (
+ Account,
+ CustomPropertyDefinition,
+ CustomPropertySource,
+ CustomPropertyValue,
+)
+from products.customer_analytics.backend.models.custom_property_definition import DisplayType
+from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
+
+DataWarehouseSavedQuery = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
+
+_EXECUTE = "products.customer_analytics.backend.logic.custom_property_sync.execute_hogql_query"
+
+
+class _Response:
+ def __init__(self, results):
+ self.results = results
+
+
+class CustomPropertySyncTest(TeamScopedTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.view = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="billing_view", columns={"org_id": {}, "mrr": {}, "plan": {}}
+ )
+ self.acme = Account.objects.create(team=self.team, name="Acme", external_id="acme")
+ self.globex = Account.objects.create(team=self.team, name="Globex", external_id="globex")
+ self.mrr_def = CustomPropertyDefinition.objects.create(
+ team=self.team, name="MRR", display_type=DisplayType.NUMBER
+ )
+ self.plan_def = CustomPropertyDefinition.objects.create(team=self.team, name="Plan")
+
+ def _source(self, definition, source_column, key_column="org_id"):
+ return CustomPropertySource.objects.create(
+ team=self.team,
+ definition=definition,
+ saved_query=self.view,
+ source_column=source_column,
+ key_column=key_column,
+ )
+
+ def _sync(self, rows):
+ with patch(_EXECUTE, return_value=_Response(rows)):
+ return sync_custom_property_values(team_id=self.team.id, saved_query_id=self.view.id)
+
+ def _active(self, account, definition):
+ return CustomPropertyValue.objects.filter(account=account, definition=definition, is_deleted=False).get()
+
+ def test_writes_matched_values_for_every_source(self):
+ self._source(self.mrr_def, "mrr")
+ self._source(self.plan_def, "plan")
+ # selected columns are sorted: mrr, org_id, plan
+ result = self._sync([(100.0, "acme", "enterprise"), (200.0, "globex", "free")])
+
+ assert result.written == 4
+ assert self._active(self.acme, self.mrr_def).value_num == 100.0
+ assert self._active(self.globex, self.mrr_def).value_num == 200.0
+ assert self._active(self.acme, self.plan_def).value_str == "enterprise"
+ assert self._active(self.globex, self.plan_def).value_str == "free"
+
+ def test_skips_and_counts_unmatched_keys(self):
+ self._source(self.mrr_def, "mrr")
+ # selected columns are sorted: mrr, org_id
+ result = self._sync([(100.0, "acme"), (999.0, "nobody")])
+
+ assert result.written == 1
+ assert result.unmatched_keys == 1
+ assert not CustomPropertyValue.objects.filter(definition=self.mrr_def, account=self.globex).exists()
+
+ def test_missing_column_marks_source_error_and_skips(self):
+ source = self._source(self.mrr_def, "does_not_exist")
+ result = self._sync([(100.0, "acme")])
+
+ assert result.written == 0
+ assert str(source.id) in result.source_errors
+
+ def test_deleted_view_returns_not_found(self):
+ self._source(self.mrr_def, "mrr")
+ self.view.deleted = True
+ self.view.save()
+
+ result = self._sync([(100.0, "acme")])
+
+ assert result.view_found is False
+ assert result.written == 0
+
+ def test_skips_null_values(self):
+ self._source(self.mrr_def, "mrr")
+ # selected columns are sorted: mrr, org_id
+ result = self._sync([(None, "acme")])
+
+ assert result.written == 0
+ assert not CustomPropertyValue.objects.filter(definition=self.mrr_def, account=self.acme).exists()
+
+ def test_skips_null_keys(self):
+ self._source(self.mrr_def, "mrr")
+ # selected columns are sorted: mrr, org_id — org_id (the key) is null, so the row can't match
+ result = self._sync([(100.0, None)])
+
+ assert result.written == 0
+ assert result.unmatched_keys == 0
+
+ def test_run_sync_records_success_outcome(self):
+ source = self._source(self.mrr_def, "mrr")
+ with patch(_EXECUTE, return_value=_Response([(100.0, "acme")])):
+ run_custom_property_sync(team_id=self.team.id, saved_query_id=self.view.id)
+
+ source.refresh_from_db()
+ assert source.last_synced_at is not None
+ assert source.last_sync_error is None
+ assert source.consecutive_failures == 0
+
+ @patch("products.customer_analytics.backend.logic.custom_property_sync.capture_exception")
+ def test_run_sync_records_failure_outcome_and_reraises(self, mock_capture):
+ source = self._source(self.mrr_def, "mrr")
+ sync_path = "products.customer_analytics.backend.logic.custom_property_sync.sync_custom_property_values"
+ with patch(sync_path, side_effect=RuntimeError("boom")), pytest.raises(RuntimeError):
+ run_custom_property_sync(team_id=self.team.id, saved_query_id=self.view.id)
+
+ source.refresh_from_db()
+ assert source.consecutive_failures == 1
+ assert source.last_sync_error == "boom"
+ mock_capture.assert_called_once()
+
+
+class RecordSyncOutcomeTest(TeamScopedTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.view = DataWarehouseSavedQuery.objects.create(team=self.team, name="billing_view", columns={})
+ self.definition = CustomPropertyDefinition.objects.create(team=self.team, name="MRR")
+ self.source = CustomPropertySource.objects.create(
+ team=self.team, definition=self.definition, saved_query=self.view, source_column="mrr", key_column="org_id"
+ )
+
+ def _record(self, **kwargs):
+ record_sync_outcome(team_id=self.team.id, saved_query_id=self.view.id, **kwargs)
+ self.source.refresh_from_db()
+
+ @parameterized.expand(
+ [
+ ("clean_success", {}, True, 0, None),
+ ("view_not_found", {"view_found": False}, False, 0, "View not found"),
+ ("run_failed", {"run_failed": True, "run_error": "boom"}, True, 1, "boom"),
+ ]
+ )
+ def test_single_run_outcome(self, _name, kwargs, expected_enabled, expected_failures, expected_error):
+ self._record(**kwargs)
+
+ assert self.source.is_enabled is expected_enabled
+ assert self.source.consecutive_failures == expected_failures
+ assert self.source.last_sync_error == expected_error
+ assert self.source.last_synced_at is not None
+
+ def test_per_source_column_error_increments_only_that_source(self):
+ other_def = CustomPropertyDefinition.objects.create(team=self.team, name="Plan")
+ other = CustomPropertySource.objects.create(
+ team=self.team, definition=other_def, saved_query=self.view, source_column="plan", key_column="org_id"
+ )
+
+ self._record(source_errors={str(self.source.id): "View billing_view has no column(s): mrr"})
+ other.refresh_from_db()
+
+ assert self.source.consecutive_failures == 1
+ assert self.source.last_sync_error == "View billing_view has no column(s): mrr"
+ assert other.consecutive_failures == 0
+ assert other.last_sync_error is None
+
+ def test_success_resets_failure_streak_and_clears_error(self):
+ CustomPropertySource.objects.filter(id=self.source.id).update(consecutive_failures=3, last_sync_error="old")
+
+ self._record()
+
+ assert self.source.consecutive_failures == 0
+ assert self.source.last_sync_error is None
+
+ def test_view_not_found_disables_and_resets_failure_streak(self):
+ CustomPropertySource.objects.filter(id=self.source.id).update(consecutive_failures=3)
+
+ self._record(view_found=False)
+
+ assert self.source.is_enabled is False
+ assert self.source.consecutive_failures == 0
+
+ @parameterized.expand(
+ [("below_cap", MAX_CONSECUTIVE_SYNC_FAILURES - 2, True), ("at_cap", MAX_CONSECUTIVE_SYNC_FAILURES - 1, False)]
+ )
+ def test_auto_disables_at_failure_cap(self, _name, starting_failures, expected_enabled):
+ CustomPropertySource.objects.filter(id=self.source.id).update(consecutive_failures=starting_failures)
+
+ self._record(run_failed=True, run_error="boom")
+
+ assert self.source.consecutive_failures == starting_failures + 1
+ assert self.source.is_enabled is expected_enabled
+
+ def test_disabled_sources_are_not_touched(self):
+ CustomPropertySource.objects.filter(id=self.source.id).update(consecutive_failures=2, is_enabled=False)
+
+ self._record()
+
+ assert self.source.consecutive_failures == 2
+ assert self.source.last_synced_at is None
diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.py
index 3f068c9546e0..e38ab83c26ea 100644
--- a/products/customer_analytics/backend/presentation/views/external.py
+++ b/products/customer_analytics/backend/presentation/views/external.py
@@ -263,6 +263,10 @@ _CUSTOM_PROPERTIES_ERROR_RESPONSES = {
"Failed to update custom properties",
status.HTTP_500_INTERNAL_SERVER_ERROR,
),
+ contracts.ExternalAccountCustomPropertiesError.SOURCE_MANAGED: (
+ "This custom property is managed by a data warehouse source and can't be set manually",
+ status.HTTP_400_BAD_REQUEST,
+ ),
}
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 9d6e197078ce..740a061a1e8e 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -35,6 +35,7 @@ from products.customer_analytics.backend.facade.contracts import (
CustomerProfileConfigView,
CustomPropertyDefinitionView,
CustomPropertyReference,
+ CustomPropertySourceView,
)
# Scope (value, label) pairs, kept in sync with ``CustomerProfileConfig.Scope``. Declared
@@ -280,12 +281,68 @@ class CustomPropertyReferenceSerializer(DataclassSerializer):
fields = ["id", "name", "status", "type"]
+class CustomPropertySourceSerializer(DataclassSerializer):
+ """Binds a materialized data-warehouse view column to a custom property definition; the view's
+ values are synced onto matching accounts on each materialization."""
+
+ id = serializers.UUIDField(read_only=True)
+ definition = serializers.UUIDField(
+ help_text="UUID of the custom property definition this source feeds. One source per definition."
+ )
+ saved_query = serializers.UUIDField(
+ help_text="UUID of the data-warehouse saved query (materialized view) to read values from."
+ )
+ source_column = serializers.CharField(
+ max_length=400, help_text="Column in the view whose value is written to the property."
+ )
+ key_column = serializers.CharField(
+ max_length=400, help_text="Column in the view whose value matches an account's external_id."
+ )
+ is_enabled = serializers.BooleanField(
+ required=False,
+ default=True,
+ help_text=(
+ "Whether the source syncs. Auto-disabled after repeated failures or a missing view; "
+ "re-enabling resets the failure count."
+ ),
+ )
+ consecutive_failures = serializers.IntegerField(
+ read_only=True, help_text="Consecutive failed sync runs; the source auto-disables at the cap."
+ )
+ last_synced_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the most recent sync run finished."
+ )
+ last_sync_error = serializers.CharField(
+ read_only=True, allow_null=True, help_text="Error summary from the last run, or null if it succeeded."
+ )
+ created_at = serializers.DateTimeField(read_only=True)
+ created_by = serializers.IntegerField(read_only=True, allow_null=True)
+ updated_at = serializers.DateTimeField(read_only=True, allow_null=True)
+
+ class Meta:
+ dataclass = CustomPropertySourceView
+ ref_name = "CustomPropertySource"
+ fields = [
+ "id",
+ "definition",
+ "saved_query",
+ "source_column",
+ "key_column",
+ "is_enabled",
+ "consecutive_failures",
+ "last_synced_at",
+ "last_sync_error",
+ "created_at",
+ "created_by",
+ "updated_at",
+ ]
+
+
class CustomPropertyDefinitionSerializer(DataclassSerializer):
"""A team-scoped definition of a custom account property — the attribute side of the model.
Holds only the property's shape (name, display type, big-number flag). Per-account values are
- stored separately, so this serializer never reads or writes account values. The numeric-only
- big-number rule and the unique-name conflict are enforced behind the facade.
+ stored separately, so this serializer never reads or writes account values.
"""
id = serializers.UUIDField(read_only=True)
@@ -311,6 +368,11 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
default=False,
help_text="Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties.",
)
+ source = CustomPropertySourceSerializer( # type: ignore[assignment]
+ read_only=True,
+ allow_null=True,
+ help_text="The data-warehouse view-sync binding feeding this property, or null when values are set manually.",
+ )
created_at = serializers.DateTimeField(read_only=True)
created_by = serializers.IntegerField(read_only=True, allow_null=True)
updated_at = serializers.DateTimeField(read_only=True, allow_null=True)
@@ -322,8 +384,6 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
class Meta:
dataclass = CustomPropertyDefinitionView
- # Pin the OpenAPI component name to the pre-isolation one (DataclassSerializer would
- # otherwise name it after the wrapped dataclass, ``CustomPropertyDefinitionView``).
ref_name = "CustomPropertyDefinition"
fields = [
"id",
@@ -331,6 +391,7 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
"description",
"display_type",
"is_big_number",
+ "source",
"created_at",
"created_by",
"updated_at",
@@ -338,6 +399,21 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
]
+class CustomPropertySourceUpdateSerializer(serializers.Serializer):
+ """Writable fields for updating a source. ``definition`` and ``saved_query`` are create-only, so
+ they are intentionally absent — only these reach the facade's update."""
+
+ source_column = serializers.CharField(
+ max_length=400, required=False, help_text="Column in the view whose value is written to the property."
+ )
+ key_column = serializers.CharField(
+ max_length=400, required=False, help_text="Column in the view whose value matches an account's external_id."
+ )
+ is_enabled = serializers.BooleanField(
+ required=False, help_text="Whether the source syncs; re-enabling it resets the failure count."
+ )
+
+
@extend_schema_field({"oneOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}]})
class CustomPropertyValueField(serializers.Field):
"""A custom property value — a JSON scalar (string, number, or boolean).
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index a6fa3904acd6..629d424d3922 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -37,6 +37,8 @@ from products.customer_analytics.backend.presentation.views.serializers import (
CustomerJourneySerializer,
CustomerProfileConfigSerializer,
CustomPropertyDefinitionSerializer,
+ CustomPropertySourceSerializer,
+ CustomPropertySourceUpdateSerializer,
CustomPropertyValueSerializer,
CustomPropertyValueWriteSerializer,
)
@@ -283,6 +285,70 @@ def _custom_property_definition_write_fields(validated, raw_data: dict) -> dict:
return fields
+class CustomPropertySourceViewSet(
+ TeamAndOrgViewSetMixin,
+ AccessControlViewSetMixin,
+ _FacadePaginationMixin,
+ viewsets.ModelViewSet,
+):
+ scope_object = "account"
+ serializer_class = CustomPropertySourceSerializer
+ queryset = None # data is reached through the facade; declared for router/schema only
+
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_custom_property_sources(self.team_id, offset=offset, limit=limit),
+ CustomPropertySourceSerializer,
+ )
+
+ def retrieve(self, request: Request, *args, **kwargs) -> Response:
+ source = api.get_custom_property_source(self.team_id, self.kwargs["pk"])
+ if source is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomPropertySourceSerializer(instance=source).data)
+
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ serializer = CustomPropertySourceSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ try:
+ source = api.create_custom_property_source(
+ team_id=self.team_id,
+ definition_id=data.definition,
+ saved_query_id=data.saved_query,
+ source_column=data.source_column,
+ key_column=data.key_column,
+ is_enabled=data.is_enabled,
+ user=cast(User, request.user),
+ )
+ except api.CustomPropertySourceValidationError as e:
+ raise ValidationError(str(e))
+ return Response(CustomPropertySourceSerializer(instance=source).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(request=CustomPropertySourceUpdateSerializer)
+ def update(self, request: Request, *args, **kwargs) -> Response:
+ write = CustomPropertySourceUpdateSerializer(data=request.data, partial=kwargs.pop("partial", False))
+ write.is_valid(raise_exception=True)
+ source = api.update_custom_property_source(
+ team_id=self.team_id, source_id=self.kwargs["pk"], fields=write.validated_data
+ )
+ if source is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomPropertySourceSerializer(instance=source).data)
+
+ @extend_schema(request=CustomPropertySourceUpdateSerializer)
+ def partial_update(self, request: Request, *args, **kwargs) -> Response:
+ kwargs["partial"] = True
+ return self.update(request, *args, **kwargs)
+
+ def destroy(self, request: Request, *args, **kwargs) -> Response:
+ deleted = api.delete_custom_property_source(team_id=self.team_id, source_id=self.kwargs["pk"])
+ if not deleted:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+
class CustomerJourneyViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
@@ -791,6 +857,8 @@ class CustomPropertyValueViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
except api.CustomPropertyDefinitionNotFound:
raise ValidationError({"definition": "Custom property definition not found."})
+ except api.CustomPropertyValueSourceManaged as exc:
+ raise ValidationError({"definition": str(exc)})
except api.InvalidCustomPropertyValue as exc:
raise ValidationError({"value": str(exc)})
except api.CustomPropertyValueConflict as exc:
diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.py
index 2141a7169059..35a73717adb5 100644
--- a/products/customer_analytics/backend/routes.py
+++ b/products/customer_analytics/backend/routes.py
@@ -9,6 +9,7 @@ from products.customer_analytics.backend.presentation.views.views import (
CustomerJourneyViewSet,
CustomerProfileConfigViewSet,
CustomPropertyDefinitionViewSet,
+ CustomPropertySourceViewSet,
CustomPropertyValueViewSet,
)
@@ -35,6 +36,12 @@ def register_routes(routers: RouterRegistry) -> None:
"project_custom_property_definitions",
["team_id"],
)
+ routers.projects.register(
+ r"custom_property_sources",
+ CustomPropertySourceViewSet,
+ "project_custom_property_sources",
+ ["team_id"],
+ )
project_accounts_router, environment_accounts_router = routers.register_legacy_dual_route(
r"accounts", AccountViewSet, "project_accounts", ["team_id"]
)
diff --git a/products/customer_analytics/backend/tasks/__init__.py b/products/customer_analytics/backend/tasks/__init__.py
new file mode 100644
index 000000000000..d9d3d048f71f
--- /dev/null
+++ b/products/customer_analytics/backend/tasks/__init__.py
@@ -0,0 +1,2 @@
+# Re-exported so Celery autodiscovers the task when the tasks package is imported.
+from products.customer_analytics.backend.tasks.tasks import process_custom_property_sync # noqa: F401
diff --git a/products/customer_analytics/backend/tasks/tasks.py b/products/customer_analytics/backend/tasks/tasks.py
new file mode 100644
index 000000000000..556540f0fdeb
--- /dev/null
+++ b/products/customer_analytics/backend/tasks/tasks.py
@@ -0,0 +1,8 @@
+from celery import shared_task
+
+from products.customer_analytics.backend.logic.custom_property_sync import run_custom_property_sync
+
+
+@shared_task(name="customer_analytics.process_custom_property_sync", ignore_result=True)
+def process_custom_property_sync(team_id: int, saved_query_id: str) -> None:
+ run_custom_property_sync(team_id=team_id, saved_query_id=saved_query_id)
diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.py
index a2768ab5f01b..540e7fb06625 100644
--- a/products/customer_analytics/backend/test/test_facade.py
+++ b/products/customer_analytics/backend/test/test_facade.py
@@ -1,7 +1,14 @@
+from uuid import uuid4
+
+import pytest
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
-from posthog.models import Organization, User
+from django.apps import apps
+
+from parameterized import parameterized
+
+from posthog.models import Organization, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.tag import Tag
from posthog.models.tagged_item import TaggedItem
@@ -11,8 +18,9 @@ from products.customer_analytics.backend.facade import (
api as facade,
contracts,
)
-from products.customer_analytics.backend.models import Account
+from products.customer_analytics.backend.models import Account, CustomPropertyDefinition, CustomPropertySource
from products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties
+from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
from products.customer_analytics.backend.test.factories import create_account
from products.notebooks.backend.models import Notebook, ResourceNotebook
from products.product_analytics.backend.models.insight import Insight
@@ -485,3 +493,158 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):
)
is None
)
+
+
+class TestCustomPropertySourceFacade(TeamScopedTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
+ self.view = saved_query_model.objects.create(
+ team=self.team, name="billing_view", columns={"org_id": {}, "mrr": {}}
+ )
+ self.definition = CustomPropertyDefinition.objects.create(team=self.team, name="MRR")
+
+ def _create(self, **overrides):
+ kwargs: dict = {
+ "team_id": self.team.id,
+ "definition_id": self.definition.id,
+ "saved_query_id": self.view.id,
+ "source_column": "mrr",
+ "key_column": "org_id",
+ "is_enabled": True,
+ "user": self.user,
+ }
+ kwargs.update(overrides)
+ return facade.create_custom_property_source(**kwargs)
+
+ def test_create_returns_contract(self):
+ result = self._create()
+
+ assert isinstance(result, contracts.CustomPropertySourceView)
+ assert result.definition == self.definition.id
+ assert result.saved_query == self.view.id
+ assert result.source_column == "mrr"
+ assert result.is_enabled is True
+ assert result.id is not None
+ assert CustomPropertySource.objects.for_team(self.team.id).filter(id=result.id).exists()
+
+ def test_create_rejects_saved_query_from_another_team(self):
+ saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other_view = saved_query_model.objects.create(team=other_team, name="other_view", columns={})
+
+ with pytest.raises(facade.CustomPropertySourceValidationError):
+ self._create(saved_query_id=other_view.id)
+
+ def test_create_rejects_definition_from_another_team(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other_definition = CustomPropertyDefinition.objects.create(team=other_team, name="Other MRR")
+
+ with pytest.raises(facade.CustomPropertySourceValidationError):
+ self._create(definition_id=other_definition.id)
+
+ def test_create_rejects_second_source_for_same_definition(self):
+ self._create()
+
+ with pytest.raises(facade.CustomPropertySourceValidationError):
+ self._create()
+
+ def test_update_reenable_resets_failure_streak_and_clears_error(self):
+ source = self._create()
+ CustomPropertySource.objects.filter(id=source.id).update(
+ is_enabled=False, consecutive_failures=5, last_sync_error="boom"
+ )
+
+ result = facade.update_custom_property_source(
+ team_id=self.team.id, source_id=source.id, fields={"is_enabled": True}
+ )
+ assert result is not None
+
+ assert result.is_enabled is True
+ assert result.consecutive_failures == 0
+ assert result.last_sync_error is None
+
+ def test_update_returns_none_for_missing_source(self):
+ result = facade.update_custom_property_source(
+ team_id=self.team.id, source_id=str(uuid4()), fields={"is_enabled": False}
+ )
+ assert result is None
+
+ def test_delete_removes_source(self):
+ source = self._create()
+
+ assert facade.delete_custom_property_source(team_id=self.team.id, source_id=source.id) is True
+ assert not CustomPropertySource.objects.for_team(self.team.id).filter(id=source.id).exists()
+
+ @parameterized.expand([("enabled", True, True), ("disabled", False, False)])
+ def test_create_enqueues_initial_sync_only_when_enabled(self, _name, is_enabled, expect_enqueued):
+ with patch.object(facade, "current_app") as mock_app, self.captureOnCommitCallbacks(execute=True):
+ self._create(is_enabled=is_enabled)
+
+ if expect_enqueued:
+ mock_app.send_task.assert_called_once_with(
+ "customer_analytics.process_custom_property_sync",
+ kwargs={"team_id": self.team.id, "saved_query_id": str(self.view.id)},
+ )
+ else:
+ mock_app.send_task.assert_not_called()
+
+ def test_reenabling_a_source_enqueues_a_sync(self):
+ source = self._create(is_enabled=False)
+
+ with patch.object(facade, "current_app") as mock_app, self.captureOnCommitCallbacks(execute=True):
+ facade.update_custom_property_source(team_id=self.team.id, source_id=source.id, fields={"is_enabled": True})
+
+ mock_app.send_task.assert_called_once_with(
+ "customer_analytics.process_custom_property_sync",
+ kwargs={"team_id": self.team.id, "saved_query_id": str(self.view.id)},
+ )
+
+ @parameterized.expand(
+ [
+ ("noop", {}, False),
+ ("already_enabled", {"is_enabled": True}, False),
+ ("column_change", {"source_column": "org_id"}, True),
+ ]
+ )
+ def test_update_enqueues_only_on_meaningful_change(self, _name, fields, expect_enqueued):
+ source = self._create()
+
+ with patch.object(facade, "current_app") as mock_app, self.captureOnCommitCallbacks(execute=True):
+ facade.update_custom_property_source(team_id=self.team.id, source_id=source.id, fields=fields)
+
+ if expect_enqueued:
+ mock_app.send_task.assert_called_once()
+ else:
+ mock_app.send_task.assert_not_called()
+
+ def test_external_batch_rejects_source_backed_definition(self):
+ self._create()
+ create_account(team_id=self.team.id, name="Acme", external_id="acme")
+
+ result = facade.set_external_account_custom_properties(
+ self.team.id, "acme", properties={str(self.definition.id): 100}
+ )
+
+ assert result.error == contracts.ExternalAccountCustomPropertiesError.SOURCE_MANAGED
+ assert result.values is None
+
+ def test_get_definition_carries_source(self):
+ uac = UserAccessControl(user=self.user, team=self.team)
+ view = facade.get_custom_property_definition(self.team.id, self.definition.id, user_access_control=uac)
+ assert view is not None
+ assert view.source is None
+
+ source = self._create()
+ view = facade.get_custom_property_definition(self.team.id, self.definition.id, user_access_control=uac)
+ assert view is not None
+ assert view.source is not None
+ assert view.source.id == source.id
+ assert view.source.source_column == "mrr"
+
+ def test_manual_value_write_rejected_on_source_backed_definition(self):
+ self._create()
+ account = create_account(team_id=self.team.id, external_id="org_1")
+
+ with pytest.raises(facade.CustomPropertyValueSourceManaged):
+ facade.set_custom_property_value(self.team.id, account.id, self.definition.id, 42)
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 2f90d798710c..444fad7e17b0 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -5,6 +5,8 @@ from freezegun import freeze_time
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
@@ -21,6 +23,7 @@ from products.customer_analytics.backend.models import (
CustomerJourney,
CustomerProfileConfig,
CustomPropertyDefinition,
+ CustomPropertySource,
DisplayType,
)
from products.customer_analytics.backend.models.account import AccountAssignment
@@ -1849,3 +1852,53 @@ class TestCustomPropertyValueViewSet(APIBaseTest):
response = self.client.get(self.endpoint)
self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
+
+ def test_source_backed_definition_rejects_manual_write(self):
+ saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
+ view = saved_query_model.objects.create(team=self.team, name="v", columns={"k": {}, "c": {}})
+ CustomPropertySource.objects.unscoped().create(
+ team_id=self.team.id,
+ definition_id=self.text_def.id,
+ saved_query=view,
+ source_column="c",
+ key_column="k",
+ )
+
+ response = self._set(self.text_def.id, "manual")
+
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
+ self.assertEqual("definition", response.json()["attr"])
+
+
+class TestCustomPropertySourceViewSet(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.endpoint = f"/api/projects/{self.team.id}/custom_property_sources/"
+ saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
+ self.view = saved_query_model.objects.create(
+ team=self.team, name="billing_view", columns={"org_id": {}, "mrr": {}}
+ )
+ self.definition = create_custom_property_definition(team_id=self.team.id, name="MRR")
+
+ def test_create_list_and_toggle_round_trip(self):
+ created = self.client.post(
+ self.endpoint,
+ {
+ "definition": str(self.definition.id),
+ "saved_query": str(self.view.id),
+ "source_column": "mrr",
+ "key_column": "org_id",
+ },
+ format="json",
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.content
+ source_id = created.json()["id"]
+ assert created.json()["is_enabled"] is True
+
+ listed = self.client.get(self.endpoint)
+ assert listed.status_code == status.HTTP_200_OK
+ assert [s["id"] for s in listed.json()["results"]] == [source_id]
+
+ toggled = self.client.patch(f"{self.endpoint}{source_id}/", {"is_enabled": False}, format="json")
+ assert toggled.status_code == status.HTTP_200_OK
+ assert toggled.json()["is_enabled"] is False
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
index fa896ff34c29..d1d4f5726d4d 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
@@ -19,6 +19,7 @@ function definition(
created_by: null,
updated_at: null,
references: [],
+ source: null,
...overrides,
}
}
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 82a71fc4df68..d7209ecd223b 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -288,6 +288,47 @@ export const CustomPropertyDisplayTypeEnumApi = {
Boolean: 'boolean',
} as const
+/**
+ * Binds a materialized data-warehouse view column to a custom property definition; the view's
+ * values are synced onto matching accounts on each materialization.
+ */
+export interface CustomPropertySourceApi {
+ readonly id: string
+ /** UUID of the custom property definition this source feeds. One source per definition. */
+ definition: string
+ /** UUID of the data-warehouse saved query (materialized view) to read values from. */
+ saved_query: string
+ /**
+ * Column in the view whose value is written to the property.
+ * @maxLength 400
+ */
+ source_column: string
+ /**
+ * Column in the view whose value matches an account's external_id.
+ * @maxLength 400
+ */
+ key_column: string
+ /** Whether the source syncs. Auto-disabled after repeated failures or a missing view; re-enabling resets the failure count. */
+ is_enabled?: boolean
+ /** Consecutive failed sync runs; the source auto-disables at the cap. */
+ readonly consecutive_failures: number
+ /**
+ * When the most recent sync run finished.
+ * @nullable
+ */
+ readonly last_synced_at: string | null
+ /**
+ * Error summary from the last run, or null if it succeeded.
+ * @nullable
+ */
+ readonly last_sync_error: string | null
+ readonly created_at: string
+ /** @nullable */
+ readonly created_by: number | null
+ /** @nullable */
+ readonly updated_at: string | null
+}
+
/**
* A place that uses a custom property definition (read-only).
*/
@@ -306,8 +347,7 @@ export interface CustomPropertyReferenceApi {
* A team-scoped definition of a custom account property — the attribute side of the model.
*
* Holds only the property's shape (name, display type, big-number flag). Per-account values are
- * stored separately, so this serializer never reads or writes account values. The numeric-only
- * big-number rule and the unique-name conflict are enforced behind the facade.
+ * stored separately, so this serializer never reads or writes account values.
*/
export interface CustomPropertyDefinitionApi {
readonly id: string
@@ -333,6 +373,8 @@ export interface CustomPropertyDefinitionApi {
display_type: CustomPropertyDisplayTypeEnumApi
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean
+ /** The data-warehouse view-sync binding feeding this property, or null when values are set manually. */
+ readonly source: CustomPropertySourceApi | null
readonly created_at: string
/** @nullable */
readonly created_by: number | null
@@ -355,8 +397,7 @@ export interface PaginatedCustomPropertyDefinitionListApi {
* A team-scoped definition of a custom account property — the attribute side of the model.
*
* Holds only the property's shape (name, display type, big-number flag). Per-account values are
- * stored separately, so this serializer never reads or writes account values. The numeric-only
- * big-number rule and the unique-name conflict are enforced behind the facade.
+ * stored separately, so this serializer never reads or writes account values.
*/
export interface PatchedCustomPropertyDefinitionApi {
readonly id?: string
@@ -382,6 +423,8 @@ export interface PatchedCustomPropertyDefinitionApi {
display_type?: CustomPropertyDisplayTypeEnumApi
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean
+ /** The data-warehouse view-sync binding feeding this property, or null when values are set manually. */
+ readonly source?: CustomPropertySourceApi | null
readonly created_at?: string
/** @nullable */
readonly created_by?: number | null
@@ -391,6 +434,53 @@ export interface PatchedCustomPropertyDefinitionApi {
readonly references?: readonly CustomPropertyReferenceApi[]
}
+export interface PaginatedCustomPropertySourceListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: CustomPropertySourceApi[]
+}
+
+/**
+ * Writable fields for updating a source. ``definition`` and ``saved_query`` are create-only, so
+ * they are intentionally absent — only these reach the facade's update.
+ */
+export interface CustomPropertySourceUpdateApi {
+ /**
+ * Column in the view whose value is written to the property.
+ * @maxLength 400
+ */
+ source_column?: string
+ /**
+ * Column in the view whose value matches an account's external_id.
+ * @maxLength 400
+ */
+ key_column?: string
+ /** Whether the source syncs; re-enabling it resets the failure count. */
+ is_enabled?: boolean
+}
+
+/**
+ * Writable fields for updating a source. ``definition`` and ``saved_query`` are create-only, so
+ * they are intentionally absent — only these reach the facade's update.
+ */
+export interface PatchedCustomPropertySourceUpdateApi {
+ /**
+ * Column in the view whose value is written to the property.
+ * @maxLength 400
+ */
+ source_column?: string
+ /**
+ * Column in the view whose value matches an account's external_id.
+ * @maxLength 400
+ */
+ key_column?: string
+ /** Whether the source syncs; re-enabling it resets the failure count. */
+ is_enabled?: boolean
+}
+
export interface CustomerJourneyApi {
readonly id: string
insight: number
@@ -684,6 +774,17 @@ export type CustomPropertyDefinitionsListParams = {
offset?: number
}
+export type CustomPropertySourcesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type CustomerJourneysListParams = {
/**
* Number of results to return per page.
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index d91e061c663f..ff813e70d5c7 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -15,6 +15,9 @@ import type {
AccountsNotebooksListParams,
CustomPropertyDefinitionApi,
CustomPropertyDefinitionsListParams,
+ CustomPropertySourceApi,
+ CustomPropertySourceUpdateApi,
+ CustomPropertySourcesListParams,
CustomPropertyValueApi,
CustomPropertyValueWriteApi,
CustomerJourneyApi,
@@ -26,11 +29,13 @@ import type {
PaginatedAccountListApi,
PaginatedAccountNotebookListApi,
PaginatedCustomPropertyDefinitionListApi,
+ PaginatedCustomPropertySourceListApi,
PaginatedCustomerJourneyListApi,
PaginatedCustomerProfileConfigListApi,
PaginatedGroupUsageMetricListApi,
PatchedAccountApi,
PatchedCustomPropertyDefinitionApi,
+ PatchedCustomPropertySourceUpdateApi,
PatchedCustomerJourneyApi,
PatchedCustomerProfileConfigApi,
PatchedGroupUsageMetricApi,
@@ -386,6 +391,116 @@ export const customPropertyDefinitionsDestroy = async (
})
}
+export const getCustomPropertySourcesListUrl = (projectId: string, params?: CustomPropertySourcesListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/custom_property_sources/?${stringifiedParams}`
+ : `/api/projects/${projectId}/custom_property_sources/`
+}
+
+export const customPropertySourcesList = async (
+ projectId: string,
+ params?: CustomPropertySourcesListParams,
+ options?: RequestInit
+): Promise<PaginatedCustomPropertySourceListApi> => {
+ return apiMutator<PaginatedCustomPropertySourceListApi>(getCustomPropertySourcesListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getCustomPropertySourcesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/custom_property_sources/`
+}
+
+export const customPropertySourcesCreate = async (
+ projectId: string,
+ customPropertySourceApi: NonReadonly<CustomPropertySourceApi>,
+ options?: RequestInit
+): Promise<CustomPropertySourceApi> => {
+ return apiMutator<CustomPropertySourceApi>(getCustomPropertySourcesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(customPropertySourceApi),
+ })
+}
+
+export const getCustomPropertySourcesRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/custom_property_sources/${id}/`
+}
+
+export const customPropertySourcesRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<CustomPropertySourceApi> => {
+ return apiMutator<CustomPropertySourceApi>(getCustomPropertySourcesRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getCustomPropertySourcesUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/custom_property_sources/${id}/`
+}
+
+export const customPropertySourcesUpdate = async (
+ projectId: string,
+ id: string,
+ customPropertySourceUpdateApi?: CustomPropertySourceUpdateApi,
+ options?: RequestInit
+): Promise<CustomPropertySourceApi> => {
+ return apiMutator<CustomPropertySourceApi>(getCustomPropertySourcesUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(customPropertySourceUpdateApi),
+ })
+}
+
+export const getCustomPropertySourcesPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/custom_property_sources/${id}/`
+}
+
+export const customPropertySourcesPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedCustomPropertySourceUpdateApi?: PatchedCustomPropertySourceUpdateApi,
+ options?: RequestInit
+): Promise<CustomPropertySourceApi> => {
+ return apiMutator<CustomPropertySourceApi>(getCustomPropertySourcesPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedCustomPropertySourceUpdateApi),
+ })
+}
+
+export const getCustomPropertySourcesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/custom_property_sources/${id}/`
+}
+
+export const customPropertySourcesDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getCustomPropertySourcesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getCustomerJourneysListUrl = (projectId: string, params?: CustomerJourneysListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index ebaebe352857..7c5160791796 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -218,7 +218,7 @@ export const CustomPropertyDefinitionsCreateBody = /* @__PURE__ */ zod
.describe('Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties.'),
})
.describe(
- "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values. The numeric-only\nbig-number rule and the unique-name conflict are enforced behind the facade."
+ "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values."
)
export const customPropertyDefinitionsUpdateBodyNameMax = 400
@@ -246,7 +246,7 @@ export const CustomPropertyDefinitionsUpdateBody = /* @__PURE__ */ zod
.describe('Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties.'),
})
.describe(
- "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values. The numeric-only\nbig-number rule and the unique-name conflict are enforced behind the facade."
+ "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values."
)
export const customPropertyDefinitionsPartialUpdateBodyNameMax = 400
@@ -276,7 +276,90 @@ export const CustomPropertyDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
.describe('Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties.'),
})
.describe(
- "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values. The numeric-only\nbig-number rule and the unique-name conflict are enforced behind the facade."
+ "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values."
+ )
+
+export const customPropertySourcesCreateBodySourceColumnMax = 400
+
+export const customPropertySourcesCreateBodyKeyColumnMax = 400
+
+export const customPropertySourcesCreateBodyIsEnabledDefault = true
+
+export const CustomPropertySourcesCreateBody = /* @__PURE__ */ zod
+ .object({
+ definition: zod
+ .uuid()
+ .describe('UUID of the custom property definition this source feeds. One source per definition.'),
+ saved_query: zod
+ .uuid()
+ .describe('UUID of the data-warehouse saved query (materialized view) to read values from.'),
+ source_column: zod
+ .string()
+ .max(customPropertySourcesCreateBodySourceColumnMax)
+ .describe('Column in the view whose value is written to the property.'),
+ key_column: zod
+ .string()
+ .max(customPropertySourcesCreateBodyKeyColumnMax)
+ .describe("Column in the view whose value matches an account's external_id."),
+ is_enabled: zod
+ .boolean()
+ .default(customPropertySourcesCreateBodyIsEnabledDefault)
+ .describe(
+ 'Whether the source syncs. Auto-disabled after repeated failures or a missing view; re-enabling resets the failure count.'
+ ),
+ })
+ .describe(
+ "Binds a materialized data-warehouse view column to a custom property definition; the view's\nvalues are synced onto matching accounts on each materialization."
+ )
+
+export const customPropertySourcesUpdateBodySourceColumnMax = 400
+
+export const customPropertySourcesUpdateBodyKeyColumnMax = 400
+
+export const CustomPropertySourcesUpdateBody = /* @__PURE__ */ zod
+ .object({
+ source_column: zod
+ .string()
+ .max(customPropertySourcesUpdateBodySourceColumnMax)
+ .optional()
+ .describe('Column in the view whose value is written to the property.'),
+ key_column: zod
+ .string()
+ .max(customPropertySourcesUpdateBodyKeyColumnMax)
+ .optional()
+ .describe("Column in the view whose value matches an account's external_id."),
+ is_enabled: zod
+ .boolean()
+ .optional()
+ .describe('Whether the source syncs; re-enabling it resets the failure count.'),
+ })
+ .describe(
+ "Writable fields for updating a source. ``definition`` and ``saved_query`` are create-only, so\nthey are intentionally absent — only these reach the facade's update."
+ )
+
+export const customPropertySourcesPartialUpdateBodySourceColumnMax = 400
+
+export const customPropertySourcesPartialUpdateBodyKeyColumnMax = 400
+
+export const CustomPropertySourcesPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ source_column: zod
+ .string()
+ .max(customPropertySourcesPartialUpdateBodySourceColumnMax)
+ .optional()
+ .describe('Column in the view whose value is written to the property.'),
+ key_column: zod
+ .string()
+ .max(customPropertySourcesPartialUpdateBodyKeyColumnMax)
+ .optional()
+ .describe("Column in the view whose value matches an account's external_id."),
+ is_enabled: zod
+ .boolean()
+ .optional()
+ .describe('Whether the source syncs; re-enabling it resets the failure count.'),
+ })
+ .describe(
+ "Writable fields for updating a source. ``definition`` and ``saved_query`` are create-only, so\nthey are intentionally absent — only these reach the facade's update."
)
export const customerJourneysCreateBodyNameMax = 400
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx
index 092fcccb240e..0b9b93dd7bfd 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx
@@ -1,13 +1,14 @@
import { useActions, useValues } from 'kea'
import { useState } from 'react'
-import { IconInfo, IconPencil, IconTrash } from '@posthog/icons'
+import { IconDatabase, IconInfo, IconPencil, IconTrash } from '@posthog/icons'
import { LemonButton, LemonTable, LemonTableColumns, Tooltip } from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TZLabel } from 'lib/components/TZLabel'
import { TeamMembershipLevel } from 'lib/constants'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
import { Link } from 'lib/lemon-ui/Link'
import { Popover } from 'lib/lemon-ui/Popover'
import { urls } from 'scenes/urls'
@@ -19,11 +20,20 @@ import type {
import { customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'
import { CustomPropertyModal } from './CustomPropertyModal'
-import { labelForDisplayType } from './customPropertyTypes'
+import { CustomPropertySourceModal } from './CustomPropertySourceModal'
+import { labelForDisplayType, type SourceSyncStatusLevel, sourceSyncStatus } from './customPropertyTypes'
+
+const TAG_TYPE_BY_SYNC_LEVEL: Record<SourceSyncStatusLevel, LemonTagType> = {
+ synced: 'success',
+ error: 'danger',
+ disabled: 'muted',
+ pending: 'default',
+}
export function CustomPropertiesConfig(): JSX.Element {
const { definitions, definitionsLoading } = useValues(customPropertyDefinitionsLogic)
- const { openCreateModal, openEditModal, deleteDefinition } = useActions(customPropertyDefinitionsLogic)
+ const { openCreateModal, openEditModal, openSourceModal, deleteDefinition } =
+ useActions(customPropertyDefinitionsLogic)
const restrictionReason = useRestrictedArea({
scope: RestrictionScope.Project,
minimumAccessLevel: TeamMembershipLevel.Admin,
@@ -78,11 +88,38 @@ export function CustomPropertiesConfig(): JSX.Element {
<span className="text-secondary">—</span>
),
},
+ {
+ title: 'Sync',
+ render: (_, definition) => {
+ if (!definition.source) {
+ return <span className="text-secondary">Manual</span>
+ }
+ const status = sourceSyncStatus(definition.source)
+ return (
+ <Tooltip title={status.tooltip}>
+ <span className="flex items-center gap-2">
+ <LemonTag type={TAG_TYPE_BY_SYNC_LEVEL[status.level]}>{status.label}</LemonTag>
+ {status.level === 'synced' && definition.source.last_synced_at && (
+ <TZLabel time={definition.source.last_synced_at} className="text-secondary" />
+ )}
+ </span>
+ </Tooltip>
+ )
+ },
+ },
{
title: '',
width: 0,
render: (_, definition) => (
<div className="flex gap-1 justify-end">
+ <LemonButton
+ size="small"
+ icon={<IconDatabase />}
+ tooltip={definition.source ? 'Configure sync' : 'Sync from a view'}
+ active={!!definition.source}
+ onClick={() => openSourceModal(definition)}
+ disabledReason={restrictionReason}
+ />
<LemonButton
size="small"
icon={<IconPencil />}
@@ -122,6 +159,7 @@ export function CustomPropertiesConfig(): JSX.Element {
emptyState="No custom properties yet. Create one to get started."
/>
<CustomPropertyModal />
+ <CustomPropertySourceModal />
</div>
)
}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySourceModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySourceModal.tsx
new file mode 100644
index 000000000000..4d2cfd9eb902
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySourceModal.tsx
@@ -0,0 +1,140 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonBanner, LemonButton, LemonModal, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'
+
+export function CustomPropertySourceModal(): JSX.Element {
+ const {
+ sourceModalVisible,
+ sourceDefinition,
+ customPropertySourceForm,
+ isCustomPropertySourceFormSubmitting,
+ materializedViews,
+ selectedSourceColumns,
+ savedQueriesLoading,
+ definitionsLoading,
+ } = useValues(customPropertyDefinitionsLogic)
+ const { closeSourceModal, submitCustomPropertySourceForm, removeSource, setCustomPropertySourceFormValue } =
+ useActions(customPropertyDefinitionsLogic)
+
+ const editing = !!sourceDefinition?.source
+ const noViews = !savedQueriesLoading && materializedViews.length === 0
+
+ return (
+ <LemonModal
+ isOpen={sourceModalVisible}
+ onClose={closeSourceModal}
+ title={`Sync “${sourceDefinition?.name ?? ''}” from a view`}
+ description="Pull this property's values from a materialized view column on each materialization, matched to accounts by external ID."
+ footer={
+ <div className="flex justify-between items-center w-full">
+ <div>
+ {editing && sourceDefinition && (
+ <LemonButton
+ type="secondary"
+ status="danger"
+ onClick={() => removeSource({ definition: sourceDefinition })}
+ loading={definitionsLoading}
+ >
+ Remove sync
+ </LemonButton>
+ )}
+ </div>
+ <div className="flex gap-2">
+ <LemonButton type="secondary" onClick={closeSourceModal}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={submitCustomPropertySourceForm}
+ loading={isCustomPropertySourceFormSubmitting}
+ disabledReason={noViews ? 'No materialized views are available' : undefined}
+ >
+ {editing ? 'Save' : 'Configure sync'}
+ </LemonButton>
+ </div>
+ </div>
+ }
+ >
+ {noViews ? (
+ <LemonBanner type="info">
+ No materialized views found. Create and materialize a view in the data warehouse first, then it can
+ feed this property.
+ </LemonBanner>
+ ) : (
+ <Form
+ logic={customPropertyDefinitionsLogic}
+ formKey="customPropertySourceForm"
+ enableFormOnSubmit
+ className="flex flex-col gap-4"
+ >
+ <LemonField name="savedQuery" label="View">
+ {({ value, onChange }) => (
+ <LemonSelect
+ value={value}
+ onChange={(newValue) => {
+ onChange(newValue)
+ // Columns are view-specific, so a view change invalidates the picks.
+ setCustomPropertySourceFormValue('sourceColumn', null)
+ setCustomPropertySourceFormValue('keyColumn', null)
+ }}
+ options={materializedViews.map((view) => ({ value: view.id, label: view.name }))}
+ loading={savedQueriesLoading}
+ disabledReason={editing ? 'The view is fixed once a sync is created' : undefined}
+ placeholder="Select a materialized view"
+ fullWidth
+ />
+ )}
+ </LemonField>
+ <LemonField
+ name="sourceColumn"
+ label="Value column"
+ help="The column whose value is written to this property."
+ >
+ {({ value, onChange }) => (
+ <LemonSelect
+ value={value}
+ onChange={onChange}
+ options={selectedSourceColumns.map((column) => ({ value: column, label: column }))}
+ loading={savedQueriesLoading}
+ disabledReason={
+ !customPropertySourceForm.savedQuery ? 'Select a view first' : undefined
+ }
+ placeholder="Column to read the value from"
+ fullWidth
+ />
+ )}
+ </LemonField>
+ <LemonField
+ name="keyColumn"
+ label="Key column"
+ help="The column matched against each account's external ID."
+ >
+ {({ value, onChange }) => (
+ <LemonSelect
+ value={value}
+ onChange={onChange}
+ options={selectedSourceColumns.map((column) => ({ value: column, label: column }))}
+ loading={savedQueriesLoading}
+ disabledReason={
+ !customPropertySourceForm.savedQuery ? 'Select a view first' : undefined
+ }
+ placeholder="Column matching the account external ID"
+ fullWidth
+ />
+ )}
+ </LemonField>
+ <LemonField name="isEnabled">
+ {({ value, onChange }) => (
+ <LemonSwitch checked={value} onChange={onChange} label="Sync enabled" bordered />
+ )}
+ </LemonField>
+ </Form>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
index 63359ff894d4..848fcc64e3ea 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
@@ -7,12 +7,35 @@ import { userLogic } from 'scenes/userLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import type {
+ CustomPropertyDefinitionApi,
+ CustomPropertySourceApi,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
import { customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'
const DEFINITIONS_URL = '/api/projects/:team_id/custom_property_definitions/'
const DEFINITION_URL = '/api/projects/:team_id/custom_property_definitions/:id/'
+const SAVED_QUERIES_URL = '/api/environments/:team_id/warehouse_saved_queries/'
+const SOURCES_URL = '/api/projects/:team_id/custom_property_sources/'
+const SOURCE_URL = '/api/projects/:team_id/custom_property_sources/:id/'
+
+const buildSource = (overrides: Partial<CustomPropertySourceApi> = {}): CustomPropertySourceApi =>
+ ({
+ id: 'src-1',
+ definition: 'def-1',
+ saved_query: 'view-1',
+ source_column: 'mrr',
+ key_column: 'org_id',
+ is_enabled: true,
+ consecutive_failures: 0,
+ last_synced_at: '2026-01-02T00:00:00Z',
+ last_sync_error: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: 1,
+ updated_at: '2026-01-02T00:00:00Z',
+ ...overrides,
+ }) as CustomPropertySourceApi
const buildDefinition = (overrides: Partial<CustomPropertyDefinitionApi> = {}): CustomPropertyDefinitionApi =>
({
@@ -21,17 +44,30 @@ const buildDefinition = (overrides: Partial<CustomPropertyDefinitionApi> = {}):
description: null,
display_type: 'currency',
is_big_number: true,
+ source: null,
created_at: '2026-01-01T00:00:00Z',
created_by: 1,
updated_at: '2026-01-01T00:00:00Z',
...overrides,
}) as CustomPropertyDefinitionApi
+// Loosely-typed warehouse view — the logic only reads id/name/columns[].name/is_materialized.
+const buildView = (overrides: Record<string, any> = {}): any => ({
+ id: 'view-1',
+ name: 'billing_view',
+ columns: [{ name: 'org_id' }, { name: 'mrr' }],
+ is_materialized: true,
+ ...overrides,
+})
+
const defaultMocks = (): Parameters<typeof useMocks>[0] => ({
- get: { [DEFINITIONS_URL]: { count: 1, results: [buildDefinition()] } },
- post: { [DEFINITIONS_URL]: buildDefinition({ id: 'def-2' }) },
- patch: { [DEFINITION_URL]: buildDefinition() },
- delete: { [DEFINITION_URL]: {} },
+ get: {
+ [DEFINITIONS_URL]: { count: 1, results: [buildDefinition()] },
+ [SAVED_QUERIES_URL]: { count: 1, results: [buildView()] },
+ },
+ post: { [DEFINITIONS_URL]: buildDefinition({ id: 'def-2' }), [SOURCES_URL]: buildSource() },
+ patch: { [DEFINITION_URL]: buildDefinition(), [SOURCE_URL]: buildSource() },
+ delete: { [DEFINITION_URL]: {}, [SOURCE_URL]: {} },
})
describe('customPropertyDefinitionsLogic', () => {
@@ -144,4 +180,97 @@ describe('customPropertyDefinitionsLogic', () => {
.toDispatchActions(['deleteDefinitionSuccess'])
.toMatchValues({ definitions: [] })
})
+
+ it('loads warehouse views and hydrates the form when configuring an existing source', async () => {
+ useMocks(defaultMocks())
+ mountLogic()
+ await expectLogic(logic, () => logic.actions.openSourceModal(buildDefinition({ source: buildSource() })))
+ .toDispatchActions(['loadSavedQueries', 'loadSavedQueriesSuccess'])
+ .toFinishAllListeners()
+
+ expect(logic.values.sourceModalVisible).toBe(true)
+ expect(logic.values.customPropertySourceForm).toEqual({
+ savedQuery: 'view-1',
+ sourceColumn: 'mrr',
+ keyColumn: 'org_id',
+ isEnabled: true,
+ })
+ })
+
+ it('exposes the selected view columns for the pickers', async () => {
+ useMocks(defaultMocks())
+ mountLogic()
+ await expectLogic(logic, () => logic.actions.openSourceModal(buildDefinition())).toDispatchActions([
+ 'loadSavedQueriesSuccess',
+ ])
+ logic.actions.setCustomPropertySourceFormValue('savedQuery', 'view-1')
+ expect(logic.values.selectedSourceColumns).toEqual(['org_id', 'mrr'])
+ })
+
+ it('creates a source for a definition without one', async () => {
+ let postedBody: Record<string, any> | null = null
+ useMocks({
+ ...defaultMocks(),
+ post: {
+ ...defaultMocks().post,
+ [SOURCES_URL]: async ({ request }) => {
+ postedBody = (await request.json()) as Record<string, any>
+ return buildSource()
+ },
+ },
+ })
+ mountLogic()
+ logic.actions.openSourceModal(buildDefinition())
+ logic.actions.setCustomPropertySourceFormValues({
+ savedQuery: 'view-1',
+ sourceColumn: 'mrr',
+ keyColumn: 'org_id',
+ isEnabled: true,
+ })
+
+ await expectLogic(logic, () => logic.actions.submitCustomPropertySourceForm()).toDispatchActions([
+ 'submitCustomPropertySourceFormSuccess',
+ 'loadDefinitions',
+ 'closeSourceModal',
+ ])
+ expect(postedBody).toEqual({
+ definition: 'def-1',
+ saved_query: 'view-1',
+ source_column: 'mrr',
+ key_column: 'org_id',
+ is_enabled: true,
+ })
+ })
+
+ it('updates an existing source via PATCH without the create-only fields', async () => {
+ let patchedBody: Record<string, any> | null = null
+ useMocks({
+ ...defaultMocks(),
+ patch: {
+ ...defaultMocks().patch,
+ [SOURCE_URL]: async ({ request }) => {
+ patchedBody = (await request.json()) as Record<string, any>
+ return buildSource()
+ },
+ },
+ })
+ mountLogic()
+ logic.actions.openSourceModal(buildDefinition({ source: buildSource() }))
+ logic.actions.setCustomPropertySourceFormValue('isEnabled', false)
+
+ await expectLogic(logic, () => logic.actions.submitCustomPropertySourceForm()).toDispatchActions([
+ 'submitCustomPropertySourceFormSuccess',
+ ])
+ expect(patchedBody).toEqual({ source_column: 'mrr', key_column: 'org_id', is_enabled: false })
+ })
+
+ it('removes a source and closes the modal', async () => {
+ useMocks(defaultMocks())
+ mountLogic()
+ const definition = buildDefinition({ source: buildSource() })
+ await expectLogic(logic, () => logic.actions.removeSource({ definition })).toDispatchActions([
+ 'removeSourceSuccess',
+ 'closeSourceModal',
+ ])
+ })
})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
index 38f8e07fa8f3..97c872158f26 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
@@ -1,16 +1,22 @@
-import { actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
+import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { projectLogic } from 'scenes/projectLogic'
+import type { DataWarehouseSavedQuery } from '~/types'
+
import {
customPropertyDefinitionsCreate,
customPropertyDefinitionsDestroy,
customPropertyDefinitionsList,
customPropertyDefinitionsPartialUpdate,
+ customPropertySourcesCreate,
+ customPropertySourcesDestroy,
+ customPropertySourcesPartialUpdate,
} from 'products/customer_analytics/frontend/generated/api'
import type {
CustomPropertyDefinitionApi,
@@ -34,6 +40,20 @@ const DEFAULT_FORM_VALUES: CustomPropertyFormValues = {
isBigNumber: false,
}
+export interface CustomPropertySourceFormValues {
+ savedQuery: string | null
+ sourceColumn: string | null
+ keyColumn: string | null
+ isEnabled: boolean
+}
+
+const DEFAULT_SOURCE_FORM_VALUES: CustomPropertySourceFormValues = {
+ savedQuery: null,
+ sourceColumn: null,
+ keyColumn: null,
+ isEnabled: true,
+}
+
export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogicType>([
path([
'products',
@@ -51,6 +71,8 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
openCreateModal: true,
openEditModal: (definition: CustomPropertyDefinitionApi) => ({ definition }),
closeModal: true,
+ openSourceModal: (definition: CustomPropertyDefinitionApi) => ({ definition }),
+ closeSourceModal: true,
}),
reducers({
modalVisible: [
@@ -69,6 +91,20 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
closeModal: () => null,
},
],
+ sourceModalVisible: [
+ false,
+ {
+ openSourceModal: () => true,
+ closeSourceModal: () => false,
+ },
+ ],
+ sourceDefinition: [
+ null as CustomPropertyDefinitionApi | null,
+ {
+ openSourceModal: (_, { definition }) => definition,
+ closeSourceModal: () => null,
+ },
+ ],
}),
loaders(({ values }) => ({
definitions: [
@@ -82,6 +118,27 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
await customPropertyDefinitionsDestroy(String(values.currentProjectId), id)
return values.definitions.filter((definition) => definition.id !== id)
},
+ removeSource: async ({
+ definition,
+ }: {
+ definition: CustomPropertyDefinitionApi
+ }): Promise<CustomPropertyDefinitionApi[]> => {
+ if (definition.source) {
+ await customPropertySourcesDestroy(String(values.currentProjectId), definition.source.id)
+ }
+ // Re-fetch so the cleared `source` is reflected — it can't be derived locally.
+ const response = await customPropertyDefinitionsList(String(values.currentProjectId))
+ return response.results
+ },
+ },
+ ],
+ savedQueries: [
+ [] as DataWarehouseSavedQuery[],
+ {
+ loadSavedQueries: async (): Promise<DataWarehouseSavedQuery[]> => {
+ const response = await api.dataWarehouseSavedQueries.list()
+ return response.results
+ },
},
],
})),
@@ -107,7 +164,51 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
}
},
},
+ customPropertySourceForm: {
+ defaults: DEFAULT_SOURCE_FORM_VALUES,
+ errors: ({ savedQuery, sourceColumn, keyColumn }: CustomPropertySourceFormValues) => ({
+ savedQuery: !savedQuery ? 'Select a view' : undefined,
+ sourceColumn: !sourceColumn ? 'Select the value column' : undefined,
+ keyColumn: !keyColumn ? 'Select the key column' : undefined,
+ }),
+ submit: async ({ savedQuery, sourceColumn, keyColumn, isEnabled }: CustomPropertySourceFormValues) => {
+ const definition = values.sourceDefinition
+ if (!definition || !savedQuery || !sourceColumn || !keyColumn) {
+ return
+ }
+ if (definition.source) {
+ // saved_query is create-only — only the mutable fields are sent on update.
+ await customPropertySourcesPartialUpdate(String(values.currentProjectId), definition.source.id, {
+ source_column: sourceColumn,
+ key_column: keyColumn,
+ is_enabled: isEnabled,
+ })
+ } else {
+ await customPropertySourcesCreate(String(values.currentProjectId), {
+ definition: definition.id,
+ saved_query: savedQuery,
+ source_column: sourceColumn,
+ key_column: keyColumn,
+ is_enabled: isEnabled,
+ })
+ }
+ },
+ },
})),
+ selectors({
+ materializedViews: [
+ (s) => [s.savedQueries],
+ (savedQueries: DataWarehouseSavedQuery[]): DataWarehouseSavedQuery[] =>
+ savedQueries.filter((query) => query.is_materialized),
+ ],
+ selectedSourceColumns: [
+ (s) => [s.savedQueries, s.customPropertySourceForm],
+ (savedQueries: DataWarehouseSavedQuery[], form: CustomPropertySourceFormValues): string[] => {
+ const view = savedQueries.find((query) => query.id === form.savedQuery)
+ return (view?.columns ?? []).map((column) => column.name)
+ },
+ ],
+ }),
listeners(({ actions, values }) => ({
openCreateModal: () => {
actions.resetCustomPropertyForm()
@@ -146,6 +247,40 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.load' })
lemonToast.error('Failed to load custom properties')
},
+ openSourceModal: ({ definition }) => {
+ actions.loadSavedQueries()
+ if (definition.source) {
+ actions.setCustomPropertySourceFormValues({
+ savedQuery: definition.source.saved_query,
+ sourceColumn: definition.source.source_column,
+ keyColumn: definition.source.key_column,
+ isEnabled: definition.source.is_enabled ?? true,
+ })
+ } else {
+ actions.resetCustomPropertySourceForm()
+ }
+ },
+ submitCustomPropertySourceFormSuccess: () => {
+ lemonToast.success(values.sourceDefinition?.source ? 'Sync updated' : 'Sync configured')
+ actions.loadDefinitions()
+ actions.closeSourceModal()
+ },
+ submitCustomPropertySourceFormFailure: ({ error }) => {
+ posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.submitSource' })
+ lemonToast.error((error as { detail?: string })?.detail ?? 'Failed to save sync configuration')
+ },
+ removeSourceSuccess: () => {
+ lemonToast.success('Sync removed')
+ actions.closeSourceModal()
+ },
+ removeSourceFailure: ({ error }) => {
+ posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.removeSource' })
+ lemonToast.error('Failed to remove sync')
+ },
+ loadSavedQueriesFailure: ({ error }) => {
+ posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.loadSavedQueries' })
+ lemonToast.error('Failed to load data warehouse views')
+ },
})),
afterMount(({ actions }) => {
actions.loadDefinitions()
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.test.ts
index 910f35eee185..b509029c3be0 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.test.ts
@@ -1,10 +1,14 @@
-import type { CustomPropertyDisplayTypeEnumApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import type {
+ CustomPropertyDisplayTypeEnumApi,
+ CustomPropertySourceApi,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
import {
DISPLAY_TYPE_OPTIONS,
formatCustomPropertyValue,
isNumericDisplayType,
labelForDisplayType,
+ sourceSyncStatus,
} from './customPropertyTypes'
function definition(
@@ -14,6 +18,14 @@ function definition(
return { display_type, is_big_number }
}
+const buildSource = (overrides: Partial<CustomPropertySourceApi>): CustomPropertySourceApi =>
+ ({
+ is_enabled: true,
+ last_sync_error: null,
+ last_synced_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ }) as CustomPropertySourceApi
+
describe('customPropertyTypes', () => {
it('labels each display type with its option label', () => {
expect(labelForDisplayType('currency')).toBe('Currency')
@@ -57,4 +69,22 @@ describe('customPropertyTypes', () => {
expect(formatCustomPropertyValue('n/a', definition('number'))).toBe('n/a')
})
})
+
+ it('derives sync status from the source state', () => {
+ expect(sourceSyncStatus(buildSource({})).level).toBe('synced')
+ expect(sourceSyncStatus(buildSource({ last_synced_at: null })).level).toBe('pending')
+ expect(sourceSyncStatus(buildSource({ last_sync_error: 'boom' })).level).toBe('error')
+ })
+
+ it('shows the last error as the reason when a source is auto-disabled', () => {
+ const status = sourceSyncStatus(buildSource({ is_enabled: false, last_sync_error: 'View not found' }))
+ expect(status.level).toBe('disabled')
+ expect(status.tooltip).toBe('View not found')
+ })
+
+ it('explains manual disabling when a disabled source has no error', () => {
+ const status = sourceSyncStatus(buildSource({ is_enabled: false, last_sync_error: null }))
+ expect(status.level).toBe('disabled')
+ expect(status.tooltip).toBe('Syncing is turned off for this source.')
+ })
})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.ts
index 2711a9cad217..37f04263ed43 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.ts
@@ -3,6 +3,7 @@ import { humanFriendlyCurrency, humanFriendlyLargeNumber, humanFriendlyNumber, p
import type {
CustomPropertyDefinitionApi,
CustomPropertyDisplayTypeEnumApi,
+ CustomPropertySourceApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
// The backend stores the granular display type directly, so the form value maps 1:1 to the API.
@@ -62,3 +63,30 @@ export function formatCustomPropertyValue(
return raw
}
}
+
+export type SourceSyncStatusLevel = 'synced' | 'error' | 'disabled' | 'pending'
+
+export interface SourceSyncStatus {
+ level: SourceSyncStatusLevel
+ label: string
+ tooltip?: string
+}
+
+// Derives the displayed sync state from the source's stored fields. The backend records only
+// `is_enabled` + `last_sync_error` + `last_synced_at`; status is computed, not stored.
+export function sourceSyncStatus(source: CustomPropertySourceApi): SourceSyncStatus {
+ if (!source.is_enabled) {
+ return {
+ level: 'disabled',
+ label: 'Disabled',
+ tooltip: source.last_sync_error ?? 'Syncing is turned off for this source.',
+ }
+ }
+ if (source.last_sync_error) {
+ return { level: 'error', label: 'Sync error', tooltip: source.last_sync_error }
+ }
+ if (!source.last_synced_at) {
+ return { level: 'pending', label: 'Awaiting first sync' }
+ }
+ return { level: 'synced', label: 'Synced' }
+}
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 58204f2b3d7f..4b8aeeab204a 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -309,6 +309,24 @@ tools:
custom-property-definitions-update:
operation: custom_property_definitions_update
enabled: false
+ custom-property-sources-create:
+ operation: custom_property_sources_create
+ enabled: false
+ custom-property-sources-destroy:
+ operation: custom_property_sources_destroy
+ enabled: false
+ custom-property-sources-list:
+ operation: custom_property_sources_list
+ enabled: false
+ custom-property-sources-partial-update:
+ operation: custom_property_sources_partial_update
+ enabled: false
+ custom-property-sources-retrieve:
+ operation: custom_property_sources_retrieve
+ enabled: false
+ custom-property-sources-update:
+ operation: custom_property_sources_update
+ enabled: false
customer-journeys-create:
operation: customer_journeys_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a3c1a5a914d8..00b95c71fa7c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14113,6 +14113,47 @@ export namespace Schemas {
Boolean: 'boolean',
} as const;
+ /**
+ * Binds a materialized data-warehouse view column to a custom property definition; the view's
+ * values are synced onto matching accounts on each materialization.
+ */
+ export interface CustomPropertySource {
+ readonly id: string;
+ /** UUID of the custom property definition this source feeds. One source per definition. */
+ definition: string;
+ /** UUID of the data-warehouse saved query (materialized view) to read values from. */
+ saved_query: string;
+ /**
+ * Column in the view whose value is written to the property.
+ * @maxLength 400
+ */
+ source_column: string;
+ /**
+ * Column in the view whose value matches an account's external_id.
+ * @maxLength 400
+ */
+ key_column: string;
+ /** Whether the source syncs. Auto-disabled after repeated failures or a missing view; re-enabling resets the failure count. */
+ is_enabled?: boolean;
+ /** Consecutive failed sync runs; the source auto-disables at the cap. */
+ readonly consecutive_failures: number;
+ /**
+ * When the most recent sync run finished.
+ * @nullable
+ */
+ readonly last_synced_at: string | null;
+ /**
+ * Error summary from the last run, or null if it succeeded.
+ * @nullable
+ */
+ readonly last_sync_error: string | null;
+ readonly created_at: string;
+ /** @nullable */
+ readonly created_by: number | null;
+ /** @nullable */
+ readonly updated_at: string | null;
+ }
+
/**
* A place that uses a custom property definition (read-only).
*/
@@ -14131,8 +14172,7 @@ export namespace Schemas {
* A team-scoped definition of a custom account property — the attribute side of the model.
*
* Holds only the property's shape (name, display type, big-number flag). Per-account values are
- * stored separately, so this serializer never reads or writes account values. The numeric-only
- * big-number rule and the unique-name conflict are enforced behind the facade.
+ * stored separately, so this serializer never reads or writes account values.
*/
export interface CustomPropertyDefinition {
readonly id: string;
@@ -14158,6 +14198,8 @@ export namespace Schemas {
display_type: CustomPropertyDisplayTypeEnum;
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean;
+ /** The data-warehouse view-sync binding feeding this property, or null when values are set manually. */
+ readonly source: CustomPropertySource | null;
readonly created_at: string;
/** @nullable */
readonly created_by: number | null;
@@ -14167,6 +14209,25 @@ export namespace Schemas {
readonly references: readonly CustomPropertyReference[];
}
+ /**
+ * Writable fields for updating a source. ``definition`` and ``saved_query`` are create-only, so
+ * they are intentionally absent — only these reach the facade's update.
+ */
+ export interface CustomPropertySourceUpdate {
+ /**
+ * Column in the view whose value is written to the property.
+ * @maxLength 400
+ */
+ source_column?: string;
+ /**
+ * Column in the view whose value matches an account's external_id.
+ * @maxLength 400
+ */
+ key_column?: string;
+ /** Whether the source syncs; re-enabling it resets the failure count. */
+ is_enabled?: boolean;
+ }
+
/**
* An account's current value for a custom property (read shape).
*/
@@ -31164,6 +31225,15 @@ export namespace Schemas {
results: CustomPropertyDefinition[];
}
+ export interface PaginatedCustomPropertySourceList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: CustomPropertySource[];
+ }
+
export interface PaginatedCustomerJourneyList {
count: number;
/** @nullable */
@@ -36243,8 +36313,7 @@ export namespace Schemas {
* A team-scoped definition of a custom account property — the attribute side of the model.
*
* Holds only the property's shape (name, display type, big-number flag). Per-account values are
- * stored separately, so this serializer never reads or writes account values. The numeric-only
- * big-number rule and the unique-name conflict are enforced behind the facade.
+ * stored separately, so this serializer never reads or writes account values.
*/
export interface PatchedCustomPropertyDefinition {
readonly id?: string;
@@ -36270,6 +36339,8 @@ export namespace Schemas {
display_type?: CustomPropertyDisplayTypeEnum;
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean;
+ /** The data-warehouse view-sync binding feeding this property, or null when values are set manually. */
+ readonly source?: CustomPropertySource | null;
readonly created_at?: string;
/** @nullable */
readonly created_by?: number | null;
@@ -36279,6 +36350,25 @@ export namespace Schemas {
readonly references?: readonly CustomPropertyReference[];
}
+ /**
+ * Writable fields for updating a source. ``definition`` and ``saved_query`` are create-only, so
+ * they are intentionally absent — only these reach the facade's update.
+ */
+ export interface PatchedCustomPropertySourceUpdate {
+ /**
+ * Column in the view whose value is written to the property.
+ * @maxLength 400
+ */
+ source_column?: string;
+ /**
+ * Column in the view whose value matches an account's external_id.
+ * @maxLength 400
+ */
+ key_column?: string;
+ /** Whether the source syncs; re-enabling it resets the failure count. */
+ is_enabled?: boolean;
+ }
+
export interface PatchedCustomerJourney {
readonly id?: string;
insight?: number;
@@ -61079,6 +61169,17 @@ export namespace Schemas {
offset?: number;
};
+ export type CustomPropertySourcesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type CustomerJourneysListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index 92f979a204ad..67439c1978cc 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -317,7 +317,7 @@ export const CustomPropertyDefinitionsCreateBody = /* @__PURE__ */ zod
.describe('Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties.'),
})
.describe(
- "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values. The numeric-only\nbig-number rule and the unique-name conflict are enforced behind the facade."
+ "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values."
)
export const CustomPropertyDefinitionsRetrieveParams = /* @__PURE__ */ zod.object({
@@ -363,7 +363,7 @@ export const CustomPropertyDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
.describe('Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties.'),
})
.describe(
- "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values. The numeric-only\nbig-number rule and the unique-name conflict are enforced behind the facade."
+ "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values."
)
export const CustomPropertyDefinitionsDestroyParams = /* @__PURE__ */ zod.object({