: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): show the bound table and mappings when editing a warehouse property (#81108)
Tom Owers7cf0b71dc163
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 3db4b0e275aa..f926e473d565 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -1344,7 +1344,7 @@ def _resolve_person_source_schema(source: CustomPropertySource, user_access_contschema_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")+ .select_related("source", "table").first())if schema is None:@@ -1356,6 +1356,19 @@ def _resolve_person_source_schema(source: CustomPropertySource, user_access_contreturn schema+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+ is deferred to keep the heavy database module off this module's import path."""+ from posthog.hogql.database.database import (+ get_data_warehouse_table_name, # noqa: PLC0415 — keeps HogQL off the import path+ )++ if schema.table_id is None:+ return schema.name+ 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 schemahas no sync frequency configured."""@@ -1390,6 +1403,8 @@ def _to_custom_property_source_view(sync_frequency_interval_seconds: float | None = Nonenext_sync_at: datetime | None = Nonelatest_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@@ -1399,6 +1414,8 @@ def _to_custom_property_source_view(if schema is not None:sync_frequency_interval_seconds, next_sync_at = _schema_schedule(schema)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@@ -1427,6 +1444,8 @@ def _to_custom_property_source_view(sync_frequency_interval_seconds=sync_frequency_interval_seconds,next_sync_at=next_sync_at,latest_run=latest_run,+ external_data_source=external_data_source,+ table_name=table_name,)@@ -1445,7 +1464,7 @@ def _batch_source_enrichment(schema.id: schemafor 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")+ ).select_related("source", "table")}# 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] = {diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 1d7e57bb96f6..8beccde4139d 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -599,6 +599,11 @@ class CustomPropertySourceView: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.+ external_data_source: UUID | None = None+ table_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 75433a7075f2..6582b428d95d 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@@ -12,8 +12,10 @@ from 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 TeamScopedTestMixinfrom products.customer_analytics.backend.test.factories import create_custom_property_definition+from 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+from products.warehouse_sources.backend.models.table import DataWarehouseTableclass TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):@@ -251,11 +253,34 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):# Column descriptions leak warehouse metadata to a caller without warehouse-source access.assert denied.column_descriptions == {}+ # The binding a link would be built from names a warehouse source the caller can't see.+ assert denied.external_data_source is None and denied.table_name is None+allowed = api.get_custom_property_source(self.team.id, source.id, user_access_control=self._uac(allowed=True))assert allowed is not Noneassert allowed.sync_frequency_interval_seconds == timedelta(hours=6).total_seconds()assert allowed.last_sync_error == "boom: internal warehouse detail" and allowed.consecutive_failures == 3assert allowed.column_descriptions == {"plan": "internal warehouse column note"}+ assert allowed.external_data_source == self.schema.source_id+ # No table row yet, so the schema name is the best label available.+ assert allowed.table_name == "users"++ def test_source_view_names_the_bound_table_as_hogql_queries_it(self):+ credential = DataWarehouseCredential.objects.create(access_key="k", access_secret="s", team=self.team)+ self.schema.table = DataWarehouseTable.objects.create(+ team=self.team,+ name="stripe_users",+ format="Parquet",+ credential=credential,+ url_pattern="https://bucket.s3/data/*",+ )+ self.schema.save(update_fields=["table"])+ source = self._create(user_access_control=self._uac(allowed=True))++ view = api.get_custom_property_source(self.team.id, source.id, user_access_control=self._uac(allowed=True))++ assert view is not None+ assert view.table_name == "stripe.users"def test_list_sync_runs_requires_warehouse_source_viewer(self):source = self._create(user_access_control=self._uac(allowed=True))diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 740cd4ac9248..989bd3265e39 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -634,6 +634,22 @@ class CustomPropertySourceSerializer(DataclassSerializer):allow_null=True,help_text="Person and group sources only: the most recent sync/backfill run, or null if none yet.",)+ external_data_source = serializers.UUIDField(+ 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_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."+ ),+ )class Meta:dataclass = CustomPropertySourceView@@ -657,6 +673,8 @@ class CustomPropertySourceSerializer(DataclassSerializer):"sync_frequency_interval_seconds","next_sync_at","latest_run",+ "external_data_source",+ "table_name",]diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex eea285f6fe3d..377f49effbec 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -926,6 +926,16 @@ export interface CustomPropertySourceApi {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.+ * @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.+ * @nullable+ */+ readonly table_name: string | null}/**diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsxindex 90d693fdcc6c..0067d806907d 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx@@ -31,6 +31,7 @@ import { groupsModel } from '~/models/groupsModel'import type { CustomPropertyOptionApi } from 'products/customer_analytics/frontend/generated/api.schemas'import {+ ColumnPropertyMapping,CustomPropertySourceMode,CustomPropertyTargetType,customPropertyDefinitionsLogic,@@ -54,6 +55,81 @@ 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({+ entityPlural,+ tableName,+ schemaUrl,+}: {+ entityPlural: string+ tableName: string | null+ schemaUrl: string | null+}): JSX.Element {+ return (+ <div className="flex flex-col gap-1">+ <LemonLabel>Warehouse table</LemonLabel>+ {tableName ? (+ schemaUrl ? (+ <Link to={schemaUrl} target="_blank" targetBlankIcon>+ <code>{tableName}</code>+ </Link>+ ) : (+ <code>{tableName}</code>+ )+ ) : (+ <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.+ </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.+ </span>+ </div>+ )+}++// An existing source's column mappings. Create-only on the backend, so they're listed rather than+// edited: what a property reads is the thing you open the modal to check.+function ReadOnlyColumnMappings({+ entityLabel,+ mappings,+}: {+ entityLabel: string+ mappings: ColumnPropertyMapping[]+}): JSX.Element {+ const mapped = mappings.filter((mapping) => mapping.column && mapping.property)+ return (+ <div className="flex flex-col gap-2">+ <LemonLabel>Column mappings</LemonLabel>+ {mapped.length ? (+ <div className="flex flex-col gap-1">+ {mapped.map((mapping) => (+ <div key={mapping.column} className="flex flex-col border rounded px-2 py-1">+ <span className="flex items-center gap-2">+ <code>{mapping.column}</code>+ <span className="text-secondary">→</span>+ <code>{mapping.property}</code>+ </span>+ {mapping.description && (+ <span className="text-secondary text-xs">{mapping.description}</span>+ )}+ </div>+ ))}+ </div>+ ) : (+ <span className="text-secondary">This source has no column mappings.</span>+ )}+ <span className="text-secondary text-xs">+ Which warehouse column sets which {entityLabel} property. You can't change the mappings after the+ property is created. To change them, delete this property and create a new one.+ </span>+ </div>+ )+}+// Warehouse-profile editor (person or group target): pick a synced warehouse table, the key column// (a person's distinct_id or a group's key), and the column → property mappings. For group targets it// also picks which group type. The binding + mappings are create-only on the backend, so they're@@ -75,7 +151,9 @@ function PersonSourceEditor(): JSX.Element {const isGroup = customPropertyForm.targetType === 'group'const entityLabel = isGroup ? 'group' : 'person'- const hasExistingSource = !!editingDefinition?.source+ const entityPlural = isGroup ? 'groups' : 'people'+ const existingSource = editingDefinition?.source+ const 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.@@ -127,11 +205,18 @@ function PersonSourceEditor(): JSX.Element {</LemonField>)}{hasExistingSource ? (- <LemonBanner type="info">- The warehouse table and column mappings are fixed once a source is created. To change them, delete- this property and create a new one. You can still update the {isGroup ? 'group key' : 'distinct ID'}{' '}- column and toggle syncing.- </LemonBanner>+ <ReadOnlyWarehouseTable+ entityPlural={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+ }+ />) : (<LemonFieldname="warehouseTable"@@ -185,7 +270,9 @@ function PersonSourceEditor(): JSX.Element {/>)}</LemonField>- {!hasExistingSource && (+ {hasExistingSource ? (+ <ReadOnlyColumnMappings entityLabel={entityLabel} mappings={mappings} />+ ) : (<div className="flex flex-col gap-2"><LemonLabel>Column mappings</LemonLabel><span className="text-secondary text-xs">diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsxindex 60c9edd29fc2..79a60fbaaee2 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { IconPencil, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'+import { IconExternal, IconPencil, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'import { LemonButton, LemonTable, LemonTableColumns, Spinner, Tooltip } from '@posthog/lemon-ui'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'@@ -8,9 +8,11 @@ import { TZLabel } from 'lib/components/TZLabel'import { TeamMembershipLevel } from 'lib/constants'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'+import { urls } from 'scenes/urls'import type {CustomPropertyDefinitionApi,+ CustomPropertySourceApi,CustomPropertySyncRunApi,} from 'products/customer_analytics/frontend/generated/api.schemas'@@ -51,8 +53,26 @@ function RunCount({ value }: { value: number }): JSX.Element {return <span className={value ? 'font-medium' : 'text-secondary'}>{value}</span>}-// Run history for one source, loaded lazily when its row is expanded.-function ProfilePropertyRuns({ sourceId, labels }: { sourceId: string; labels: ProfileLabels }): JSX.Element {+// 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 {+ if (!source.external_data_source || !source.external_data_schema) {+ return null+ }+ return urls.dataWarehouseSourceSchema(source.external_data_source, source.external_data_schema, 'syncs')+}++// Run history for one source, loaded lazily when its row is expanded. `syncsUrl` points at the+// warehouse table's own sync history, where a run that rode a failing import shows the real error.+function ProfilePropertyRuns({+ sourceId,+ labels,+ syncsUrl,+}: {+ sourceId: string+ labels: ProfileLabels+ syncsUrl: string | null+}): JSX.Element {const { runsBySourceId, runsLoadingBySourceId } = useValues(customPropertyDefinitionsLogic)const runs = runsBySourceId[sourceId] ?? []@@ -126,6 +146,22 @@ function ProfilePropertyRuns({ sourceId, labels }: { sourceId: string; labels: P},]+ if (syncsUrl) {+ columns.push({+ title: '',+ width: 0,+ render: () => (+ <LemonButton+ size="small"+ icon={<IconExternal />}+ to={syncsUrl}+ targetBlank+ tooltip="Open this table's sync history in the data warehouse to see import errors"+ />+ ),+ })+ }+return (<LemonTablecolumns={columns}@@ -330,7 +366,11 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'persononRowExpand: (definition) => definition.source && loadRuns({ sourceId: definition.source.id }),expandedRowRender: (definition) =>definition.source ? (- <ProfilePropertyRuns sourceId={definition.source.id} labels={labels} />+ <ProfilePropertyRuns+ sourceId={definition.source.id}+ labels={labels}+ syncsUrl={schemaSyncsUrl(definition.source)}+ />) : null,}}emptyState={`No warehouse-backed ${labels.entity} properties yet. Add one to sync warehouse columns onto ${labels.entityPlural}.`}diff --git a/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx b/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsxindex 2d3a64a970bb..0034bb49dbfe 100644--- a/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx+++ b/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx@@ -9,7 +9,7 @@ import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'import { AvailableFeature } from '~/types'-import type { CustomPropertyDefinitionApi } from '../../generated/api.schemas'+import type { CustomPropertyDefinitionApi, CustomPropertySyncRunApi } from '../../generated/api.schemas'// The Groups tab only renders when group analytics is available, so the story has to grant it.const userWithGroupAnalytics = {@@ -35,6 +35,8 @@ const definitions: CustomPropertyDefinitionApi[] = [id: '01890000-0000-0000-0000-0000000000a1',definition: '01890000-0000-0000-0000-000000000001',external_data_schema: '01890000-0000-0000-0000-0000000000f1',+ external_data_source: '01890000-0000-0000-0000-0000000000e1',+ table_name: 'stripe.customers',key_column: 'user_email',column_property_map: { plan_name: 'billing_plan', mrr_cents: 'billing_mrr' },is_enabled: true,@@ -76,6 +78,8 @@ const definitions: CustomPropertyDefinitionApi[] = [id: '01890000-0000-0000-0000-0000000000a2',definition: '01890000-0000-0000-0000-000000000002',external_data_schema: '01890000-0000-0000-0000-0000000000f2',+ external_data_source: '01890000-0000-0000-0000-0000000000e2',+ table_name: 'zendesk.users',key_column: 'distinct_id',column_property_map: { tier: 'support_tier' },is_enabled: true,@@ -105,6 +109,8 @@ const definitions: CustomPropertyDefinitionApi[] = [id: '01890000-0000-0000-0000-0000000000a3',definition: '01890000-0000-0000-0000-000000000003',external_data_schema: '01890000-0000-0000-0000-0000000000f3',+ external_data_source: '01890000-0000-0000-0000-0000000000e3',+ table_name: 'stripe.subscriptions',key_column: 'account_id',column_property_map: { arr_cents: 'account_arr' },is_enabled: true,@@ -121,6 +127,37 @@ const definitions: CustomPropertyDefinitionApi[] = [},]+const runs: CustomPropertySyncRunApi[] = [+ {+ id: '01890000-0000-0000-0000-0000000000c1',+ trigger: 'scheduled',+ status: 'completed',+ started_at: '2023-02-15T14:29:00Z',+ finished_at: '2023-02-15T14:30:00Z',+ rows_read: 4210,+ changed: 118,+ existing: 112,+ produced: 112,+ skipped_missing_person: 6,+ error: null,+ created_at: '2023-02-15T14:29:00Z',+ },+ {+ id: '01890000-0000-0000-0000-0000000000c2',+ trigger: 'manual',+ status: 'failed',+ started_at: '2023-02-14T09:00:00Z',+ finished_at: '2023-02-14T09:01:00Z',+ rows_read: 0,+ changed: 0,+ existing: 0,+ produced: 0,+ skipped_missing_person: 0,+ error: 'The warehouse import for this table failed.',+ created_at: '2023-02-14T09:00:00Z',+ },+]+const meta: Meta = {component: App,title: 'Scenes-App/Data Management',@@ -139,6 +176,12 @@ const meta: Meta = {{ count: definitions.length, next: null, previous: null, results: definitions },],'/api/users/@me/': () => [200, userWithGroupAnalytics],+ // Expanding a row loads its run history, which carries the link to the table's+ // warehouse syncs.+ '/api/projects/:team_id/custom_property_sources/:source_id/runs/': () => [+ 200,+ { count: runs.length, next: null, previous: null, results: runs },+ ],},}),],diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 37e227340e09..14ae4030a60e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17743,6 +17743,16 @@ export namespace Schemas {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.+ * @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.+ * @nullable+ */+ readonly table_name: string | null;}/**