: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): read warehouse properties from materialized views (#83850)
Tom Owers60d5777e08e0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a0999f07fbdc..20e9543e60b3 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5937,13 +5937,13 @@ snapshots:scenes-app-data-management--ingestion-warnings--light:hash: v1.k794b7964.3209e00fefa6b56227f01db9fe3f231e0bef672e4fbae05757144510e79094f1.hzeCCQksEIyxI52va51UNvenmIlxwKNAFf21tLkD_MIscenes-app-data-management--warehouse-properties--dark:- hash: v1.k794b7964.665922080691f05ad35d117c89b0eb715ad678a707cb278892eb627eb2ff62c2.ESs6rHGY5A-Ss_ssl5SyF7uc98sfu2wZij4pmR6la18+ hash: v1.k794b7964.ee5d8237fc9ebc790c7e71a71e01e1831e8f132caa2363d93ddae59ecfd6eaf8.j44UeGwvBsVjvX8fHyKOsRlpYvR9PRu9gUMayoeysRUscenes-app-data-management--warehouse-properties--light:- hash: v1.k794b7964.cbb43b5ac8dd2d367d44359ebfc3153294dfdb618b7663a5202d9fbfd14d77e6.3zG1301UKdyuoQRz9vTIjlLTTs8LygETMtOTsDK5UqA+ hash: v1.k794b7964.119edaac6990f8debc3d44e00bd2a355642af239e35c11a4d7c6c1d4856c68be.RlUIPKdDbZoCIAxIPtqWcxv6fcd7EfgOQAuiYJRREjIscenes-app-data-management--warehouse-properties-groups-tab--dark:- hash: v1.k794b7964.e7a956ea10bc12b0665dacf6f77e06007c5c881e6af54e6253010a378d216f29.DG8_wQnqLMr-LisByo39mZnjiMBs5r22TzkUYIWBGhc+ hash: v1.k794b7964.75e04bee3fdb59a1843eaa5161081a18503dab7819507ea18cdc58c1b6530a30.bp087q5qYwr2GjacmAfRqtEjwnzqO4qbBACRunoW5vMscenes-app-data-management--warehouse-properties-groups-tab--light:- hash: v1.k794b7964.64bfec93b16ecc0852691d8f407d19f27b5c3c07b3292ef7fe3eddf57e23c56d.pRBZME1SPf0vemOSwV41eu3dIa91C2E6c5r1imkukTI+ hash: v1.k794b7964.055dad5f89f7a11a6b6d0bb732e7f9420d68508a00745e8de1fcf8b204450779.Ab4pvOaOoH-NBrU1x5hj1DJs--s5NlJM6B3cyqiWbNUscenes-app-data-management-actions--action--dark:hash: v1.k794b7964.00b57c65346e514c9454e88054c04eb8aef6f1093d64fdc46cbbef3604e7f2d6.89yiroC6COFhV4T8jtCoYYdBQat6ZW24vyN_AW3GRTIscenes-app-data-management-actions--action--light:diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex c9e5ebfc2988..e99d092df1cb 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -22,6 +22,7 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_ast_for_printing, print_prepared_astfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Teamfrom posthog.ph_client import feature_enabled_or_falsefrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME@@ -59,6 +60,8 @@ from products.data_quality.backend.facade import api as data_quality_facadefrom products.data_quality.backend.facade.contracts import QUALITY_AUDIT_SKIP, QualityAuditModefrom products.data_warehouse.backend.facade.api import ensure_bucket_exists, get_s3_clientfrom products.endpoints.backend.facade.temporal import prepare_executable_query+from products.warehouse_sources.backend.facade.hooks import saved_query_binding+from products.warehouse_sources.backend.facade.temporal import PersonPropertyRowSinkLOGGER = get_logger(__name__)@@ -179,7 +182,7 @@ class MaterializeViewInputs:}[email protected](frozen=False)[email protected](frozen=True)class MaterializeViewResult:node_id: strnode_name: str@@ -191,6 +194,10 @@ class MaterializeViewResult:# Whether this run upserted a window rather than rebuilding. Defaulted so old workflow# histories decode without it.incremental: bool = False+ # Whether this run staged row projections for a person/group-target warehouse property, which is+ # what the workflow gates the person-property child on. Defaulted to the skip value so an old+ # history decodes without it and never fires that child during replay.+ person_property_sync_enabled: bool = Falsedef _build_model_table_uri(team_id: int, saved_query_id_hex: str, normalized_name: str) -> str:@@ -603,6 +610,65 @@ def _get_matview_input_objects(return MatviewInputObjects(team=team, node=node, saved_query=saved_query, job=job)+async def _build_person_property_sink(+ objects: MatviewInputObjects, job_id: str, logger: FilteringBoundLogger, *, incremental: bool+) -> PersonPropertyRowSink | None:+ """A sink for this view, or None when no warehouse property reads it.++ The gate is one query behind ``should_run()``, so a view nobody maps pays that and nothing else.+ A failure to resolve it must not fail the materialization, which is the run that matters.+ """+ sink = PersonPropertyRowSink(+ team_id=objects.team.pk,+ binding=saved_query_binding(objects.saved_query.id),+ job_id=job_id,+ logger=logger,+ is_incremental=incremental,+ )+ try:+ return sink if await sink.should_run() else None+ except Exception as e:+ await logger.awarning(f"Could not resolve person-property staging for this view: {e}")+ capture_exception(e)+ return None+++async def _clear_person_property_staging(sink: PersonPropertyRowSink, logger: FilteringBoundLogger) -> None:+ """Clear stale staged rows at run start. Never raises, for the same reason staging doesn't."""+ try:+ await sink.clear()+ except Exception as e:+ await logger.awarning(f"Could not clear stale person-property staging: {e}")+ capture_exception(e)+++async def _stage_person_property_batch(+ sink: PersonPropertyRowSink | None, batch_index: int, batch: pa.RecordBatch, *, fatal: bool+) -> None:+ """Stage one written batch's projected columns, if a warehouse property reads this view.++ Staged from the transformed batch, so the values a person property gets are the ones the Delta+ table gets.++ ``fatal`` follows the write path. A full rebuild re-stages every row on its next run, so there a+ staging failure only costs that run's updates and is swallowed (``fatal=False``). An incremental+ run stages only its own window and then advances the watermark past it, so a swallowed failure+ would move the watermark past rows that never reached staging, which no later incremental run+ re-stages until they change again. The incremental path therefore raises (``fatal=True``) to fail+ the run before the watermark is recorded — matching the import pipeline's sink contract — so+ Temporal retries the whole window.+ """+ if sink is None:+ return+ try:+ await sink.stage_chunk(batch_index, pa.Table.from_batches([batch]))+ except Exception as e:+ await sink.logger.awarning(f"Failed to stage person-property batch {batch_index}: {e}")+ if fatal:+ raise+ capture_exception(e)++async def _materialize_fully(objects: MatviewInputObjects,plan: WritePlan,@@ -610,6 +676,7 @@ async def _materialize_fully(table_uri: str,storage_options: dict[str, str],logger: FilteringBoundLogger,+ person_property_sink: PersonPropertyRowSink | None = None,) -> tuple[int, list[str]]:"""Rebuild the whole table from the query. The only path that creates a Delta table, and thefallback for every case the incremental path cannot serve."""@@ -640,12 +707,15 @@ async def _materialize_fully(# batch (hogql_table yields ~100MB combined batches) and, because each write is a# brief to_thread released between batches, never pins a worker thread for the whole# read — which is what starved the shared executor that heartbeats/db/logging use.+ batch_index = 0async for batch, ch_types in hogql_table(hogql_query, objects.team, logger):batch = _transform_unsupported_decimals(batch)batch = _transform_date_and_datetimes(batch, ch_types)batch = _force_nullable(batch)if tracker is not None:await asyncio.to_thread(tracker.check, batch)+ await _stage_person_property_batch(person_property_sink, batch_index, batch, fatal=False)+ batch_index += 1if delta_table is None:pa_schema = batch.schemaawait asyncio.to_thread(@@ -702,6 +772,7 @@ async def _materialize_incrementally(table_uri: str,storage_options: dict[str, str],logger: FilteringBoundLogger,+ person_property_sink: PersonPropertyRowSink | None = None,) -> tuple[int, list[str]]:"""Upsert only the rows at or after the watermark into the existing table.@@ -723,6 +794,9 @@ async def _materialize_incrementally(row_count = 0watermark: typing.Any = Nonetracker = UniqueKeyTracker(config.unique_key)+ # Staged per attempt, never cleared: a retry resumes past the watermark the failed attempt+ # already saved, so its staged rows are that window's only record (see PersonPropertyRowSink).+ batch_index = 0try:async for batch, ch_types in hogql_table(hogql_query, objects.team, logger, window=window):@@ -738,6 +812,8 @@ async def _materialize_incrementally(# Checked before the upsert so a duplicate split across batches fails the run instead# of the later batch silently replacing the earlier one.await asyncio.to_thread(tracker.check, batch)+ await _stage_person_property_batch(person_property_sink, batch_index, batch, fatal=True)+ batch_index += 1stats = await asyncio.to_thread(upsert_batch,@@ -829,16 +905,26 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ)await database_sync_to_async_pool(objects.job.save)()+ person_property_sink = await _build_person_property_sink(+ objects, inputs.job_id, logger, incremental=plan.incremental+ )+ if person_property_sink is not None:+ # Cleared once at run start, like the import pipeline's sinks. The sink itself decides what to+ # drop: a rebuild re-reads every row so a dead attempt's files are safe to remove, while an+ # incremental retry resumes past its saved watermark and must keep them. Either way this is+ # what sweeps long-abandoned sibling job prefixes.+ await _clear_person_property_staging(person_property_sink, logger)+async with Heartbeater():hogql_query = typing.cast(dict, objects.saved_query.query)["query"]if plan.incremental:row_count, file_uris = await _materialize_incrementally(- objects, plan, hogql_query, table_uri, storage_options, logger+ objects, plan, hogql_query, table_uri, storage_options, logger, person_property_sink)else:row_count, file_uris = await _materialize_fully(- objects, plan, hogql_query, table_uri, storage_options, logger+ objects, plan, hogql_query, table_uri, storage_options, logger, person_property_sink)await logger.ainfo(f"Materialized node {objects.node.name} with {row_count} rows")@@ -854,4 +940,5 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializsaved_query_id=str(objects.saved_query.id),quality_audit=quality_audit,incremental=plan.incremental,+ person_property_sync_enabled=person_property_sink is not None,)diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.pyindex dba3f2071cce..66bcc3fc28ee 100644--- a/posthog/temporal/data_modeling/workflows/materialize_view.py+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py@@ -1,4 +1,5 @@import json+import uuidimport asyncioimport datetime as dtimport dataclasses@@ -64,6 +65,10 @@ from products.data_quality.backend.facade.contracts import (is_quality_audit_mode,)from products.data_quality.backend.facade.enums import SuiteRunTrigger+from products.warehouse_sources.backend.facade.hooks import (+ MATERIALIZED_VIEW_SOURCE_TYPE,+ PersonPropertySyncActivityInputs,+)# Covers every command the data quality feature adds here: the stage/audit/publish trio and the# warn-mode suite child.@@ -357,6 +362,10 @@ class MaterializeViewWorkflow(PostHogWorkflow):if quality_audit == QUALITY_AUDIT_WARN:quality_audited = await self._start_suite_on_published_data(inputs, job_id, materialize_result)+ # Upsert this view's columns onto person/group properties for any warehouse property+ # that reads it. Fire-and-forget on the metadata queue, like enrichment above.+ await self._maybe_sync_person_properties(inputs, materialize_result, job_id)+# after the main workflow succeeds, collect shadow stats for comparisonif duckgres_shadow_handle is not None:await self._collect_shadow_comparison(@@ -546,6 +555,56 @@ class MaterializeViewWorkflow(PostHogWorkflow):)return QUALITY_AUDIT_SKIP+ async def _maybe_sync_person_properties(+ self,+ inputs: MaterializeViewWorkflowInputs,+ materialize_result: MaterializeViewResult,+ job_id: str,+ ) -> None:+ """Fire the person-property sync child when this run staged rows for a warehouse property.++ Same isolation as enrichment above: ABANDON so it never blocks or fails this workflow, and+ every error swallowed. Keyed per job rather than per view, because each run stages its rows+ under a job-scoped S3 prefix that only its own child consumes — a per-view id would coalesce+ a concurrent run's child and silently drop that run's staged rows.++ Gated on ``person_property_sync_enabled``, a defaulted field on the materialize activity's+ result, so an in-flight run recorded before this existed decodes it as False and never runs+ this command during replay.+ """+ if not materialize_result.person_property_sync_enabled:+ return+ try:+ await temporalio.workflow.start_child_workflow(+ "sync-warehouse-person-properties",+ PersonPropertySyncActivityInputs(+ team_id=inputs.team_id,+ schema_id=None,+ source_id=None,+ job_id=job_id,+ source_type=MATERIALIZED_VIEW_SOURCE_TYPE,+ schema_name=materialize_result.node_name,+ last_synced_at=None,+ saved_query_id=uuid.UUID(materialize_result.saved_query_id),+ ),+ id=f"sync-warehouse-person-properties-{job_id}",+ id_reuse_policy=temporalio.common.WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,+ parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,+ execution_timeout=dt.timedelta(hours=6),+ )+ except WorkflowAlreadyStartedError:+ temporalio.workflow.logger.info(+ "Person-property sync already running for this job, skipping",+ extra={"job_id": job_id},+ )+ except Exception as e:+ capture_exception(e)+ temporalio.workflow.logger.warning(+ "Failed to start person-property sync",+ extra={"job_id": job_id, "error": str(e)},+ )+async def _maybe_enrich_view_semantics(self,inputs: MaterializeViewWorkflowInputs,diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 44e92bce7dc8..7bc43a1f4afd 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -54,7 +54,11 @@ from products.data_modeling.backend.facade.models import ()from products.data_warehouse.backend.facade.api import CreateTableResultfrom products.notifications.backend.facade.api import NotificationType, TargetType+from products.warehouse_sources.backend.facade.hooks import PersonPropertySourceProjection, saved_query_bindingfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_paths import (+ job_staged_prefix,+)pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]@@ -1719,3 +1723,83 @@ class TestHogqlTableResolutionDeadline:batches = [batch async for batch in hogql_table("SELECT now() AS ts", ateam, LOGGER.bind())]assert [name for name, _ in batches[0][1]] == ["ts"]+++class TestMaterializeViewStagesPersonPropertyRows:+ """A view feeding a warehouse property stages its projected rows as it writes, so the post-run sync+ reads only this run's rows instead of the whole table."""++ @staticmethod+ def _hogql_table(*args, **kwargs):+ del args, kwargs+ data = cast(+ Collection[pa.Array],+ [pa.array(["a", "b"], type=pa.string()), pa.array(["pro", "free"], type=pa.string())],+ )+ batch = pa.RecordBatch.from_arrays(data, names=["distinct_id", "plan"])++ async def async_generator():+ yield batch, [("distinct_id", "String"), ("plan", "String")]++ return async_generator()++ @contextlib.contextmanager+ def _env(self, bucket_name, projection):+ with (+ override_settings(+ BUCKET_URL=f"s3://{bucket_name}",+ DATAWAREHOUSE_BUCKET=bucket_name,+ DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,+ DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,+ DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",+ USE_LOCAL_SETUP=True,+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.materialize_view.hogql_table", self._hogql_table+ ),+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports."+ "pipelines.core.person_property_row_sink.person_property_projection_for",+ return_value=projection,+ ),+ ):+ yield++ async def test_stages_projected_columns_and_flags_the_run(+ self, activity_environment, ateam, anode, asaved_query, ajob, adag, bucket_name, minio_client+ ):+ projection = [PersonPropertySourceProjection(key_column="distinct_id", columns=frozenset({"distinct_id"}))]+ inputs = MaterializeViewInputs(+ team_id=ateam.pk, dag_id=str(adag.id), node_id=str(anode.id), job_id=str(ajob.id)+ )+ with self._env(bucket_name, projection):+ result = await activity_environment.run(materialize_view_activity, inputs)+ # Resolved inside the overridden settings, so it names the same bucket the sink wrote to.+ prefix = job_staged_prefix(ateam.pk, saved_query_binding(asaved_query.id), str(ajob.id))++ # The workflow gates the person-property child on this field.+ assert result.person_property_sync_enabled is True++ listing = await minio_client.list_objects_v2(Bucket=bucket_name, Prefix=prefix.removeprefix(f"{bucket_name}/"))+ keys = [obj["Key"] for obj in listing.get("Contents", [])]+ assert len(keys) == 1, f"expected one staged chunk under {prefix}, got {keys}"++ staged = await minio_client.get_object(Bucket=bucket_name, Key=keys[0])+ table = pq.read_table(BytesIO(await staged["Body"].read()))+ # Only the projected columns leave the pipeline — "plan" isn't mapped by this projection.+ assert table.column_names == ["distinct_id"]+ assert table.column("distinct_id").to_pylist() == ["a", "b"]++ async def test_unmapped_view_stages_nothing_and_leaves_the_flag_off(+ self, activity_environment, ateam, anode, ajob, adag, bucket_name, minio_client+ ):+ # The gate is what keeps an unmapped view (the vast majority) from paying for staging at all.+ inputs = MaterializeViewInputs(+ team_id=ateam.pk, dag_id=str(adag.id), node_id=str(anode.id), job_id=str(ajob.id)+ )+ with self._env(bucket_name, None):+ result = await activity_environment.run(materialize_view_activity, inputs)++ assert result.person_property_sync_enabled is False+ listing = await minio_client.list_objects_v2(Bucket=bucket_name, Prefix="person_property_sync/")+ assert listing.get("Contents", []) == []diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_staging.py b/posthog/temporal/tests/data_modeling/test_materialize_view_staging.pynew file mode 100644index 000000000000..48c983fc9edb--- /dev/null+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_staging.py@@ -0,0 +1,37 @@+import pytest+from unittest.mock import AsyncMock, MagicMock++import pyarrow as pa++from posthog.temporal.data_modeling.activities.materialize_view import _stage_person_property_batch++pytestmark = pytest.mark.asyncio+++def _sink() -> MagicMock:+ return MagicMock(stage_chunk=AsyncMock(), logger=MagicMock(awarning=AsyncMock()))+++def _batch() -> pa.RecordBatch:+ return pa.RecordBatch.from_arrays([pa.array(["a"])], names=["distinct_id"])+++class TestStagePersonPropertyBatch:+ async def test_incremental_staging_failure_fails_the_run(self) -> None:+ # Swallowing this would let the watermark advance past rows that never reached staging, and an+ # incremental run never re-stages them until they change again. It must raise so Temporal+ # retries the window before the watermark is recorded — the import pipeline's sink contract.+ sink = _sink()+ sink.stage_chunk.side_effect = RuntimeError("staging blew up")+ with pytest.raises(RuntimeError, match="staging blew up"):+ await _stage_person_property_batch(sink, 0, _batch(), fatal=True)++ async def test_full_refresh_staging_failure_is_swallowed(self) -> None:+ # A rebuild re-stages every row on its next run, so a single miss is acceptable and must not+ # fail the materialization.+ sink = _sink()+ sink.stage_chunk.side_effect = RuntimeError("staging blew up")++ await _stage_person_property_batch(sink, 0, _batch(), fatal=False)++ sink.logger.awarning.assert_awaited_once()diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.pyindex c538b8888187..458fbf09f3ac 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py@@ -22,6 +22,7 @@ from posthog.temporal.data_modeling.workflows.materialize_view import ()from products.data_quality.backend.facade.contracts import CHECK_SUITE_WORKFLOW_NAME, QualityAuditMode+from products.warehouse_sources.backend.facade.hooks import PersonPropertySyncActivityInputspytestmark = pytest.mark.asyncio@@ -372,3 +373,60 @@ class TestCollectShadowComparison:assert activity is fail_materialization_activityassert payload.job_id == "job-123"assert payload.update_node is False+++def _person_sync_result(**overrides) -> MaterializeViewResult:+ kwargs: dict = {+ "node_id": "node-1",+ "node_name": "enriched_users",+ "row_count": 3,+ "table_uri": "s3://bucket/team_7_model_abc/modeling/enriched_users",+ "file_uris": ["s3://bucket/f.parquet"],+ "saved_query_id": "0198f2b1-0000-7000-8000-000000000001",+ }+ kwargs.update(overrides)+ return MaterializeViewResult(**kwargs)+++class TestMaybeSyncPersonProperties:+ async def test_starts_child_with_the_view_binding_when_rows_were_staged(self):+ workflow = MaterializeViewWorkflow()+ result = _person_sync_result(person_property_sync_enabled=True)+ with patch.object(temporalio.workflow, "start_child_workflow", new=AsyncMock()) as start_child:+ await workflow._maybe_sync_person_properties(_inputs(), result, "job-123")++ start_child.assert_awaited_once()+ assert start_child.await_args is not None+ name, payload = start_child.await_args.args+ assert name == "sync-warehouse-person-properties"+ assert isinstance(payload, PersonPropertySyncActivityInputs)+ # The child reads the rows this run staged, so it has to name the view, not a schema.+ assert payload.schema_id is None+ assert str(payload.saved_query_id) == result.saved_query_id+ assert payload.binding.kind == "saved_query"+ assert payload.job_id == "job-123"+ # Keyed per job: a per-view id would coalesce a concurrent run's child and drop its staged rows.+ assert start_child.await_args.kwargs["id"] == "sync-warehouse-person-properties-job-123"++ async def test_no_child_when_nothing_was_staged(self):+ # The flag defaults to False, so a run recorded before this existed decodes it as False and+ # never fires this command during replay — which is what keeps in-flight runs deterministic.+ workflow = MaterializeViewWorkflow()+ assert _person_sync_result().person_property_sync_enabled is False+ with patch.object(temporalio.workflow, "start_child_workflow", new=AsyncMock()) as start_child:+ await workflow._maybe_sync_person_properties(_inputs(), _person_sync_result(), "job-123")+ start_child.assert_not_awaited()++ @pytest.mark.parametrize(+ "error",+ [WorkflowAlreadyStartedError("sync-warehouse-person-properties-job-123", "type"), RuntimeError("boom")],+ )+ async def test_start_failures_never_fail_the_materialization(self, error):+ workflow = MaterializeViewWorkflow()+ result = _person_sync_result(person_property_sync_enabled=True)+ with (+ patch.object(temporalio.workflow, "start_child_workflow", new=AsyncMock(side_effect=error)),+ patch.object(temporalio.workflow, "logger"),+ patch(f"{WORKFLOW_MODULE}.capture_exception"),+ ):+ await workflow._maybe_sync_person_properties(_inputs(), result, "job-123")diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex f274fb3ecc7d..449cb527880a 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -63,6 +63,7 @@ from pydantic import ValidationError as PydanticValidationErrorfrom temporalio.common import RetryPolicy, WorkflowIDReusePolicyfrom temporalio.exceptions import WorkflowAlreadyStartedError+from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Integration, OrganizationMembership, Tagfrom posthog.models.activity_logging.activity_log import AuditableScope, Detail, Trigger, changes_between, log_activity@@ -156,6 +157,7 @@ from products.notebooks.backend.facade import (# cross a data facade. All account-notebook CRUD goes through `notebooks` (the facade). Tracked by# the notebooks legacy-leak interface block.from products.notebooks.backend.models import ResourceNotebook+from products.warehouse_sources.backend.facade.hooks import WarehouseBinding, saved_query_binding, schema_bindingfrom products.workflows.backend.services.template_input_usage import get_hog_flows_referencing_template_input_keysfrom . import contracts@@ -827,6 +829,12 @@ class WarehouseSyncPausedError(Exception):message the canonical warehouse schema reload/resync endpoints return."""+class ViewNotSyncableError(Exception):+ """Raised when a person-property "sync now" targets a materialized view that can't be+ materialized on demand — it was deleted, or its DAG still runs on the older data-modeling+ schedule, whose workflow never stages person-property rows. The view maps this to 400."""++# Re-export the "not found" exceptions so the view can branch to 404 without importing the# models. They are model ``DoesNotExist`` subclasses raised by the team-scoped detail fetches.Account_DoesNotExist = Account.DoesNotExist@@ -1364,19 +1372,44 @@ def _to_sync_run_view(run: "CustomPropertySyncRun") -> contracts.CustomPropertyS)-def _resolve_person_source_schema(source: CustomPropertySource, user_access_control: "UserAccessControl | None") -> Any:- """The ``ExternalDataSchema`` (with ``.source`` loaded) backing a person source, or None when the- source has no warehouse binding or the caller lacks object-level ``external_data_source`` viewer- access. ``user_access_control`` None (service auth) skips the object check, matching- ``_enforce_object_access``. ``apps.get_model`` keeps this off a warehouse_sources internal import."""- if source.external_data_schema_id is None:+@frozen+class _ProfileWarehouseMeta:+ """Display metadata a profile source derives from the warehouse object it reads.++ Resolved for both binding kinds so the view builder doesn't branch on kind. ``external_data_source``+ is set only for a schema binding (a view has no import source), ``saved_query_name`` only for a view.+ """++ table_name: str+ sync_frequency_interval_seconds: float | None = None+ next_sync_at: datetime | None = None+ external_data_source: UUID | None = None+ saved_query_name: str | None = None+++def _profile_binding(source: CustomPropertySource) -> "WarehouseBinding | None":+ """The warehouse object a person/group-target source reads, or None for an account source.++ Reads ``definition.target_type`` rather than inferring from which column is set: an account source+ is also bound to a saved query, so the binding column alone no longer tells the two apart. Callers+ pass a source with its definition selected.+ """+ if source.definition.target_type not in _WAREHOUSE_PROFILE_TARGETS:return None+ if source.saved_query_id is not None:+ return saved_query_binding(source.saved_query_id)+ if source.external_data_schema_id is not None:+ return schema_binding(source.external_data_schema_id)+ return None+++def _resolve_schema(team_id: int, schema_id: Any, user_access_control: "UserAccessControl | None") -> Any:+ """The ``ExternalDataSchema`` (with ``.source`` loaded) for a schema-bound source, or None when it+ no longer exists or the caller lacks object-level ``external_data_source`` viewer access.+ ``user_access_control`` None (service auth) skips the object check, matching ``_enforce_object_access``.+ ``apps.get_model`` keeps this off a warehouse_sources internal import."""schema_model = apps.get_model("warehouse_sources", "ExternalDataSchema")- schema = (- schema_model.objects.filter(id=source.external_data_schema_id, team_id=source.team_id)- .select_related("source", "table")- .first()- )+ schema = schema_model.objects.filter(id=schema_id, team_id=team_id).select_related("source", "table").first()if schema is None:return Noneif user_access_control is not None and not user_access_control.check_access_level_for_object(@@ -1386,6 +1419,53 @@ def _resolve_person_source_schema(source: CustomPropertySource, user_access_contreturn schema+def _resolve_saved_query(team_id: int, saved_query_id: Any, user_access_control: "UserAccessControl | None") -> Any:+ """The ``DataWarehouseSavedQuery`` for a view-bound source, or None when it no longer resolves or+ the caller lacks object-level ``warehouse_view`` viewer access — the same gate the warehouse view+ endpoints and HogQL resolution apply."""+ saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")+ saved_query = saved_query_model.objects.filter(id=saved_query_id, team_id=team_id).exclude(deleted=True).first()+ if saved_query is None:+ return None+ if user_access_control is not None and not user_access_control.check_access_level_for_object(+ saved_query, required_level="viewer"+ ):+ return None+ return saved_query+++def _saved_query_meta(saved_query: Any) -> _ProfileWarehouseMeta:+ """Display metadata for a view-bound source. A view's name is already its HogQL name, so it needs+ no table-name resolution. ``sync_frequency_interval`` is null once the view's DAG runs on a shared+ schedule (the frequency lives on the DAG node), which leaves the next run unknown rather than+ guessable — so both schedule fields stay None."""+ interval = saved_query.sync_frequency_interval+ next_sync_at = (+ saved_query.last_run_at + interval if interval is not None and saved_query.last_run_at is not None else None+ )+ return _ProfileWarehouseMeta(+ table_name=saved_query.name,+ sync_frequency_interval_seconds=interval.total_seconds() if interval is not None else None,+ next_sync_at=next_sync_at,+ saved_query_name=saved_query.name,+ )+++def _resolve_profile_warehouse_meta(+ source: CustomPropertySource, user_access_control: "UserAccessControl | None"+) -> _ProfileWarehouseMeta | None:+ """Warehouse-derived display metadata for a profile source, or None for an account source, a+ warehouse object that no longer exists, or a caller without viewer access to it."""+ binding = _profile_binding(source)+ if binding is None:+ return None+ if binding.is_saved_query:+ saved_query = _resolve_saved_query(source.team_id, binding.id, user_access_control)+ return _saved_query_meta(saved_query) if saved_query is not None else None+ schema = _resolve_schema(source.team_id, binding.id, user_access_control)+ return _schema_meta(schema) if schema is not None else None++def _schema_table_name(schema: Any) -> str:"""The bound table as it is named in HogQL, so the UI shows the name the table picker offered.Falls back to the schema name when the first sync hasn't created the table yet. The HogQL import@@ -1399,14 +1479,19 @@ def _schema_table_name(schema: Any) -> str:return get_data_warehouse_table_name(schema.source, schema.table.name)-def _schema_schedule(schema: Any) -> tuple[float | None, datetime | None]:- """(sync_frequency_interval_seconds, next_sync_at) for a resolved schema, both None when the schema- has no sync frequency configured."""+def _schema_meta(schema: Any) -> _ProfileWarehouseMeta:+ """Display metadata for a schema-bound source. Both schedule fields stay None when the schema has+ no sync frequency configured."""interval = schema.sync_frequency_interval- if interval is None:- return None, None- next_sync_at = schema.last_synced_at + interval if schema.last_synced_at is not None else None- return interval.total_seconds(), next_sync_at+ next_sync_at = (+ schema.last_synced_at + interval if interval is not None and schema.last_synced_at is not None else None+ )+ return _ProfileWarehouseMeta(+ table_name=_schema_table_name(schema),+ sync_frequency_interval_seconds=interval.total_seconds() if interval is not None else None,+ next_sync_at=next_sync_at,+ external_data_source=schema.source_id,+ )# Sentinel so a caller can pass a prefetched (schema, latest_run) pair — including ``(None, None)``@@ -1421,39 +1506,30 @@ _RESOLVE_ENRICHMENT_INLINE = _ResolveEnrichmentInline()def _to_custom_property_source_view(source: CustomPropertySource,user_access_control: "UserAccessControl | None" = None,- enrichment: "tuple[Any, CustomPropertySyncRun | None] | _ResolveEnrichmentInline" = _RESOLVE_ENRICHMENT_INLINE,+ enrichment: "tuple[_ProfileWarehouseMeta | None, CustomPropertySyncRun | None] | _ResolveEnrichmentInline" = _RESOLVE_ENRICHMENT_INLINE,) -> contracts.CustomPropertySourceView:- # Schedule + latest-run enrichment applies only to person sources; account sources leave it None.- # A person source is exactly the one bound to a warehouse schema (the facade enforces one binding),- # so this discriminates without a definition fetch. The enrichment exposes the underlying billable- # warehouse source's schedule and run metadata, so it's gated on the caller's warehouse-source viewer- # access — a caller without it sees the source but not its warehouse-derived metadata.- # ``enrichment`` lets list endpoints prefetch the schema + latest run in one batched query each- # (see ``_batch_source_enrichment``) instead of paying two queries per row.- sync_frequency_interval_seconds: float | None = None- next_sync_at: datetime | None = None+ # Schedule + latest-run enrichment applies only to person/group sources; account sources leave it+ # None. The enrichment exposes the underlying warehouse object's schedule and run metadata, so it's+ # gated on the caller's viewer access to that object — a caller without it sees the source but not+ # its warehouse-derived metadata. ``enrichment`` lets list endpoints prefetch the metadata + latest+ # run in one batched query each (see ``_batch_source_enrichment``) instead of two per row.latest_run: contracts.CustomPropertySyncRunView | None = None- external_data_source: UUID | None = None- table_name: str | None = Noneif isinstance(enrichment, _ResolveEnrichmentInline):- schema = _resolve_person_source_schema(source, user_access_control)- latest = source.sync_runs.order_by("-created_at").first() if schema is not None else None+ meta = _resolve_profile_warehouse_meta(source, user_access_control)+ latest = source.sync_runs.order_by("-created_at").first() if meta is not None else None_expire_stale_running_runs(source.team_id, [latest])else:- schema, latest = enrichment- if schema is not None:- sync_frequency_interval_seconds, next_sync_at = _schema_schedule(schema)+ meta, latest = enrichment+ if meta is not None:latest_run = _to_sync_run_view(latest) if latest is not None else None- external_data_source = schema.source_id- table_name = _schema_table_name(schema)- # A person source's sync status (raw error text, failure streak, last-synced time) is produced by- # the underlying billable warehouse source, so it's warehouse-derived metadata gated the same way as- # the schedule/latest-run above — a caller without warehouse-source viewer access sees the mapping- # but not its status. Column descriptions are likewise warehouse-derived (populated from the source's- # ``information_schema.columns`` or set by a warehouse-source editor), so they're gated the same way.- # Account sources have no warehouse binding; their status and descriptions stay visible.- warehouse_status_visible = source.external_data_schema_id is None or schema is not None+ # A profile source's sync status (raw error text, failure streak, last-synced time) is produced by+ # the underlying warehouse object, so it's warehouse-derived metadata gated the same way as the+ # schedule/latest-run above — a caller without viewer access on that object sees the mapping but not+ # its status. Column descriptions are likewise warehouse-derived (populated from the object's+ # ``information_schema.columns`` or set by a warehouse editor), so they're gated the same way.+ # Account sources are not warehouse-gated; their status and descriptions stay visible.+ warehouse_status_visible = _profile_binding(source) is None or meta is not Nonereturn contracts.CustomPropertySourceView(id=source.id,@@ -1471,59 +1547,102 @@ def _to_custom_property_source_view(created_at=source.created_at,created_by=source.created_by_id,updated_at=source.updated_at,- sync_frequency_interval_seconds=sync_frequency_interval_seconds,- next_sync_at=next_sync_at,+ sync_frequency_interval_seconds=meta.sync_frequency_interval_seconds if meta else None,+ next_sync_at=meta.next_sync_at if meta else None,latest_run=latest_run,- external_data_source=external_data_source,- table_name=table_name,+ external_data_source=meta.external_data_source if meta else None,+ table_name=meta.table_name if meta else None,+ saved_query_name=meta.saved_query_name if meta else None,)def _batch_source_enrichment(team_id: int, sources: list[CustomPropertySource], user_access_control: "UserAccessControl | None"-) -> dict[Any, "tuple[Any, CustomPropertySyncRun | None]"]:- """Resolve the schema (with warehouse-viewer access applied) and latest run for a page of person- sources in one query each, so a list endpoint doesn't issue two per-row queries (see the per-row- path in ``_to_custom_property_source_view``). Returns ``{source_id: (schema_or_None, latest_run)}``;- account sources (no warehouse binding) are absent, so they resolve inline to no enrichment."""- person_sources = [s for s in sources if s.external_data_schema_id is not None]- if not person_sources:+) -> dict[Any, "tuple[_ProfileWarehouseMeta | None, CustomPropertySyncRun | None]"]:+ """Resolve the warehouse metadata (with viewer access applied) and latest run for a page of profile+ sources in one query per warehouse kind, so a list endpoint doesn't issue two per-row queries (see+ the per-row path in ``_to_custom_property_source_view``). Returns+ ``{source_id: (meta_or_None, latest_run)}``; account sources are absent, so they resolve inline to no+ enrichment."""+ bindings = {s.id: _profile_binding(s) for s in sources}+ profile_sources = [s for s in sources if bindings[s.id] is not None]+ if not profile_sources:return {}- schema_model = apps.get_model("warehouse_sources", "ExternalDataSchema")- schemas_by_id = {- schema.id: schema- for schema in schema_model.objects.filter(- id__in={s.external_data_schema_id for s in person_sources}, team_id=team_id- ).select_related("source", "table")- }++ schema_ids = {b.id for b in bindings.values() if b is not None and not b.is_saved_query}+ saved_query_ids = {b.id for b in bindings.values() if b is not None and b.is_saved_query}+ schemas_by_id: dict[str, Any] = {}+ if schema_ids:+ schema_model = apps.get_model("warehouse_sources", "ExternalDataSchema")+ schemas_by_id = {+ str(schema.id): schema+ for schema in schema_model.objects.filter(id__in=schema_ids, team_id=team_id).select_related(+ "source", "table"+ )+ }+ saved_queries_by_id: dict[str, Any] = {}+ if saved_query_ids:+ saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")+ saved_queries_by_id = {+ str(saved_query.id): saved_query+ for saved_query in saved_query_model.objects.filter(id__in=saved_query_ids, team_id=team_id).exclude(+ deleted=True+ )+ }+# Latest run per source in one query: DISTINCT ON (source_id) keeps the newest row per source.latest_run_by_source_id: dict[Any, CustomPropertySyncRun] = {run.source_id: runfor run in CustomPropertySyncRun.objects.for_team(team_id)- .filter(source_id__in=[s.id for s in person_sources])+ .filter(source_id__in=[s.id for s in profile_sources]).order_by("source_id", "-created_at").distinct("source_id")}- enrichment: dict[Any, tuple[Any, CustomPropertySyncRun | None]] = {}+ enrichment: dict[Any, tuple[_ProfileWarehouseMeta | None, CustomPropertySyncRun | None]] = {}authorized_runs: list[CustomPropertySyncRun | None] = []- for source in person_sources:- schema = schemas_by_id.get(source.external_data_schema_id)- if (- schema is not None- and user_access_control is not None- and not user_access_control.check_access_level_for_object(schema.source, required_level="viewer")- ):- schema = None- latest = latest_run_by_source_id.get(source.id) if schema is not None else None- # Only mutate runs the caller can view; expiring runs for hidden schemas would let a+ for source in profile_sources:+ binding = bindings[source.id]+ assert binding is not None # profile_sources is filtered on exactly this+ meta = _batched_meta(binding, schemas_by_id, saved_queries_by_id, user_access_control)+ latest = latest_run_by_source_id.get(source.id) if meta is not None else None+ # Only mutate runs the caller can view; expiring runs for hidden warehouse objects would let a# denied viewer flip their status through the source-list endpoint.if latest is not None:authorized_runs.append(latest)- enrichment[source.id] = (schema, latest)+ enrichment[source.id] = (meta, latest)_expire_stale_running_runs(team_id, authorized_runs)return enrichment+def _batched_meta(+ binding: "WarehouseBinding",+ schemas_by_id: dict[str, Any],+ saved_queries_by_id: dict[str, Any],+ user_access_control: "UserAccessControl | None",+) -> _ProfileWarehouseMeta | None:+ """One binding's metadata from the prefetched maps, or None when it is missing or access-denied.+ The access check mirrors the per-row resolvers: the import source for a schema, the view itself for+ a saved query."""+ if binding.is_saved_query:+ saved_query = saved_queries_by_id.get(binding.id)+ if saved_query is None:+ return None+ if user_access_control is not None and not user_access_control.check_access_level_for_object(+ saved_query, required_level="viewer"+ ):+ return None+ return _saved_query_meta(saved_query)++ schema = schemas_by_id.get(binding.id)+ if schema is None:+ return None+ if user_access_control is not None and not user_access_control.check_access_level_for_object(+ schema.source, required_level="viewer"+ ):+ return None+ return _schema_meta(schema)++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`` socustomer_analytics never imports data_modeling (which isn't a dependency)."""@@ -1531,6 +1650,17 @@ def _saved_query_belongs_to_team(team_id: int, saved_query_id) -> bool:return saved_query_model.objects.filter(id=saved_query_id, team_id=team_id).exclude(deleted=True).exists()+def _materialized_saved_query_belongs_to_team(team_id: int, saved_query_id) -> bool:+ """Whether the saved query resolves for this team *and* is materialized. A profile source reads the+ view's Delta table directly, which only a materialized view has."""+ saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")+ return (+ saved_query_model.objects.filter(id=saved_query_id, team_id=team_id, is_materialized=True)+ .exclude(deleted=True)+ .exists()+ )++def _external_data_schema_belongs_to_team(team_id: int, schema_id) -> bool:"""Whether the warehouse schema (raw synced table) exists for this team. ``apps.get_model`` keepscustomer_analytics from importing warehouse_sources internals (isolation)."""@@ -1593,6 +1723,8 @@ def _enqueue_sync_if_enabled(source: CustomPropertySource) -> None:# materialized-view path. These share the sync-now / backfill / run-history machinery._WAREHOUSE_PROFILE_TARGETS = (TargetType.PERSON.value, TargetType.GROUP.value)+_ONE_PROFILE_BINDING_ERROR = "A person/group property source needs exactly one of external_data_schema and saved_query."+# A run row only reaches a terminal state when its activity records one, so a sync that died before# getting there — an import that failed ahead of the person-property step, a killed worker — would sit@@ -1623,22 +1755,26 @@ def _expire_stale_running_runs(team_id: int, runs: "Iterable[CustomPropertySyncRrun.error = STALE_RUNNING_RUN_ERROR-def _create_running_runs(team_id: int, schema_id: str, trigger: str) -> list[Any]:- """Insert a 'running' run for each enabled person/group source on the schema that isn't already+def _create_running_runs(team_id: int, binding: "WarehouseBinding", trigger: str) -> list[Any]:+ """Insert a 'running' run for each enabled person/group source on the binding that isn't alreadyrunning. The UI shows these as in-progress and disables the trigger while they exist; the sync andbackfill activities reconcile them to their terminal state (see record_sync_run). Skipping sourcesthat already have a running run makes this a no-op when a run for the table is already in flight(coalesced). Returns the source ids a placeholder was created for, so the caller can reconcile themto FAILED if the workflow start never happens (see ``_fail_created_runs``)."""+ # A source and a run name the same binding through different columns: a source's schema binding is+ # the `external_data_schema` FK, a run's is the plain `schema_id`.+ source_field = "saved_query_id" if binding.is_saved_query else "external_data_schema_id"+ run_field = "saved_query_id" if binding.is_saved_query else "schema_id"with transaction.atomic():- # Lock the candidate sources so a concurrent trigger for the same schema can't pass the+ # Lock the candidate sources so a concurrent trigger for the same binding can't pass the# "already running" check and insert a duplicate RUNNING row before this one commits.sources = list(CustomPropertySource.objects.for_team(team_id).filter(- external_data_schema_id=schema_id,is_enabled=True,definition__target_type__in=_WAREHOUSE_PROFILE_TARGETS,+ **{source_field: binding.id},).select_for_update())@@ -1657,10 +1793,10 @@ def _create_running_runs(team_id: int, schema_id: str, trigger: str) -> list[AnyCustomPropertySyncRun(team_id=team_id,source=source,- schema_id=schema_id,trigger=trigger,status=SyncStatus.RUNNING.value,started_at=now,+ **{run_field: binding.id},)for source in to_create]@@ -1679,16 +1815,16 @@ def _fail_created_runs(team_id: int, source_ids: list[Any], error: str) -> None:).update(status=SyncStatus.FAILED.value, finished_at=timezone.now(), error=error)-def _start_backfill(team_id: int, schema_id: str, trigger: str) -> None:+def _start_backfill(team_id: int, binding: "WarehouseBinding", trigger: str) -> None:"""Start the person-property backfill workflow. Failure must not fail the originating write."""created_source_ids: list[Any] = []try:# Placeholder rows before starting, so the activity always finds a running row to reconcile.- created_source_ids = _create_running_runs(team_id, schema_id, trigger)+ created_source_ids = _create_running_runs(team_id, binding, trigger)# The temporal client is heavy; keep it off the CA facade import (django.setup) path.from products.warehouse_sources.backend.facade.temporal import start_person_property_backfill # noqa: PLC0415- start_person_property_backfill(team_id=team_id, schema_id=schema_id, trigger=trigger)+ start_person_property_backfill(team_id=team_id, binding=binding, trigger=trigger)except Exception as e:# The workflow never started, so nothing will reconcile the placeholders — fail them here._fail_created_runs(team_id, created_source_ids, "Failed to start backfill")@@ -1696,95 +1832,113 @@ def _start_backfill(team_id: int, schema_id: str, trigger: str) -> None:def _start_person_backfill_if_enabled(source: CustomPropertySource) -> None:- """Auto-start a backfill after a person source is created/enabled so historical rows populate- immediately rather than waiting for the next incremental sync. Person sources only (account- sources have no external_data_schema); deduped per table by the workflow id."""- if not source.is_enabled or source.external_data_schema_id is None:+ """Auto-start a backfill after a person/group source is created/enabled so historical rows populate+ immediately rather than waiting for the next warehouse run. Profile sources only (an account source+ has its own Celery sync); deduped per table by the workflow id."""+ binding = _profile_binding(source)+ if not source.is_enabled or binding is None:return- team_id, schema_id = source.team_id, str(source.external_data_schema_id)- transaction.on_commit(lambda: _start_backfill(team_id, schema_id, "backfill"))+ team_id = source.team_id+ transaction.on_commit(lambda: _start_backfill(team_id, binding, "backfill"))-def _triggerable_person_schema_id(team_id: int, source_id: str) -> str | None:- """The schema id to act on for a person/group-property trigger, or None when the source isn't a- valid, flag-enabled warehouse-profile source (→ the view returns 400)."""+def _triggerable_profile_binding(team_id: int, source_id: str) -> "WarehouseBinding | None":+ """The warehouse object to act on for a person/group-property trigger, or None when the source isn't+ a valid, flag-enabled warehouse-profile source (→ the view returns 400)."""source = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).select_related("definition").first()- if source is None or source.external_data_schema_id is None:+ if source is None:return None# A disabled source (e.g. auto-disabled after repeated failures) can't be re-triggered until it's- # re-enabled — otherwise the "sync now"/backfill actions would keep launching billable imports for- # a mapping the system already turned off.+ # re-enabled — otherwise the "sync now"/backfill actions would keep launching billable warehouse+ # runs for a mapping the system already turned off.if not source.is_enabled:return None- if source.definition.target_type not in _WAREHOUSE_PROFILE_TARGETS:- return Noneif not person_properties_flag_enabled(team_id):return None- return str(source.external_data_schema_id)+ return _profile_binding(source)-def _assert_warehouse_source_access(+def _assert_warehouse_access(team_id: int,- external_data_schema_id: str | UUID | None,+ binding: "WarehouseBinding | None",user_access_control: "UserAccessControl | None",level: str,) -> None:- """A person-property source drives a real (billable) warehouse source, so acting on it or reading- its warehouse metadata requires the caller's object-level ``external_data_source`` access at- ``level``, not account-scope access alone. Mirrors the canonical warehouse endpoints, which gate- through ``get_object``. ``None`` (service auth, which the permission layer skips object checks for)- is a no-op, matching ``_enforce_object_access``. Raises ``ResourceForbiddenError`` (→ 403) when the- caller is denied. ``apps.get_model`` keeps this off a warehouse_sources internal import."""- if user_access_control is None or external_data_schema_id is None:+ """A profile source drives a real warehouse run, so acting on it or reading its warehouse metadata+ requires the caller's object-level access to what it reads at ``level``, not account-scope access+ alone: the ``external_data_source`` for a schema, the ``warehouse_view`` for a materialized view.+ Mirrors the canonical warehouse endpoints, which gate through ``get_object``. ``None`` (service auth,+ which the permission layer skips object checks for) is a no-op, matching ``_enforce_object_access``.+ Raises ``ResourceForbiddenError`` (→ 403) when the caller is denied. A warehouse object that no+ longer resolves is a no-op: there is nothing left to protect, and the caller's own write will fail+ its validation. ``apps.get_model`` keeps this off a warehouse_sources/data_modeling internal import."""+ if user_access_control is None or binding is None:+ return+ if binding.is_saved_query:+ saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")+ saved_query = saved_query_model.objects.filter(id=binding.id, team_id=team_id).exclude(deleted=True).first()+ if saved_query is None:+ return+ _enforce_object_access(saved_query, user_access_control, level)returnschema_model = apps.get_model("warehouse_sources", "ExternalDataSchema")- schema = schema_model.objects.filter(id=external_data_schema_id, team_id=team_id).select_related("source").first()+ schema = schema_model.objects.filter(id=binding.id, team_id=team_id).select_related("source").first()if schema is None:return_enforce_object_access(schema.source, user_access_control, level)-def _assert_warehouse_source_editor(- team_id: int, external_data_schema_id: str | UUID | None, user_access_control: "UserAccessControl | None"+def _assert_warehouse_editor(+ team_id: int, binding: "WarehouseBinding | None", user_access_control: "UserAccessControl | None") -> None:- """Editor gate for acting on a person source — a manual sync/backfill, or creating/enabling the+ """Editor gate for acting on a profile source — a manual sync/backfill, or creating/enabling themapping (which auto-triggers one)."""- _assert_warehouse_source_access(team_id, external_data_schema_id, user_access_control, "editor")+ _assert_warehouse_access(team_id, binding, user_access_control, "editor")-def _assert_warehouse_source_viewer(- team_id: int, external_data_schema_id: str | UUID | None, user_access_control: "UserAccessControl | None"+def _assert_warehouse_viewer(+ team_id: int, binding: "WarehouseBinding | None", user_access_control: "UserAccessControl | None") -> None:- """Viewer gate for reading a person source's warehouse run metadata (row counts, schedule, sync- errors), which exposes its billable warehouse source."""- _assert_warehouse_source_access(team_id, external_data_schema_id, user_access_control, "viewer")+ """Viewer gate for reading a profile source's warehouse run metadata (row counts, schedule, sync+ errors), which exposes the warehouse object it reads."""+ _assert_warehouse_access(team_id, binding, user_access_control, "viewer")def trigger_person_property_sync(*, team_id: int, source_id: str, user_access_control: "UserAccessControl | None" = None) -> bool:- """ "Sync now" for a person source: trigger the underlying warehouse schema's sync (a real,- billable sync; the incremental person-property child runs off it). Returns False for an invalid- source (→ 400). Requires ``external_data_source`` editor access (→ 403) and honors the team's- warehouse sync pause (→ ``WarehouseSyncPausedError``)."""- schema_id = _triggerable_person_schema_id(team_id, source_id)- if schema_id is None:+ """ "Sync now" for a profile source: start a fresh warehouse run of whatever it reads — an import for+ a schema (billable), a materialization for a view. The person-property child runs off that run.+ Returns False for an invalid source (→ 400). Requires editor access to the warehouse object (→ 403),+ honors the team's warehouse sync pause (→ ``WarehouseSyncPausedError``), and rejects a view still on+ the older data-modeling schedule (→ ``ViewNotSyncableError``)."""+ binding = _triggerable_profile_binding(team_id, source_id)+ if binding is None:return False- _assert_warehouse_source_editor(team_id, schema_id, user_access_control)+ _assert_warehouse_editor(team_id, binding, user_access_control)from products.warehouse_sources.backend.facade.temporal import ( # noqa: PLC0415ExternalDataSchemaSyncPausedError,+ SavedQueryNotFoundError,+ SavedQueryNotOnV2ScheduleError,+ trigger_saved_query_materialization,trigger_schema_sync,)- # Open the run rows before the sync starts, so the history shows it in progress right away and the- # trigger buttons stay disabled until it settles. The person-property activity reconciles them- # when the import reaches it (see record_sync_run).- created_source_ids = _create_running_runs(team_id, schema_id, SyncTrigger.SYNC.value)+ # Open the run rows before the warehouse run starts, so the history shows it in progress right away+ # and the trigger buttons stay disabled until it settles. The person-property activity reconciles+ # them when the run reaches it (see record_sync_run).+ created_source_ids = _create_running_runs(team_id, binding, SyncTrigger.SYNC.value)try:- trigger_schema_sync(team_id=team_id, schema_id=schema_id)+ if binding.is_saved_query:+ trigger_saved_query_materialization(team_id=team_id, saved_query_id=binding.id)+ else:+ trigger_schema_sync(team_id=team_id, schema_id=binding.id)except ExternalDataSchemaSyncPausedError as e:_fail_created_runs(team_id, created_source_ids, "Warehouse syncs are paused for this project")raise WarehouseSyncPausedError(str(e)) from e+ except (SavedQueryNotOnV2ScheduleError, SavedQueryNotFoundError) as e:+ _fail_created_runs(team_id, created_source_ids, str(e))+ raise ViewNotSyncableError(str(e)) from eexcept Exception:_fail_created_runs(team_id, created_source_ids, "Failed to start sync")raise@@ -1794,19 +1948,19 @@ def trigger_person_property_sync(def trigger_person_property_backfill(*, team_id: int, source_id: str, trigger: str = "manual", user_access_control: "UserAccessControl | None" = None) -> bool | None:- """Start a backfill for a person source's table. Returns True (started), False (already running →- coalesced), or None for an invalid source (→ 400). Requires ``external_data_source`` editor access+ """Start a backfill for a profile source's table. Returns True (started), False (already running →+ coalesced), or None for an invalid source (→ 400). Requires editor access to the warehouse object(→ 403)."""- schema_id = _triggerable_person_schema_id(team_id, source_id)- if schema_id is None:+ binding = _triggerable_profile_binding(team_id, source_id)+ if binding is None:return None- _assert_warehouse_source_editor(team_id, schema_id, user_access_control)+ _assert_warehouse_editor(team_id, binding, user_access_control)# Placeholder rows before starting, so the activity always finds a running row to reconcile.- created_source_ids = _create_running_runs(team_id, schema_id, trigger)+ created_source_ids = _create_running_runs(team_id, binding, trigger)from products.warehouse_sources.backend.facade.temporal import start_person_property_backfill # noqa: PLC0415try:- return start_person_property_backfill(team_id=team_id, schema_id=schema_id, trigger=trigger)+ return start_person_property_backfill(team_id=team_id, binding=binding, trigger=trigger)except Exception:# The workflow never started; reconcile the placeholders so the source isn't stuck 'running'# with its trigger disabled, then surface the error to the caller.@@ -1827,7 +1981,7 @@ def list_custom_property_sources(``exclude_group_targets`` hides sources feeding a group-target definition from callers without``group`` read authorization."""- queryset = CustomPropertySource.objects.for_team(team_id).order_by("-created_at")+ queryset = CustomPropertySource.objects.for_team(team_id).select_related("definition").order_by("-created_at")if exclude_group_targets:queryset = queryset.exclude(definition__target_type=TargetType.GROUP.value)total_count = queryset.count()@@ -1842,10 +1996,31 @@ def list_custom_property_sources(def get_custom_property_source(team_id: int, source_id: str, user_access_control: "UserAccessControl | None" = None) -> contracts.CustomPropertySourceView | None:- source = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).first()+ source = CustomPropertySource.objects.for_team(team_id).select_related("definition").filter(id=source_id).first()return _to_custom_property_source_view(source, user_access_control) if source is not None else None+def get_custom_property_source_binding_id(team_id: int, source_id: str) -> str | None:+ """The id of the warehouse object a source reads — its saved query for a view binding, its external+ data schema for a table binding — or None when the source doesn't resolve or reads neither. Kept to+ two id columns (no definition join, no view building) because the sync throttle calls it per request+ to key its limit on the warehouse object rather than the mapping."""+ try:+ row = (+ CustomPropertySource.objects.for_team(team_id)+ .filter(id=source_id)+ .values_list("saved_query_id", "external_data_schema_id")+ .first()+ )+ except (ValidationError, ValueError): # a non-UUID id from the URL is simply unknown+ return None+ if row is None:+ return None+ saved_query_id, schema_id = row+ binding_id = saved_query_id or schema_id+ return str(binding_id) if binding_id is not None else None++def create_custom_property_source(*,team_id: int,@@ -1864,8 +2039,9 @@ def create_custom_property_source(if definition is None:raise CustomPropertySourceValidationError("Custom property definition not found for this team.")- # The definition's target decides which binding is valid: account sources read a saved query- # column; person sources read a raw incremental schema and map columns onto person properties.+ # The definition's target decides which binding is valid: an account source reads one saved-query+ # column; a person/group source maps columns from either an imported schema's table or a+ # materialized view onto profile properties.create_kwargs: dict[str, Any] = {"team_id": team_id,"created_by": user,@@ -1874,24 +2050,35 @@ def create_custom_property_source("is_enabled": is_enabled,}if definition.target_type in _WAREHOUSE_PROFILE_TARGETS:- if external_data_schema_id is None:- raise CustomPropertySourceValidationError("A person/group property source needs an external_data_schema.")- if saved_query_id is not None or source_column:+ if saved_query_id is not None and external_data_schema_id is not None:+ raise CustomPropertySourceValidationError(_ONE_PROFILE_BINDING_ERROR)+ if source_column:raise CustomPropertySourceValidationError(- "A person/group property source uses external_data_schema + column_property_map, not saved_query."+ "A person/group property source maps columns with column_property_map, not source_column.")- # Validate the map shape in memory before the DB lookup below.+ # Validate the map shape in memory before the DB lookups below.validated_map = _validate_column_property_map(column_property_map)create_kwargs["column_property_map"] = validated_mapcreate_kwargs["column_descriptions"] = _validate_column_descriptions(column_descriptions, set(validated_map.keys()))- if not _external_data_schema_belongs_to_team(team_id, external_data_schema_id):- raise CustomPropertySourceValidationError("Warehouse schema not found for this team.")- # Mapping (and enabling) a warehouse table into person properties drives its billable source,- # so require the caller's warehouse-source editor access, not account-scope editor alone.- _assert_warehouse_source_editor(team_id, external_data_schema_id, user_access_control)- create_kwargs["external_data_schema_id"] = external_data_schema_id+ if saved_query_id is not None:+ # An unmaterialized view has no table to read, so the source could never sync — reject it+ # here rather than creating a mapping that stays silently empty.+ if not _materialized_saved_query_belongs_to_team(team_id, saved_query_id):+ raise CustomPropertySourceValidationError("Materialized view not found for this team.")+ binding = saved_query_binding(saved_query_id)+ create_kwargs["saved_query_id"] = saved_query_id+ elif external_data_schema_id is not None:+ if not _external_data_schema_belongs_to_team(team_id, external_data_schema_id):+ raise CustomPropertySourceValidationError("Warehouse schema not found for this team.")+ binding = schema_binding(external_data_schema_id)+ create_kwargs["external_data_schema_id"] = external_data_schema_id+ else:+ raise CustomPropertySourceValidationError(_ONE_PROFILE_BINDING_ERROR)+ # Mapping (and enabling) a warehouse table into profile properties drives real warehouse runs,+ # so require the caller's editor access on what it reads, not account-scope editor alone.+ _assert_warehouse_editor(team_id, binding, user_access_control)else:if saved_query_id is None or not source_column:raise CustomPropertySourceValidationError(@@ -1925,21 +2112,22 @@ def update_custom_property_source("""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()+ source = CustomPropertySource.objects.for_team(team_id).select_related("definition").filter(id=source_id).first()if source is None:return Nonereenabling = fields.get("is_enabled") is True and not source.is_enabledcolumns_changed = any(attr in fields and fields[attr] != getattr(source, attr) for attr in ("source_column", "key_column"))- # A person source's backfill drives its billable warehouse source, so any change that will trigger- # one — re-enabling, or changing the mapped columns while it stays enabled — requires the caller's- # warehouse-source editor access, not account-scope editor alone (matching create). Both routes reach+ # A profile source's backfill drives a real warehouse run, so any change that will trigger one —+ # re-enabling, or changing the mapped columns while it stays enabled — requires the caller's editor+ # access on the warehouse object, not account-scope editor alone (matching create). Both routes reach# _start_person_backfill_if_enabled below via ``reenabling or columns_changed``; ``is_enabled`` here is# the post-update state that decides whether that helper actually starts a backfill.will_be_enabled = fields.get("is_enabled", source.is_enabled) is True- if source.external_data_schema_id is not None and will_be_enabled and (reenabling or columns_changed):- _assert_warehouse_source_editor(team_id, source.external_data_schema_id, user_access_control)+ binding = _profile_binding(source)+ if binding is not None and will_be_enabled and (reenabling or columns_changed):+ _assert_warehouse_editor(team_id, binding, user_access_control)for attr, value in fields.items():setattr(source, attr, value)if reenabling:@@ -1956,14 +2144,13 @@ def update_custom_property_source(def delete_custom_property_source(*, team_id: int, source_id: str, user_access_control: "UserAccessControl | None" = None) -> bool:- """Delete a team-scoped source. Returns False when none matched (→ 404). Deleting a person source- permanently stops its billable warehouse-driven updates, so it requires the caller's warehouse-source- editor access (→ 403 via ``ResourceForbiddenError``), matching create/update/sync/backfill."""- source = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).first()+ """Delete a team-scoped source. Returns False when none matched (→ 404). Deleting a profile source+ permanently stops its warehouse-driven updates, so it requires the caller's editor access on the+ warehouse object (→ 403 via ``ResourceForbiddenError``), matching create/update/sync/backfill."""+ source = CustomPropertySource.objects.for_team(team_id).select_related("definition").filter(id=source_id).first()if source is None:return False- if source.external_data_schema_id is not None:- _assert_warehouse_source_editor(team_id, source.external_data_schema_id, user_access_control)+ _assert_warehouse_editor(team_id, _profile_binding(source), user_access_control)deleted, _ = source.delete()return deleted > 0@@ -1973,11 +2160,11 @@ def list_custom_property_sync_runs() -> tuple[list[contracts.CustomPropertySyncRunView], int]:"""Person-property sync/backfill runs for a source, newest first. Returns ``(page, total_count)``.Scoped by team and source, so a run of another team's/source's is never returned. The runs expose- the underlying warehouse source's row counts and raw sync errors, so reading them requires the- caller's warehouse-source viewer access (→ 403 via ``ResourceForbiddenError``)."""- source = CustomPropertySource.objects.for_team(team_id).filter(id=source_id).first()- if source is not None and source.external_data_schema_id is not None:- _assert_warehouse_source_viewer(team_id, source.external_data_schema_id, user_access_control)+ the warehouse object's row counts and raw sync errors, so reading them requires the caller's viewer+ access on it (→ 403 via ``ResourceForbiddenError``)."""+ source = CustomPropertySource.objects.for_team(team_id).select_related("definition").filter(id=source_id).first()+ if source is not None:+ _assert_warehouse_viewer(team_id, _profile_binding(source), user_access_control)queryset = CustomPropertySyncRun.objects.for_team(team_id).filter(source_id=source_id).order_by("-created_at")total_count = queryset.count()page = list(queryset[offset : offset + limit])diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex ebaa3d0618ce..363c5f466d1c 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -719,14 +719,15 @@ class CustomPropertyDefinitionView:@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.- Account-target sources set ``saved_query`` + ``source_column``; person-target sources set- ``external_data_schema`` + ``column_property_map`` instead. Defaults exist so the wrapping- serializer can parse partial request bodies (see :class:`AccountView`).+ """A custom-property source: binds warehouse columns to a definition, feeding its values on every+ warehouse run of what it reads.++ ``definition`` / ``saved_query`` / ``external_data_schema`` are ids (the definition this feeds, and+ the warehouse object read from). ``last_sync_error`` is null when the last run succeeded or hasn't+ run. Account-target sources set ``saved_query`` + ``source_column``; person- and group-target+ sources set ``column_property_map`` plus exactly one of ``external_data_schema`` (an imported+ table) and ``saved_query`` (a materialized view). Defaults exist so the wrapping serializer can+ parse partial request bodies (see :class:`AccountView`)."""id: UUID | None = None@@ -744,17 +745,20 @@ class CustomPropertySourceView:created_at: datetime | None = Nonecreated_by: int | None = Noneupdated_at: datetime | None = None- # Person-target schedule visibility (None for account sources). ``sync_frequency_interval`` is- # in seconds; ``next_sync_at`` is approximate (last synced + interval), it drifts if the- # underlying schedule was paused. ``latest_run`` is the most recent sync/backfill run.+ # Person/group-target schedule visibility (None for account sources). ``sync_frequency_interval``+ # is in seconds; ``next_sync_at`` is approximate (last run + interval), it drifts if the underlying+ # schedule was paused, and is null for a view whose frequency lives on its DAG node.+ # ``latest_run`` is the most recent sync/backfill run.sync_frequency_interval_seconds: float | None = Nonenext_sync_at: datetime | None = Nonelatest_run: "CustomPropertySyncRunView | None" = None- # Person-target warehouse binding, for naming and linking to the table this source reads.- # ``external_data_source`` is the warehouse source owning the schema; ``table_name`` is the- # table as it is named in HogQL. Both None for account sources.+ # Person/group-target warehouse binding, for naming and linking to what this source reads.+ # ``table_name`` is the imported table as named in HogQL, or the view's name. ``external_data_source``+ # is the warehouse source owning the schema, set only for a table binding; ``saved_query_name`` is+ # set only for a view binding. All None for account sources.external_data_source: UUID | None = Nonetable_name: str | None = None+ saved_query_name: str | None = None@stdlib_dataclass(frozen=True)diff --git a/products/customer_analytics/backend/facade/custom_property_source_person_test.py b/products/customer_analytics/backend/facade/custom_property_source_person_test.pyindex 6582b428d95d..16b2508b3be1 100644--- a/products/customer_analytics/backend/facade/custom_property_source_person_test.py+++ b/products/customer_analytics/backend/facade/custom_property_source_person_test.py@@ -11,7 +11,7 @@ from parameterized import parameterizedfrom products.customer_analytics.backend.facade import apifrom products.customer_analytics.backend.models import CustomPropertySource, CustomPropertySyncRun, TargetTypefrom products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin-from products.customer_analytics.backend.test.factories import create_custom_property_definition+from products.customer_analytics.backend.test.factories import create_custom_property_definition, create_saved_queryfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -31,6 +31,7 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):team=self.team, source_id="s", connection_id="c", status="Running", source_type="Stripe")self.schema = ExternalDataSchema.objects.create(team=self.team, source=source, name="users")+ self.saved_query = create_saved_query(team_id=self.team.id)def _create(self, **overrides):kwargs: dict = {@@ -81,19 +82,19 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):@parameterized.expand([(- "person_without_schema",+ "person_without_a_binding",{"external_data_schema_id": None},- "needs an external_data_schema",+ "exactly one of external_data_schema and saved_query",),(- "person_with_saved_query_binding",+ "person_with_both_bindings",{"saved_query_id": uuid4()},- "not saved_query",+ "exactly one of external_data_schema and saved_query",),(- "person_with_source_column_binding",+ "person_with_source_column",{"source_column": "plan"},- "not saved_query",+ "not source_column",),("person_empty_map",@@ -388,3 +389,96 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):)is None)++ # --- materialized-view bindings ------------------------------------------------------------++ def _create_view_source(self, **overrides):+ kwargs: dict = {"external_data_schema_id": None, "saved_query_id": self.saved_query.id}+ kwargs.update(overrides)+ return self._create(**kwargs)++ def test_create_view_backed_person_source_round_trips(self):+ view = self._create_view_source(user_access_control=self._uac(allowed=True))++ assert view.saved_query == self.saved_query.id+ assert view.external_data_schema is None+ assert view.column_property_map == {"plan": "plan_tier"}+ # The UI names and links a view-backed source off these, so both have to resolve.+ assert view.table_name == "enriched_users"+ assert view.saved_query_name == "enriched_users"+ assert view.external_data_source is None++ row = CustomPropertySource.objects.unscoped().get(id=view.id)+ assert row.saved_query_id == self.saved_query.id and row.external_data_schema_id is None++ def test_view_backed_person_source_rejects_an_unmaterialized_view(self):+ # A view with no materialization has no Delta table, so the source could never sync — an+ # accepted mapping would sit silently empty forever.+ unmaterialized = create_saved_query(team_id=self.team.id, name="draft_users", is_materialized=False)+ with self.assertRaisesMessage(api.CustomPropertySourceValidationError, "not found for this team"):+ self._create_view_source(saved_query_id=unmaterialized.id)++ def test_view_backed_person_source_rejects_a_view_from_another_team(self):+ foreign = create_saved_query(team_id=self.organization.teams.create(name="other").id, name="their_users")+ with self.assertRaisesMessage(api.CustomPropertySourceValidationError, "not found for this team"):+ self._create_view_source(saved_query_id=foreign.id)++ def test_create_view_backed_person_source_requires_view_editor(self):+ # Mapping a view into person properties drives real materializations, so it needs editor access+ # on the view, not account-scope editor alone — the same bar a table binding clears.+ with self.assertRaises(api.ResourceForbiddenError):+ self._create_view_source(user_access_control=self._uac(allowed=False))++ @patch("products.customer_analytics.backend.facade.api.person_properties_flag_enabled", return_value=True)+ def test_sync_now_materializes_the_view_and_opens_a_running_run(self, _flag):+ source = self._create_view_source(user_access_control=self._uac(allowed=True))+ with patch(+ "products.warehouse_sources.backend.facade.temporal.trigger_saved_query_materialization"+ ) as materialize:+ assert (+ api.trigger_person_property_sync(+ team_id=self.team.id, source_id=source.id, user_access_control=self._uac(allowed=True)+ )+ is True+ )++ materialize.assert_called_once_with(team_id=self.team.id, saved_query_id=str(self.saved_query.id))+ run = CustomPropertySyncRun.objects.unscoped().get(source_id=source.id)+ # The run is attributed to the view, not to a schema it never read.+ assert run.saved_query_id == self.saved_query.id and run.schema_id is None+ assert run.status == "running" and run.trigger == "sync"++ @patch("products.customer_analytics.backend.facade.api.person_properties_flag_enabled", return_value=True)+ def test_sync_now_on_a_view_outside_v2_reports_it_and_fails_the_run(self, _flag):+ # Only the v2 materialization stages person-property rows. Starting a v1 run would look like a+ # successful "Sync now" while the properties never update, so it has to surface as an error.+ from products.warehouse_sources.backend.facade.temporal import SavedQueryNotOnV2ScheduleError++ source = self._create_view_source(user_access_control=self._uac(allowed=True))+ with patch(+ "products.warehouse_sources.backend.facade.temporal.trigger_saved_query_materialization",+ side_effect=SavedQueryNotOnV2ScheduleError("older data modeling schedule"),+ ):+ with self.assertRaises(api.ViewNotSyncableError):+ api.trigger_person_property_sync(+ team_id=self.team.id, source_id=source.id, user_access_control=self._uac(allowed=True)+ )++ run = CustomPropertySyncRun.objects.unscoped().get(source_id=source.id)+ assert run.status == "failed" and "older data modeling schedule" in (run.error or "")++ @patch("products.customer_analytics.backend.facade.api.person_properties_flag_enabled", return_value=True)+ def test_backfill_targets_the_view_binding(self, _flag):+ source = self._create_view_source(user_access_control=self._uac(allowed=True))+ with patch(+ "products.warehouse_sources.backend.facade.temporal.start_person_property_backfill", return_value=True+ ) as start:+ assert (+ api.trigger_person_property_backfill(+ team_id=self.team.id, source_id=source.id, user_access_control=self._uac(allowed=True)+ )+ is True+ )++ binding = start.call_args.kwargs["binding"]+ assert (binding.kind, binding.id) == ("saved_query", str(self.saved_query.id))diff --git a/products/customer_analytics/backend/logic/person_property_projection.py b/products/customer_analytics/backend/logic/person_property_projection.pyindex dd469062e600..75c25262c1b4 100644--- a/products/customer_analytics/backend/logic/person_property_projection.py+++ b/products/customer_analytics/backend/logic/person_property_projection.py@@ -1,17 +1,16 @@-"""Resolves the person-property source configs the warehouse import pipeline asks for.+"""Resolves the person-property source configs a warehouse run asks for.-Registered as the data-import pipeline's projection and sync-config hooks (see apps.ready).-Called from the pipeline, outside request context, so it scopes explicitly with ``for_team``.+Registered as the warehouse pipeline's projection and sync-config hooks (see apps.ready). Called from+a data-import job or a view materialization, outside request context, so it scopes explicitly with+``for_team``.Both resolvers are the feature's pipeline choke point: they return None when the``warehouse-person-properties`` rollout flag is off for the team's organization, which switches-off staging, the post-sync workflow gate, and the upsert in one place. The flag is only evaluated-once a schema is confirmed to have enabled person sources, so unconfigured schemas (the vast-majority of syncs) never pay a flag-service call.+off staging, the post-run workflow gate, and the upsert in one place. The flag is only evaluated+once a binding is confirmed to have enabled person sources, so unconfigured tables and views (the+vast majority of runs) never pay a flag-service call."""-from uuid import UUID-import posthoganalyticsfrom posthog.exceptions_capture import capture_exception@@ -19,7 +18,12 @@ from posthog.models import Teamfrom products.customer_analytics.backend.constants import WAREHOUSE_PERSON_PROPERTIES_FLAGfrom products.customer_analytics.backend.models import CustomPropertySource, TargetType-from products.warehouse_sources.backend.facade.hooks import PersonPropertySourceProjection, PersonPropertySyncSource+from products.warehouse_sources.backend.facade.hooks import (+ BINDING_KIND_SAVED_QUERY,+ PersonPropertySourceProjection,+ PersonPropertySyncSource,+ WarehouseBinding,+)def person_properties_flag_enabled(team_id: int) -> bool:@@ -47,33 +51,34 @@ def person_properties_flag_enabled(team_id: int) -> bool:return False-# Warehouse-backed profile targets (person or group). Account sources use the materialized-view-# (saved_query) path, not the warehouse staging pipeline, so they're excluded here.+# Warehouse-backed profile targets (person or group). Account sources read a single view column+# through their own Celery sync, not the warehouse staging pipeline, so they're excluded here._PROFILE_TARGETS = (TargetType.PERSON.value, TargetType.GROUP.value)-def _enabled_profile_sources(team_id: int, schema_id: str | UUID) -> list[CustomPropertySource]:+def _enabled_profile_sources(team_id: int, binding: WarehouseBinding) -> list[CustomPropertySource]:# Sources without a key column are skipped: their rows have no identifier (person distinct_id or# group key) to attach the properties to. select_related the definition so target_type /# group_type_index don't lazy-load per source.+ binding_field = "saved_query_id" if binding.kind == BINDING_KIND_SAVED_QUERY else "external_data_schema_id"return [sourcefor source in CustomPropertySource.objects.for_team(team_id).select_related("definition").filter(- external_data_schema_id=schema_id,is_enabled=True,definition__target_type__in=_PROFILE_TARGETS,+ **{binding_field: binding.id},)if source.key_column]-def person_property_projection(team_id: int, schema_id: str | UUID) -> list[PersonPropertySourceProjection] | None:- """One projection per enabled person/group-target source on the schema (its key column plus its- mapped columns), or None when the schema feeds no such properties (so the pipeline stages+def person_property_projection(team_id: int, binding: WarehouseBinding) -> list[PersonPropertySourceProjection] | None:+ """One projection per enabled person/group-target source on the binding (its key column plus its+ mapped columns), or None when the binding feeds no such properties (so the pipeline stagesnothing). The projection is target-agnostic — the group type is config, not a staged column."""- sources = _enabled_profile_sources(team_id, schema_id)+ sources = _enabled_profile_sources(team_id, binding)if not sources or not person_properties_flag_enabled(team_id):return Nonereturn [@@ -85,11 +90,11 @@ def person_property_projection(team_id: int, schema_id: str | UUID) -> list[Pers]-def person_property_sync_sources(team_id: int, schema_id: str | UUID) -> list[PersonPropertySyncSource] | None:- """Full sync config per enabled person/group-target source on the schema, for the warehouse-owned- post-sync upsert job — or None when the schema feeds no such properties. Carries ``target`` and,+def person_property_sync_sources(team_id: int, binding: WarehouseBinding) -> list[PersonPropertySyncSource] | None:+ """Full sync config per enabled person/group-target source on the binding, for the warehouse-owned+ post-run upsert job — or None when the binding feeds no such properties. Carries ``target`` and,for group targets, ``group_type_index`` so the upsert can write the right entity."""- sources = _enabled_profile_sources(team_id, schema_id)+ sources = _enabled_profile_sources(team_id, binding)if not sources or not person_properties_flag_enabled(team_id):return Nonereturn [diff --git a/products/customer_analytics/backend/logic/person_property_projection_test.py b/products/customer_analytics/backend/logic/person_property_projection_test.pyindex fb78a63bcbca..87de041c60a3 100644--- a/products/customer_analytics/backend/logic/person_property_projection_test.py+++ b/products/customer_analytics/backend/logic/person_property_projection_test.py@@ -1,24 +1,33 @@from posthog.test.base import BaseTestfrom unittest.mock import patch+from parameterized import parameterized, parameterized_class+from products.customer_analytics.backend.logic.person_property_projection import (person_property_projection,person_property_sync_sources,)from products.customer_analytics.backend.models import CustomPropertySource, TargetTypefrom products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin-from products.customer_analytics.backend.test.factories import create_custom_property_definition+from products.customer_analytics.backend.test.factories import create_custom_property_definition, create_saved_query+from products.warehouse_sources.backend.facade.hooks import saved_query_binding, schema_bindingfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+# Both binding kinds run every case: the resolvers pick the filter column from the binding, and picking+# the wrong one leaves a configured source silently never syncing.+@parameterized_class(("binding_kind",), [("schema",), ("saved_query",)])class PersonPropertyProjectionTest(TeamScopedTestMixin, BaseTest):+ binding_kind = "schema"+def setUp(self):super().setUp()source = ExternalDataSource.objects.create(team=self.team, source_id="s", connection_id="c", status="Running", source_type="Stripe")self.schema = ExternalDataSchema.objects.create(team=self.team, source=source, name="users")+ self.saved_query = create_saved_query(team_id=self.team.id)flag_patch = patch("products.customer_analytics.backend.logic.person_property_projection.person_properties_flag_enabled",return_value=True,@@ -26,28 +35,37 @@ class PersonPropertyProjectionTest(TeamScopedTestMixin, BaseTest):flag_patch.start()self.addCleanup(flag_patch.stop)- def _person_source(- self, name, key_column, column_property_map, *, is_enabled=True, schema=None, column_descriptions=None- ):+ @property+ def binding(self):+ if self.binding_kind == "saved_query":+ return saved_query_binding(self.saved_query.id)+ return schema_binding(self.schema.id)++ def _binding_kwargs(self):+ if self.binding_kind == "saved_query":+ return {"saved_query": self.saved_query}+ return {"external_data_schema": self.schema}++ def _person_source(self, name, key_column, column_property_map, *, is_enabled=True, column_descriptions=None):definition = create_custom_property_definition(team_id=self.team.id, name=name, target_type=TargetType.PERSON.value)return CustomPropertySource.objects.for_team(self.team.id).create(team_id=self.team.id,definition=definition,- external_data_schema=schema or self.schema,key_column=key_column,column_property_map=column_property_map,column_descriptions=column_descriptions,is_enabled=is_enabled,+ **self._binding_kwargs(),)def _projected(self):- projection = person_property_projection(self.team.id, self.schema.id)+ projection = person_property_projection(self.team.id, self.binding)return {source.key_column: sorted(source.columns) for source in (projection or [])}def test_returns_none_when_no_person_sources(self):- assert person_property_projection(self.team.id, self.schema.id) is None+ assert person_property_projection(self.team.id, self.binding) is Nonedef test_projects_key_and_mapped_columns_per_enabled_person_source(self):self._person_source("A", "distinct_id", {"plan": "plan_tier"})@@ -62,32 +80,45 @@ class PersonPropertyProjectionTest(TeamScopedTestMixin, BaseTest):# A source with no key column has no person identifier to attach properties to.self._person_source("keyless", "", {"plan": "plan_tier"})- assert person_property_projection(self.team.id, self.schema.id) is None+ assert person_property_projection(self.team.id, self.binding) is None- def test_ignores_disabled_account_and_other_schema_sources(self):+ def test_ignores_disabled_account_and_other_binding_sources(self):self._person_source("enabled", "distinct_id", {"plan": "plan_tier"})self._person_source("disabled", "other_id", {"col": "prop"}, is_enabled=False)- # Account-target source on the same schema must not contribute.+ # Account-target source on the same warehouse object must not contribute.account_def = create_custom_property_definition(team_id=self.team.id, name="MRR", target_type=TargetType.ACCOUNT.value)CustomPropertySource.objects.for_team(self.team.id).create(team_id=self.team.id,definition=account_def,- external_data_schema=self.schema,key_column="acct_id",column_property_map={"mrr": "mrr"},+ **self._binding_kwargs(),)assert self._projected() == {"distinct_id": ["distinct_id", "plan"]}+ def test_ignores_a_source_bound_to_the_other_warehouse_object(self):+ # The two binding kinds must not bleed into each other: a source on the view must not surface+ # for the schema's run, or its properties would update off the wrong table's rows.+ self._person_source("A", "distinct_id", {"plan": "plan_tier"})+ other = (+ schema_binding(self.schema.id)+ if self.binding_kind == "saved_query"+ else saved_query_binding(self.saved_query.id)+ )++ assert person_property_projection(self.team.id, other) is None+ assert person_property_sync_sources(self.team.id, other) is None+def test_sync_sources_carry_full_config_for_the_upsert_job(self):# The warehouse-owned sync job consumes these configs through the hook; a wrong field# mapping here mis-stamps provenance or upserts the wrong columns.source = self._person_source("A", "distinct_id", {"plan": "plan_tier"})- configs = person_property_sync_sources(self.team.id, self.schema.id)+ configs = person_property_sync_sources(self.team.id, self.binding)assert configs is not None and len(configs) == 1config = configs[0]@@ -108,16 +139,17 @@ class PersonPropertyProjectionTest(TeamScopedTestMixin, BaseTest):column_descriptions={"plan": "The plan tier", "unmapped": "ignored", "seats": ""},)- configs = person_property_sync_sources(self.team.id, self.schema.id)+ configs = person_property_sync_sources(self.team.id, self.binding)assert configs is not None and len(configs) == 1# 'plan' re-keyed to 'plan_tier'; 'unmapped' dropped (no column); 'seats' dropped (blank).assert configs[0].property_descriptions == {"plan_tier": "The plan tier"}def test_sync_sources_none_when_no_person_sources(self):- assert person_property_sync_sources(self.team.id, self.schema.id) is None+ assert person_property_sync_sources(self.team.id, self.binding) is None- def test_flag_off_disables_both_resolvers_despite_configured_sources(self):+ @parameterized.expand([("projection", person_property_projection), ("sync_sources", person_property_sync_sources)])+ def test_flag_off_disables_the_resolver_despite_configured_sources(self, _name, resolver):# The resolvers are the pipeline choke point for the rollout flag: with the flag off,# configured sources must not stage rows or start the sync workflow.self._person_source("A", "distinct_id", {"plan": "plan_tier"})@@ -125,5 +157,4 @@ class PersonPropertyProjectionTest(TeamScopedTestMixin, BaseTest):"products.customer_analytics.backend.logic.person_property_projection.person_properties_flag_enabled",return_value=False,):- assert person_property_projection(self.team.id, self.schema.id) is None- assert person_property_sync_sources(self.team.id, self.schema.id) is None+ assert resolver(self.team.id, self.binding) is Nonediff --git a/products/customer_analytics/backend/logic/person_property_runs.py b/products/customer_analytics/backend/logic/person_property_runs.pyindex 5f80cdf12f02..2ee8f022062c 100644--- a/products/customer_analytics/backend/logic/person_property_runs.py+++ b/products/customer_analytics/backend/logic/person_property_runs.py@@ -1,6 +1,6 @@"""Persists person-property sync/backfill run outcomes.-Registered as the data-import pipeline's run recorder (see apps.ready). Called from the warehouse+Registered as the warehouse pipeline's run recorder (see apps.ready). Called from the warehousesync/backfill activities, outside request context, so it scopes explicitly with ``for_team``. Writesa ``CustomPropertySyncRun`` row and folds the outcome back onto the source's status fields so theaccount-path ``sourceSyncStatus`` UI helper works for person sources too.@@ -18,7 +18,7 @@ from products.customer_analytics.backend.models import (SyncStatus,SyncTrigger,)-from products.warehouse_sources.backend.facade.hooks import PersonPropertySyncRunRecord+from products.warehouse_sources.backend.facade.hooks import BINDING_KIND_SAVED_QUERY, PersonPropertySyncRunRecordlogger = structlog.get_logger(__name__)@@ -36,6 +36,14 @@ _SYNC_TRIGGERS = frozenset({SyncTrigger.SCHEDULED.value, SyncTrigger.SYNC.value}_USER_TRIGGERS = frozenset({SyncTrigger.SYNC.value, SyncTrigger.MANUAL.value})+def _binding_fields(record: PersonPropertySyncRunRecord) -> dict[str, str | None]:+ """The run row's binding columns. Both are kept nullable and only one is ever set, so a run stays+ readable after the schema or view it read is deleted."""+ if record.binding_kind == BINDING_KIND_SAVED_QUERY:+ return {"schema_id": None, "saved_query_id": record.binding_id or None}+ return {"schema_id": record.binding_id or None, "saved_query_id": None}++def _parse_iso(value: str | None) -> datetime | None:if not value:return None@@ -69,7 +77,8 @@ def record_sync_run(record: PersonPropertySyncRunRecord) -> None:log = logger.bind(team_id=record.team_id,source_id=record.source_id,- schema_id=record.schema_id,+ binding_kind=record.binding_kind,+ binding_id=record.binding_id,trigger=record.trigger,status=record.status,)@@ -89,8 +98,8 @@ def record_sync_run(record: PersonPropertySyncRunRecord) -> None:# the source from retry noise rather than distinct failed syncs).already_failed = run is not None and run.status == SyncStatus.FAILED.value- fields = {- "schema_id": record.schema_id or None,+ fields: dict = {+ **_binding_fields(record),"job_id": record.job_id,"trigger": record.trigger,"status": record.status,diff --git a/products/customer_analytics/backend/logic/person_property_runs_test.py b/products/customer_analytics/backend/logic/person_property_runs_test.pyindex 7e758a78e1f1..8a929b1c9191 100644--- a/products/customer_analytics/backend/logic/person_property_runs_test.py+++ b/products/customer_analytics/backend/logic/person_property_runs_test.py@@ -40,7 +40,8 @@ class TestRecordSyncRun(TeamScopedTestMixin, APIBaseTest):def _record(self, **overrides) -> PersonPropertySyncRunRecord:kwargs: dict = {"team_id": self.team.id,- "schema_id": self.schema_id,+ "binding_kind": "schema",+ "binding_id": self.schema_id,"source_id": str(self.source.id),"job_id": "job-1","trigger": "scheduled",@@ -185,3 +186,12 @@ class TestRecordSyncRun(TeamScopedTestMixin, APIBaseTest):assert self.source.consecutive_failures == 0assert self.source.last_synced_at is not Noneassert self.source.last_sync_error is None++ def test_view_binding_lands_in_the_saved_query_column(self):+ # The two binding columns are how a run stays attributable after its schema or view is deleted.+ # Writing a view's id into schema_id would attribute the run to a schema that never ran it.+ record_sync_run(self._record(binding_kind="saved_query", binding_id="7bd1a4de-0000-4000-8000-000000000001"))++ run = CustomPropertySyncRun.objects.unscoped().get(source_id=self.source.id)+ assert str(run.saved_query_id) == "7bd1a4de-0000-4000-8000-000000000001"+ assert run.schema_id is Nonediff --git a/products/customer_analytics/backend/migrations/0036_custompropertysyncrun_saved_query_id.py b/products/customer_analytics/backend/migrations/0036_custompropertysyncrun_saved_query_id.pynew file mode 100644index 000000000000..cd1d7880afc8--- /dev/null+++ b/products/customer_analytics/backend/migrations/0036_custompropertysyncrun_saved_query_id.py@@ -0,0 +1,15 @@+# Generated by Django 5.2.17 on 2026-08-17 14:12++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("customer_analytics", "0035_alter_feature_request_description")]++ operations = [+ migrations.AddField(+ model_name="custompropertysyncrun",+ name="saved_query_id",+ field=models.UUIDField(blank=True, null=True),+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 5426f81c4960..5cc3a0695b0b 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0035_alter_feature_request_description+0036_custompropertysyncrun_saved_query_iddiff --git a/products/customer_analytics/backend/models/custom_property_sync_run.py b/products/customer_analytics/backend/models/custom_property_sync_run.pyindex 0ea890baf7df..d3d33ec8a029 100644--- a/products/customer_analytics/backend/models/custom_property_sync_run.py+++ b/products/customer_analytics/backend/models/custom_property_sync_run.py@@ -36,10 +36,13 @@ class CustomPropertySyncRun(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):source = models.ForeignKey("customer_analytics.CustomPropertySource", on_delete=models.CASCADE, related_name="sync_runs")- # The warehouse schema the rows came from. Kept as a plain id (not an FK) because a schema can be- # deleted while its historical runs stay meaningful.+ # The warehouse object the rows came from — exactly one is set, matching the source's binding.+ # Both are plain ids (not FKs) because a schema or view can be deleted while its historical runs+ # stay meaningful.schema_id = models.UUIDField(null=True, blank=True)- # The import job this run rode on. Null for backfill/manual runs that don't come from an import job.+ saved_query_id = models.UUIDField(null=True, blank=True)+ # The warehouse job this run rode on: an import job, or a view materialization. Null for+ # backfill/manual runs, which read the table directly instead of riding a job.job_id = models.CharField(max_length=400, null=True, blank=True)trigger = models.CharField(max_length=20, choices=SyncTrigger.choices)diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex debdfe2fceb8..f1c994233771 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -1054,9 +1054,10 @@ class CustomPropertySyncRunSerializer(DataclassSerializer):class CustomPropertySourceSerializer(DataclassSerializer):- """Binds a data-warehouse source to a custom property definition. Account sources read a- materialized view column and sync onto matching accounts; person and group sources read a- warehouse schema and sync onto matching persons or groups on each warehouse sync."""+ """Binds warehouse columns to a custom property definition. Account sources read a materialized+ view column and sync onto matching accounts; person and group sources read either an imported+ warehouse table or a materialized view, and sync onto matching persons or groups on every+ warehouse run of what they read."""id = serializers.UUIDField(read_only=True)definition = serializers.UUIDField(@@ -1066,16 +1067,17 @@ class CustomPropertySourceSerializer(DataclassSerializer):required=False,allow_null=True,help_text=(- "Account sources only: UUID of the data-warehouse saved query (materialized view) to read "- "values from. Mutually exclusive with external_data_schema."+ "UUID of the data-warehouse saved query to read from. Required for an account source. For a "+ "person or group source it must be a materialized view, and is one of the two binding "+ "options. Mutually exclusive with external_data_schema."),)external_data_schema = serializers.UUIDField(required=False,allow_null=True,help_text=(- "Person and group sources only: UUID of the warehouse schema (raw incremental table) to "- "read from. Mutually exclusive with saved_query."+ "Person and group sources only: UUID of the warehouse schema (an imported table) to read "+ "from. Mutually exclusive with saved_query; a person or group source sets exactly one."),)source_column = serializers.CharField(@@ -1096,7 +1098,7 @@ class CustomPropertySourceSerializer(DataclassSerializer):required=False,allow_null=True,help_text=(- "Person sources only: {warehouse_column: description} giving each mapped column a "+ "Person and group sources only: {warehouse_column: description} giving each mapped column a ""human-facing description, seeded from the warehouse column's information_schema ""description. Optional per column. Create-only."),@@ -1132,17 +1134,18 @@ class CustomPropertySourceSerializer(DataclassSerializer):read_only=True,allow_null=True,help_text=(- "Person and group sources only: how often the underlying warehouse schema syncs, in "- "seconds. Null for account sources or when unavailable."+ "Person and group sources only: how often the bound table or view runs, in seconds. Null "+ "for account sources, or when the schedule is unavailable — including a view whose "+ "frequency is set on its data-modeling DAG."),)next_sync_at = serializers.DateTimeField(read_only=True,allow_null=True,help_text=(- "Person and group sources only: approximate time of the next scheduled sync (last synced + "- "interval). Approximate — drifts if the schedule was paused. Null for account sources or if "- "never synced."+ "Person and group sources only: approximate time of the next scheduled run (last run + "+ "interval). Approximate — drifts if the schedule was paused. Null for account sources, if "+ "never run, or when the interval is unavailable."),)latest_run = CustomPropertySyncRunSerializer(@@ -1154,16 +1157,25 @@ class CustomPropertySourceSerializer(DataclassSerializer):read_only=True,allow_null=True,help_text=(- "Person and group sources only: UUID of the warehouse source owning the schema, so the UI "- "can link to the table. Null for account sources or when unavailable."+ "Table-bound person and group sources only: UUID of the warehouse source owning the schema, "+ "so the UI can link to the table. Null for account sources, view-bound sources, or when "+ "unavailable."),)table_name = serializers.CharField(read_only=True,allow_null=True,help_text=(- "Person and group sources only: the bound warehouse table as it is named in HogQL. Null "- "for account sources or when unavailable."+ "Person and group sources only: what this source reads, as it is named in HogQL — the "+ "imported table, or the view. Null for account sources or when unavailable."+ ),+ )+ saved_query_name = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text=(+ "View-bound person and group sources only: the materialized view's name, so the UI can tell "+ "a view-backed source from a table-backed one. Null for account and table-bound sources."),)@@ -1191,6 +1203,7 @@ class CustomPropertySourceSerializer(DataclassSerializer):"latest_run","external_data_source","table_name",+ "saved_query_name",]diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 1c30b90b3e75..3d80d0e5815d 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -44,6 +44,7 @@ from posthog.permissions import (get_authenticator_scopes,is_service_auth,)+from posthog.rate_limit import RunSavedQueryRateThrottlefrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControl, model_to_resource@@ -97,14 +98,20 @@ _OBJECT_READ_LEVEL = "viewer"_OBJECT_WRITE_LEVEL = "editor"+# The warehouse resources a person/group-property source can bind to: the import source behind a+# table, or a materialized view. Each needs its own API-token scope folded into the object check.+_WAREHOUSE_SCOPE_GATED_RESOURCES = frozenset({"external_data_source", "warehouse_view"})++class _WarehouseScopeGatedAccessControl:- """Wraps ``UserAccessControl`` so object-level ``external_data_source`` access additionally- requires the request token to carry the matching ``external_data_source`` scope (``read`` for- viewer, ``write`` for editor). Person-property sources gate all warehouse read/write through- ``check_access_level_for_object`` on the linked ``external_data_source``, so folding the token- scope in here enforces the cross-resource scope on every path without threading it through the- facade. Session auth (no token scopes) and ``*`` tokens are unaffected — API scopes never gate- session requests, which stay RBAC-only. Everything else delegates to the wrapped instance."""+ """Wraps ``UserAccessControl`` so object-level warehouse access additionally requires the request+ token to carry the matching scope for that resource (``read`` for viewer, ``write`` for editor) —+ ``external_data_source`` for a table binding, ``warehouse_view`` for a view binding.+ Person-property sources gate all warehouse read/write through ``check_access_level_for_object`` on+ the bound warehouse object, so folding the token scope in here enforces the cross-resource scope on+ every path without threading it through the facade. Session auth (no token scopes) and ``*`` tokens+ are unaffected — API scopes never gate session requests, which stay RBAC-only. Everything else+ delegates to the wrapped instance."""def __init__(self, inner: UserAccessControl, token_scopes: list[str]) -> None:self._inner = inner@@ -120,16 +127,17 @@ class _WarehouseScopeGatedAccessControl:def _token_lacks_scope_for(self, obj: Any, required_level: Any) -> bool:scopes = self._token_scopes- if "*" in scopes or model_to_resource(obj) != "external_data_source":+ resource = model_to_resource(obj)+ if "*" in scopes or resource not in _WAREHOUSE_SCOPE_GATED_RESOURCES:return False- if "external_data_source:write" in scopes:+ if f"{resource}:write" in scopes:return False # write implies read, so it satisfies both viewer and editor- return not (required_level == "viewer" and "external_data_source:read" in scopes)+ return not (required_level == "viewer" and f"{resource}:read" in scopes)def _warehouse_scoped_uac(view: Any) -> UserAccessControl:- """The view's ``UserAccessControl``, additionally gating ``external_data_source`` object access on- the request token's warehouse scope. A no-op for session/other non-token auth (no token scopes)."""+ """The view's ``UserAccessControl``, additionally gating warehouse object access on the request+ token's scope for that resource. A no-op for session/other non-token auth (no token scopes)."""scopes = get_authenticator_scopes(getattr(view.request, "successful_authenticator", None))if scopes is None:return view.user_access_control@@ -805,6 +813,22 @@ def _account_relationship_definition_write_fields(validated, raw_data: dict) ->return fields+class CustomPropertySourceSyncThrottle(RunSavedQueryRateThrottle):+ """A manual sync starts a real warehouse run — a billable import for a table binding, a+ materialization for a view. Keying on the bound warehouse object instead of the mapping puts a+ view-bound sync in the same bucket as the canonical saved-query run endpoint, so a caller can't+ exceed that view's run limit by pointing two mappings at it (or by using this route instead)."""++ def get_cache_key(self, request, view):+ team_id = self.safely_get_team_id_from_view(view)+ source_id = view.kwargs.get("pk", "")+ if team_id and source_id:+ binding_id = api.get_custom_property_source_binding_id(team_id, source_id)+ if binding_id:+ return self.cache_format % {"scope": self.scope, "ident": f"{team_id}_{binding_id}"}+ return super().get_cache_key(request, view)++class CustomPropertySourceViewSet(TeamAndOrgViewSetMixin,AccessControlViewSetMixin,@@ -948,11 +972,11 @@ class CustomPropertySourceViewSet(request=None,responses={202: CustomPropertySyncTriggerResponseSerializer},)- @action(methods=["POST"], detail=True)+ @action(methods=["POST"], detail=True, throttle_classes=[CustomPropertySourceSyncThrottle])def sync(self, request: Request, *args, **kwargs) -> Response:- """Person and group sources only: trigger the underlying warehouse schema's sync now. This- re-runs a real (billable) warehouse sync; the incremental person/group-property update runs- off it."""+ """Person and group sources only: run what this source reads now — an import for a table+ binding (a real, billable warehouse sync), a materialization for a view binding. The+ incremental person/group-property update runs off that run."""self._guard_group_source(request, self.kwargs["pk"])try:triggered = api.trigger_person_property_sync(@@ -960,7 +984,7 @@ class CustomPropertySourceViewSet()except api.ResourceForbiddenError:raise PermissionDenied()- except api.WarehouseSyncPausedError as e:+ except (api.WarehouseSyncPausedError, api.ViewNotSyncableError) as e:return Response({"message": str(e)}, status=status.HTTP_400_BAD_REQUEST)if not triggered:raise ValidationError("This action is only available for enabled person- or group-property sources.")diff --git a/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.py b/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.pyindex d107c6a1ffa9..358fcb0648d7 100644--- a/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.py+++ b/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.py@@ -25,19 +25,35 @@ class TestWarehouseScopeGatedAccessControl(SimpleTestCase):@parameterized.expand([- # (token scopes, required level, allowed?)- ("no_warehouse_scope_editor", ["account:write"], "editor", False),- ("no_warehouse_scope_viewer", ["account:read"], "viewer", False),- ("read_scope_covers_viewer", ["external_data_source:read"], "viewer", True),- ("read_scope_not_editor", ["external_data_source:read"], "editor", False),- ("write_scope_covers_editor", ["external_data_source:write"], "editor", True),- ("write_scope_covers_viewer", ["external_data_source:write"], "viewer", True),- ("wildcard_allows", ["*"], "editor", True),+ # (model name, token scopes, required level, allowed?)+ ("table_no_warehouse_scope_editor", "externaldatasource", ["account:write"], "editor", False),+ ("table_no_warehouse_scope_viewer", "externaldatasource", ["account:read"], "viewer", False),+ ("table_read_covers_viewer", "externaldatasource", ["external_data_source:read"], "viewer", True),+ ("table_read_not_editor", "externaldatasource", ["external_data_source:read"], "editor", False),+ ("table_write_covers_editor", "externaldatasource", ["external_data_source:write"], "editor", True),+ ("table_write_covers_viewer", "externaldatasource", ["external_data_source:write"], "viewer", True),+ ("table_wildcard_allows", "externaldatasource", ["*"], "editor", True),+ # A view binding gates on warehouse_view — the table's scope doesn't cover it, or vice versa.+ ("view_no_warehouse_scope_editor", "datawarehousesavedquery", ["account:write"], "editor", False),+ ("view_no_warehouse_scope_viewer", "datawarehousesavedquery", ["account:read"], "viewer", False),+ ("view_read_covers_viewer", "datawarehousesavedquery", ["warehouse_view:read"], "viewer", True),+ ("view_read_not_editor", "datawarehousesavedquery", ["warehouse_view:read"], "editor", False),+ ("view_write_covers_editor", "datawarehousesavedquery", ["warehouse_view:write"], "editor", True),+ ("view_write_covers_viewer", "datawarehousesavedquery", ["warehouse_view:write"], "viewer", True),+ ("view_wildcard_allows", "datawarehousesavedquery", ["*"], "editor", True),+ (+ "view_not_covered_by_table_scope",+ "datawarehousesavedquery",+ ["external_data_source:write"],+ "editor",+ False,+ ),+ ("table_not_covered_by_view_scope", "externaldatasource", ["warehouse_view:write"], "editor", False),])- def test_external_data_source_object_gated_on_token_scope(self, _name, scopes, level, allowed):+ def test_warehouse_object_gated_on_token_scope(self, _name, model_name, scopes, level, allowed):gate, inner = self._gate(scopes)- result = gate.check_access_level_for_object(_FakeModel("externaldatasource"), required_level=level)+ result = gate.check_access_level_for_object(_FakeModel(model_name), required_level=level)assert result is allowed# When the token scope denies, the wrapped RBAC check is never consulted (fail closed on scope).if not allowed:diff --git a/products/customer_analytics/backend/test/factories.py b/products/customer_analytics/backend/test/factories.pyindex c34b14f516c7..147e671722f6 100644--- a/products/customer_analytics/backend/test/factories.py+++ b/products/customer_analytics/backend/test/factories.py@@ -1,5 +1,7 @@from typing import Any+from django.apps import apps+from products.customer_analytics.backend.models import Account, CustomPropertyDefinition, DisplayType@@ -15,3 +17,18 @@ def create_custom_property_definition(return CustomPropertyDefinition.objects.unscoped().create(team_id=team_id, name=name, display_type=display_type, **kwargs)+++def create_saved_query(+ *, team_id: int, name: str = "enriched_users", is_materialized: bool = True, **kwargs: Any+) -> Any:+ """Create a data-warehouse view for tests. Materialized by default, which is what a view-backed+ property source binds to.++ Resolved with ``apps.get_model`` because customer_analytics does not depend on data_modeling; the+ production code reaches the same model the same way.+ """+ saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")+ return saved_query_model.objects.create(+ team_id=team_id, name=name, query={"query": "select 1"}, is_materialized=is_materialized, **kwargs+ )diff --git a/products/customer_analytics/backend/test/test_custom_property_source_sync_throttle.py b/products/customer_analytics/backend/test/test_custom_property_source_sync_throttle.pynew file mode 100644index 000000000000..0be90ac14f30--- /dev/null+++ b/products/customer_analytics/backend/test/test_custom_property_source_sync_throttle.py@@ -0,0 +1,52 @@+from posthog.test.base import APIBaseTest++from posthog.rate_limit import RunSavedQueryRateThrottle++from products.customer_analytics.backend.models import CustomPropertySource, TargetType+from products.customer_analytics.backend.presentation.views.views import CustomPropertySourceSyncThrottle+from products.customer_analytics.backend.test.factories import create_custom_property_definition, create_saved_query+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+++class _FakeView:+ def __init__(self, team_id: int, pk: str) -> None:+ self.team_id = team_id+ self.kwargs = {"pk": pk}+++class TestCustomPropertySourceSyncThrottle(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.saved_query = create_saved_query(team_id=self.team.id)++ def _source(self, name: str, **binding) -> CustomPropertySource:+ definition = create_custom_property_definition(+ team_id=self.team.id, name=name, target_type=TargetType.PERSON.value+ )+ return CustomPropertySource.objects.unscoped().create(+ team_id=self.team.id, definition=definition, key_column="distinct_id", **binding+ )++ def _sync_key(self, source: CustomPropertySource) -> str | None:+ return CustomPropertySourceSyncThrottle().get_cache_key(None, _FakeView(self.team.id, str(source.id)))++ def test_view_backed_sync_shares_the_canonical_saved_query_bucket(self):+ first = self._source("Plan tier", saved_query_id=self.saved_query.id)+ second = self._source("Seat count", saved_query_id=self.saved_query.id)+ canonical = RunSavedQueryRateThrottle().get_cache_key(None, _FakeView(self.team.id, str(self.saved_query.id)))++ # Syncing either mapping counts against the view's own run limit, so a caller can't get extra+ # materializations by routing through this endpoint or by adding a second mapping on the view.+ assert self._sync_key(first) == canonical+ assert self._sync_key(second) == canonical++ def test_table_backed_sync_keys_on_the_schema(self):+ external_source = ExternalDataSource.objects.create(+ team=self.team, source_id="s", connection_id="c", status="Running", source_type="Stripe"+ )+ schema = ExternalDataSchema.objects.create(team=self.team, source=external_source, name="users")+ source = self._source("Plan tier", external_data_schema_id=schema.id)++ assert str(schema.id) in (self._sync_key(source) or "")+ assert str(source.id) not in (self._sync_key(source) or "")diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex d2009274fb8b..c12bf993859a 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -983,21 +983,22 @@ export interface CustomPropertySyncRunApi {}/**- * Binds a data-warehouse source to a custom property definition. Account sources read a- * materialized view column and sync onto matching accounts; person and group sources read a- * warehouse schema and sync onto matching persons or groups on each warehouse sync.+ * Binds warehouse columns to a custom property definition. Account sources read a materialized+ * view column and sync onto matching accounts; person and group sources read either an imported+ * warehouse table or a materialized view, and sync onto matching persons or groups on every+ * warehouse run of what they read.*/export interface CustomPropertySourceApi {readonly id: string/** UUID of the custom property definition this source feeds. One source per definition. */definition: string/**- * Account sources only: UUID of the data-warehouse saved query (materialized view) to read values from. Mutually exclusive with external_data_schema.+ * UUID of the data-warehouse saved query to read from. Required for an account source. For a person or group source it must be a materialized view, and is one of the two binding options. Mutually exclusive with external_data_schema.* @nullable*/saved_query?: string | null/**- * Person and group sources only: UUID of the warehouse schema (raw incremental table) to read from. Mutually exclusive with saved_query.+ * Person and group sources only: UUID of the warehouse schema (an imported table) to read from. Mutually exclusive with saved_query; a person or group source sets exactly one.* @nullable*/external_data_schema?: string | null@@ -1009,7 +1010,7 @@ export interface CustomPropertySourceApi {source_column?: string | null/** Person and group sources only: {warehouse_column: property_name} mapping the columns this source writes onto the person or group. */column_property_map?: unknown- /** Person sources only: {warehouse_column: description} giving each mapped column a human-facing description, seeded from the warehouse column's information_schema description. Optional per column. Create-only. */+ /** Person and group sources only: {warehouse_column: description} giving each mapped column a human-facing description, seeded from the warehouse column's information_schema description. Optional per column. Create-only. */column_descriptions?: unknown/*** Column whose value identifies the target: an account's external_id for account sources, the person's distinct_id for person sources, or the group key for group sources.@@ -1036,27 +1037,32 @@ export interface CustomPropertySourceApi {/** @nullable */readonly updated_at: string | null/**- * Person and group sources only: how often the underlying warehouse schema syncs, in seconds. Null for account sources or when unavailable.+ * Person and group sources only: how often the bound table or view runs, in seconds. Null for account sources, or when the schedule is unavailable — including a view whose frequency is set on its data-modeling DAG.* @nullable*/readonly sync_frequency_interval_seconds: number | null/**- * Person and group sources only: approximate time of the next scheduled sync (last synced + interval). Approximate — drifts if the schedule was paused. Null for account sources or if never synced.+ * Person and group sources only: approximate time of the next scheduled run (last run + interval). Approximate — drifts if the schedule was paused. Null for account sources, if never run, or when the interval is unavailable.* @nullable*/readonly next_sync_at: string | null/** Person and group sources only: the most recent sync/backfill run, or null if none yet. */readonly latest_run: CustomPropertySyncRunApi | null/**- * Person and group sources only: UUID of the warehouse source owning the schema, so the UI can link to the table. Null for account sources or when unavailable.+ * Table-bound person and group sources only: UUID of the warehouse source owning the schema, so the UI can link to the table. Null for account sources, view-bound sources, or when unavailable.* @nullable*/readonly external_data_source: string | null/**- * Person and group sources only: the bound warehouse table as it is named in HogQL. Null for account sources or when unavailable.+ * Person and group sources only: what this source reads, as it is named in HogQL — the imported table, or the view. Null for account sources or when unavailable.* @nullable*/readonly table_name: string | null+ /**+ * View-bound person and group sources only: the materialized view's name, so the UI can tell a view-backed source from a table-backed one. Null for account and table-bound sources.+ * @nullable+ */+ readonly saved_query_name: string | null}/**diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex b148ec6b3f9b..7a6bd76cc779 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -1143,9 +1143,9 @@ export const getCustomPropertySourcesSyncUrl = (projectId: string, id: string) =}/**- * Person and group sources only: trigger the underlying warehouse schema's sync now. This- * re-runs a real (billable) warehouse sync; the incremental person/group-property update runs- * off it.+ * Person and group sources only: run what this source reads now — an import for a table+ * binding (a real, billable warehouse sync), a materialization for a view binding. The+ * incremental person/group-property update runs off that run.*/export const customPropertySourcesSync = async (projectId: string,diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 0596a3465d81..76aff87e7d0d 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -600,13 +600,13 @@ export const CustomPropertySourcesCreateBody = /* @__PURE__ */ zod.uuid().nullish().describe(- 'Account sources only: UUID of the data-warehouse saved query (materialized view) to read values from. Mutually exclusive with external_data_schema.'+ 'UUID of the data-warehouse saved query to read from. Required for an account source. For a person or group source it must be a materialized view, and is one of the two binding options. Mutually exclusive with external_data_schema.'),external_data_schema: zod.uuid().nullish().describe(- 'Person and group sources only: UUID of the warehouse schema (raw incremental table) to read from. Mutually exclusive with saved_query.'+ 'Person and group sources only: UUID of the warehouse schema (an imported table) to read from. Mutually exclusive with saved_query; a person or group source sets exactly one.'),source_column: zod.string()@@ -623,7 +623,7 @@ export const CustomPropertySourcesCreateBody = /* @__PURE__ */ zod.unknown().optional().describe(- "Person sources only: {warehouse_column: description} giving each mapped column a human-facing description, seeded from the warehouse column's information_schema description. Optional per column. Create-only."+ "Person and group sources only: {warehouse_column: description} giving each mapped column a human-facing description, seeded from the warehouse column's information_schema description. Optional per column. Create-only."),key_column: zod.string()@@ -639,7 +639,7 @@ export const CustomPropertySourcesCreateBody = /* @__PURE__ */ zod),}).describe(- 'Binds a data-warehouse source to a custom property definition. Account sources read a\nmaterialized view column and sync onto matching accounts; person and group sources read a\nwarehouse schema and sync onto matching persons or groups on each warehouse sync.'+ 'Binds warehouse columns to a custom property definition. Account sources read a materialized\nview column and sync onto matching accounts; person and group sources read either an imported\nwarehouse table or a materialized view, and sync onto matching persons or groups on every\nwarehouse run of what they read.')export const customPropertySourcesUpdateBodySourceColumnMax = 400diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsxindex 42c1a0c2d00a..13d95e481365 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx@@ -56,37 +56,42 @@ const TARGET_TYPE_OPTIONS: { value: CustomPropertyTargetType; label: string }[]{ value: 'group', label: 'Group' },]-// The table an existing source reads, shown as text because the binding is create-only. Links to the-// table's own page, where its sync history and import errors are.-function ReadOnlyWarehouseTable({+// What an existing source reads, shown as text because the binding is create-only. Links to the table+// or view's own page, where its run history and errors are.+function ReadOnlyWarehouseSource({entityPlural,+ isView,tableName,- schemaUrl,+ sourceUrl,}: {entityPlural: string+ isView: booleantableName: string | null- schemaUrl: string | null+ sourceUrl: string | null}): JSX.Element {return (<div className="flex flex-col gap-1">- <LemonLabel>Warehouse table</LemonLabel>+ <LemonLabel>{isView ? 'Materialized view' : 'Warehouse table'}</LemonLabel>{tableName ? (- schemaUrl ? (- <Link to={schemaUrl} target="_blank" targetBlankIcon>+ <span className="flex items-center gap-2">+ {sourceUrl ? (+ <Link to={sourceUrl} target="_blank" targetBlankIcon>+ <code>{tableName}</code>+ </Link>+ ) : (<code>{tableName}</code>- </Link>- ) : (- <code>{tableName}</code>- )+ )}+ <LemonTag type="muted">{isView ? 'View' : 'Table'}</LemonTag>+ </span>) : (<span className="text-secondary">- This table isn't available. It may have been deleted, or you may not have access to the source it- belongs to.+ This {isView ? 'view' : 'table'} isn't available. It may have been deleted, or you may not have+ access to it.</span>)}<span className="text-secondary text-xs">- Rows from this table update matching {entityPlural} on every sync. You can't change the table after the- property is created.+ Rows from here update matching {entityPlural} on every run. You can't change what a property reads after+ it's created.</span></div>)@@ -160,13 +165,14 @@ function ReadOnlyColumnMappings({function PersonSourceEditor(): JSX.Element {const {customPropertyForm,- warehouseTables,+ warehouseSourceOptions,warehouseTablesLoading,+ savedQueriesLoading,editingDefinition,columnMappingWarnings,selectedTableColumns,selectedTableColumnsLoading,- hasSyncedWarehouseTables,+ hasWarehouseSourceOptions,} = useValues(customPropertyDefinitionsLogic)const { setCustomPropertyFormValue, loadSelectedTableColumns, loadWarehouseTables } =useActions(customPropertyDefinitionsLogic)@@ -177,10 +183,11 @@ function PersonSourceEditor(): JSX.Element {const entityPlural = isGroup ? 'groups' : 'people'const existingSource = editingDefinition?.sourceconst hasExistingSource = !!existingSource- // Deliberately not derived from `warehouseTables` — the picker's search narrows that list, and a- // search with no matches would otherwise collapse the whole editor into the empty-state banner,- // taking the search box with it. The picker shows its own "no options matching" instead.- const noTables = hasSyncedWarehouseTables === false+ // Deliberately not derived from the picker's options — its search narrows that list, and a search+ // with no matches would otherwise collapse the whole editor into the empty-state banner, taking the+ // search box with it. The picker shows its own "no options matching" instead.+ const noSources = hasWarehouseSourceOptions === false+ const existingBindsAView = !!existingSource?.saved_query && !existingSource?.external_data_schemaconst mappings = customPropertyForm.columnMappingsconst setMappings = (next: typeof mappings): void => setCustomPropertyFormValue('columnMappings', next)const columnByName = new Map(selectedTableColumns.map((column) => [column.name, column]))@@ -203,13 +210,13 @@ function PersonSourceEditor(): JSX.Element {const selectedGroupTypeLabel =groupTypeOptions.find((option) => option.value === customPropertyForm.groupTypeIndex)?.label ?? null- // Only block on missing tables while creating a source — an existing source still needs its- // key column and enabled switch editable even if its table was later deleted or filtered out.- if (noTables && !hasExistingSource) {+ // Only block on missing sources while creating a property — an existing source still needs its key+ // column and enabled switch editable even if what it reads was later deleted or filtered out.+ if (noSources && !hasExistingSource) {return (<LemonBanner type="info">- No synced data warehouse tables found. Connect and sync a source (e.g. your users table) first, then it- can feed person properties.+ No data warehouse tables or materialized views found. Connect and sync a source, or materialize a view,+ then it can feed {entityLabel} properties.</LemonBanner>)}@@ -239,23 +246,26 @@ function PersonSourceEditor(): JSX.Element {</LemonField>))}{hasExistingSource ? (- <ReadOnlyWarehouseTable+ <ReadOnlyWarehouseSourceentityPlural={entityPlural}- tableName={existingSource?.table_name ?? null}- schemaUrl={- existingSource?.external_data_source && existingSource.external_data_schema- ? urls.dataWarehouseSourceSchema(- existingSource.external_data_source,- existingSource.external_data_schema- )- : null+ isView={existingBindsAView}+ tableName={existingSource?.saved_query_name ?? existingSource?.table_name ?? null}+ sourceUrl={+ existingBindsAView && existingSource?.saved_query+ ? urls.sqlEditor({ view_id: existingSource.saved_query })+ : existingSource?.external_data_source && existingSource.external_data_schema+ ? urls.dataWarehouseSourceSchema(+ existingSource.external_data_source,+ existingSource.external_data_schema+ )+ : null}/>) : (<LemonField- name="warehouseTable"- label="Warehouse table"- help={`Rows from this synced table are upserted onto matching ${entityLabel}s. Type to search all synced tables.`}+ name="warehouseSource"+ label="Warehouse source"+ help={`Rows from this table or view are written onto matching ${entityLabel}s. Type to search synced tables and materialized views.`}>{({ value, onChange }) => (<LemonInputSelect@@ -264,23 +274,30 @@ function PersonSourceEditor(): JSX.Element {onChange={(newValues) => {const newValue = newValues[0] ?? nullonChange(newValue)- // Columns are table-specific, so a table change invalidates the picks and- // loads the new table's columns for the pickers below.+ // Columns belong to one source, so a change invalidates the picks and+ // loads the new source's columns for the pickers below.setCustomPropertyFormValue('keyColumn', null)setMappings(mappings.map((mapping) => ({ ...mapping, column: '', description: '' })))- // Also load on clear (tableId null) so the pickers below drop the previous- // table's stale columns; the loader returns an empty list for null.- loadSelectedTableColumns({ tableId: newValue })+ // Also load on clear (null) so the pickers below drop the previous source's+ // stale columns; the loader returns an empty list for null.+ loadSelectedTableColumns({ source: newValue })}}- // Search runs on the backend so the whole synced catalog is reachable, not just- // the first page loaded into the picker.+ // Table search runs on the backend so the whole synced catalog is reachable,+ // not just the first page loaded into the picker. Views are all loaded already,+ // so the picker filters those itself.onInputChange={(search) => loadWarehouseTables({ search })}- options={warehouseTables.map((table) => ({- key: table.id,- label: table.hogql_name || table.name,+ options={warehouseSourceOptions.map((option) => ({+ key: option.value,+ label: option.label,+ labelComponent: (+ <span className="flex items-center gap-2">+ <span>{option.label}</span>+ <LemonTag type="muted">{option.kind === 'view' ? 'View' : 'Table'}</LemonTag>+ </span>+ ),}))}- loading={warehouseTablesLoading}- placeholder="Select a warehouse table"+ loading={warehouseTablesLoading || savedQueriesLoading}+ placeholder="Select a table or view"/>)}</LemonField>@@ -385,7 +402,7 @@ function PersonSourceEditor(): JSX.Element {)}<LemonFieldname="isEnabled"- help={`When on, this table's syncs update the mapped ${entityLabel} properties, and each sync backfills changed rows. Turn it off to stop updating those properties without deleting the mapping; values already synced stay.`}+ help={`When on, every run of the table or view updates the mapped ${entityLabel} properties, and each run writes the rows that changed. Turn it off to stop updating those properties without deleting the mapping. Values already written stay.`}>{({ value, onChange }) => (<LemonSwitch@@ -395,7 +412,7 @@ function PersonSourceEditor(): JSX.Element {<span className="flex items-center gap-1">Sync enabled<Tooltip- title={`Keeps the mapped ${entityLabel} properties updated from this warehouse table on every sync. Disabling stops updates; it doesn't remove values already written.`}+ title={`Keeps the mapped ${entityLabel} properties updated on every run of what this property reads. Disabling stops updates. It doesn't remove values already written.`}><IconInfo className="text-secondary" /></Tooltip>diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsxindex 389a13a0ecaf..be51f7f95aee 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { IconExternal, IconPencil, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'-import { LemonButton, LemonTable, LemonTableColumns, Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonTable, LemonTableColumns, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'import { TZLabel } from 'lib/components/TZLabel'@@ -70,9 +70,17 @@ function updatedShare(existing: number, changed: number): string | null {return percentage(Math.min(share, 0.99), 0)}-// The bound table's sync history in the data warehouse. Null when the source has no warehouse-// binding, or when the caller can't view the warehouse source that owns it.-function schemaSyncsUrl(source: CustomPropertySourceApi): string | null {+// Whether the source reads a materialized view rather than a synced table.+function bindsAView(source: CustomPropertySourceApi): boolean {+ return !!source.saved_query && !source.external_data_schema+}++// Where the bound table or view's own run history lives. Null when the source has no warehouse+// binding, or when the caller can't view what it reads.+function sourceRunsUrl(source: CustomPropertySourceApi): string | null {+ if (bindsAView(source)) {+ return source.saved_query ? urls.sqlEditor({ view_id: source.saved_query }) : null+ }if (!source.external_data_source || !source.external_data_schema) {return null}@@ -234,6 +242,24 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'persondataIndex: 'name',render: (_, definition) => <span className="font-semibold">{definition.name}</span>,},+ {+ title: 'Reads',+ tooltip: 'The warehouse table or materialized view this property reads its values from.',+ render: (_, definition) => {+ const source = definition.source+ const name = source?.saved_query_name ?? source?.table_name+ if (!source || !name) {+ return <span className="text-secondary">—</span>+ }+ const url = sourceRunsUrl(source)+ return (+ <span className="flex items-center gap-2">+ {url ? <Link to={url}>{name}</Link> : <span>{name}</span>}+ <LemonTag type="muted">{bindsAView(source) ? 'View' : 'Table'}</LemonTag>+ </span>+ )+ },+ },{title: labels.keyColumn,tooltip: `The warehouse column holding each row's ${targetType === 'person' ? 'distinct ID' : 'group key'}. It's how a row is matched to ${labels.entityPlural} — rows with no match are skipped.`,@@ -396,7 +422,7 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person<ProfilePropertyRunssourceId={definition.source.id}labels={labels}- syncsUrl={schemaSyncsUrl(definition.source)}+ syncsUrl={sourceRunsUrl(definition.source)}/>) : null,}}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.tsindex 9ff70cb461f5..e27b259defbf 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts@@ -166,7 +166,7 @@ describe('customPropertyDefinitionsLogic', () => {savedQuery: 'view-1',sourceColumn: 'mrr',keyColumn: 'org_id',- warehouseTable: null,+ warehouseSource: null,columnMappings: [{ column: '', property: '', description: '' }],isEnabled: true,})@@ -345,7 +345,7 @@ describe('customPropertyDefinitionsLogic', () => {logic.actions.setCustomPropertyFormValues({name: 'Plan tier',targetType: 'person',- warehouseTable: 'table-1',+ warehouseSource: 'table:table-1',keyColumn: 'distinct_id',columnMappings: [{ column: 'plan', property: 'plan_tier', description: 'The plan tier' },@@ -372,7 +372,7 @@ describe('customPropertyDefinitionsLogic', () => {})})- it('resolves the selected table schema id and serialized column map for the person source', async () => {+ it('resolves the selected table binding and serialized column map for the person source', async () => {useMocks(defaultMocks())mountLogic()await expectLogic(logic, () => logic.actions.openCreateModal()).toDispatchActions([@@ -380,19 +380,81 @@ describe('customPropertyDefinitionsLogic', () => {])logic.actions.setCustomPropertyFormValues({targetType: 'person',- warehouseTable: 'table-1',+ warehouseSource: 'table:table-1',columnMappings: [{ column: ' plan ', property: ' plan_tier ', description: ' The plan tier ' },{ column: 'seats', property: '', description: 'ignored — no property' },],})- expect(logic.values.selectedWarehouseSchemaId).toBe('schema-1')+ expect(logic.values.profileSourceBinding).toEqual({ field: 'external_data_schema', id: 'schema-1' })// Trims and drops incomplete pairs.expect(logic.values.serializedColumnPropertyMap).toEqual({ plan: 'plan_tier' })// Descriptions trim and drop alongside their pair; a description without a complete pair is dropped.expect(logic.values.serializedColumnDescriptions).toEqual({ plan: 'The plan tier' })})+ it('binds a person source to a materialized view when one is picked', async () => {+ let sourceBody: Record<string, any> | null = null+ useMocks({+ ...defaultMocks(),+ post: {+ ...defaultMocks().post,+ [SOURCES_URL]: async ({ request }) => {+ sourceBody = (await request.json()) as Record<string, any>+ return buildSource()+ },+ },+ })+ mountLogic()+ await expectLogic(logic, () => logic.actions.openCreateModal()).toDispatchActions(['loadSavedQueriesSuccess'])+ logic.actions.setCustomPropertyFormValues({+ name: 'Plan tier',+ targetType: 'person',+ warehouseSource: 'view:view-1',+ keyColumn: 'org_id',+ columnMappings: [{ column: 'mrr', property: 'mrr', description: '' }],+ isEnabled: true,+ })++ await expectLogic(logic, () => logic.actions.submitCustomPropertyForm()).toDispatchActions([+ 'submitCustomPropertyFormSuccess',+ ])+ // A view binds by its own id under saved_query; sending external_data_schema would 400.+ expect(sourceBody).toEqual({+ definition: 'def-2',+ saved_query: 'view-1',+ column_property_map: { mrr: 'mrr' },+ column_descriptions: {},+ key_column: 'org_id',+ is_enabled: true,+ })+ })++ it('offers synced tables and materialized views in one picker', async () => {+ useMocks(defaultMocks())+ mountLogic()+ // The table loader debounces, so it lands after the saved queries — wait on the later one.+ await expectLogic(logic, () => logic.actions.openCreateModal()).toDispatchActions([+ 'loadWarehouseTablesSuccess',+ ])+ expect(logic.values.warehouseSourceOptions).toEqual([+ { value: 'table:table-1', label: 'users', kind: 'table' },+ { value: 'view:view-1', label: 'billing_view', kind: 'view' },+ ])+ // A project with views but no synced tables can still map properties.+ expect(logic.values.hasWarehouseSourceOptions).toBe(true)+ })++ it("loads a view's columns from the saved query rather than fetching a table", async () => {+ useMocks(defaultMocks())+ mountLogic()+ await expectLogic(logic, () => logic.actions.openCreateModal()).toDispatchActions(['loadSavedQueriesSuccess'])+ await expectLogic(logic, () =>+ logic.actions.loadSelectedTableColumns({ source: 'view:view-1' })+ ).toDispatchActions(['loadSelectedTableColumnsSuccess'])+ expect(logic.values.selectedTableColumns.map((column) => column.name)).toEqual(['org_id', 'mrr'])+ })+it('follows pagination so warehouse tables past the first page are reachable', async () => {useMocks({...defaultMocks(),diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.tsindex 4eeba47d6a60..3dbd845e2628 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts@@ -53,6 +53,48 @@ const RUNS_POLL_MAX_ATTEMPTS = 130// is the state right after a trigger while the workflow starts up) means keep polling.const TERMINAL_RUN_STATUSES = new Set(['completed', 'failed'])+// What a person/group source reads. Both land as a Delta table the sync reads the same way; the kind+// picks which field the create call sends (`external_data_schema` or `saved_query`).+export type WarehouseSourceKind = 'table' | 'view'++export interface WarehouseSourceRef {+ kind: WarehouseSourceKind+ id: string+}++// The picker holds one string so a single LemonInputSelect can offer tables and views together.+const WAREHOUSE_SOURCE_SEPARATOR = ':'++export function encodeWarehouseSource(kind: WarehouseSourceKind, id: string): string {+ return `${kind}${WAREHOUSE_SOURCE_SEPARATOR}${id}`+}++export function decodeWarehouseSource(value: string | null): WarehouseSourceRef | null {+ if (!value) {+ return null+ }+ const separatorAt = value.indexOf(WAREHOUSE_SOURCE_SEPARATOR)+ const kind = value.slice(0, separatorAt)+ const id = value.slice(separatorAt + 1)+ if ((kind !== 'table' && kind !== 'view') || !id) {+ return null+ }+ return { kind, id }+}++// A picker entry: the encoded value, its display label, and which kind it is (rendered as a tag).+export interface WarehouseSourceOption {+ value: string+ label: string+ kind: WarehouseSourceKind+}++// The create call's binding field and id for the picked source.+export interface ProfileSourceBinding {+ field: 'external_data_schema' | 'saved_query'+ id: string+}+// One warehouse-column → person-property pair in the person-target editor. Serialized to the// backend's `column_property_map` object ({column: property}) on save; the optional per-mapping// description is serialized to `column_descriptions` ({column: description}).@@ -85,8 +127,9 @@ export interface CustomPropertyFormValues {savedQuery: string | nullsourceColumn: string | nullkeyColumn: string | null- // Person/group target: the warehouse table (its schema id backs the source) + the column mappings.- warehouseTable: string | null+ // Person/group target: what the source reads (a synced table or a materialized view, encoded by+ // `encodeWarehouseSource`) plus the column mappings.+ warehouseSource: string | nullcolumnMappings: ColumnPropertyMapping[]isEnabled: boolean}@@ -103,7 +146,7 @@ const DEFAULT_FORM_VALUES: CustomPropertyFormValues = {savedQuery: null,sourceColumn: null,keyColumn: null,- warehouseTable: null,+ warehouseSource: null,columnMappings: [{ column: '', property: '', description: '' }],isEnabled: true,}@@ -201,6 +244,7 @@ export interface customPropertyDefinitionsLogicValues {editingReferences: readonly CustomPropertyReferenceApi[]filteredDefinitions: CustomPropertyDefinitionApi[]hasSyncedWarehouseTables: boolean | null+ hasWarehouseSourceOptions: boolean | nullisCustomPropertyFormSubmitting: booleanisCustomPropertyFormValid: booleanmaterializedViews: DataWarehouseSavedQuery[]@@ -209,6 +253,7 @@ export interface customPropertyDefinitionsLogicValues {newWorkflowUrlLoading: booleanpersonPropertyDefinitions: PropertyDefinition[]personPropertyDefinitionsLoading: boolean+ profileSourceBinding: ProfileSourceBinding | nullrunsBySourceId: Record<string, CustomPropertySyncRunApi[]>runsLoadingBySourceId: Record<string, boolean>savedQueries: DataWarehouseSavedQuery[]@@ -217,13 +262,13 @@ export interface customPropertyDefinitionsLogicValues {selectedSourceColumns: string[]selectedTableColumns: WarehouseColumn[]selectedTableColumnsLoading: boolean- selectedWarehouseSchemaId: string | nullserializedColumnDescriptions: Record<string, string>serializedColumnPropertyMap: Record<string, string>showCustomPropertyFormErrors: booleantargetTypeFilter: CustomPropertyTargetTypeFiltertargetTypeLocked: booleantriggeringSourceIds: string[]+ warehouseSourceOptions: WarehouseSourceOption[]warehouseTables: DataWarehouseTable[]warehouseTablesLoading: boolean}@@ -320,8 +365,8 @@ export interface customPropertyDefinitionsLogicActions {savedQueries: DataWarehouseSavedQuery[]payload?: any}- loadSelectedTableColumns: ({ tableId }: { tableId: string | null }) => {- tableId: string | null+ loadSelectedTableColumns: ({ source }: { source: string | null }) => {+ source: string | null}loadSelectedTableColumnsFailure: (error: string,@@ -333,12 +378,12 @@ export interface customPropertyDefinitionsLogicActions {loadSelectedTableColumnsSuccess: (selectedTableColumns: WarehouseColumn[],payload?: {- tableId: string | null+ source: string | null}) => {selectedTableColumns: WarehouseColumn[]payload?: {- tableId: string | null+ source: string | null}}loadWarehouseTables: ({ search }?: { search?: string }) => {@@ -446,10 +491,19 @@ export interface customPropertyDefinitionsLogicMeta {savedQueries: DataWarehouseSavedQuery[],customPropertyForm: CustomPropertyFormValues) => string[]- selectedWarehouseSchemaId: (+ warehouseSourceOptions: (warehouseTables: DataWarehouseTable[],+ materializedViews: DataWarehouseSavedQuery[]+ ) => WarehouseSourceOption[]+ hasWarehouseSourceOptions: (+ hasSyncedWarehouseTables: boolean | null,+ materializedViews: DataWarehouseSavedQuery[]+ ) => boolean | null+ profileSourceBinding: (+ warehouseTables: DataWarehouseTable[],+ materializedViews: DataWarehouseSavedQuery[],customPropertyForm: CustomPropertyFormValues- ) => string | null+ ) => ProfileSourceBinding | nullserializedColumnPropertyMap: (customPropertyForm: CustomPropertyFormValues) => Record<string, string>serializedColumnDescriptions: (customPropertyForm: CustomPropertyFormValues) => Record<string, string>columnMappingWarnings: (@@ -665,15 +719,16 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogicbreak}}- // Only synced tables carry an external_schema, which is what a person source binds to.+ // Only synced tables carry an external_schema, which is what a table binding needs.const synced = collected.filter((table) => !!table.external_schema)// Keep the currently-selected table in the list even if the active search filters it// out, so the picker can still render its label rather than a bare id.- const selectedId = values.customPropertyForm.warehouseTable+ const selected = decodeWarehouseSource(values.customPropertyForm.warehouseSource)+ const selectedId = selected?.kind === 'table' ? selected.id : nullif (selectedId && !synced.some((table) => table.id === selectedId)) {- const selected = values.warehouseTables.find((table) => table.id === selectedId)- if (selected) {- return [selected, ...synced]+ const known = values.warehouseTables.find((table) => table.id === selectedId)+ if (known) {+ return [known, ...synced]}}return synced@@ -683,25 +738,44 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogicselectedTableColumns: [[] as WarehouseColumn[],{- loadSelectedTableColumns: async ({- tableId,- }: {- tableId: string | null- }): Promise<WarehouseColumn[]> => {- if (!tableId) {+ loadSelectedTableColumns: async (+ { source }: { source: string | null },+ breakpoint+ ): Promise<WarehouseColumn[]> => {+ const ref = decodeWarehouseSource(source)+ if (!ref) {return []}- const table = await api.dataWarehouseTables.get(tableId)- const columns: WarehouseColumn[] = (table.columns ?? []).map((column) => ({- name: column.name,- type: String(column.type),- description: null,- }))+ // A view's columns are already on the saved query the picker was built from, so only+ // the table branch pays for a fetch.+ let tableName: string+ let columns: WarehouseColumn[]+ if (ref.kind === 'view') {+ const view = values.savedQueries.find((query) => query.id === ref.id)+ if (!view) {+ return []+ }+ tableName = view.name+ columns = (view.columns ?? []).map((column) => ({+ name: column.name,+ type: String(column.type),+ description: null,+ }))+ } else {+ const table = await api.dataWarehouseTables.get(ref.id)+ breakpoint()+ tableName = table.hogql_name || table.name+ columns = (table.columns ?? []).map((column) => ({+ name: column.name,+ type: String(column.type),+ description: null,+ }))+ }// Seed each column's canonical description from the warehouse catalog. Best-effort:// descriptions are often unset for warehouse columns, and the catalog query mustn't// block picking columns, so any failure leaves descriptions null.+ const descriptionByColumn = new Map<string, string>()try {- const tableName = table.hogql_name || table.nameconst response = (await api.query({kind: NodeKind.HogQLQuery,query: hogql`@@ -710,7 +784,6 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogicwhere table_name = ${tableName}`,})) as HogQLQueryResponse- const descriptionByColumn = new Map<string, string>()for (const row of (response.results ?? []) as unknown[][]) {const name = row[0] as string | nullconst description = row[1] as string | null@@ -718,13 +791,16 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogicdescriptionByColumn.set(name, description)}}- return columns.map((column) => ({- ...column,- description: descriptionByColumn.get(column.name) ?? null,- }))} catch {- return columns+ // Descriptions stay null on failure — the catalog query must not block picking columns.}+ // Drop this result if a newer source selection has started since, so a slow table fetch+ // can't overwrite the columns of the source the user has since picked.+ breakpoint()+ return columns.map((column) => ({+ ...column,+ description: descriptionByColumn.get(column.name) ?? null,+ }))},},],@@ -777,13 +853,13 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogicsavedQuery,sourceColumn,keyColumn,- warehouseTable,+ warehouseSource,}: CustomPropertyFormValues) => {- // Person and group both feed from a warehouse table; account can also via a view.+ // Person and group read a synced table or a materialized view; account reads a view.const isProfile = targetType === 'person' || targetType === 'group'const isAccountWarehouse = !isProfile && sourceMode === 'data_warehouse'- // The table + column map are create-only, so only require them when creating a new- // profile source — an existing source keeps only key_column and enabled editable.+ // The binding + column map are create-only, so only require them when creating a new+ // profile source. An existing source keeps only key_column and enabled editable.const isNewProfileSource = isProfile && !values.editingDefinition?.sourcereturn {name: !name?.trim() ? 'Name is required' : undefined,@@ -797,7 +873,8 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogicsourceColumn: isAccountWarehouse && !sourceColumn ? 'Select the value column' : undefined,keyColumn:(isAccountWarehouse || isProfile) && !keyColumn?.trim() ? 'Enter the key column' : undefined,- warehouseTable: isNewProfileSource && !warehouseTable ? 'Select a warehouse table' : undefined,+ warehouseSource:+ isNewProfileSource && !warehouseSource ? 'Select a table or view to read from' : undefined,}},submit: async (formValues: CustomPropertyFormValues) => {@@ -816,27 +893,28 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogictry {const { targetType, sourceMode, savedQuery, sourceColumn, keyColumn, isEnabled } = formValuesconst existingSource = editing?.source ?? null- // Person and group sources share the same warehouse binding (schema + column map).+ // Person and group sources map columns from one warehouse object: a synced table's+ // schema, or a materialized view.if (targetType === 'person' || targetType === 'group') {- const schemaId = values.selectedWarehouseSchemaId+ const binding = values.profileSourceBindingif (existingSource) {// The binding + column map are create-only on the backend; only key_column- // and is_enabled are mutable on a person source.+ // and is_enabled are mutable on a profile source.await customPropertySourcesPartialUpdate(projectId, existingSource.id, {key_column: keyColumn ?? '',is_enabled: isEnabled,})- } else if (!schemaId) {- // Form validation passed but the table's schema no longer resolves — it was- // deleted or unsynced between load and save. Surface it instead of silently- // creating the definition without its source.- throw new Error('The selected warehouse table is no longer available')+ } else if (!binding) {+ // Form validation passed but the picked table or view no longer resolves: it+ // was deleted, unsynced, or unmaterialized between load and save. Surface it+ // instead of silently creating the definition without its source.+ throw new Error('The selected table or view is no longer available')} else if (!keyColumn?.trim()) {throw new Error('Enter the distinct ID column')} else {await customPropertySourcesCreate(projectId, {definition: definition.id,- external_data_schema: schemaId,+ [binding.field]: binding.id,column_property_map: values.serializedColumnPropertyMap,column_descriptions: values.serializedColumnDescriptions,key_column: keyColumn.trim(),@@ -889,11 +967,53 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogicreturn (view?.columns ?? []).map((column) => column.name)},],- // The chosen warehouse table's schema id — what a person source actually binds to.- selectedWarehouseSchemaId: [- (s) => [s.warehouseTables, s.customPropertyForm],- (warehouseTables: DataWarehouseTable[], form: CustomPropertyFormValues): string | null =>- warehouseTables.find((table) => table.id === form.warehouseTable)?.external_schema?.id ?? null,+ // Tables and views in one list, each tagged with its kind, so the picker offers both.+ warehouseSourceOptions: [+ (s) => [s.warehouseTables, s.materializedViews],+ (+ warehouseTables: DataWarehouseTable[],+ materializedViews: DataWarehouseSavedQuery[]+ ): WarehouseSourceOption[] => [+ ...warehouseTables.map((table) => ({+ value: encodeWarehouseSource('table', table.id),+ label: table.hogql_name || table.name,+ kind: 'table' as const,+ })),+ ...materializedViews.map((view) => ({+ value: encodeWarehouseSource('view', view.id),+ label: view.name,+ kind: 'view' as const,+ })),+ ],+ ],+ // Whether the project has anything a profile source could read. A project with views but no+ // synced tables is still usable, so the empty state has to consider both.+ hasWarehouseSourceOptions: [+ (s) => [s.hasSyncedWarehouseTables, s.materializedViews],+ (hasSyncedWarehouseTables: boolean | null, materializedViews: DataWarehouseSavedQuery[]): boolean | null =>+ materializedViews.length > 0 ? true : hasSyncedWarehouseTables,+ ],+ // What the create call sends for the picked source: a table resolves to its schema id, a view+ // binds by its own id. Null when the pick no longer resolves.+ profileSourceBinding: [+ (s) => [s.warehouseTables, s.materializedViews, s.customPropertyForm],+ (+ warehouseTables: DataWarehouseTable[],+ materializedViews: DataWarehouseSavedQuery[],+ form: CustomPropertyFormValues+ ): ProfileSourceBinding | null => {+ const ref = decodeWarehouseSource(form.warehouseSource)+ if (!ref) {+ return null+ }+ if (ref.kind === 'view') {+ return materializedViews.some((view) => view.id === ref.id)+ ? { field: 'saved_query', id: ref.id }+ : null+ }+ const schemaId = warehouseTables.find((table) => table.id === ref.id)?.external_schema?.id+ return schemaId ? { field: 'external_data_schema', id: schemaId } : null+ },],// The person-target column mappings as the backend's `column_property_map` object.serializedColumnPropertyMap: [@@ -1007,9 +1127,9 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogicsavedQuery: definition.source?.saved_query ?? null,sourceColumn: definition.source?.source_column ?? null,keyColumn: definition.source?.key_column ?? null,- // The warehouse-table binding is create-only, so on edit we surface the existing map- // (read-only in the modal) rather than resolving the table back for the picker.- warehouseTable: null,+ // The warehouse binding is create-only, so on edit we surface the existing map+ // (read-only in the modal) rather than resolving the source back for the picker.+ warehouseSource: null,columnMappings: isProfile? parseColumnPropertyMap(definition.source?.column_property_map,@@ -1020,19 +1140,27 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic})},loadWarehouseTablesSuccess: () => {- // On edit the table binding is create-only and hidden, but the distinct-ID column stays- // editable — so resolve the bound table from the source's schema and load its columns to- // drive that picker. Resolving here (not in openEditModal) waits for the table list to load.+ // On edit the binding is create-only and hidden, but the distinct-ID column stays editable,+ // so resolve the bound table from the source's schema and load its columns to drive that+ // picker. Resolving here (not in openEditModal) waits for the table list to load.const source = values.editingDefinition?.sourceif (source?.external_data_schema) {const table = values.warehouseTables.find((candidate) => candidate.external_schema?.id === source.external_data_schema)if (table) {- actions.loadSelectedTableColumns({ tableId: table.id })+ actions.loadSelectedTableColumns({ source: encodeWarehouseSource('table', table.id) })}}},+ loadSavedQueriesSuccess: () => {+ // The view-bound counterpart of the above: a view-backed source keeps its key column+ // editable too, and its columns come off the saved query rather than a table fetch.+ const source = values.editingDefinition?.source+ if (source?.saved_query && !source.external_data_schema) {+ actions.loadSelectedTableColumns({ source: encodeWarehouseSource('view', source.saved_query) })+ }+ },submitCustomPropertyFormSuccess: () => {lemonToast.success('Custom property saved')actions.loadDefinitions()diff --git a/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx b/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsxindex f16bce1dd215..f9f57a97485d 100644--- a/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx+++ b/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx@@ -37,6 +37,7 @@ const definitions: CustomPropertyDefinitionApi[] = [external_data_schema: '01890000-0000-0000-0000-0000000000f1',external_data_source: '01890000-0000-0000-0000-0000000000e1',table_name: 'stripe.customers',+ saved_query_name: null,key_column: 'user_email',column_property_map: { plan_name: 'billing_plan', mrr_cents: 'billing_mrr' },is_enabled: true,@@ -80,6 +81,7 @@ const definitions: CustomPropertyDefinitionApi[] = [external_data_schema: '01890000-0000-0000-0000-0000000000f2',external_data_source: '01890000-0000-0000-0000-0000000000e2',table_name: 'zendesk.users',+ saved_query_name: null,key_column: 'distinct_id',column_property_map: { tier: 'support_tier' },is_enabled: true,@@ -111,6 +113,7 @@ const definitions: CustomPropertyDefinitionApi[] = [external_data_schema: '01890000-0000-0000-0000-0000000000f3',external_data_source: '01890000-0000-0000-0000-0000000000e3',table_name: 'stripe.subscriptions',+ saved_query_name: null,key_column: 'account_id',column_property_map: { arr_cents: 'account_arr' },is_enabled: true,@@ -125,6 +128,52 @@ const definitions: CustomPropertyDefinitionApi[] = [latest_run: null,},},+ {+ id: '01890000-0000-0000-0000-000000000004',+ name: 'Lifecycle stage',+ display_type: 'text',+ target_type: 'person',+ is_canonical: false,+ created_at: '2023-02-13T09:00:00Z',+ created_by: null,+ updated_at: null,+ references: [],+ // View-backed: bound to a materialized view rather than an imported table, so it carries a+ // saved_query and no warehouse source to link through.+ source: {+ id: '01890000-0000-0000-0000-0000000000a4',+ definition: '01890000-0000-0000-0000-000000000004',+ saved_query: '01890000-0000-0000-0000-0000000000d4',+ external_data_source: null,+ table_name: 'enriched_users',+ saved_query_name: 'enriched_users',+ key_column: 'distinct_id',+ column_property_map: { lifecycle: 'lifecycle_stage' },+ is_enabled: true,+ consecutive_failures: 0,+ last_synced_at: '2023-02-15T12:00:00Z',+ last_sync_error: null,+ created_at: '2023-02-13T09:00:00Z',+ created_by: null,+ updated_at: null,+ sync_frequency_interval_seconds: 3600,+ next_sync_at: '2023-02-15T13:00:00Z',+ latest_run: {+ id: '01890000-0000-0000-0000-0000000000b4',+ trigger: 'scheduled',+ status: 'completed',+ started_at: '2023-02-15T11:59:00Z',+ finished_at: '2023-02-15T12:00:00Z',+ rows_read: 320,+ changed: 12,+ existing: 12,+ produced: 12,+ skipped_missing_person: 0,+ error: null,+ created_at: '2023-02-15T11:59:00Z',+ },+ },+ },]const runs: CustomPropertySyncRunApi[] = [diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex b4a6855b2635..80034b1ba2cd 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -514,9 +514,9 @@ tools:currency, percent, date, datetime, boolean), and optional `is_big_number` to abbreviate large numeric values(e.g. 10,000 → 10K; only valid for numeric display types). `target_type` picks what the property attachesto: `account` (default; value set manually or from a materialized view), `person`, or `group` (person/group- properties are populated from a warehouse table via a custom property source and become usable like any- other person/group property in feature flags, cohorts, and insights). For `group` targets, also pass- `group_type_index` (0-4) selecting the group type. Person and group targets require the+ properties are populated from a warehouse table or a materialized view via a custom property source and+ become usable like any other person/group property in feature flags, cohorts, and insights). For `group`+ targets, also pass `group_type_index` (0-4) selecting the group type. Person and group targets require the`warehouse-person-properties` feature; creating a `group` target additionally requires the `group:write`scope. Definitions are team-scoped; for account targets, set the value a specific account holds via theaccount custom property value tools.@@ -615,11 +615,12 @@ tools:idempotent: falsetitle: Backfill a warehouse person- or group-property sourcedescription: >- Person- and group-property sources only: start a backfill that reads the whole warehouse table and populates- person or group properties for its historical rows. Backfill is per table — one call refreshes every enabled- property mapped from that table — and it coalesces if one is already running for the table (the response's- `already_running` is then true). Returns 400 for a source that is not an enabled person- or group-property- source. Backfilling a group-target source additionally requires the `group:write` scope.+ Person- and group-property sources only: start a backfill that reads the whole warehouse table or view and+ populates person or group properties for its historical rows. Backfill is per table or view — one call+ refreshes every enabled property mapped from it — and it coalesces if one is already running for that table+ or view (the response's `already_running` is then true). Returns 400 for a source that is not an enabled+ person- or group-property source. Backfilling a group-target source additionally requires the `group:write`+ scope.feature_flag: warehouse-person-propertiescustom-property-sources-create:operation: custom_property_sources_create@@ -633,9 +634,10 @@ tools:title: Create custom property sourcedescription: >Bind a custom property definition to a data source. Account sources read a materialized view (`saved_query`- + `source_column`); person and group sources read a synced warehouse table (`external_data_schema` +- `column_property_map` mapping warehouse columns to person/group properties, plus `key_column` = the- distinct_id column for person sources or the group-key column for group sources). One source per definition.+ + `source_column`). Person and group sources read either a synced warehouse table (`external_data_schema`)+ or a materialized view (`saved_query`) — pass exactly one — plus `column_property_map` mapping warehouse+ columns to person/group properties and `key_column` = the distinct_id column for person sources or the+ group-key column for group sources. A view binding must already be materialized. One source per definition.The target (account, person, or group) follows the bound definition's `target_type`; creating a source for agroup-target definition additionally requires the `group:write` scope.feature_flag: customer-analytics-csp@@ -730,10 +732,11 @@ tools:idempotent: falsetitle: Sync a warehouse person- or group-property source nowdescription: >- Person- and group-property sources only: trigger the underlying warehouse schema's sync now. This re-runs a- real (billable) warehouse sync, and the incremental person/group-property update rides off it. It does not- reset the schema's recurring sync schedule. Returns 400 for a source that is not an enabled person- or- group-property source. Syncing a group-target source additionally requires the `group:write` scope.+ Person- and group-property sources only: run what the source reads now. A table binding re-runs a real+ (billable) warehouse sync; a view binding materializes the view. The incremental person/group-property+ update rides off that run. It does not reset the recurring schedule. Returns 400 for a source that is not an+ enabled person- or group-property source, and for a view whose data-modeling DAG is not on the v2 schedule+ (use backfill there instead). Syncing a group-target source additionally requires the `group:write` scope.feature_flag: warehouse-person-propertiescustom-property-sources-update:operation: custom_property_sources_updatediff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 73a1fd79edbc..be137ef6e701 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -18,8 +18,12 @@ _LAZY = {"promote_view_nodes_to_matview": "logic.saved_query_dag_sync","sync_saved_query_to_dag": "logic.saved_query_dag_sync","update_node_type": "logic.saved_query_dag_sync",+ "SavedQueryNotFoundError": "logic.node_materialization",+ "SavedQueryNotOnV2ScheduleError": "logic.node_materialization","is_saved_query_on_v2_schedule": "logic.node_materialization","materialize_saved_query": "logic.node_materialization",+ "run_saved_query_materialization": "logic.node_materialization",+ "get_materialized_table_uri": "logic.saved_query_reads","get_saved_query_ids_for_nodes": "logic.saved_query_reads","get_saved_query_summary": "logic.saved_query_reads","saved_query_materialized_at": "logic.saved_query_freshness",diff --git a/products/data_modeling/backend/logic/node_materialization.py b/products/data_modeling/backend/logic/node_materialization.pyindex d18e94c07530..b6bf80be5916 100644--- a/products/data_modeling/backend/logic/node_materialization.py+++ b/products/data_modeling/backend/logic/node_materialization.py@@ -1,6 +1,7 @@import asynciofrom dataclasses import asdictfrom datetime import UTC, datetime, timedelta+from uuid import UUIDfrom django.conf import settings@@ -73,6 +74,32 @@ def is_saved_query_on_v2_schedule(saved_query: DataWarehouseSavedQuery) -> bool:return saved_query.id in get_v2_saved_query_ids([saved_query.id])+class SavedQueryNotFoundError(Exception):+ """Raised by ``run_saved_query_materialization`` when the saved query no longer resolves."""+++class SavedQueryNotOnV2ScheduleError(Exception):+ """Raised by ``run_saved_query_materialization`` when the saved query still runs on the older+ per-query schedule, whose frozen workflow lacks what the caller needs from a materialization."""+++def run_saved_query_materialization(team_id: int, saved_query_id: UUID | str) -> None:+ """Materialize one saved query now, for a caller outside this product.++ Restricted to the v2 workflow, and raising rather than falling back, because a caller reaching+ here wants what only a v2 materialization does. Keeps the saved-query model inside this product:+ the caller passes ids and handles the two errors above.+ """+ saved_query = (+ DataWarehouseSavedQuery.objects.exclude(deleted=True).filter(id=saved_query_id, team_id=team_id).first()+ )+ if saved_query is None:+ raise SavedQueryNotFoundError(f"Saved query {saved_query_id} not found for team {team_id}")+ if not is_saved_query_on_v2_schedule(saved_query):+ raise SavedQueryNotOnV2ScheduleError(f"Saved query {saved_query_id} is not on the v2 schedule")+ materialize_saved_query(saved_query)++def materialize_saved_query(saved_query: DataWarehouseSavedQuery) -> None:"""Materialize the saved query's backing node via the v2 workflow.diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.pyindex f9082ff5b684..e06616228e07 100644--- a/products/data_modeling/backend/logic/saved_query_reads.py+++ b/products/data_modeling/backend/logic/saved_query_reads.py@@ -3,6 +3,8 @@from collections.abc import Iterablefrom uuid import UUID+from django.conf import settings+from ..facade.contracts import SavedQuerySummaryfrom ..models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom ..models.node import Node@@ -27,6 +29,21 @@ def get_saved_query_summary(team_id: int, saved_query_id: UUID | str) -> SavedQu)+def get_materialized_table_uri(team_id: int, saved_query_id: UUID | str) -> str | None:+ """The S3 Delta table a materialized view's rows live in, for a consumer that reads them directly.++ None when the view no longer resolves or was never materialized — either way there is no Delta+ table to read. The path is built from the same two model properties the materialization activity+ writes to (``_build_model_table_uri``), so a reader lands on the table that run produced.+ """+ saved_query = (+ DataWarehouseSavedQuery.objects.filter(team_id=team_id, id=saved_query_id).exclude(deleted=True).first()+ )+ if saved_query is None or not saved_query.is_materialized:+ return None+ return f"{settings.BUCKET_URL}/{saved_query.folder_path}/{saved_query.normalized_name}"++def get_saved_query_ids_for_nodes(team_id: int, node_ids: Iterable[UUID | str]) -> list[str]:"""The saved queries behind these DAG nodes. Source-table nodes have none and are dropped."""rows = Node.objects.filter(team_id=team_id, id__in=list(node_ids), saved_query__isnull=False).values_list(diff --git a/products/warehouse_sources/backend/facade/hooks.py b/products/warehouse_sources/backend/facade/hooks.pyindex 4b07b1e0dc0b..b83819ed828e 100644--- a/products/warehouse_sources/backend/facade/hooks.py+++ b/products/warehouse_sources/backend/facade/hooks.py@@ -9,10 +9,15 @@ on the startup path does not drag the whole pipeline onto every process boot."""from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (+ BINDING_KIND_SAVED_QUERY,+ BINDING_KIND_SCHEMA,+ MATERIALIZED_VIEW_SOURCE_TYPE,EmitSignalsActivityInputs,PersonPropertySourceProjection,+ PersonPropertySyncActivityInputs,PersonPropertySyncRunRecord,PersonPropertySyncSource,+ WarehouseBinding,person_property_projection_for,register_data_quality_checks_gate,register_emit_signals_gate,@@ -22,16 +27,23 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_hregister_person_property_sync_sources,register_revenue_view_sync,run_revenue_view_sync,+ saved_query_binding,+ schema_binding,)from .contracts import RevenueViewSyncInput__all__ = [+ "BINDING_KIND_SAVED_QUERY",+ "BINDING_KIND_SCHEMA",+ "MATERIALIZED_VIEW_SOURCE_TYPE","EmitSignalsActivityInputs","PersonPropertySourceProjection",+ "PersonPropertySyncActivityInputs","PersonPropertySyncRunRecord","PersonPropertySyncSource","RevenueViewSyncInput",+ "WarehouseBinding","person_property_projection_for","register_data_quality_checks_gate","register_emit_signals_gate",@@ -41,4 +53,6 @@ __all__ = ["register_person_property_sync_sources","register_revenue_view_sync","run_revenue_view_sync",+ "saved_query_binding",+ "schema_binding",]diff --git a/products/warehouse_sources/backend/facade/temporal.py b/products/warehouse_sources/backend/facade/temporal.pyindex 517cb4ad1bc0..a18c0e157a26 100644--- a/products/warehouse_sources/backend/facade/temporal.py+++ b/products/warehouse_sources/backend/facade/temporal.py@@ -2,7 +2,8 @@Temporal registration wiring for warehouse_sources.Re-exports the workflow/activity registration the temporal worker bootstrap loads,-plus the queryable-table prep helper the data-modeling temporal workflow calls.+plus the queryable-table prep helper and person-property row sink the data-modeling+temporal workflow calls.This module imports the data-import ``settings`` (which pull temporalio, dlt, pandas,...), so it must only be imported **off** the ``django.setup()`` path — i.e. from the@@ -26,9 +27,15 @@ from products.warehouse_sources.backend.temporal.data_imports.person_property_sy)from products.warehouse_sources.backend.temporal.data_imports.person_property_triggers import (ExternalDataSchemaSyncPausedError,+ SavedQueryNotFoundError,+ SavedQueryNotOnV2ScheduleError,start_person_property_backfill,+ trigger_saved_query_materialization,trigger_schema_sync,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink import (+ PersonPropertyRowSink,+)from products.warehouse_sources.backend.temporal.data_imports.settings import ACTIVITIES, WORKFLOWSfrom products.warehouse_sources.backend.temporal.data_imports.sources import load_all_sourcesfrom products.warehouse_sources.backend.temporal.data_imports.table_metadata_settings import (@@ -47,8 +54,12 @@ __all__ = ["PERSON_PROPERTY_SYNC_WORKFLOWS","WORKFLOWS","ExternalDataSchemaSyncPausedError",+ "PersonPropertyRowSink",+ "SavedQueryNotFoundError",+ "SavedQueryNotOnV2ScheduleError","load_all_sources","prepare_s3_files_for_querying","start_person_property_backfill",+ "trigger_saved_query_materialization","trigger_schema_sync",]diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.pyindex f3c3d121d661..6c3a196a908d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py@@ -102,10 +102,52 @@ def run_engineering_analytics_view_sync(schema: "ExternalDataSchema", source: "E_engineering_analytics_view_sync(schema, source)+# --- Warehouse binding ----------------------------------------------------------------+# A person/group-target source reads one warehouse object: a schema imported by a data-import job,+# or a materialized view maintained by a data-modeling job. Both land as a Delta table on S3 and+# both stage row projections for the same post-run upsert, so everything downstream of "here are+# the rows" is shared — only the staging prefix and the Delta location differ. The kind is a plain+# string so the binding crosses the Temporal payload boundary without a custom converter.++BINDING_KIND_SCHEMA = "schema"+BINDING_KIND_SAVED_QUERY = "saved_query"++# Log/label value for a view-backed run, where there is no import source type to name.+MATERIALIZED_VIEW_SOURCE_TYPE = "materialized_view"++[email protected](frozen=True)+class WarehouseBinding:+ """Which warehouse object a person/group-target source reads."""++ kind: str+ id: str++ @property+ def is_saved_query(self) -> bool:+ return self.kind == BINDING_KIND_SAVED_QUERY+++def schema_binding(schema_id: "str | uuid.UUID") -> WarehouseBinding:+ return WarehouseBinding(kind=BINDING_KIND_SCHEMA, id=str(schema_id))+++def saved_query_binding(saved_query_id: "str | uuid.UUID") -> WarehouseBinding:+ return WarehouseBinding(kind=BINDING_KIND_SAVED_QUERY, id=str(saved_query_id))+++def _binding_from_ids(schema_id: "uuid.UUID | None", saved_query_id: "uuid.UUID | None") -> WarehouseBinding:+ if saved_query_id is not None:+ return saved_query_binding(saved_query_id)+ if schema_id is None:+ raise ValueError("A person-property payload needs either a schema_id or a saved_query_id")+ return schema_binding(schema_id)++# --- Person-property staging projection ------------------------------------------------# Person-target Customer analytics sources stage a projection of each synced chunk to S3 so a-# post-sync job can upsert warehouse columns onto person properties. The pipeline asks this hook-# which columns to stage for a schema; each enabled person source contributes its key (the person+# Person-target Customer analytics sources stage a projection of each written chunk to S3 so a+# post-run job can upsert warehouse columns onto person properties. The pipeline asks this hook+# which columns to stage for a binding; each enabled person source contributes its key (the person# identifier) plus its mapped property columns. Key columns are tracked separately from mapped# columns so the sink never stages property values with no person identifier to attach them to.# The hook returns None when nothing needs staging. customer_analytics registers the resolver at@@ -122,7 +164,7 @@ class PersonPropertySourceProjection:columns: frozenset[str]-PersonPropertyProjectionResolver = Callable[[int, "str | uuid.UUID"], Optional[list[PersonPropertySourceProjection]]]+PersonPropertyProjectionResolver = Callable[[int, WarehouseBinding], Optional[list[PersonPropertySourceProjection]]]_person_property_projection_resolver: Optional[PersonPropertyProjectionResolver] = None@@ -132,17 +174,17 @@ def register_person_property_projection(fn: PersonPropertyProjectionResolver) ->def person_property_projection_for(- team_id: int, schema_id: "str | uuid.UUID"+ team_id: int, binding: WarehouseBinding) -> Optional[list[PersonPropertySourceProjection]]:if _person_property_projection_resolver is None:return None- return _person_property_projection_resolver(team_id, schema_id)+ return _person_property_projection_resolver(team_id, binding)-def person_property_sync_enabled_for(team_id: int, schema_id: "uuid.UUID") -> bool:- """Gate for starting the person-property sync child workflow: true when the schema feeds at+def person_property_sync_enabled_for(team_id: int, binding: WarehouseBinding) -> bool:+ """Gate for starting the person-property sync child workflow: true when the binding feeds atleast one enabled person-target source (i.e. there are columns to stage/upsert)."""- return person_property_projection_for(team_id, schema_id) is not None+ return person_property_projection_for(team_id, binding) is not None@dataclasses.dataclass(frozen=True)@@ -164,7 +206,7 @@ class PersonPropertySyncSource:group_type_index: int | None = None-PersonPropertySyncSourcesResolver = Callable[[int, "str | uuid.UUID"], Optional[list[PersonPropertySyncSource]]]+PersonPropertySyncSourcesResolver = Callable[[int, WarehouseBinding], Optional[list[PersonPropertySyncSource]]]_person_property_sync_sources_resolver: Optional[PersonPropertySyncSourcesResolver] = None@@ -174,31 +216,43 @@ def register_person_property_sync_sources(fn: PersonPropertySyncSourcesResolver)def person_property_sync_sources_for(- team_id: int, schema_id: "str | uuid.UUID"+ team_id: int, binding: WarehouseBinding) -> Optional[list[PersonPropertySyncSource]]:if _person_property_sync_sources_resolver is None:return None- return _person_property_sync_sources_resolver(team_id, schema_id)+ return _person_property_sync_sources_resolver(team_id, binding)@dataclasses.dataclass(frozen=True)class PersonPropertySyncActivityInputs:- """Payload the import workflow sends to the person-property sync child workflow."""+ """Payload a warehouse run sends to the person-property sync child workflow.++ Exactly one of ``schema_id`` (an import job's schema) and ``saved_query_id`` (a materialized+ view) identifies what was written; read the pair through ``binding``. Both stay positional, and+ ``saved_query_id`` is appended with a default, so a history recorded before views were supported+ still decodes. ``source_type``/``schema_name`` are the run's log labels for either kind.+ """team_id: int- schema_id: uuid.UUID- source_id: uuid.UUID+ schema_id: uuid.UUID | None+ source_id: uuid.UUID | Nonejob_id: strsource_type: strschema_name: strlast_synced_at: str | None+ saved_query_id: uuid.UUID | None = None++ @property+ def binding(self) -> WarehouseBinding:+ return _binding_from_ids(self.schema_id, self.saved_query_id)@propertydef properties_to_log(self) -> dict[str, Any]:return {"team_id": self.team_id,- "schema_id": str(self.schema_id),- "source_id": str(self.source_id),+ "schema_id": str(self.schema_id) if self.schema_id else None,+ "saved_query_id": str(self.saved_query_id) if self.saved_query_id else None,+ "source_id": str(self.source_id) if self.source_id else None,"job_id": self.job_id,"source_type": self.source_type,"schema_name": self.schema_name,@@ -208,26 +262,35 @@ class PersonPropertySyncActivityInputs:# --- Person-property backfill trigger contract ----------------------------------------# A backfill reads a warehouse table's full Delta data from S3 (rather than the incrementally# staged rows) to populate historical rows a new/changed person mapping never saw. It is keyed by-# schema, not source: one backfill workflow reads the table once and upserts every enabled person+# binding, not source: one backfill workflow reads the table once and upserts every enabled person# source on it.@dataclasses.dataclass(frozen=True)class PersonPropertyBackfillActivityInputs:- """Payload for the person-property backfill workflow (see person_property_backfill_job.py)."""+ """Payload for the person-property backfill workflow (see person_property_backfill_job.py).++ Carries the same either/or binding as :class:`PersonPropertySyncActivityInputs`.+ """team_id: int- schema_id: uuid.UUID+ schema_id: uuid.UUID | Nonesource_type: strschema_name: str# "backfill" (auto on create/enable) or "manual" (a user asked to re-run). Recorded on the run.trigger: str+ saved_query_id: uuid.UUID | None = None++ @property+ def binding(self) -> WarehouseBinding:+ return _binding_from_ids(self.schema_id, self.saved_query_id)@propertydef properties_to_log(self) -> dict[str, Any]:return {"team_id": self.team_id,- "schema_id": str(self.schema_id),+ "schema_id": str(self.schema_id) if self.schema_id else None,+ "saved_query_id": str(self.saved_query_id) if self.saved_query_id else None,"source_type": self.source_type,"schema_name": self.schema_name,"trigger": self.trigger,@@ -288,7 +351,10 @@ class PersonPropertySyncRunRecord:without timezone/serialization surprises."""team_id: int- schema_id: str+ # The warehouse object the rows came from, flattened to a kind + id so the record stays a plain+ # serializable payload across the hook boundary.+ binding_kind: str+ binding_id: strsource_id: strjob_id: str | Nonetrigger: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.pyindex 57103ac7956f..b149c952e3c6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.py@@ -1,12 +1,13 @@"""Temporal workflow that backfills person properties from a warehouse table's full Delta data.-Unlike the incremental sync (which reads only the rows a sync staged), this reads the whole table's+Unlike the incremental sync (which reads only the rows a run staged), this reads the whole table'sparquet from S3 so a newly-created or changed person mapping populates historical rows it never saw.-It is keyed by schema, not source: one workflow reads the table once and upserts every enabled person-source on it, so mapping several properties from one table runs a single backfill.+It is keyed by binding, not source: one workflow reads the table once and upserts every enabled person+source on it, so mapping several properties from one table runs a single backfill. The table is either+an imported schema's or a materialized view's — the read is the same either way.Started from the customer_analytics facade (auto on mapping create/enable, or a manual "backfill"-button) with a per-``{team, schema}`` workflow id so concurrent triggers for the same table coalesce.+button) with a per-``{team, binding}`` workflow id so concurrent triggers for the same table coalesce.Runs on the DATA_WAREHOUSE_METADATA_TASK_QUEUE alongside the incremental sync so post-sync processingnever competes with the sync workers. The snapshot diff still skips unchanged values, so a re-run ischeap and idempotent.@@ -58,18 +59,17 @@ async def backfill_warehouse_person_properties_activity(inputs: PersonPropertyBalog.info(f"Starting person-property backfill for {inputs.source_type}/{inputs.schema_name}")start = time.monotonic()started_at = datetime.now(UTC).isoformat()+ binding = inputs.bindingtry:async with Heartbeater():- result = await run_person_property_backfill(- team_id=inputs.team_id, schema_id=str(inputs.schema_id), trigger=inputs.trigger- )+ result = await run_person_property_backfill(team_id=inputs.team_id, binding=binding, trigger=inputs.trigger)except Exception as e:PERSON_PROPERTY_BACKFILL_TOTAL.labels(team_id=str(inputs.team_id), outcome="failed").inc()log.exception("Person-property backfill failed")capture_exception(e)await record_failed_runs(team_id=inputs.team_id,- schema_id=str(inputs.schema_id),+ binding=binding,job_id=None,trigger=inputs.trigger,started_at=started_at,@@ -80,7 +80,7 @@ async def backfill_warehouse_person_properties_activity(inputs: PersonPropertyBaawait record_completed_runs(team_id=inputs.team_id,- schema_id=str(inputs.schema_id),+ binding=binding,job_id=None,trigger=inputs.trigger,started_at=started_at,diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.pyindex 1bd21a0294f6..b4e4485ff943 100644--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.py@@ -63,23 +63,22 @@ PERSON_PROPERTY_SYNC_DURATION_SECONDS = Histogram(@activity.defnasync def sync_warehouse_person_properties_activity(inputs: PersonPropertySyncActivityInputs) -> dict[str, Any]:- """Read the rows a sync staged and upsert them onto person properties via Kafka."""+ """Read the rows a warehouse run staged and upsert them onto person properties via Kafka."""log = logger.bind(**inputs.properties_to_log)log.info(f"Starting person-property sync for {inputs.source_type}/{inputs.schema_name}")start = time.monotonic()started_at = datetime.now(UTC).isoformat()+ binding = inputs.bindingawait record_started_runs(team_id=inputs.team_id,- schema_id=str(inputs.schema_id),+ binding=binding,job_id=inputs.job_id,trigger="scheduled",started_at=started_at,)try:async with Heartbeater():- result = await run_person_property_sync(- team_id=inputs.team_id, schema_id=str(inputs.schema_id), job_id=inputs.job_id- )+ result = await run_person_property_sync(team_id=inputs.team_id, binding=binding, job_id=inputs.job_id)except Exception as e:# Re-raised so Temporal retries; captured so a terminal failure is visible in error# tracking rather than dying silently in an abandoned child workflow.@@ -88,7 +87,7 @@ async def sync_warehouse_person_properties_activity(inputs: PersonPropertySyncAccapture_exception(e)await record_failed_runs(team_id=inputs.team_id,- schema_id=str(inputs.schema_id),+ binding=binding,job_id=inputs.job_id,trigger="scheduled",started_at=started_at,@@ -99,7 +98,7 @@ async def sync_warehouse_person_properties_activity(inputs: PersonPropertySyncAcawait record_completed_runs(team_id=inputs.team_id,- schema_id=str(inputs.schema_id),+ binding=binding,job_id=inputs.job_id,trigger="scheduled",started_at=started_at,diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.pyindex d9eaf1c3bbf3..5e77435b0344 100644--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.py+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.py@@ -1,10 +1,16 @@"""Temporal trigger seams for the person-property feature, exposed through the warehouse_sources-facade so customer_analytics (which can't import data_warehouse) can start these from a DRF request.+facade so customer_analytics (which can't import data_warehouse or data_modeling) can start these+from a DRF request.-Both open a Temporal client, so this module must stay off the ``django.setup()`` path — it's reached-only from the facade on a request, never from an AppConfig or model.+A "sync now" means a fresh warehouse run of whatever the source binds to: an import for a schema, a+materialization for a view. Both produce staged rows the person-property child then consumes.++Every entry point opens a Temporal client, so this module must stay off the ``django.setup()`` path —+it's reached only from the facade on a request, never from an AppConfig or model."""+from uuid import UUID+from django.conf import settingsimport structlog@@ -19,7 +25,9 @@ from posthog.temporal.common.schedule import trigger_schedulefrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (+ MATERIALIZED_VIEW_SOURCE_TYPE,PersonPropertyBackfillActivityInputs,+ WarehouseBinding,)logger = structlog.get_logger(__name__)@@ -30,12 +38,27 @@ BACKFILL_WORKFLOW_NAME = "backfill-warehouse-person-properties"# the team's syncing is paused (monthly limit reached); reused so person-property "sync now" matches.SYNC_PAUSED_MESSAGE = "Monthly sync limit reached. Please increase your billing limit to resume syncing."+VIEW_MISSING_MESSAGE = "This view no longer exists."+VIEW_NOT_ON_V2_MESSAGE = (+ "This view still runs on the older data modeling schedule, which can't update warehouse properties. "+ "Use Backfill to update them from the last materialization."+)+class ExternalDataSchemaSyncPausedError(Exception):"""Raised by ``trigger_schema_sync`` when the team's warehouse syncing is paused, so a manualperson-property sync can't be used to run billable imports past the monthly limit."""+class SavedQueryNotFoundError(Exception):+ """Raised by ``trigger_saved_query_materialization`` when the view no longer resolves."""+++class SavedQueryNotOnV2ScheduleError(Exception):+ """Raised by ``trigger_saved_query_materialization`` when the view is still on the older+ per-query data-modeling schedule, whose workflow never stages person-property rows."""++def trigger_schema_sync(*, team_id: int, schema_id: str) -> None:"""Trigger the underlying warehouse schema's Temporal schedule — a real, billable sync. The normalincremental person-property child runs off it, so this doubles as person-property "sync now".@@ -60,30 +83,89 @@ def trigger_schema_sync(*, team_id: int, schema_id: str) -> None:log.info("Triggered warehouse schema sync for person-property sync-now")-def start_person_property_backfill(*, team_id: int, schema_id: str, trigger: str) -> bool:- """Start the per-table backfill workflow. One workflow per ``{team, schema}`` (id-keyed), so+def start_person_property_backfill(*, team_id: int, binding: WarehouseBinding, trigger: str) -> bool:+ """Start the per-table backfill workflow. One workflow per ``{team, binding}`` (id-keyed), soconcurrent triggers for the same table coalesce: returns False (does not raise) when one is- already running. Also returns False when the schema no longer exists."""- log = logger.bind(team_id=team_id, schema_id=str(schema_id), trigger=trigger)+ already running. Also returns False when the warehouse object no longer exists."""+ log = logger.bind(team_id=team_id, binding_kind=binding.kind, binding_id=binding.id, trigger=trigger)+ inputs = _backfill_inputs(team_id, binding, trigger)+ if inputs is None:+ log.warning("person-property backfill not started: warehouse table no longer exists")+ return False+ workflow_id = f"{BACKFILL_WORKFLOW_NAME}-{team_id}-{binding.id}"+ return _start_backfill_workflow(inputs, workflow_id)+++def _backfill_inputs(+ team_id: int, binding: WarehouseBinding, trigger: str+) -> PersonPropertyBackfillActivityInputs | None:+ """The workflow payload for a binding, or None when it no longer resolves.++ ``source_type``/``schema_name`` are the activity's log labels, so a view fills them with the kind+ and its own name rather than an import source's.+ """+ if binding.is_saved_query:+ # Resolved lazily: the data_modeling facade is PEP 562 lazy-loaded over HogQL/temporal-heavy+ # modules, so a module-top import would pull that chain onto this module's import path.+ from products.data_modeling.backend.facade.api import get_saved_query_summary # noqa: PLC0415++ summary = get_saved_query_summary(team_id, binding.id)+ if summary is None:+ return None+ return PersonPropertyBackfillActivityInputs(+ team_id=team_id,+ schema_id=None,+ source_type=MATERIALIZED_VIEW_SOURCE_TYPE,+ schema_name=summary.name,+ trigger=trigger,+ saved_query_id=UUID(binding.id),+ )+# exclude(deleted=True): a soft-deleted schema (its source removed) must not kick off a backfill.schema = (ExternalDataSchema.objects.exclude(deleted=True)- .filter(id=schema_id, team_id=team_id)+ .filter(id=binding.id, team_id=team_id).select_related("source").first())if schema is None:- log.warning("person-property backfill not started: schema no longer exists")- return False- inputs = PersonPropertyBackfillActivityInputs(+ return None+ return PersonPropertyBackfillActivityInputs(team_id=team_id,schema_id=schema.id,source_type=schema.source.source_type,schema_name=schema.name,trigger=trigger,)- workflow_id = f"{BACKFILL_WORKFLOW_NAME}-{team_id}-{schema_id}"- return _start_backfill_workflow(inputs, workflow_id)+++def trigger_saved_query_materialization(*, team_id: int, saved_query_id: str) -> None:+ """Trigger a materialization of the view — person-property "sync now" for a view-backed source.++ The materialization stages its rows and forks the person-property sync child, mirroring how a+ schema's sync does. Only the v2 data-modeling workflow stages rows, so a view still on the older+ per-query schedule raises ``SavedQueryNotOnV2ScheduleError`` rather than starting a run whose rows+ would never reach person properties.+ """+ # Lazy for the same reason as _backfill_inputs above.+ from products.data_modeling.backend.facade import api as data_modeling # noqa: PLC0415++ log = logger.bind(team_id=team_id, saved_query_id=str(saved_query_id))+ try:+ data_modeling.run_saved_query_materialization(team_id, saved_query_id)+ except data_modeling.SavedQueryNotFoundError as e:+ log.warning("person-property sync-now rejected: view no longer exists")+ raise SavedQueryNotFoundError(VIEW_MISSING_MESSAGE) from e+ except data_modeling.SavedQueryNotOnV2ScheduleError as e:+ log.info("person-property sync-now rejected: view is not on the v2 data modeling schedule")+ raise SavedQueryNotOnV2ScheduleError(VIEW_NOT_ON_V2_MESSAGE) from e+ except Exception as e:+ # Surfaces to the caller as a 500, but capture with context so a failing "sync now" is+ # diagnosable rather than an opaque Temporal client error in the request log.+ log.exception("Failed to materialize view for person-property sync-now")+ capture_exception(e, {"team_id": team_id, "saved_query_id": str(saved_query_id)})+ raise+ log.info("Triggered view materialization for person-property sync-now")@async_to_sync@@ -104,7 +186,7 @@ async def _start_backfill_workflow(inputs: PersonPropertyBackfillActivityInputs,return Trueexcept WorkflowAlreadyStartedError:# Expected: a backfill for this table is already in flight, so this trigger coalesces into it.- log.info("person-property backfill already running for schema, coalescing")+ log.info("person-property backfill already running for binding, coalescing")return Falseexcept Exception as e:# A real failure to reach Temporal — capture it; the caller (facade) treats a raise asdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_paths.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_paths.pynew file mode 100644index 000000000000..5ac49c700690--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_paths.py@@ -0,0 +1,40 @@+"""S3 layout for the person-property staging and dedup-snapshot folders.++Both the sink that stages rows during a warehouse run and the sync that consumes them derive their+prefixes from here, so the two can never drift apart. Kept in its own module so the sink — which both+the data-import and the data-modeling write path build — doesn't pull in the sync's heavier imports.+"""++from django.conf import settings++from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import WarehouseBinding+++def binding_path_segment(binding: WarehouseBinding) -> str:+ """The folder segment identifying one binding's staged rows and snapshot.++ A schema keeps the bare id it has always used, so folders written before materialized views were+ supported still resolve. A view gets a prefixed segment, which also keeps the two id spaces from+ colliding.+ """+ if binding.is_saved_query:+ return f"model_{binding.id}"+ return binding.id+++def binding_staged_prefix(team_id: int, binding: WarehouseBinding) -> str:+ """Every staged job folder for one binding — the parent the sink sweeps abandoned siblings from."""+ return f"{settings.DATAWAREHOUSE_BUCKET}/person_property_sync/{team_id}/{binding_path_segment(binding)}"+++def job_staged_prefix(team_id: int, binding: WarehouseBinding, job_id: str) -> str:+ """Where one run's staged row projections live."""+ return f"{binding_staged_prefix(team_id, binding)}/{job_id}"+++def snapshot_prefix(team_id: int, binding: WarehouseBinding, source_id: str) -> str:+ """Where one source's last-sent bundle hashes live, per binding."""+ return (+ f"{settings.DATAWAREHOUSE_BUCKET}/person_property_snapshot/"+ f"{team_id}/{source_id}/{binding_path_segment(binding)}"+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_paths_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_paths_test.pynew file mode 100644index 000000000000..e2fe2f5bb8cf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_paths_test.py@@ -0,0 +1,39 @@+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (+ saved_query_binding,+ schema_binding,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import person_property_paths as paths++_ID = "0198f2b1-0000-7000-8000-000000000001"+++class TestBindingPathSegment:+ def test_schema_segment_is_the_bare_id(self):+ # Live staged folders and dedup snapshots were written under the bare schema id. Prefixing it+ # would orphan every one of them, and each source would re-send its whole table on the next run.+ assert paths.binding_path_segment(schema_binding(_ID)) == _ID++ def test_saved_query_segment_is_prefixed(self):+ assert paths.binding_path_segment(saved_query_binding(_ID)) == f"model_{_ID}"++ def test_kinds_sharing_an_id_do_not_collide(self):+ schema, view = schema_binding(_ID), saved_query_binding(_ID)+ assert paths.binding_staged_prefix(1, schema) != paths.binding_staged_prefix(1, view)+ assert paths.snapshot_prefix(1, schema, "src") != paths.snapshot_prefix(1, view, "src")++ @parameterized.expand(+ [+ ("staged", lambda binding: paths.job_staged_prefix(1, binding, "job-1")),+ ("snapshot", lambda binding: paths.snapshot_prefix(1, binding, "src")),+ ]+ )+ def test_job_and_snapshot_prefixes_carry_the_segment(self, _name, build):+ assert paths.binding_path_segment(saved_query_binding(_ID)) in build(saved_query_binding(_ID))++ def test_job_prefix_nests_under_the_binding_prefix(self):+ # The sink sweeps abandoned sibling jobs by listing the binding prefix, so a job folder has to+ # sit directly under it.+ binding = saved_query_binding(_ID)+ assert paths.job_staged_prefix(1, binding, "job-1") == f"{paths.binding_staged_prefix(1, binding)}/job-1"diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.pyindex f415fbceb46d..7f072e492ae9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py@@ -15,8 +15,13 @@ from posthog.sync import database_sync_to_async_poolfrom products.data_warehouse.backend.facade.api import aget_s3_client, ensure_bucket_existsfrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (PersonPropertySourceProjection,+ WarehouseBinding,person_property_projection_for,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_paths import (+ binding_staged_prefix,+ job_staged_prefix,+)# A sibling job prefix whose newest file is older than this is considered abandoned (its consumer# never ran, or gave up retrying) and is swept. Anything younger may belong to a consumer that is@@ -26,15 +31,18 @@ ABANDONED_STAGED_PREFIX_TTL = timedelta(days=7)class PersonPropertyRowSink:- """Stages a projection of each synced chunk to S3 for the person-property upsert job.+ """Stages a projection of each written chunk to S3 for the person-property upsert job.Mirrors ``CDPProducer``: gated on a hook so a table with no person-target source stagesnothing, and only the columns the sources actually need (key + mapped columns) leave thepipeline. A source is staged only when its key (person identifier) column is present in the- synced chunk, so a staged file always carries an identifier to attach its properties to. A- post-sync job (later PR) reads these files and upserts person properties, then clears them.+ chunk, so a staged file always carries an identifier to attach its properties to. A post-run+ job reads these files and upserts person properties, then clears them.++ Both warehouse write paths build one: a data-import job (per synced chunk) and a data-modeling+ materialization (per written batch). The binding is what distinguishes their staged folders.- Multiple job prefixes can coexist under a schema while the consumer lags, so the consumer+ Multiple job prefixes can coexist under a binding while the consumer lags, so the consumermust apply prefixes in job order (or last-write-wins per person key) — a lagged older jobapplied after a newer one would regress properties to stale values. Within one job, stagedfiles from a retried attempt sort after the failed attempt's (attempt-timestamped names), so@@ -42,10 +50,16 @@ class PersonPropertyRowSink:"""def __init__(- self, team_id: int, schema_id: str, job_id: str, logger: FilteringBoundLogger, *, is_incremental: bool+ self,+ team_id: int,+ binding: WarehouseBinding,+ job_id: str,+ logger: FilteringBoundLogger,+ *,+ is_incremental: bool,) -> None:self.team_id = team_id- self.schema_id = schema_id+ self.binding = bindingself.job_id = job_idself.logger = loggerself._is_incremental = is_incremental@@ -83,18 +97,18 @@ class PersonPropertyRowSink:return self._fs_cache- def _get_schema_prefix(self) -> str:- return f"{settings.DATAWAREHOUSE_BUCKET}/person_property_sync/{self.team_id}/{self.schema_id}"+ def _get_binding_prefix(self) -> str:+ return binding_staged_prefix(self.team_id, self.binding)def _get_path_prefix(self) -> str:- return f"{self._get_schema_prefix()}/{self.job_id}"+ return job_staged_prefix(self.team_id, self.binding, self.job_id)async def _get_projection(self) -> list[PersonPropertySourceProjection] | None:- """One projection per enabled person source on the schema (key + mapped columns), or None+ """One projection per enabled person source on the binding (key + mapped columns), or Nonewhen nothing needs staging. Resolved once per run."""if not self._projection_resolved:self._projection = await database_sync_to_async_pool(person_property_projection_for)(- self.team_id, self.schema_id+ self.team_id, self.binding)self._projection_resolved = Truereturn self._projection@@ -156,18 +170,18 @@ class PersonPropertyRowSink:async def _sweep_abandoned_sibling_prefixes(self, s3_client: Any) -> None:try:- entries = await s3_client._find(f"s3://{self._get_schema_prefix()}/", detail=True)+ entries = await s3_client._find(f"s3://{self._get_binding_prefix()}/", detail=True)except FileNotFoundError:returnif not isinstance(entries, dict) or not entries:return- schema_prefix = self._get_schema_prefix().lstrip("/")+ binding_prefix = self._get_binding_prefix().lstrip("/")files_by_job: dict[str, list[str]] = {}newest_by_job: dict[str, datetime] = {}for path, info in entries.items():key = path.lstrip("/")- relative = key[len(schema_prefix) :].lstrip("/")+ relative = key[len(binding_prefix) :].lstrip("/")job_segment = relative.split("/", 1)[0]if not job_segment or job_segment == str(self.job_id):continue@@ -189,6 +203,6 @@ class PersonPropertyRowSink:if not stale_files:returnawait self.logger.adebug(- f"Sweeping {len(stale_files)} abandoned person-property staged files under {schema_prefix}"+ f"Sweeping {len(stale_files)} abandoned person-property staged files under {binding_prefix}")await s3_client._rm([f"s3://{key}" for key in stale_files])diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.pyindex d001daeb5fd0..b10a475953c9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py@@ -10,6 +10,9 @@ from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (PersonPropertySourceProjection,+ WarehouseBinding,+ saved_query_binding,+ schema_binding,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink import (ABANDONED_STAGED_PREFIX_TTL,@@ -19,11 +22,15 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.per_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink"-def _sink(is_incremental: bool = False) -> PersonPropertyRowSink:+def _sink(is_incremental: bool = False, binding: WarehouseBinding | None = None) -> PersonPropertyRowSink:logger = MagicMock()logger.adebug = AsyncMock()return PersonPropertyRowSink(- team_id=1, schema_id="schema-1", job_id="job-1", logger=logger, is_incremental=is_incremental+ team_id=1,+ binding=binding or schema_binding("schema-1"),+ job_id="job-1",+ logger=logger,+ is_incremental=is_incremental,)@@ -123,9 +130,9 @@ async def test_clear_keeps_fresh_sibling_prefixes_and_sweeps_abandoned_ones():# A fresh sibling prefix belongs to a consumer that is merely lagging — deleting it loses an# incremental sync's staged delta for good. Only long-abandoned prefixes may be swept.sink = _sink()- schema_prefix = sink._get_schema_prefix()- fresh_file = f"{schema_prefix}/job-recent/chunk_0.parquet"- stale_file = f"{schema_prefix}/job-old/chunk_0.parquet"+ binding_prefix = sink._get_binding_prefix()+ fresh_file = f"{binding_prefix}/job-recent/chunk_0.parquet"+ stale_file = f"{binding_prefix}/job-old/chunk_0.parquet"now = datetime.now(UTC)s3_client = _s3_client(find_result={@@ -148,7 +155,7 @@ async def test_clear_keeps_own_prefix_on_incremental_syncs():# An incremental retry resumes past the committed cursor, so the failed attempt's staged# files are the only record of those rows — clearing the job prefix would lose them for good.sink = _sink(is_incremental=True)- stale_file = f"{sink._get_schema_prefix()}/job-old/chunk_0.parquet"+ stale_file = f"{sink._get_binding_prefix()}/job-old/chunk_0.parquet"s3_client = _s3_client(find_result={stale_file: {"LastModified": datetime.now(UTC) - ABANDONED_STAGED_PREFIX_TTL - timedelta(days=1)}})@@ -210,3 +217,21 @@ async def test_clear_tolerates_missing_prefixes():with patch(f"{_MODULE}.aget_s3_client", return_value=_FakeS3ClientCM(s3_client)):await sink.clear()++[email protected]([("schema", schema_binding("schema-1")), ("saved_query", saved_query_binding("view-1"))])+async def test_stages_under_the_binding_it_was_built_for(_name, binding):+ # A view materialization and an import job build the same sink; the binding is what keeps their+ # staged rows apart, so a source only ever consumes rows from the object it reads.+ sink = _sink(binding=binding)+ with (+ patch(f"{_MODULE}.person_property_projection_for", return_value=[_projection("distinct_id", "plan")]) as gate,+ patch.object(sink, "_get_fs", return_value=MagicMock()),+ patch(f"{_MODULE}.asyncio.to_thread", new=AsyncMock()) as to_thread,+ ):+ await sink.stage_chunk(chunk=0, table=_table())++ gate.assert_called_once_with(1, binding)+ assert to_thread.await_args is not None+ assert to_thread.await_args.args[2].startswith(f"{sink._get_path_prefix()}/")diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.pyindex 0dd52b9cf830..d5319bdb3443 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py@@ -1,7 +1,7 @@-"""Upsert warehouse columns onto person properties from the rows a sync staged to S3.+"""Upsert warehouse columns onto person properties from the rows a warehouse run staged to S3.-Runs in a post-sync Temporal activity (see data_imports/person_property_sync_job.py). Per enabled-person-target source for the schema it:+Runs in a post-run Temporal activity (see data_imports/person_property_sync_job.py). Per enabled+person-target source for the binding it:1. reads the staged parquet (already just this run's changed rows),2. builds each row's {property: value} bundle keyed by distinct_id,@@ -12,6 +12,10 @@ person-target source for the schema it:6. updates the snapshot, stamps provenance on the person PropertyDefinitions, and clears the stagedfiles.+A source binds to either an imported schema or a materialized view (see ``WarehouseBinding``). Both+write a Delta table on S3 and stage the same row projections, so everything from step 2 on is shared;+only the staged/snapshot prefix and the full-table Delta location differ per kind.+The source configs (key column + column -> property map) are resolved through the``person_property_sync_sources_for`` hook so this module never imports the customer_analyticsconfig models. The pure functions (bundle building, hashing, diff) are unit-tested directly; the@@ -45,11 +49,16 @@ from products.warehouse_sources.backend.models.external_data_schema import Exterfrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (PersonPropertySyncRunRecord,PersonPropertySyncSource,+ WarehouseBinding,person_property_sync_sources_for,record_person_property_sync_run,)from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import delta_storage_options+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_paths import (+ job_staged_prefix,+ snapshot_prefix,+)logger = structlog.get_logger(__name__)@@ -59,6 +68,12 @@ EVENT_SOURCE = "customer_analytics_person_property_sync"# customer_analytics config models, matching the isolation the hooks already preserve)._GROUP_TARGET = "group"++def _log_fields(binding: WarehouseBinding) -> dict[str, str]:+ """Structlog fields naming the warehouse object a run read from."""+ return {"binding_kind": binding.kind, "binding_id": binding.id}++# Identifiers per existence-lookup call. Both personhog helpers return whole Person/Group models,# properties included, and accumulate every model before returning. This activity only needs the# identifier back, so chunking here caps peak memory at one chunk's models instead of the entire@@ -165,27 +180,23 @@ def select_changed(# --- S3 / Kafka / personhog boundaries (mocked in tests) ----------------------------------def _staged_prefix(team_id: int, schema_id: str, job_id: str) -> str:- return f"{settings.DATAWAREHOUSE_BUCKET}/person_property_sync/{team_id}/{schema_id}/{job_id}"---def _snapshot_prefix(team_id: int, schema_id: str, source_id: str) -> str:+def _snapshot_prefix(team_id: int, binding: WarehouseBinding, source_id: str) -> str:# A folder, not a single file: each run drops a uniquely-named parquet of the hashes it produced,# and the reader unions every file in the folder. Two writers (a scheduled sync and a backfill)# for the same source can't clobber each other, since they write different filenames. Growth is# bounded by _write_snapshot_hashes, which compacts the folder back down as it writes.- return f"{settings.DATAWAREHOUSE_BUCKET}/person_property_snapshot/{team_id}/{source_id}/{schema_id}"+ return snapshot_prefix(team_id, binding, source_id)-async def _read_staged_rows(team_id: int, schema_id: str, job_id: str) -> list[dict]:- prefix = _staged_prefix(team_id, schema_id, job_id)+async def _read_staged_rows(team_id: int, binding: WarehouseBinding, job_id: str) -> list[dict]:+ prefix = job_staged_prefix(team_id, binding, job_id)rows: list[dict] = []async with aget_s3_client() as s3_client:try:listing = await s3_client._ls(f"s3://{prefix}/", detail=True)except FileNotFoundError:- # No staged folder — the sync staged nothing for this run (common on a no-change sync).- logger.debug("person-property sync: no staged rows folder", team_id=team_id, schema_id=schema_id)+ # No staged folder — the run staged nothing (common on a no-change incremental run).+ logger.debug("person-property sync: no staged rows folder", team_id=team_id, **_log_fields(binding))return []values = listing.values() if isinstance(listing, dict) else listingfiles = [f["Key"] for f in values if f.get("type") != "directory"]@@ -248,17 +259,17 @@ async def _merge_snapshot_files(s3_client, file_keys: list[str]) -> dict[str, streturn hashes-async def _read_snapshot_hashes(team_id: int, schema_id: str, source_id: str) -> dict[str, str]:+async def _read_snapshot_hashes(team_id: int, binding: WarehouseBinding, source_id: str) -> dict[str, str]:"""Union every parquet file in the source's snapshot folder into {distinct_id: sent_hash}, readingoldest file first so a newer run's hash wins for a repeated distinct_id (a stale hash would onlycost an idempotent re-send, but newest-wins avoids even that). Ordering never affects correctness."""- prefix = _snapshot_prefix(team_id, schema_id, source_id)+ prefix = _snapshot_prefix(team_id, binding, source_id)async with aget_s3_client() as s3_client:return await _merge_snapshot_files(s3_client, await _list_snapshot_files(s3_client, prefix))async def _write_snapshot_hashes(- team_id: int, schema_id: str, source_id: str, run_token: str, hashes: dict[str, str]+ team_id: int, binding: WarehouseBinding, source_id: str, run_token: str, hashes: dict[str, str]) -> None:"""Persist this run's produced ``hashes`` and compact the source's snapshot folder in one pass.Writes the union of every existing snapshot file and ``hashes`` into ``{run_token}.parquet`` (this@@ -272,7 +283,7 @@ async def _write_snapshot_hashes(between the two harmless — the reader unions both the new file and the not-yet-deleted old ones."""import pyarrow as pa # noqa: PLC0415- prefix = _snapshot_prefix(team_id, schema_id, source_id)+ prefix = _snapshot_prefix(team_id, binding, source_id)write_path = f"{prefix}/{run_token}.parquet"async with aget_s3_client() as s3_client:existing_keys = await _list_snapshot_files(s3_client, prefix)@@ -293,8 +304,8 @@ async def _write_snapshot_hashes(pass-async def _clear_staged(team_id: int, schema_id: str, job_id: str) -> None:- prefix = _staged_prefix(team_id, schema_id, job_id)+async def _clear_staged(team_id: int, binding: WarehouseBinding, job_id: str) -> None:+ prefix = job_staged_prefix(team_id, binding, job_id)async with aget_s3_client() as s3_client:try:await s3_client._rm(f"s3://{prefix}/", recursive=True)@@ -392,16 +403,21 @@ def _produce_intents(def _stamp_provenance(- team_id: int, schema_id: str, source: PersonPropertySyncSource, property_names: list[str]+ team_id: int, binding: WarehouseBinding, source: PersonPropertySyncSource, property_names: list[str]) -> None:# UPDATE-only on purpose: definitions are created by ingestion's propdef upsert when the $set /# $groupidentify lands, so a brand-new property may not have a row yet on the first sync — the next# sync's stamp catches it. Never inserting means this can't race that upsert.- origin = {+ origin: dict[str, str] = {"source_id": str(source.definition_id),- "schema_id": str(schema_id),"custom_property_source_id": str(source.source_id),+ "binding_kind": binding.kind,+ "binding_id": binding.id,}+ # Kept for schema bindings: rows stamped before views were supported carry this key, so dropping+ # it would leave two stamps of the same schema describing it differently.+ if not binding.is_saved_query:+ origin["schema_id"] = binding.idquery = PropertyDefinition.objects.filter(team_id=team_id)if source.target == _GROUP_TARGET:# Group propdefs are keyed per group type, so the index predicate is mandatory.@@ -426,7 +442,7 @@ def _stamp_provenance(async def _process_source_bundles(*,team_id: int,- schema_id: str,+ binding: WarehouseBinding,team_api_token: str,team_uuid: str,source: PersonPropertySyncSource,@@ -439,7 +455,7 @@ async def _process_source_bundles(Shared by the incremental sync and the backfill — they differ only in how ``bundles`` are sourced(staged rows vs a full Delta read)."""ps = PerSourceResult(source_id=str(source.source_id), rows_read=rows_read)- prior = await _read_snapshot_hashes(team_id, schema_id, str(source.source_id))+ prior = await _read_snapshot_hashes(team_id, binding, str(source.source_id))changed, new_hashes = select_changed(bundles, prior)ps.changed = len(changed)if not changed:@@ -455,7 +471,7 @@ async def _process_source_bundles(logger.info("person-property sync: no existing entities among changed rows for source",team_id=team_id,- schema_id=schema_id,+ **_log_fields(binding),source_id=str(source.source_id),target=source.target,changed=len(changed),@@ -473,7 +489,7 @@ async def _process_source_bundles(logger.warning("person-property sync: group type not found, skipping source",team_id=team_id,- schema_id=schema_id,+ **_log_fields(binding),source_id=str(source.source_id),group_type_index=source.group_type_index,)@@ -487,18 +503,18 @@ async def _process_source_bundles(# these rows look unchanged on the next run, so anything that must accompany a produce has to# happen first. Stamping is an idempotent update, safe to repeat if a retry re-produces.await database_sync_to_async(_stamp_provenance, thread_sensitive=False)(- team_id, schema_id, source, list((source.column_property_map or {}).values())+ team_id, binding, source, list((source.column_property_map or {}).values()))# Record only the distinct_ids we actually produced, as this run's snapshot file.sent_ids = {distinct_id for distinct_id, _ in to_send}produced_hashes = {d: h for d, h in new_hashes.items() if d in sent_ids}- await _write_snapshot_hashes(team_id, schema_id, str(source.source_id), run_token, produced_hashes)+ await _write_snapshot_hashes(team_id, binding, str(source.source_id), run_token, produced_hashes)logger.info("person-property sync: source processed",team_id=team_id,- schema_id=schema_id,+ **_log_fields(binding),source_id=str(source.source_id),bundles=len(bundles),changed=len(changed),@@ -516,26 +532,26 @@ def _accumulate(result: SyncResult, ps: PerSourceResult) -> None:result.skipped_missing_person += ps.skipped_missing_person-async def run_person_property_sync(*, team_id: int, schema_id: str, job_id: str) -> SyncResult:+async def run_person_property_sync(*, team_id: int, binding: WarehouseBinding, job_id: str) -> SyncResult:result = SyncResult()- sources = await database_sync_to_async(person_property_sync_sources_for, thread_sensitive=False)(team_id, schema_id)+ sources = await database_sync_to_async(person_property_sync_sources_for, thread_sensitive=False)(team_id, binding)if not sources:logger.info(- "person-property sync: no enabled person sources for schema, nothing to do",+ "person-property sync: no enabled person sources for binding, nothing to do",team_id=team_id,- schema_id=str(schema_id),+ **_log_fields(binding),job_id=job_id,)return resultteam = await database_sync_to_async(Team.objects.get, thread_sensitive=False)(id=team_id)- rows = await _read_staged_rows(team_id, str(schema_id), job_id)+ rows = await _read_staged_rows(team_id, binding, job_id)result.sources = len(sources)result.rows_read = len(rows)logger.info("person-property sync: read staged rows",team_id=team_id,- schema_id=str(schema_id),+ **_log_fields(binding),job_id=job_id,sources=len(sources),rows_read=len(rows),@@ -545,7 +561,7 @@ async def run_person_property_sync(*, team_id: int, schema_id: str, job_id: str)bundles = build_bundles(rows, source.key_column, source.column_property_map or {})ps = await _process_source_bundles(team_id=team_id,- schema_id=str(schema_id),+ binding=binding,team_api_token=team.api_token,team_uuid=str(team.uuid),source=source,@@ -555,7 +571,7 @@ async def run_person_property_sync(*, team_id: int, schema_id: str, job_id: str))_accumulate(result, ps)- await _clear_staged(team_id, str(schema_id), job_id)+ await _clear_staged(team_id, binding, job_id)return result@@ -617,46 +633,66 @@ def _read_delta_bundles(return accumulated, rows_read-async def run_person_property_backfill(*, team_id: int, schema_id: str, trigger: str) -> SyncResult:+def _schema_delta_uri(team_id: int, schema_id: str) -> str | None:+ """The Delta table an imported schema's rows live in, or None when the schema is gone."""+ schema = _get_schema(team_id, schema_id)+ if schema is None:+ return None+ # Resolve the Delta folder leaf the same way the loader wrote it: `resolved_s3_folder_name`+ # (or the schema name) normalized, never `normalized_name`. For schema-qualified/migration-pinned+ # sources (e.g. Postgres `public.users` → folder `users`) these diverge, and `normalized_name`+ # would point at a prefix with no Delta log — a silent 0-row no-op.+ folder_leaf = NamingConvention.normalize_identifier(schema.resolved_s3_folder_name or schema.name)+ return f"{settings.BUCKET_URL}/{schema.folder_path()}/{folder_leaf}"+++def _delta_uri_for_binding(team_id: int, binding: WarehouseBinding) -> str | None:+ """The Delta table a binding's full row set lives in, or None when there is nothing to read."""+ if binding.is_saved_query:+ # Resolved lazily: the data_modeling facade is PEP 562 lazy-loaded over HogQL/temporal-heavy+ # modules, so a module-top import would pull that chain onto this module's import path.+ from products.data_modeling.backend.facade.api import get_materialized_table_uri # noqa: PLC0415++ return get_materialized_table_uri(team_id, binding.id)+ return _schema_delta_uri(team_id, binding.id)+++async def run_person_property_backfill(*, team_id: int, binding: WarehouseBinding, trigger: str) -> SyncResult:"""Populate person properties from a warehouse table's full Delta data (rather than theincrementally staged rows) — for a new/changed mapping that never saw historical rows. Reads the- table once and upserts every enabled person source on the schema; the snapshot diff still skips+ table once and upserts every enabled person source on the binding; the snapshot diff still skipsunchanged values, so re-running is cheap."""result = SyncResult()- sources = await database_sync_to_async(person_property_sync_sources_for, thread_sensitive=False)(team_id, schema_id)+ sources = await database_sync_to_async(person_property_sync_sources_for, thread_sensitive=False)(team_id, binding)if not sources:logger.info(- "person-property backfill: no enabled person sources for schema, nothing to do",+ "person-property backfill: no enabled person sources for binding, nothing to do",team_id=team_id,- schema_id=str(schema_id),+ **_log_fields(binding),trigger=trigger,)return result- schema = await database_sync_to_async(_get_schema, thread_sensitive=False)(team_id, schema_id)- if schema is None:+ uri = await database_sync_to_async(_delta_uri_for_binding, thread_sensitive=False)(team_id, binding)+ if uri is None:+ # The schema or view was deleted, or the view was never materialized — either way there is no+ # Delta table to read, so there is nothing to backfill from.logger.warning(- "person-property backfill: schema no longer exists, nothing to do",+ "person-property backfill: no warehouse table to read, nothing to do",team_id=team_id,- schema_id=str(schema_id),+ **_log_fields(binding),trigger=trigger,)return resultteam = await database_sync_to_async(Team.objects.get, thread_sensitive=False)(id=team_id)- # Resolve the Delta folder leaf the same way the loader wrote it: `resolved_s3_folder_name`- # (or the schema name) normalized, never `normalized_name`. For schema-qualified/migration-pinned- # sources (e.g. Postgres `public.users` → folder `users`) these diverge, and `normalized_name`- # would point at a prefix with no Delta log — a silent 0-row no-op.- folder_leaf = NamingConvention.normalize_identifier(schema.resolved_s3_folder_name or schema.name)- uri = f"{settings.BUCKET_URL}/{schema.folder_path()}/{folder_leaf}"accumulated, rows_read = await asyncio.to_thread(_read_delta_bundles, uri, delta_storage_options(), sources)result.sources = len(sources)result.rows_read = rows_readlogger.info("person-property backfill: read full Delta table",team_id=team_id,- schema_id=str(schema_id),+ **_log_fields(binding),trigger=trigger,sources=len(sources),rows_read=rows_read,@@ -666,7 +702,7 @@ async def run_person_property_backfill(*, team_id: int, schema_id: str, trigger:bundles = list(accumulated[str(source.source_id)].items())ps = await _process_source_bundles(team_id=team_id,- schema_id=str(schema_id),+ binding=binding,team_api_token=team.api_token,team_uuid=str(team.uuid),source=source,@@ -685,7 +721,7 @@ async def run_person_property_backfill(*, team_id: int, schema_id: str, trigger:def _record(*,team_id: int,- schema_id: str,+ binding: WarehouseBinding,job_id: str | None,trigger: str,status: str,@@ -697,7 +733,8 @@ def _record(record_person_property_sync_run(PersonPropertySyncRunRecord(team_id=team_id,- schema_id=schema_id,+ binding_kind=binding.kind,+ binding_id=binding.id,source_id=ps.source_id,job_id=job_id,trigger=trigger,@@ -715,19 +752,19 @@ def _record(async def record_started_runs(- *, team_id: int, schema_id: str, job_id: str | None, trigger: str, started_at: str+ *, team_id: int, binding: WarehouseBinding, job_id: str | None, trigger: str, started_at: str) -> None:- """Open a 'running' run row per source the schema feeds, so a sync in flight shows up in the UI+ """Open a 'running' run row per source the binding feeds, so a sync in flight shows up in the UIinstead of appearing only once it finishes. The terminal record reconciles the same row (seerecord_sync_run). Never raises — bookkeeping must not fail the sync it describes."""try:sources = await database_sync_to_async(person_property_sync_sources_for, thread_sensitive=False)(- team_id, schema_id+ team_id, binding)for source in sources or []:await database_sync_to_async(_record, thread_sensitive=False)(team_id=team_id,- schema_id=schema_id,+ binding=binding,job_id=job_id,trigger=trigger,status="running",@@ -740,17 +777,17 @@ async def record_started_runs(logger.exception("person-property run: failed to record started runs",team_id=team_id,- schema_id=schema_id,+ **_log_fields(binding),job_id=job_id,trigger=trigger,)- capture_exception(e, {"team_id": team_id, "schema_id": schema_id, "trigger": trigger})+ capture_exception(e, {"team_id": team_id, **_log_fields(binding), "trigger": trigger})async def record_completed_runs(*,team_id: int,- schema_id: str,+ binding: WarehouseBinding,job_id: str | None,trigger: str,started_at: str,@@ -764,7 +801,7 @@ async def record_completed_runs(for ps in result.per_source:await database_sync_to_async(_record, thread_sensitive=False)(team_id=team_id,- schema_id=schema_id,+ binding=binding,job_id=job_id,trigger=trigger,status="completed",@@ -777,28 +814,35 @@ async def record_completed_runs(logger.exception("person-property run: failed to record completed runs",team_id=team_id,- schema_id=schema_id,+ **_log_fields(binding),job_id=job_id,trigger=trigger,)- capture_exception(e, {"team_id": team_id, "schema_id": schema_id, "trigger": trigger})+ capture_exception(e, {"team_id": team_id, **_log_fields(binding), "trigger": trigger})async def record_failed_runs(- *, team_id: int, schema_id: str, job_id: str | None, trigger: str, started_at: str, finished_at: str, error: str+ *,+ team_id: int,+ binding: WarehouseBinding,+ job_id: str | None,+ trigger: str,+ started_at: str,+ finished_at: str,+ error: str,) -> None:- """Persist a failed run row per source the schema feeds, so a failure is visible in the UI (not+ """Persist a failed run row per source the binding feeds, so a failure is visible in the UI (notonly in error tracking). Never raises — this runs on the already-failing path, so any error here(a bad DB state while resolving sources, or the record write itself) is captured, not propagated,to avoid masking the original failure that Temporal needs to see."""try:sources = await database_sync_to_async(person_property_sync_sources_for, thread_sensitive=False)(- team_id, schema_id+ team_id, binding)for source in sources or []:await database_sync_to_async(_record, thread_sensitive=False)(team_id=team_id,- schema_id=schema_id,+ binding=binding,job_id=job_id,trigger=trigger,status="failed",@@ -811,8 +855,8 @@ async def record_failed_runs(logger.exception("person-property run: failed to record failed runs",team_id=team_id,- schema_id=schema_id,+ **_log_fields(binding),job_id=job_id,trigger=trigger,)- capture_exception(e, {"team_id": team_id, "schema_id": schema_id, "trigger": trigger})+ capture_exception(e, {"team_id": team_id, **_log_fields(binding), "trigger": trigger})diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.pyindex abc16257a4d2..fedf90f8470a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.py@@ -9,11 +9,18 @@ from parameterized import parameterizedfrom posthog.models import Organization, PropertyDefinition, Team-from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import PersonPropertySyncSource+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (+ PersonPropertySyncSource,+ saved_query_binding,+ schema_binding,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import person_property_sync as pps_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_sync"+_SCHEMA = schema_binding("schema-1")+_VIEW = saved_query_binding("view-1")+class TestBuildBundles:def test_maps_columns_and_stringifies_key(self):@@ -122,7 +129,7 @@ class TestRunOrchestration:patch(f"{_MODULE}._clear_staged", new=AsyncMock()) as clear,):team_cls.objects.get.return_value = team- result = await pps.run_person_property_sync(team_id=1, schema_id="schema-1", job_id="job-1")+ result = await pps.run_person_property_sync(team_id=1, binding=_SCHEMA, job_id="job-1")# ghost is filtered out; only a and b are produced.produced_items = produce.call_args.args[3]@@ -151,7 +158,7 @@ class TestRunOrchestration:patch(f"{_MODULE}._read_staged_rows", new=AsyncMock()) as read,patch(f"{_MODULE}._clear_staged", new=AsyncMock()) as clear,):- result = await pps.run_person_property_sync(team_id=1, schema_id="schema-1", job_id="job-1")+ result = await pps.run_person_property_sync(team_id=1, binding=_SCHEMA, job_id="job-1")assert result.sources == 0read.assert_not_awaited()@@ -228,7 +235,7 @@ class TestBackfillOrchestration:patch(f"{_MODULE}._stamp_provenance"),):team_cls.objects.get.return_value = team- result = await pps.run_person_property_backfill(team_id=1, schema_id="schema-1", trigger="manual")+ result = await pps.run_person_property_backfill(team_id=1, binding=_SCHEMA, trigger="manual")# The table is read exactly once, though two sources map it.read_delta.assert_called_once()@@ -241,19 +248,42 @@ class TestBackfillOrchestration:assert all(call.args[3] == pps.BACKFILL_RUN_TOKEN for call in write_snapshot.await_args_list)assert produce.call_count == 2+ @parameterized.expand([("schema", _SCHEMA), ("saved_query", _VIEW)])@pytest.mark.asyncio- async def test_missing_schema_is_a_noop(self):+ async def test_missing_warehouse_table_is_a_noop(self, _name, binding):sources = [PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"})]with (patch(f"{_MODULE}.person_property_sync_sources_for", return_value=sources),- patch(f"{_MODULE}._get_schema", return_value=None),+ patch(f"{_MODULE}._delta_uri_for_binding", return_value=None),patch(f"{_MODULE}._read_delta_bundles") as read_delta,):- result = await pps.run_person_property_backfill(team_id=1, schema_id="schema-1", trigger="backfill")+ result = await pps.run_person_property_backfill(team_id=1, binding=binding, trigger="backfill")assert result.sources == 0read_delta.assert_not_called()+ @pytest.mark.asyncio+ async def test_view_binding_reads_the_model_table_uri(self):+ # A view's rows live under its own model prefix. Reading the schema path instead would find no+ # Delta log and report a silent 0-row backfill.+ team = MagicMock(api_token="tok")+ sources = [PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"})]+ with (+ patch(f"{_MODULE}.person_property_sync_sources_for", return_value=sources),+ patch(f"{_MODULE}.Team") as team_cls,+ patch(f"{_MODULE}.delta_storage_options", return_value={}),+ patch(+ "products.data_modeling.backend.facade.api.get_materialized_table_uri",+ return_value="s3://bucket/team_1_model_abc/modeling/enriched_users",+ ) as model_uri,+ patch(f"{_MODULE}._read_delta_bundles", return_value=({"s1": {}}, 0)) as read_delta,+ ):+ team_cls.objects.get.return_value = team+ await pps.run_person_property_backfill(team_id=1, binding=_VIEW, trigger="manual")++ model_uri.assert_called_once_with(1, _VIEW.id)+ assert read_delta.call_args.args[0] == "s3://bucket/team_1_model_abc/modeling/enriched_users"+class _FakeS3:"""Minimal in-memory stand-in for the async s3fs client the snapshot helpers use — enough to store@@ -310,11 +340,11 @@ class TestSnapshotCompaction:async def test_write_compacts_prior_files_and_preserves_union(self):fake = _FakeS3()with _fake_s3_patch(fake):- await pps._write_snapshot_hashes(1, "s", "src", "job-1", {"a": "h1", "b": "h1"})- await pps._write_snapshot_hashes(1, "s", "src", "job-2", {"b": "h2", "c": "h2"})+ await pps._write_snapshot_hashes(1, _SCHEMA, "src", "job-1", {"a": "h1", "b": "h1"})+ await pps._write_snapshot_hashes(1, _SCHEMA, "src", "job-2", {"b": "h2", "c": "h2"})- keys = await pps._list_snapshot_files(fake, pps._snapshot_prefix(1, "s", "src"))- hashes = await pps._read_snapshot_hashes(1, "s", "src")+ keys = await pps._list_snapshot_files(fake, pps._snapshot_prefix(1, _SCHEMA, "src"))+ hashes = await pps._read_snapshot_hashes(1, _SCHEMA, "src")# Two producing runs collapse to a single file whose union is newest-wins (b came from job-2).assert len(keys) == 1@@ -325,11 +355,11 @@ class TestSnapshotCompaction:fake = _FakeS3()with _fake_s3_patch(fake):# Backfills share one filename; the second write must overwrite it, not delete it as "stale".- await pps._write_snapshot_hashes(1, "s", "src", pps.BACKFILL_RUN_TOKEN, {"a": "h1"})- await pps._write_snapshot_hashes(1, "s", "src", pps.BACKFILL_RUN_TOKEN, {"a": "h2", "b": "h2"})+ await pps._write_snapshot_hashes(1, _SCHEMA, "src", pps.BACKFILL_RUN_TOKEN, {"a": "h1"})+ await pps._write_snapshot_hashes(1, _SCHEMA, "src", pps.BACKFILL_RUN_TOKEN, {"a": "h2", "b": "h2"})- keys = await pps._list_snapshot_files(fake, pps._snapshot_prefix(1, "s", "src"))- hashes = await pps._read_snapshot_hashes(1, "s", "src")+ keys = await pps._list_snapshot_files(fake, pps._snapshot_prefix(1, _SCHEMA, "src"))+ hashes = await pps._read_snapshot_hashes(1, _SCHEMA, "src")assert len(keys) == 1assert hashes == {"a": "h2", "b": "h2"}@@ -392,7 +422,7 @@ class TestGroupTarget:patch(f"{_MODULE}._clear_staged", new=AsyncMock()),):team_cls.objects.get.return_value = team- result = await pps.run_person_property_sync(team_id=1, schema_id="schema-1", job_id="job-1")+ result = await pps.run_person_property_sync(team_id=1, binding=_SCHEMA, job_id="job-1")produce.assert_not_called()stamp.assert_not_called()@@ -468,7 +498,7 @@ class TestStampProvenance:property_descriptions={"plan_tier": "The plan tier"},)- pps._stamp_provenance(team.id, "schema-1", source, ["plan_tier", "seat_count"])+ pps._stamp_provenance(team.id, _SCHEMA, source, ["plan_tier", "seat_count"])described = PropertyDefinition.objects.get(team=team, name="plan_tier")plain = PropertyDefinition.objects.get(team=team, name="seat_count")@@ -480,6 +510,21 @@ class TestStampProvenance:assert plain.warehouse_origin["custom_property_source_id"] == "s1"assert "description" not in plain.warehouse_origin+ @parameterized.expand([("schema", _SCHEMA, "schema-1"), ("saved_query", _VIEW, None)])+ def test_records_the_binding_and_keeps_schema_id_only_for_a_schema(self, _name, binding, expected_schema_id):+ # `schema_id` is what rows stamped before views existed carry, so a schema binding must keep+ # writing it; a view has no schema and must not claim one.+ team = self._team()+ PropertyDefinition.objects.create(team=team, name="plan_tier", type=PropertyDefinition.Type.PERSON)+ source = PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"})++ pps._stamp_provenance(team.id, binding, source, ["plan_tier"])++ origin = PropertyDefinition.objects.get(team=team, name="plan_tier").warehouse_origin+ assert origin is not None+ assert (origin["binding_kind"], origin["binding_id"]) == (binding.kind, binding.id)+ assert origin.get("schema_id") == expected_schema_id+def test_group_target_stamps_only_matching_group_type(self):team = self._team()PropertyDefinition.objects.create(@@ -490,7 +535,7 @@ class TestStampProvenance:)source = PersonPropertySyncSource("s1", "d1", "group_key", {"plan": "tier"}, target="group", group_type_index=0)- pps._stamp_provenance(team.id, "schema-1", source, ["tier"])+ pps._stamp_provenance(team.id, _SCHEMA, source, ["tier"])assert PropertyDefinition.objects.get(id=other.id).warehouse_origin is Nonestamped = PropertyDefinition.objects.get(team=team, name="tier", group_type_index=0)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/sinks.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/sinks.pyindex aef1ebd32112..23c1de516500 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/sinks.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/sinks.py@@ -4,6 +4,7 @@ from typing import Protocolimport pyarrow as pafrom structlog.types import FilteringBoundLogger+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import schema_bindingfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer import CDPProducerfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink import (PersonPropertyRowSink,@@ -66,7 +67,7 @@ def build_pipeline_sinks(cdp_producer = CDPProducer(team_id=team_id, schema_id=schema_id, job_id=job_id, logger=logger)person_property_sink = PersonPropertyRowSink(team_id=team_id,- schema_id=schema_id,+ binding=schema_binding(schema_id),job_id=job_id,logger=logger,is_incremental=is_incremental,diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.pyindex 1d122ca2d020..9c3e9e7e3604 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.models.table import HIDDEN_COLUMNS, Datafrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (emit_signals_enabled_for,person_property_sync_enabled_for,+ schema_binding,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry import (retry_on_operational_error,@@ -296,7 +297,7 @@ def create_external_data_job_model_activity(# Whether this schema feeds any enabled person-target Customer analytics source (owned by# customer_analytics via external_product_hooks; not imported here).- person_property_sync_enabled = person_property_sync_enabled_for(inputs.team_id, schema.id)+ person_property_sync_enabled = person_property_sync_enabled_for(inputs.team_id, schema_binding(schema.id))return CreateExternalDataJobModelActivityOutputs(job_id=str(job.id),diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 36b163dfb75e..59554da6b9e6 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1889,7 +1889,7 @@}},"custom-property-definitions-create": {- "description": "Create a Customer Analytics custom property definition — the shape of a custom attribute. Provide `name` (required, unique within the team), optional `description`, `display_type` (required; one of text, number, currency, percent, date, datetime, boolean), and optional `is_big_number` to abbreviate large numeric values (e.g. 10,000 → 10K; only valid for numeric display types). `target_type` picks what the property attaches to: `account` (default; value set manually or from a materialized view), `person`, or `group` (person/group properties are populated from a warehouse table via a custom property source and become usable like any other person/group property in feature flags, cohorts, and insights). For `group` targets, also pass `group_type_index` (0-4) selecting the group type. Person and group targets require the `warehouse-person-properties` feature; creating a `group` target additionally requires the `group:write` scope. Definitions are team-scoped; for account targets, set the value a specific account holds via the account custom property value tools.",+ "description": "Create a Customer Analytics custom property definition — the shape of a custom attribute. Provide `name` (required, unique within the team), optional `description`, `display_type` (required; one of text, number, currency, percent, date, datetime, boolean), and optional `is_big_number` to abbreviate large numeric values (e.g. 10,000 → 10K; only valid for numeric display types). `target_type` picks what the property attaches to: `account` (default; value set manually or from a materialized view), `person`, or `group` (person/group properties are populated from a warehouse table or a materialized view via a custom property source and become usable like any other person/group property in feature flags, cohorts, and insights). For `group` targets, also pass `group_type_index` (0-4) selecting the group type. Person and group targets require the `warehouse-person-properties` feature; creating a `group` target additionally requires the `group:write` scope. Definitions are team-scoped; for account targets, set the value a specific account holds via the account custom property value tools.","category": "Customer analytics","feature": "customer_analytics","summary": "Create custom property definition",@@ -1964,7 +1964,7 @@"feature_flag": "customer-analytics-csp"},"custom-property-sources-backfill": {- "description": "Person- and group-property sources only: start a backfill that reads the whole warehouse table and populates person or group properties for its historical rows. Backfill is per table — one call refreshes every enabled property mapped from that table — and it coalesces if one is already running for the table (the response's `already_running` is then true). Returns 400 for a source that is not an enabled person- or group-property source. Backfilling a group-target source additionally requires the `group:write` scope.",+ "description": "Person- and group-property sources only: start a backfill that reads the whole warehouse table or view and populates person or group properties for its historical rows. Backfill is per table or view — one call refreshes every enabled property mapped from it — and it coalesces if one is already running for that table or view (the response's `already_running` is then true). Returns 400 for a source that is not an enabled person- or group-property source. Backfilling a group-target source additionally requires the `group:write` scope.","category": "Customer analytics","feature": "customer_analytics","summary": "Backfill a warehouse person- or group-property source",@@ -1979,7 +1979,7 @@"feature_flag": "warehouse-person-properties"},"custom-property-sources-create": {- "description": "Bind a custom property definition to a data source. Account sources read a materialized view (`saved_query` + `source_column`); person and group sources read a synced warehouse table (`external_data_schema` + `column_property_map` mapping warehouse columns to person/group properties, plus `key_column` = the distinct_id column for person sources or the group-key column for group sources). One source per definition. The target (account, person, or group) follows the bound definition's `target_type`; creating a source for a group-target definition additionally requires the `group:write` scope.",+ "description": "Bind a custom property definition to a data source. Account sources read a materialized view (`saved_query` + `source_column`). Person and group sources read either a synced warehouse table (`external_data_schema`) or a materialized view (`saved_query`) — pass exactly one — plus `column_property_map` mapping warehouse columns to person/group properties and `key_column` = the distinct_id column for person sources or the group-key column for group sources. A view binding must already be materialized. One source per definition. The target (account, person, or group) follows the bound definition's `target_type`; creating a source for a group-target definition additionally requires the `group:write` scope.","category": "Customer analytics","feature": "customer_analytics","summary": "Create custom property source",@@ -2069,7 +2069,7 @@"feature_flag": "warehouse-person-properties"},"custom-property-sources-sync": {- "description": "Person- and group-property sources only: trigger the underlying warehouse schema's sync now. This re-runs a real (billable) warehouse sync, and the incremental person/group-property update rides off it. It does not reset the schema's recurring sync schedule. Returns 400 for a source that is not an enabled person- or group-property source. Syncing a group-target source additionally requires the `group:write` scope.",+ "description": "Person- and group-property sources only: run what the source reads now. A table binding re-runs a real (billable) warehouse sync; a view binding materializes the view. The incremental person/group-property update rides off that run. It does not reset the recurring schedule. Returns 400 for a source that is not an enabled person- or group-property source, and for a view whose data-modeling DAG is not on the v2 schedule (use backfill there instead). Syncing a group-target source additionally requires the `group:write` scope.","category": "Customer analytics","feature": "customer_analytics","summary": "Sync a warehouse person- or group-property source now",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 227972b543b9..862c6c4ff8c9 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1904,7 +1904,7 @@}},"custom-property-definitions-create": {- "description": "Create a Customer Analytics custom property definition — the shape of a custom attribute. Provide `name` (required, unique within the team), optional `description`, `display_type` (required; one of text, number, currency, percent, date, datetime, boolean), and optional `is_big_number` to abbreviate large numeric values (e.g. 10,000 → 10K; only valid for numeric display types). `target_type` picks what the property attaches to: `account` (default; value set manually or from a materialized view), `person`, or `group` (person/group properties are populated from a warehouse table via a custom property source and become usable like any other person/group property in feature flags, cohorts, and insights). For `group` targets, also pass `group_type_index` (0-4) selecting the group type. Person and group targets require the `warehouse-person-properties` feature; creating a `group` target additionally requires the `group:write` scope. Definitions are team-scoped; for account targets, set the value a specific account holds via the account custom property value tools.",+ "description": "Create a Customer Analytics custom property definition — the shape of a custom attribute. Provide `name` (required, unique within the team), optional `description`, `display_type` (required; one of text, number, currency, percent, date, datetime, boolean), and optional `is_big_number` to abbreviate large numeric values (e.g. 10,000 → 10K; only valid for numeric display types). `target_type` picks what the property attaches to: `account` (default; value set manually or from a materialized view), `person`, or `group` (person/group properties are populated from a warehouse table or a materialized view via a custom property source and become usable like any other person/group property in feature flags, cohorts, and insights). For `group` targets, also pass `group_type_index` (0-4) selecting the group type. Person and group targets require the `warehouse-person-properties` feature; creating a `group` target additionally requires the `group:write` scope. Definitions are team-scoped; for account targets, set the value a specific account holds via the account custom property value tools.","category": "Customer analytics","feature": "customer_analytics","summary": "Create custom property definition",@@ -1979,7 +1979,7 @@"feature_flag": "customer-analytics-csp"},"custom-property-sources-backfill": {- "description": "Person- and group-property sources only: start a backfill that reads the whole warehouse table and populates person or group properties for its historical rows. Backfill is per table — one call refreshes every enabled property mapped from that table — and it coalesces if one is already running for the table (the response's `already_running` is then true). Returns 400 for a source that is not an enabled person- or group-property source. Backfilling a group-target source additionally requires the `group:write` scope.",+ "description": "Person- and group-property sources only: start a backfill that reads the whole warehouse table or view and populates person or group properties for its historical rows. Backfill is per table or view — one call refreshes every enabled property mapped from it — and it coalesces if one is already running for that table or view (the response's `already_running` is then true). Returns 400 for a source that is not an enabled person- or group-property source. Backfilling a group-target source additionally requires the `group:write` scope.","category": "Customer analytics","feature": "customer_analytics","summary": "Backfill a warehouse person- or group-property source",@@ -1994,7 +1994,7 @@"feature_flag": "warehouse-person-properties"},"custom-property-sources-create": {- "description": "Bind a custom property definition to a data source. Account sources read a materialized view (`saved_query` + `source_column`); person and group sources read a synced warehouse table (`external_data_schema` + `column_property_map` mapping warehouse columns to person/group properties, plus `key_column` = the distinct_id column for person sources or the group-key column for group sources). One source per definition. The target (account, person, or group) follows the bound definition's `target_type`; creating a source for a group-target definition additionally requires the `group:write` scope.",+ "description": "Bind a custom property definition to a data source. Account sources read a materialized view (`saved_query` + `source_column`). Person and group sources read either a synced warehouse table (`external_data_schema`) or a materialized view (`saved_query`) — pass exactly one — plus `column_property_map` mapping warehouse columns to person/group properties and `key_column` = the distinct_id column for person sources or the group-key column for group sources. A view binding must already be materialized. One source per definition. The target (account, person, or group) follows the bound definition's `target_type`; creating a source for a group-target definition additionally requires the `group:write` scope.","category": "Customer analytics","feature": "customer_analytics","summary": "Create custom property source",@@ -2084,7 +2084,7 @@"feature_flag": "warehouse-person-properties"},"custom-property-sources-sync": {- "description": "Person- and group-property sources only: trigger the underlying warehouse schema's sync now. This re-runs a real (billable) warehouse sync, and the incremental person/group-property update rides off it. It does not reset the schema's recurring sync schedule. Returns 400 for a source that is not an enabled person- or group-property source. Syncing a group-target source additionally requires the `group:write` scope.",+ "description": "Person- and group-property sources only: run what the source reads now. A table binding re-runs a real (billable) warehouse sync; a view binding materializes the view. The incremental person/group-property update rides off that run. It does not reset the recurring schedule. Returns 400 for a source that is not an enabled person- or group-property source, and for a view whose data-modeling DAG is not on the v2 schedule (use backfill there instead). Syncing a group-target source additionally requires the `group:write` scope.","category": "Customer analytics","feature": "customer_analytics","summary": "Sync a warehouse person- or group-property source now",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 03f611213efc..411f1cd09cc7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -19365,21 +19365,22 @@ export namespace Schemas {}/**- * Binds a data-warehouse source to a custom property definition. Account sources read a- * materialized view column and sync onto matching accounts; person and group sources read a- * warehouse schema and sync onto matching persons or groups on each warehouse sync.+ * Binds warehouse columns to a custom property definition. Account sources read a materialized+ * view column and sync onto matching accounts; person and group sources read either an imported+ * warehouse table or a materialized view, and sync onto matching persons or groups on every+ * warehouse run of what they read.*/export interface CustomPropertySource {readonly id: string;/** UUID of the custom property definition this source feeds. One source per definition. */definition: string;/**- * Account sources only: UUID of the data-warehouse saved query (materialized view) to read values from. Mutually exclusive with external_data_schema.+ * UUID of the data-warehouse saved query to read from. Required for an account source. For a person or group source it must be a materialized view, and is one of the two binding options. Mutually exclusive with external_data_schema.* @nullable*/saved_query?: string | null;/**- * Person and group sources only: UUID of the warehouse schema (raw incremental table) to read from. Mutually exclusive with saved_query.+ * Person and group sources only: UUID of the warehouse schema (an imported table) to read from. Mutually exclusive with saved_query; a person or group source sets exactly one.* @nullable*/external_data_schema?: string | null;@@ -19391,7 +19392,7 @@ export namespace Schemas {source_column?: string | null;/** Person and group sources only: {warehouse_column: property_name} mapping the columns this source writes onto the person or group. */column_property_map?: unknown;- /** Person sources only: {warehouse_column: description} giving each mapped column a human-facing description, seeded from the warehouse column's information_schema description. Optional per column. Create-only. */+ /** Person and group sources only: {warehouse_column: description} giving each mapped column a human-facing description, seeded from the warehouse column's information_schema description. Optional per column. Create-only. */column_descriptions?: unknown;/*** Column whose value identifies the target: an account's external_id for account sources, the person's distinct_id for person sources, or the group key for group sources.@@ -19418,27 +19419,32 @@ export namespace Schemas {/** @nullable */readonly updated_at: string | null;/**- * Person and group sources only: how often the underlying warehouse schema syncs, in seconds. Null for account sources or when unavailable.+ * Person and group sources only: how often the bound table or view runs, in seconds. Null for account sources, or when the schedule is unavailable — including a view whose frequency is set on its data-modeling DAG.* @nullable*/readonly sync_frequency_interval_seconds: number | null;/**- * Person and group sources only: approximate time of the next scheduled sync (last synced + interval). Approximate — drifts if the schedule was paused. Null for account sources or if never synced.+ * Person and group sources only: approximate time of the next scheduled run (last run + interval). Approximate — drifts if the schedule was paused. Null for account sources, if never run, or when the interval is unavailable.* @nullable*/readonly next_sync_at: string | null;/** Person and group sources only: the most recent sync/backfill run, or null if none yet. */readonly latest_run: CustomPropertySyncRun | null;/**- * Person and group sources only: UUID of the warehouse source owning the schema, so the UI can link to the table. Null for account sources or when unavailable.+ * Table-bound person and group sources only: UUID of the warehouse source owning the schema, so the UI can link to the table. Null for account sources, view-bound sources, or when unavailable.* @nullable*/readonly external_data_source: string | null;/**- * Person and group sources only: the bound warehouse table as it is named in HogQL. Null for account sources or when unavailable.+ * Person and group sources only: what this source reads, as it is named in HogQL — the imported table, or the view. Null for account sources or when unavailable.* @nullable*/readonly table_name: string | null;+ /**+ * View-bound person and group sources only: the materialized view's name, so the UI can tell a view-backed source from a table-backed one. Null for account and table-bound sources.+ * @nullable+ */+ readonly saved_query_name: string | null;}/**diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.tsindex 9eff45df67a7..572ad63143c0 100644--- a/services/mcp/src/generated/customer_analytics/api.ts+++ b/services/mcp/src/generated/customer_analytics/api.ts@@ -747,13 +747,13 @@ export const CustomPropertySourcesCreateBody = /* @__PURE__ */ zod.string().nullish().describe(- 'Account sources only: UUID of the data-warehouse saved query (materialized view) to read values from. Mutually exclusive with external_data_schema.'+ 'UUID of the data-warehouse saved query to read from. Required for an account source. For a person or group source it must be a materialized view, and is one of the two binding options. Mutually exclusive with external_data_schema.'),external_data_schema: zod.string().nullish().describe(- 'Person and group sources only: UUID of the warehouse schema (raw incremental table) to read from. Mutually exclusive with saved_query.'+ 'Person and group sources only: UUID of the warehouse schema (an imported table) to read from. Mutually exclusive with saved_query; a person or group source sets exactly one.'),source_column: zod.string()@@ -770,7 +770,7 @@ export const CustomPropertySourcesCreateBody = /* @__PURE__ */ zod.unknown().optional().describe(- "Person sources only: {warehouse_column: description} giving each mapped column a human-facing description, seeded from the warehouse column's information_schema description. Optional per column. Create-only."+ "Person and group sources only: {warehouse_column: description} giving each mapped column a human-facing description, seeded from the warehouse column's information_schema description. Optional per column. Create-only."),key_column: zod.string()@@ -786,7 +786,7 @@ export const CustomPropertySourcesCreateBody = /* @__PURE__ */ zod),}).describe(- 'Binds a data-warehouse source to a custom property definition. Account sources read a\nmaterialized view column and sync onto matching accounts; person and group sources read a\nwarehouse schema and sync onto matching persons or groups on each warehouse sync.'+ 'Binds warehouse columns to a custom property definition. Account sources read a materialized\nview column and sync onto matching accounts; person and group sources read either an imported\nwarehouse table or a materialized view, and sync onto matching persons or groups on every\nwarehouse run of what they read.')export const CustomPropertySourcesRetrieveParams = /* @__PURE__ */ zod.object({@@ -875,9 +875,9 @@ export const CustomPropertySourcesRunsListQueryParams = /* @__PURE__ */ zod.obje})/**- * Person and group sources only: trigger the underlying warehouse schema's sync now. This- * re-runs a real (billable) warehouse sync; the incremental person/group-property update runs- * off it.+ * Person and group sources only: run what this source reads now — an import for a table+ * binding (a real, billable warehouse sync), a materialization for a view binding. The+ * incremental person/group-property update runs off that run.*/export const CustomPropertySourcesSyncParams = /* @__PURE__ */ zod.object({id: zod.string(),