Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): refine warehouse person/group property config UX (#73320)

Tom Owersb1d1aa4b8b7c
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index ec9b964cb1f5..d7d831c9af40 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5702,6 +5702,8 @@ const api = {
dataWarehouseTables: {
async list(params?: {
limit?: number
+ offset?: number
+ search?: string
include_columns?: boolean
}): Promise<PaginatedResponse<DataWarehouseTable>> {
return await new ApiRequest()
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 78168d0d2529..05ddd25c5b7b 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -47,7 +47,10 @@ import { GeneralSection } from 'products/conversations/frontend/scenes/settings/
import { NotificationsSection } from 'products/conversations/frontend/scenes/settings/NotificationsSection'
import { ZendeskImportSection } from 'products/conversations/frontend/scenes/settings/ZendeskImportSection'
import { CustomerAnalyticsAccountConfig } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig'
-import { WarehousePersonPropertiesSetting } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting'
+import {
+ WarehouseGroupPropertiesSetting,
+ WarehousePersonPropertiesSetting,
+} from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting'
import { CustomerAnalyticsDashboardEvents } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/events/CustomerAnalyticsDashboardEvents'
import { ExceptionAutocaptureToggle } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings'
import { SuppressionRules } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/suppression_rules/SuppressionRules'
@@ -442,13 +445,22 @@ export const SETTINGS_MAP: SettingSection[] = [
},
{
id: 'customer-analytics-person-properties',
- title: 'Person properties from the warehouse',
+ title: 'Person properties',
description:
'Sync warehouse table columns onto matching people as person properties, and manage their schedule, backfills, and run history.',
component: <WarehousePersonPropertiesSetting />,
flag: 'WAREHOUSE_PERSON_PROPERTIES',
keywords: ['warehouse', 'person', 'properties', 'sync', 'backfill'],
},
+ {
+ id: 'customer-analytics-group-properties',
+ title: 'Group properties',
+ description:
+ 'Sync warehouse table columns onto matching groups as group properties, and manage their schedule, backfills, and run history.',
+ component: <WarehouseGroupPropertiesSetting />,
+ flag: 'WAREHOUSE_PERSON_PROPERTIES',
+ keywords: ['warehouse', 'group', 'properties', 'sync', 'backfill'],
+ },
],
},
{
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 6cc752ae0585..39ca51a489c7 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -120,6 +120,7 @@ export type SettingId =
| 'csp-reporting'
| 'customer-analytics-accounts'
| 'customer-analytics-dashboard-events'
+ | 'customer-analytics-group-properties'
| 'customer-analytics-person-properties'
| 'customer-analytics-usage-metrics'
| 'customization-irl'
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 9011cd8ab079..8613050f04b7 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -1240,7 +1240,9 @@ def _to_custom_property_source_view(
# 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. Account sources have no warehouse binding; their status stays visible.
+ # 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
return contracts.CustomPropertySourceView(
@@ -1251,6 +1253,7 @@ def _to_custom_property_source_view(
source_column=source.source_column,
key_column=source.key_column,
column_property_map=source.column_property_map,
+ column_descriptions=source.column_descriptions if warehouse_status_visible else {},
is_enabled=source.is_enabled,
consecutive_failures=source.consecutive_failures if warehouse_status_visible else 0,
last_synced_at=source.last_synced_at if warehouse_status_visible else None,
@@ -1329,6 +1332,25 @@ def _validate_column_property_map(column_property_map: Any) -> dict[str, str]:
return column_property_map
+def _validate_column_descriptions(column_descriptions: Any, mapped_columns: set[str]) -> dict[str, str]:
+ """Optional {warehouse_column: description} for a person source. Descriptions are keyed by the
+ same warehouse columns the source maps; unknown columns and blank descriptions are dropped."""
+ if column_descriptions is None:
+ return {}
+ if not isinstance(column_descriptions, dict):
+ raise CustomPropertySourceValidationError("column_descriptions must be an object.")
+ cleaned: dict[str, str] = {}
+ for column, description in column_descriptions.items():
+ if column not in mapped_columns:
+ continue
+ if description is None or (isinstance(description, str) and not description.strip()):
+ continue
+ if not isinstance(description, str):
+ raise CustomPropertySourceValidationError("column_descriptions values must be strings.")
+ cleaned[column] = description.strip()
+ return cleaned
+
+
def _enqueue_custom_property_sync(team_id: int, saved_query_id: str) -> None:
"""Dispatch the sync task by name. Enqueue failure must not fail the originating write, so it's swallowed."""
try:
@@ -1579,6 +1601,7 @@ def create_custom_property_source(
source_column: str | None = None,
external_data_schema_id: str | UUID | None = None,
column_property_map: dict | None = None,
+ column_descriptions: dict | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> contracts.CustomPropertySourceView:
definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
@@ -1602,7 +1625,11 @@ def create_custom_property_source(
"A person/group property source uses external_data_schema + column_property_map, not saved_query."
)
# Validate the map shape in memory before the DB lookup below.
- create_kwargs["column_property_map"] = _validate_column_property_map(column_property_map)
+ validated_map = _validate_column_property_map(column_property_map)
+ create_kwargs["column_property_map"] = validated_map
+ create_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,
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 3fd36a34f09a..280084de3d97 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -377,6 +377,7 @@ class CustomPropertySourceView:
source_column: str | None = ""
key_column: str = ""
column_property_map: dict | None = None
+ column_descriptions: dict | None = None
is_enabled: bool = True
consecutive_failures: int = 0
last_synced_at: datetime | None = None
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.py
index bf47ee22ccd2..18f926d07a5c 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
@@ -54,6 +54,25 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):
assert row.column_property_map == {"plan": "plan_tier", "seats": "seat_count"}
assert row.saved_query_id is None
+ def test_create_person_source_stores_and_cleans_column_descriptions(self):
+ view = self._create(
+ column_property_map={"plan": "plan_tier", "seats": "seat_count"},
+ # 'plan' kept and trimmed; 'seats' blank -> dropped; 'unmapped' -> dropped (no such column).
+ column_descriptions={"plan": " The plan tier ", "seats": " ", "unmapped": "ignored"},
+ )
+
+ assert view.column_descriptions == {"plan": "The plan tier"}
+ row = CustomPropertySource.objects.unscoped().get(id=view.id)
+ assert row.column_descriptions == {"plan": "The plan tier"}
+
+ def test_create_person_source_defaults_descriptions_to_empty(self):
+ view = self._create()
+ assert view.column_descriptions == {}
+
+ def test_person_source_rejects_non_object_column_descriptions(self):
+ with self.assertRaisesMessage(api.CustomPropertySourceValidationError, "must be an object"):
+ self._create(column_descriptions=["not", "an", "object"])
+
@parameterized.expand(
[
(
@@ -211,7 +230,11 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):
self.schema.sync_frequency_interval = timedelta(hours=6)
self.schema.save(update_fields=["sync_frequency_interval"])
- source = self._create(user_access_control=self._uac(allowed=True))
+ source = self._create(
+ user_access_control=self._uac(allowed=True),
+ # Column descriptions come from the warehouse source's information_schema, so they're gated too.
+ column_descriptions={"plan": "internal warehouse column note"},
+ )
# Warehouse-derived sync status, including the raw error text from the backfill/sync activity.
CustomPropertySource.objects.filter(id=source.id).update(
last_sync_error="boom: internal warehouse detail", consecutive_failures=3
@@ -222,11 +245,14 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):
assert denied.sync_frequency_interval_seconds is None and denied.next_sync_at is None
# Status fields must be redacted too, not just the schedule — the raw error can leak warehouse detail.
assert denied.last_sync_error is None and denied.consecutive_failures == 0
+ # Column descriptions leak warehouse metadata to a caller without warehouse-source access.
+ assert denied.column_descriptions == {}
allowed = api.get_custom_property_source(self.team.id, source.id, user_access_control=self._uac(allowed=True))
assert allowed is not None
assert allowed.sync_frequency_interval_seconds == timedelta(hours=6).total_seconds()
assert allowed.last_sync_error == "boom: internal warehouse detail" and allowed.consecutive_failures == 3
+ assert allowed.column_descriptions == {"plan": "internal warehouse column note"}
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/logic/person_property_projection.py b/products/customer_analytics/backend/logic/person_property_projection.py
index 62b2552723d2..dd469062e600 100644
--- a/products/customer_analytics/backend/logic/person_property_projection.py
+++ b/products/customer_analytics/backend/logic/person_property_projection.py
@@ -98,8 +98,21 @@ def person_property_sync_sources(team_id: int, schema_id: str | UUID) -> list[Pe
definition_id=str(source.definition_id),
key_column=source.key_column,
column_property_map=dict(source.column_property_map or {}),
+ property_descriptions=_property_descriptions(source),
target=source.definition.target_type,
group_type_index=source.definition.group_type_index,
)
for source in sources
]
+
+
+def _property_descriptions(source: CustomPropertySource) -> dict[str, str]:
+ """Re-key the source's ``{column: description}`` onto ``{property_name: description}`` so the sync
+ can stamp each mapped property with its description without knowing the warehouse columns."""
+ column_property_map = source.column_property_map or {}
+ column_descriptions = source.column_descriptions or {}
+ return {
+ column_property_map[column]: description
+ for column, description in column_descriptions.items()
+ if column in column_property_map and description
+ }
diff --git a/products/customer_analytics/backend/logic/person_property_projection_test.py b/products/customer_analytics/backend/logic/person_property_projection_test.py
index 269506a3da2c..fb78a63bcbca 100644
--- a/products/customer_analytics/backend/logic/person_property_projection_test.py
+++ b/products/customer_analytics/backend/logic/person_property_projection_test.py
@@ -26,7 +26,9 @@ 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):
+ def _person_source(
+ self, name, key_column, column_property_map, *, is_enabled=True, schema=None, column_descriptions=None
+ ):
definition = create_custom_property_definition(
team_id=self.team.id, name=name, target_type=TargetType.PERSON.value
)
@@ -36,6 +38,7 @@ class PersonPropertyProjectionTest(TeamScopedTestMixin, BaseTest):
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,
)
@@ -92,6 +95,24 @@ class PersonPropertyProjectionTest(TeamScopedTestMixin, BaseTest):
assert config.definition_id == str(source.definition_id)
assert config.key_column == "distinct_id"
assert config.column_property_map == {"plan": "plan_tier"}
+ # No descriptions configured -> empty mapping, not None.
+ assert config.property_descriptions == {}
+
+ def test_sync_sources_rekey_column_descriptions_onto_property_names(self):
+ # Descriptions are stored keyed by warehouse column but stamped onto property definitions
+ # keyed by property name; the resolver must re-key and drop descriptions for unmapped columns.
+ self._person_source(
+ "A",
+ "distinct_id",
+ {"plan": "plan_tier", "seats": "seat_count"},
+ column_descriptions={"plan": "The plan tier", "unmapped": "ignored", "seats": ""},
+ )
+
+ configs = person_property_sync_sources(self.team.id, self.schema.id)
+
+ 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
diff --git a/products/customer_analytics/backend/migrations/0021_custompropertysource_column_descriptions.py b/products/customer_analytics/backend/migrations/0021_custompropertysource_column_descriptions.py
new file mode 100644
index 000000000000..0d82b5a654d9
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0021_custompropertysource_column_descriptions.py
@@ -0,0 +1,20 @@
+# Generated by Django 5.2.14 on 2026-07-23 17:40
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ (
+ "customer_analytics",
+ "0020_custompropertydefinition_group_type_index_and_more",
+ ),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="custompropertysource",
+ name="column_descriptions",
+ field=models.JSONField(blank=True, default=None, null=True),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index 7ae5858c9b62..577e8dc2359b 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0020_custompropertydefinition_group_type_index_and_more
+0021_custompropertysource_column_descriptions
diff --git a/products/customer_analytics/backend/models/custom_property_source.py b/products/customer_analytics/backend/models/custom_property_source.py
index f6ebbc4bffb0..8319a45e1eea 100644
--- a/products/customer_analytics/backend/models/custom_property_source.py
+++ b/products/customer_analytics/backend/models/custom_property_source.py
@@ -33,6 +33,10 @@ class CustomPropertySource(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, Up
key_column = models.CharField(max_length=400)
# Person path: {warehouse_column: person_property_name} for the columns this source maps.
column_property_map = models.JSONField(null=True, blank=True, default=None)
+ # Person path: {warehouse_column: description} — the human-facing description for each mapped
+ # column, seeded from the warehouse column's information_schema description. Keyed by warehouse
+ # column so it pairs with column_property_map; entries are optional.
+ column_descriptions = models.JSONField(null=True, blank=True, default=None)
is_enabled = models.BooleanField(default=True)
consecutive_failures = models.PositiveIntegerField(default=0)
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 5cbf168a9f81..a80ef2e2e908 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -413,6 +413,15 @@ class CustomPropertySourceSerializer(DataclassSerializer):
"source writes onto the person or group."
),
)
+ column_descriptions = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "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."
+ ),
+ )
key_column = serializers.CharField(
max_length=400,
help_text=(
@@ -473,6 +482,7 @@ class CustomPropertySourceSerializer(DataclassSerializer):
"external_data_schema",
"source_column",
"column_property_map",
+ "column_descriptions",
"key_column",
"is_enabled",
"consecutive_failures",
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 48cf22358c75..6acfa944d1a9 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -587,6 +587,7 @@ class CustomPropertySourceViewSet(
source_column=data.source_column,
external_data_schema_id=data.external_data_schema,
column_property_map=data.column_property_map,
+ column_descriptions=data.column_descriptions,
key_column=data.key_column,
is_enabled=data.is_enabled,
user=cast(User, request.user),
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index d7cac5f454e5..89d2b36a7d93 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -709,6 +709,8 @@ 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. */
+ 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.
* @maxLength 400
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index 457e213c6844..2b928f104784 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -585,6 +585,12 @@ export const CustomPropertySourcesCreateBody = /* @__PURE__ */ zod
.describe(
'Person and group sources only: {warehouse_column: property_name} mapping the columns this source writes onto the person or group.'
),
+ column_descriptions: 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."
+ ),
key_column: zod
.string()
.max(customPropertySourcesCreateBodyKeyColumnMax)
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
index 5687d72a2d8c..86c134e22aaa 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
-import { IconPlus, IconRefresh, IconTrash } from '@posthog/icons'
+import { IconInfo, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
@@ -15,6 +15,7 @@ import {
LemonTag,
LemonTextArea,
Link,
+ Tooltip,
} from '@posthog/lemon-ui'
import type { DataColorToken } from 'lib/colors'
@@ -67,7 +68,8 @@ function PersonSourceEditor(): JSX.Element {
selectedTableColumns,
selectedTableColumnsLoading,
} = useValues(customPropertyDefinitionsLogic)
- const { setCustomPropertyFormValue, loadSelectedTableColumns } = useActions(customPropertyDefinitionsLogic)
+ const { setCustomPropertyFormValue, loadSelectedTableColumns, loadWarehouseTables } =
+ useActions(customPropertyDefinitionsLogic)
const { groupTypes } = useValues(groupsModel)
const isGroup = customPropertyForm.targetType === 'group'
@@ -76,7 +78,19 @@ function PersonSourceEditor(): JSX.Element {
const noTables = !warehouseTablesLoading && warehouseTables.length === 0
const mappings = customPropertyForm.columnMappings
const setMappings = (next: typeof mappings): void => setCustomPropertyFormValue('columnMappings', next)
- const columnOptions = selectedTableColumns.map((column) => ({ key: column, label: column }))
+ const columnByName = new Map(selectedTableColumns.map((column) => [column.name, column]))
+ // Each column option renders its name with a tag for its warehouse type, so a picker shows what
+ // kind of value it holds without leaving the modal.
+ const columnOptions = selectedTableColumns.map((column) => ({
+ key: column.name,
+ label: column.name,
+ labelComponent: (
+ <span className="flex items-center gap-2">
+ <span>{column.name}</span>
+ <LemonTag type="muted">{column.type}</LemonTag>
+ </span>
+ ),
+ }))
const groupTypeOptions = Array.from(groupTypes.values()).map((groupType) => ({
value: groupType.group_type_index,
label: groupType.name_singular || groupType.group_type,
@@ -118,26 +132,32 @@ function PersonSourceEditor(): JSX.Element {
<LemonField
name="warehouseTable"
label="Warehouse table"
- help={`Rows from this synced table are upserted onto matching ${entityLabel}s.`}
+ help={`Rows from this synced table are upserted onto matching ${entityLabel}s. Type to search all synced tables.`}
>
{({ value, onChange }) => (
- <LemonSearchableSelect
- value={value}
- onChange={(newValue) => {
+ <LemonInputSelect
+ mode="single"
+ value={value ? [value] : []}
+ onChange={(newValues) => {
+ const newValue = newValues[0] ?? null
onChange(newValue)
// Columns are table-specific, so a table change invalidates the picks and
// loads the new table's columns for the pickers below.
setCustomPropertyFormValue('keyColumn', null)
- setMappings(mappings.map((mapping) => ({ ...mapping, column: '' })))
+ 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 })
}}
+ // Search runs on the backend so the whole synced catalog is reachable, not just
+ // the first page loaded into the picker.
+ onInputChange={(search) => loadWarehouseTables({ search })}
options={warehouseTables.map((table) => ({
- value: table.id,
+ key: table.id,
label: table.hogql_name || table.name,
}))}
loading={warehouseTablesLoading}
placeholder="Select a warehouse table"
- fullWidth
/>
)}
</LemonField>
@@ -168,20 +188,34 @@ function PersonSourceEditor(): JSX.Element {
Map each warehouse column to the {entityLabel} property name it should set.
</span>
{mappings.map((mapping, index) => (
- <div key={index} className="flex flex-col gap-1">
+ <div key={index} className="flex flex-col gap-1 border rounded p-2">
<div className="flex items-center gap-2">
<div className="flex-1">
<LemonInputSelect
mode="single"
allowCustomValues
value={mapping.column ? [mapping.column] : []}
- onChange={(newValues) =>
+ onChange={(newValues) => {
+ const column = newValues[0] ?? ''
+ const columnMeta = columnByName.get(column)
setMappings(
mappings.map((m, i) =>
- i === index ? { ...m, column: newValues[0] ?? '' } : m
+ i === index
+ ? {
+ ...m,
+ column,
+ // Seed the property name and description from the
+ // column when they're still empty, so a mapping is
+ // one click when the warehouse names are good.
+ property: m.property.trim() ? m.property : column,
+ description: m.description.trim()
+ ? m.description
+ : (columnMeta?.description ?? ''),
+ }
+ : m
)
)
- }
+ }}
options={columnOptions}
loading={selectedTableColumnsLoading}
placeholder="Warehouse column"
@@ -208,6 +242,15 @@ function PersonSourceEditor(): JSX.Element {
onClick={() => setMappings(mappings.filter((_, i) => i !== index))}
/>
</div>
+ <LemonInput
+ value={mapping.description}
+ onChange={(description) =>
+ setMappings(mappings.map((m, i) => (i === index ? { ...m, description } : m)))
+ }
+ placeholder="Description (optional)"
+ size="small"
+ fullWidth
+ />
{columnMappingWarnings[index] && (
<span className="text-warning text-xs">{columnMappingWarnings[index]}</span>
)}
@@ -216,15 +259,32 @@ function PersonSourceEditor(): JSX.Element {
<LemonButton
type="secondary"
icon={<IconPlus />}
- onClick={() => setMappings([...mappings, { column: '', property: '' }])}
+ onClick={() => setMappings([...mappings, { column: '', property: '', description: '' }])}
>
Add mapping
</LemonButton>
</div>
)}
- <LemonField name="isEnabled">
+ <LemonField
+ name="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.`}
+ >
{({ value, onChange }) => (
- <LemonSwitch checked={value} onChange={onChange} label="Sync enabled" bordered />
+ <LemonSwitch
+ checked={value}
+ onChange={onChange}
+ label={
+ <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.`}
+ >
+ <IconInfo className="text-secondary" />
+ </Tooltip>
+ </span>
+ }
+ bordered
+ />
)}
</LemonField>
</>
@@ -304,6 +364,7 @@ export function CustomPropertyModal(): JSX.Element {
definitionsLoading,
editingReferences,
newWorkflowUrlLoading,
+ targetTypeLocked,
} = useValues(customPropertyDefinitionsLogic)
const {
closeModal,
@@ -391,7 +452,7 @@ export function CustomPropertyModal(): JSX.Element {
<LemonField name="description" label="Description">
<LemonTextArea placeholder="Optional description" minRows={2} />
</LemonField>
- {profileTargetAvailable && (
+ {profileTargetAvailable && !targetTypeLocked && (
<LemonField
name="targetType"
label="Attach to"
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx
index 553ea283d2ee..247494e7a122 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx
@@ -14,7 +14,7 @@ import type {
CustomPropertySyncRunApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
-import { customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'
+import { CustomPropertyTargetType, customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'
import { CustomPropertyModal } from './CustomPropertyModal'
import { type SourceSyncStatusLevel, sourceSyncStatus } from './customPropertyTypes'
@@ -31,8 +31,15 @@ const TAG_TYPE_BY_RUN_STATUS: Record<string, LemonTagType> = {
failed: 'danger',
}
+// Labels that differ between the person- and group-target views of the same warehouse-sync machinery.
+type ProfileLabels = { entity: string; entityPlural: string; keyColumn: string }
+const LABELS_BY_TARGET: Record<'person' | 'group', ProfileLabels> = {
+ person: { entity: 'person', entityPlural: 'people', keyColumn: 'Distinct ID column' },
+ group: { entity: 'group', entityPlural: 'groups', keyColumn: 'Group key column' },
+}
+
// Run history for one source, loaded lazily when its row is expanded.
-function PersonPropertyRuns({ sourceId }: { sourceId: string }): JSX.Element {
+function ProfilePropertyRuns({ sourceId, labels }: { sourceId: string; labels: ProfileLabels }): JSX.Element {
const { runsBySourceId, runsLoadingBySourceId } = useValues(customPropertyDefinitionsLogic)
const runs = runsBySourceId[sourceId] ?? []
@@ -47,9 +54,9 @@ function PersonPropertyRuns({ sourceId }: { sourceId: string }): JSX.Element {
},
{ title: 'Trigger', dataIndex: 'trigger' },
{ title: 'Rows produced', render: (_, run) => run.produced },
- { title: 'Affected persons', render: (_, run) => run.existing },
+ { title: `Affected ${labels.entityPlural}`, render: (_, run) => run.existing },
{
- title: 'Skipped (no person)',
+ title: `Skipped (no ${labels.entity})`,
render: (_, run) => <span className="text-secondary">{run.skipped_missing_person}</span>,
},
{
@@ -76,9 +83,10 @@ function PersonPropertyRuns({ sourceId }: { sourceId: string }): JSX.Element {
)
}
-// First-class Customer analytics view of the warehouse → person property sources: manages the person
-// mappings, shows the next scheduled sync, lets you trigger a sync or backfill, and expands to run history.
-export function WarehousePersonPropertiesSetting(): JSX.Element {
+// First-class Customer analytics view of the warehouse → person/group property sources: manages the
+// column mappings, shows the next scheduled sync, lets you trigger a sync or backfill, and expands to
+// run history. Parametrized by target so the person and group settings entries share one implementation.
+function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person' | 'group' }): JSX.Element {
const { definitions, definitionsLoading, triggeringSourceIds } = useValues(customPropertyDefinitionsLogic)
const { openCreateModal, openEditModal, deleteDefinition, triggerSync, triggerBackfill, loadRuns } =
useActions(customPropertyDefinitionsLogic)
@@ -87,12 +95,13 @@ export function WarehousePersonPropertiesSetting(): JSX.Element {
minimumAccessLevel: TeamMembershipLevel.Admin,
})
- const personDefinitions = definitions.filter((definition) => definition.target_type === 'person')
+ const labels = LABELS_BY_TARGET[targetType]
+ const profileDefinitions = definitions.filter((definition) => definition.target_type === targetType)
const confirmDelete = (definition: CustomPropertyDefinitionApi): void => {
LemonDialog.open({
title: `Delete ${definition.name}?`,
- description: `This stops syncing its warehouse columns onto people. Values already synced stay on the people, but they'll stop updating. This can't be undone.`,
+ description: `This stops syncing its warehouse columns onto ${labels.entityPlural}. Values already synced stay on the ${labels.entityPlural}, but they'll stop updating. This can't be undone.`,
primaryButton: {
children: 'Delete',
status: 'danger',
@@ -109,7 +118,7 @@ export function WarehousePersonPropertiesSetting(): JSX.Element {
render: (_, definition) => <span className="font-semibold">{definition.name}</span>,
},
{
- title: 'Distinct ID column',
+ title: labels.keyColumn,
render: (_, definition) =>
definition.source?.key_column ? (
<code>{definition.source.key_column}</code>
@@ -149,7 +158,10 @@ export function WarehousePersonPropertiesSetting(): JSX.Element {
const latestRun = definition.source.latest_run
const affected = latestRun?.status === 'completed' ? latestRun.existing : undefined
const tooltipTitle =
- [status.tooltip, affected != null ? `${affected} people affected on the last run` : null]
+ [
+ status.tooltip,
+ affected != null ? `${affected} ${labels.entityPlural} affected on the last run` : null,
+ ]
.filter(Boolean)
.join(' — ') || undefined
return (
@@ -230,26 +242,38 @@ export function WarehousePersonPropertiesSetting(): JSX.Element {
<LemonButton
type="primary"
icon={<IconPlus />}
- onClick={() => openCreateModal('person')}
+ // Lock the target: this page only manages one target, so the modal shouldn't offer
+ // the "Attach to" switch.
+ onClick={() => openCreateModal(targetType as CustomPropertyTargetType, true)}
disabledReason={restrictionReason}
>
- Add person property
+ Add {labels.entity} property
</LemonButton>
</div>
<LemonTable
columns={columns}
- dataSource={personDefinitions}
+ dataSource={profileDefinitions}
loading={definitionsLoading}
rowKey="id"
expandable={{
rowExpandable: (definition) => !!definition.source,
onRowExpand: (definition) => definition.source && loadRuns({ sourceId: definition.source.id }),
expandedRowRender: (definition) =>
- definition.source ? <PersonPropertyRuns sourceId={definition.source.id} /> : null,
+ definition.source ? (
+ <ProfilePropertyRuns sourceId={definition.source.id} labels={labels} />
+ ) : null,
}}
- emptyState="No warehouse-backed person properties yet. Add one to sync warehouse columns onto people."
+ emptyState={`No warehouse-backed ${labels.entity} properties yet. Add one to sync warehouse columns onto ${labels.entityPlural}.`}
/>
<CustomPropertyModal />
</div>
)
}
+
+export function WarehousePersonPropertiesSetting(): JSX.Element {
+ return <WarehouseProfilePropertiesSetting targetType="person" />
+}
+
+export function WarehouseGroupPropertiesSetting(): JSX.Element {
+ return <WarehouseProfilePropertiesSetting targetType="group" />
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
index db8e18269130..f8e103de38ce 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
@@ -139,7 +139,7 @@ describe('customPropertyDefinitionsLogic', () => {
sourceColumn: 'mrr',
keyColumn: 'org_id',
warehouseTable: null,
- columnMappings: [{ column: '', property: '' }],
+ columnMappings: [{ column: '', property: '', description: '' }],
isEnabled: true,
})
})
@@ -320,9 +320,9 @@ describe('customPropertyDefinitionsLogic', () => {
warehouseTable: 'table-1',
keyColumn: 'distinct_id',
columnMappings: [
- { column: 'plan', property: 'plan_tier' },
+ { column: 'plan', property: 'plan_tier', description: 'The plan tier' },
// A half-filled row is dropped rather than sent.
- { column: '', property: '' },
+ { column: '', property: '', description: '' },
],
isEnabled: true,
})
@@ -332,11 +332,13 @@ describe('customPropertyDefinitionsLogic', () => {
'submitCustomPropertyFormSuccess',
])
expect(definitionBody).toMatchObject({ name: 'Plan tier', target_type: 'person' })
- // The person source binds to the table's schema id, not the table id, with the mapped columns.
+ // The person source binds to the table's schema id, not the table id, with the mapped columns
+ // and each mapping's description keyed by warehouse column.
expect(sourceBody).toEqual({
definition: 'def-2',
external_data_schema: 'schema-1',
column_property_map: { plan: 'plan_tier' },
+ column_descriptions: { plan: 'The plan tier' },
key_column: 'distinct_id',
is_enabled: true,
})
@@ -352,13 +354,98 @@ describe('customPropertyDefinitionsLogic', () => {
targetType: 'person',
warehouseTable: 'table-1',
columnMappings: [
- { column: ' plan ', property: ' plan_tier ' },
- { column: 'seats', property: '' },
+ { column: ' plan ', property: ' plan_tier ', description: ' The plan tier ' },
+ { column: 'seats', property: '', description: 'ignored — no property' },
],
})
expect(logic.values.selectedWarehouseSchemaId).toBe('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('follows pagination so warehouse tables past the first page are reachable', async () => {
+ useMocks({
+ ...defaultMocks(),
+ get: {
+ ...defaultMocks().get,
+ [WAREHOUSE_TABLES_URL]: ({ request }) => {
+ const offset = Number(new URL(request.url).searchParams.get('offset') ?? 0)
+ if (offset === 0) {
+ // A full page (100) plus a next pointer — the loader must fetch the next page too.
+ return [
+ 200,
+ {
+ count: 101,
+ next: 'http://localhost/api/environments/1/warehouse_tables/?offset=100',
+ results: Array.from({ length: 100 }, (_, i) =>
+ buildTable({ id: `t${i}`, name: `t${i}` })
+ ),
+ },
+ ]
+ }
+ return [200, { count: 101, next: null, results: [buildTable({ id: 't100', name: 't100' })] }]
+ },
+ },
+ })
+ mountLogic()
+ await expectLogic(logic, () => logic.actions.openCreateModal()).toDispatchActions([
+ 'loadWarehouseTablesSuccess',
+ ])
+ expect(logic.values.warehouseTables).toHaveLength(101)
+ })
+
+ it('passes the search term to the backend when the picker searches', async () => {
+ let searchedFor: string | null = null
+ useMocks({
+ ...defaultMocks(),
+ get: {
+ ...defaultMocks().get,
+ [WAREHOUSE_TABLES_URL]: ({ request }) => {
+ searchedFor = new URL(request.url).searchParams.get('search')
+ return [200, { count: 1, next: null, results: [buildTable()] }]
+ },
+ },
+ })
+ mountLogic()
+ await expectLogic(logic, () => logic.actions.loadWarehouseTables({ search: 'user' })).toDispatchActions([
+ 'loadWarehouseTablesSuccess',
+ ])
+ expect(searchedFor).toBe('user')
+ })
+
+ it('locks the target type when the modal is opened from a profile settings page', async () => {
+ useMocks(defaultMocks())
+ mountLogic()
+ logic.actions.openCreateModal('group', true)
+ expect(logic.values.customPropertyForm.targetType).toBe('group')
+ expect(logic.values.targetTypeLocked).toBe(true)
+ // Opening the generic "New custom property" flow leaves the switch available again.
+ logic.actions.openCreateModal()
+ expect(logic.values.targetTypeLocked).toBe(false)
+ })
+
+ it('hydrates per-mapping descriptions when editing a person source', async () => {
+ useMocks(defaultMocks())
+ mountLogic()
+ logic.actions.openEditModal(
+ buildDefinition({
+ target_type: 'person',
+ source: buildSource({
+ saved_query: null,
+ source_column: null,
+ key_column: 'distinct_id',
+ column_property_map: { plan: 'plan_tier', seats: 'seat_count' },
+ column_descriptions: { plan: 'The plan tier' },
+ } as Partial<CustomPropertySourceApi>),
+ })
+ )
+ // Descriptions fold back in per column; a column without one gets an empty description.
+ expect(logic.values.customPropertyForm.columnMappings).toEqual([
+ { column: 'plan', property: 'plan_tier', description: 'The plan tier' },
+ { column: 'seats', property: 'seat_count', description: '' },
+ ])
})
it('warns when a person mapping targets an identity or already-existing property', async () => {
@@ -368,10 +455,10 @@ describe('customPropertyDefinitionsLogic', () => {
'loadPersonPropertyDefinitionsSuccess',
])
logic.actions.setCustomPropertyFormValue('columnMappings', [
- { column: 'a', property: 'plan_tier' }, // fine
- { column: 'b', property: 'email' }, // identity property
- { column: 'c', property: '$browser' }, // $-prefixed
- { column: 'd', property: 'existing_prop' }, // already defined on persons
+ { column: 'a', property: 'plan_tier', description: '' }, // fine
+ { column: 'b', property: 'email', description: '' }, // identity property
+ { column: 'c', property: '$browser', description: '' }, // $-prefixed
+ { column: 'd', property: 'existing_prop', description: '' }, // already defined on persons
])
const warnings = logic.values.columnMappingWarnings
expect(warnings[0]).toBeNull()
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
index 619884c11af5..c27208a06f02 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
@@ -9,6 +9,8 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'
+import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'
+import { hogql } from '~/queries/utils'
import type { DataWarehouseSavedQuery, DataWarehouseTable, PropertyDefinition } from '~/types'
import { PropertyDefinitionType } from '~/types'
@@ -43,10 +45,20 @@ const RUNS_POLL_INTERVAL_MS = 3000
const RUNS_POLL_MAX_ATTEMPTS = 20
// One warehouse-column → person-property pair in the person-target editor. Serialized to the
-// backend's `column_property_map` object ({column: property}) on save.
+// backend's `column_property_map` object ({column: property}) on save; the optional per-mapping
+// description is serialized to `column_descriptions` ({column: description}).
export interface ColumnPropertyMapping {
column: string
property: string
+ description: string
+}
+
+// A warehouse table column as offered in the pickers: its name, HogQL type (shown as a tag), and
+// canonical description (seeded into a mapping's description when the column is picked).
+export interface WarehouseColumn {
+ name: string
+ type: string
+ description: string | null
}
export interface CustomPropertyFormValues {
@@ -83,7 +95,7 @@ const DEFAULT_FORM_VALUES: CustomPropertyFormValues = {
sourceColumn: null,
keyColumn: null,
warehouseTable: null,
- columnMappings: [{ column: '', property: '' }],
+ columnMappings: [{ column: '', property: '', description: '' }],
isEnabled: true,
}
@@ -135,15 +147,19 @@ const serializeDefinition = ({
const RESERVED_PERSON_PROPERTY_NAMES = new Set(['email', 'name', 'username'])
// The backend stores column_property_map as a JSON object; the form edits it as an ordered list.
-const parseColumnPropertyMap = (value: unknown): ColumnPropertyMapping[] => {
+// Descriptions are stored in a parallel {column: description} object and folded back in per column.
+const parseColumnPropertyMap = (value: unknown, descriptions: unknown): ColumnPropertyMapping[] => {
+ const descriptionsByColumn =
+ descriptions && typeof descriptions === 'object' ? (descriptions as Record<string, unknown>) : {}
if (!value || typeof value !== 'object') {
- return [{ column: '', property: '' }]
+ return [{ column: '', property: '', description: '' }]
}
const entries = Object.entries(value as Record<string, unknown>).map(([column, property]) => ({
column,
property: String(property),
+ description: descriptionsByColumn[column] != null ? String(descriptionsByColumn[column]) : '',
}))
- return entries.length ? entries : [{ column: '', property: '' }]
+ return entries.length ? entries : [{ column: '', property: '', description: '' }]
}
const handleNameConflict = (error: unknown, setManualErrors: (errors: { name: string }) => void): boolean => {
@@ -186,11 +202,13 @@ export interface customPropertyDefinitionsLogicValues {
savedQueries: DataWarehouseSavedQuery[]
savedQueriesLoading: boolean
selectedSourceColumns: string[]
- selectedTableColumns: string[]
+ selectedTableColumns: WarehouseColumn[]
selectedTableColumnsLoading: boolean
selectedWarehouseSchemaId: string | null
+ serializedColumnDescriptions: Record<string, string>
serializedColumnPropertyMap: Record<string, string>
showCustomPropertyFormErrors: boolean
+ targetTypeLocked: boolean
triggeringSourceIds: string[]
warehouseTables: DataWarehouseTable[]
warehouseTablesLoading: boolean
@@ -299,17 +317,19 @@ export interface customPropertyDefinitionsLogicActions {
errorObject?: any
}
loadSelectedTableColumnsSuccess: (
- selectedTableColumns: string[],
+ selectedTableColumns: WarehouseColumn[],
payload?: {
tableId: string | null
}
) => {
- selectedTableColumns: string[]
+ selectedTableColumns: WarehouseColumn[]
payload?: {
tableId: string | null
}
}
- loadWarehouseTables: () => any
+ loadWarehouseTables: ({ search }?: { search?: string }) => {
+ search?: string
+ }
loadWarehouseTablesFailure: (
error: string,
errorObject?: any
@@ -319,12 +339,20 @@ export interface customPropertyDefinitionsLogicActions {
}
loadWarehouseTablesSuccess: (
warehouseTables: DataWarehouseTable[],
- payload?: any
+ payload?: {
+ search?: string
+ }
) => {
warehouseTables: DataWarehouseTable[]
- payload?: any
+ payload?: {
+ search?: string
+ }
}
- openCreateModal: (targetType?: CustomPropertyTargetType) => {
+ openCreateModal: (
+ targetType?: CustomPropertyTargetType,
+ lockTargetType?: boolean
+ ) => {
+ lockTargetType: boolean
targetType: CustomPropertyTargetType | undefined
}
openEditModal: (definition: CustomPropertyDefinitionApi) => {
@@ -402,6 +430,7 @@ export interface customPropertyDefinitionsLogicMeta {
customPropertyForm: CustomPropertyFormValues
) => string | null
serializedColumnPropertyMap: (customPropertyForm: CustomPropertyFormValues) => Record<string, string>
+ serializedColumnDescriptions: (customPropertyForm: CustomPropertyFormValues) => Record<string, string>
columnMappingWarnings: (
customPropertyForm: CustomPropertyFormValues,
personPropertyDefinitions: PropertyDefinition[]
@@ -434,9 +463,14 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
values: [projectLogic, ['currentProjectId']],
})),
actions({
- // An optional target pre-selects Account/Person (the person-properties settings entry opens
- // straight into 'person'); omitted, it falls back to the account default.
- openCreateModal: (targetType?: CustomPropertyTargetType) => ({ targetType }),
+ // An optional target pre-selects Account/Person/Group (the person- and group-properties
+ // settings entries open straight into their target); omitted, it falls back to the account
+ // default. lockTargetType hides the "Attach to" switch when the target is implied by where
+ // the modal was opened (the person/group settings pages).
+ openCreateModal: (targetType?: CustomPropertyTargetType, lockTargetType: boolean = false) => ({
+ targetType,
+ lockTargetType,
+ }),
openEditModal: (definition: CustomPropertyDefinitionApi) => ({ definition }),
closeModal: true,
setEditingDefinition: (definition: CustomPropertyDefinitionApi) => ({ definition }),
@@ -477,6 +511,16 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
closeModal: () => null,
},
],
+ // Whether the "Attach to" switch is hidden because the target is fixed by where the modal was
+ // opened (the person/group settings pages). Editing never shows the switch as a control anyway.
+ targetTypeLocked: [
+ false,
+ {
+ openCreateModal: (_, { lockTargetType }) => lockTargetType,
+ openEditModal: () => false,
+ closeModal: () => false,
+ },
+ ],
// The sources whose sync/backfill trigger is in flight, for the per-row loading/disabled guard.
// Keyed per source (not a single scalar) so a second row's trigger can't unblock the first's
// still-in-flight button.
@@ -530,24 +574,93 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
warehouseTables: [
[] as DataWarehouseTable[],
{
- loadWarehouseTables: async (): Promise<DataWarehouseTable[]> => {
- // Skip column serialization (expensive per-table HogQL work) and raise the limit off the
- // default 100 — the picker only needs names, and columns load per-table on selection.
- const response = await api.dataWarehouseTables.list({ include_columns: false, limit: 1000 })
+ loadWarehouseTables: async (
+ { search }: { search?: string } = {},
+ breakpoint
+ ): Promise<DataWarehouseTable[]> => {
+ // Debounce keystrokes from the picker's server-side search so typing doesn't fire a
+ // request per character.
+ await breakpoint(300)
+ // Skip column serialization (expensive per-table HogQL work) — the picker only needs
+ // names, and columns load per-table on selection. Search runs on the backend, and we
+ // follow pagination so more than one page of synced tables is reachable (bounded, so a
+ // broad, unsearched catalog can't pull forever).
+ const PAGE_SIZE = 100
+ const MAX_PAGES = 20
+ const collected: DataWarehouseTable[] = []
+ for (let offset = 0, page = 0; page < MAX_PAGES; page += 1, offset += PAGE_SIZE) {
+ const response = await api.dataWarehouseTables.list({
+ include_columns: false,
+ limit: PAGE_SIZE,
+ offset,
+ ...(search ? { search } : {}),
+ })
+ breakpoint()
+ collected.push(...response.results)
+ if (!response.next || response.results.length < PAGE_SIZE) {
+ break
+ }
+ }
// Only synced tables carry an external_schema, which is what a person source binds to.
- return response.results.filter((table) => !!table.external_schema)
+ 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
+ if (selectedId && !synced.some((table) => table.id === selectedId)) {
+ const selected = values.warehouseTables.find((table) => table.id === selectedId)
+ if (selected) {
+ return [selected, ...synced]
+ }
+ }
+ return synced
},
},
],
selectedTableColumns: [
- [] as string[],
+ [] as WarehouseColumn[],
{
- loadSelectedTableColumns: async ({ tableId }: { tableId: string | null }): Promise<string[]> => {
+ loadSelectedTableColumns: async ({
+ tableId,
+ }: {
+ tableId: string | null
+ }): Promise<WarehouseColumn[]> => {
if (!tableId) {
return []
}
const table = await api.dataWarehouseTables.get(tableId)
- return (table.columns ?? []).map((column) => column.name)
+ const columns: WarehouseColumn[] = (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.
+ try {
+ const tableName = table.hogql_name || table.name
+ const response = (await api.query({
+ kind: NodeKind.HogQLQuery,
+ query: hogql`
+ select column_name, description
+ from information_schema.columns
+ where 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 | null
+ const description = row[1] as string | null
+ if (name && description) {
+ descriptionByColumn.set(name, description)
+ }
+ }
+ return columns.map((column) => ({
+ ...column,
+ description: descriptionByColumn.get(column.name) ?? null,
+ }))
+ } catch {
+ return columns
+ }
},
},
],
@@ -661,6 +774,7 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
definition: definition.id,
external_data_schema: schemaId,
column_property_map: values.serializedColumnPropertyMap,
+ column_descriptions: values.serializedColumnDescriptions,
key_column: keyColumn.trim(),
is_enabled: isEnabled,
})
@@ -720,6 +834,19 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
.map((mapping) => [mapping.column.trim(), mapping.property.trim()])
),
],
+ // The per-mapping descriptions as the backend's `column_descriptions` object ({column:
+ // description}), only for complete mappings that carry a non-empty description.
+ serializedColumnDescriptions: [
+ (s) => [s.customPropertyForm],
+ (form: CustomPropertyFormValues): Record<string, string> =>
+ Object.fromEntries(
+ form.columnMappings
+ .filter(
+ (mapping) => mapping.column.trim() && mapping.property.trim() && mapping.description.trim()
+ )
+ .map((mapping) => [mapping.column.trim(), mapping.description.trim()])
+ ),
+ ],
// Warn-only collision check per mapping: a chosen person-property name that is `$`-prefixed,
// an identity property, or already defined on persons could overwrite existing values.
columnMappingWarnings: [
@@ -796,8 +923,11 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
// (read-only in the modal) rather than resolving the table back for the picker.
warehouseTable: null,
columnMappings: isProfile
- ? parseColumnPropertyMap(definition.source?.column_property_map)
- : [{ column: '', property: '' }],
+ ? parseColumnPropertyMap(
+ definition.source?.column_property_map,
+ definition.source?.column_descriptions
+ )
+ : [{ column: '', property: '', description: '' }],
isEnabled: definition.source?.is_enabled ?? true,
})
},
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.py
index 8e7e5d1f01ff..8581761a30fc 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
@@ -149,13 +149,15 @@ class PersonPropertySyncSource:
the sync job (owned by warehouse_sources) never imports the customer_analytics config models.
``source_id``/``definition_id`` identify the source for provenance stamping; ``key_column`` holds
the identifier (a person's distinct_id, or a group's key) and ``column_property_map`` maps
- warehouse column -> property name. ``target`` is "person" or "group"; ``group_type_index`` is the
+ warehouse column -> property name. ``property_descriptions`` maps property name -> description
+ (only the properties given one). ``target`` is "person" or "group"; ``group_type_index`` is the
group type (0-4) for group targets, else None."""
source_id: str
definition_id: str
key_column: str
column_property_map: dict[str, str]
+ property_descriptions: dict[str, str] = dataclasses.field(default_factory=dict)
target: str = "person"
group_type_index: int | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py
index 3311ae56e118..e097d25433f5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync.py
@@ -362,13 +362,22 @@ def _stamp_provenance(
"schema_id": str(schema_id),
"custom_property_source_id": str(source.source_id),
}
- query = PropertyDefinition.objects.filter(team_id=team_id, name__in=property_names)
+ query = 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.
query = query.filter(type=PropertyDefinition.Type.GROUP, group_type_index=source.group_type_index)
else:
query = query.filter(type=PropertyDefinition.Type.PERSON)
- query.update(warehouse_origin=origin)
+
+ # Properties given a description carry it inside their provenance, so stamp those one at a time;
+ # the rest share the base origin and go in a single bulk update.
+ descriptions = source.property_descriptions or {}
+ described = [name for name in property_names if descriptions.get(name)]
+ plain = [name for name in property_names if not descriptions.get(name)]
+ if plain:
+ query.filter(name__in=plain).update(warehouse_origin=origin)
+ for name in described:
+ query.filter(name=name).update(warehouse_origin={**origin, "description": descriptions[name]})
# --- orchestration -----------------------------------------------------------------------
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py
index 672bf6be96bc..925471e9af56 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/person_property_sync_test.py
@@ -5,6 +5,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
from parameterized import parameterized
+from 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.pipelines.pipeline import person_property_sync as pps
@@ -375,3 +377,54 @@ class TestGroupTarget:
stamp.assert_not_called()
write_snapshot.assert_not_awaited()
assert result.produced == 0
+
+
+class TestStampProvenance:
+ """`_stamp_provenance` updates existing property definitions with warehouse provenance, folding a
+ per-property description into the origin when the source carries one."""
+
+ def _team(self):
+ org = Organization.objects.create(name="o")
+ return Team.objects.create(organization=org, name="t")
+
+ def test_folds_descriptions_into_provenance_only_where_present(self):
+ team = self._team()
+ PropertyDefinition.objects.create(team=team, name="plan_tier", type=PropertyDefinition.Type.PERSON)
+ PropertyDefinition.objects.create(team=team, name="seat_count", type=PropertyDefinition.Type.PERSON)
+ source = PersonPropertySyncSource(
+ "s1",
+ "d1",
+ "distinct_id",
+ {"plan": "plan_tier", "seats": "seat_count"},
+ property_descriptions={"plan_tier": "The plan tier"},
+ )
+
+ pps._stamp_provenance(team.id, "schema-1", source, ["plan_tier", "seat_count"])
+
+ described = PropertyDefinition.objects.get(team=team, name="plan_tier")
+ plain = PropertyDefinition.objects.get(team=team, name="seat_count")
+ assert described.warehouse_origin is not None
+ assert plain.warehouse_origin is not None
+ assert described.warehouse_origin["custom_property_source_id"] == "s1"
+ assert described.warehouse_origin["description"] == "The plan tier"
+ # A property without a configured description carries provenance but no description key.
+ assert plain.warehouse_origin["custom_property_source_id"] == "s1"
+ assert "description" not in plain.warehouse_origin
+
+ def test_group_target_stamps_only_matching_group_type(self):
+ team = self._team()
+ PropertyDefinition.objects.create(
+ team=team, name="tier", type=PropertyDefinition.Type.GROUP, group_type_index=0
+ )
+ other = PropertyDefinition.objects.create(
+ team=team, name="tier", type=PropertyDefinition.Type.GROUP, group_type_index=1
+ )
+ source = PersonPropertySyncSource("s1", "d1", "group_key", {"plan": "tier"}, target="group", group_type_index=0)
+
+ pps._stamp_provenance(team.id, "schema-1", source, ["tier"])
+
+ assert PropertyDefinition.objects.get(id=other.id).warehouse_origin is None
+ stamped = PropertyDefinition.objects.get(team=team, name="tier", group_type_index=0)
+ assert stamped.warehouse_origin is not None
+ assert stamped.warehouse_origin["custom_property_source_id"] == "s1"
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 739389076c67..dcf185f2ff16 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16165,6 +16165,8 @@ 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. */
+ 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.
* @maxLength 400
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index 67eec7373921..8294f42bff6b 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -689,6 +689,12 @@ export const CustomPropertySourcesCreateBody = /* @__PURE__ */ zod
.describe(
'Person and group sources only: {warehouse_column: property_name} mapping the columns this source writes onto the person or group.'
),
+ column_descriptions: 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."
+ ),
key_column: zod
.string()
.max(customPropertySourcesCreateBodyKeyColumnMax)
diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.ts
index f0de9e101c00..021b938a0de3 100644
--- a/services/mcp/src/tools/generated/customer_analytics.ts
+++ b/services/mcp/src/tools/generated/customer_analytics.ts
@@ -693,6 +693,9 @@ const customPropertySourcesCreate = (): ToolBase<
if (params.column_property_map !== undefined) {
body['column_property_map'] = params.column_property_map
}
+ if (params.column_descriptions !== undefined) {
+ body['column_descriptions'] = params.column_descriptions
+ }
if (params.key_column !== undefined) {
body['key_column'] = params.key_column
}