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): person-target custom property editor (#70090)

Tom Owers9d50f4d043d2
diff --git a/ee/api/ee_property_definition.py b/ee/api/ee_property_definition.py
index 083196f3ad73..c128e62aa80c 100644
--- a/ee/api/ee_property_definition.py
+++ b/ee/api/ee_property_definition.py
@@ -15,6 +15,13 @@ class EnterprisePropertyDefinitionSerializer(TaggedItemSerializerMixin, serializ
updated_by = UserBasicSerializer(read_only=True)
verified_by = UserBasicSerializer(read_only=True)
is_seen_on_filtered_events = serializers.BooleanField(allow_null=True, read_only=True)
+ warehouse_origin = serializers.JSONField(
+ read_only=True,
+ help_text=(
+ "Provenance for a person property populated from a data warehouse source "
+ "(source/table/column/last synced), or null. Read-only."
+ ),
+ )
class Meta:
model = EnterprisePropertyDefinition
@@ -32,6 +39,7 @@ class EnterprisePropertyDefinitionSerializer(TaggedItemSerializerMixin, serializ
"verified_at",
"verified_by",
"hidden",
+ "warehouse_origin",
)
read_only_fields = [
"id",
@@ -40,6 +48,7 @@ class EnterprisePropertyDefinitionSerializer(TaggedItemSerializerMixin, serializ
"is_seen_on_filtered_events",
"verified_at",
"verified_by",
+ "warehouse_origin",
]
def validate(self, data):
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 12060f880663..4a6ebe54c419 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -3123,6 +3123,8 @@ export interface EnterprisePropertyDefinitionApi {
readonly verified_by: UserBasicApi
/** @nullable */
hidden?: boolean | null
+ /** Provenance for a person property populated from a data warehouse source (source/table/column/last synced), or null. Read-only. */
+ readonly warehouse_origin: unknown
}
export interface PaginatedEnterprisePropertyDefinitionListApi {
@@ -3155,6 +3157,8 @@ export interface PatchedEnterprisePropertyDefinitionApi {
readonly verified_by?: UserBasicApi
/** @nullable */
hidden?: boolean | null
+ /** Provenance for a person property populated from a data warehouse source (source/table/column/last synced), or null. Read-only. */
+ readonly warehouse_origin?: unknown
}
/**
diff --git a/frontend/src/scenes/data-management/properties/PropertyDefinitionsTable.tsx b/frontend/src/scenes/data-management/properties/PropertyDefinitionsTable.tsx
index 8e8bafdc139c..f1de63d3f31e 100644
--- a/frontend/src/scenes/data-management/properties/PropertyDefinitionsTable.tsx
+++ b/frontend/src/scenes/data-management/properties/PropertyDefinitionsTable.tsx
@@ -2,7 +2,7 @@ import './PropertyDefinitionsTable.scss'
import { useActions, useValues } from 'kea'
-import { LemonInput, LemonSelect, LemonTag, Link } from '@posthog/lemon-ui'
+import { LemonInput, LemonSelect, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
@@ -39,11 +39,28 @@ export function PropertyDefinitionsTable(): JSX.Element {
key: 'name',
render: function Render(_, definition: PropertyDefinition) {
return (
- <DefinitionHeader
- definition={definition}
- to={urls.propertyDefinition(definition.id)}
- taxonomicGroupType={TaxonomicFilterGroupType.EventProperties}
- />
+ <div className="flex items-center gap-2">
+ <DefinitionHeader
+ definition={definition}
+ to={urls.propertyDefinition(definition.id)}
+ taxonomicGroupType={TaxonomicFilterGroupType.EventProperties}
+ />
+ {definition.warehouse_origin && (
+ <Tooltip
+ title={`Populated from data warehouse${
+ definition.warehouse_origin.table_name
+ ? ` table ${definition.warehouse_origin.table_name}`
+ : ''
+ }${
+ definition.warehouse_origin.last_synced_at
+ ? ` (last synced ${definition.warehouse_origin.last_synced_at})`
+ : ''
+ }`}
+ >
+ <LemonTag type="completion">Warehouse</LemonTag>
+ </Tooltip>
+ )}
+ </div>
)
},
sorter: (a, b) => a.name.localeCompare(b.name),
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index a4f61ebdeb06..166cca568eaf 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4729,6 +4729,17 @@ export interface PropertyDefinition {
verified_by?: string
hidden?: boolean
virtual?: boolean
+ // Provenance when a person property is populated from a data warehouse source. Read-only.
+ warehouse_origin?: WarehousePropertyOrigin | null
+}
+
+export interface WarehousePropertyOrigin {
+ source_id?: string
+ schema_id?: string
+ table_name?: string
+ column?: string
+ custom_property_source_id?: string
+ last_synced_at?: string
}
export enum PropertyDefinitionState {
diff --git a/posthog/api/test/test_property_definition.py b/posthog/api/test/test_property_definition.py
index 568d267249ee..041e47afa7bf 100644
--- a/posthog/api/test/test_property_definition.py
+++ b/posthog/api/test/test_property_definition.py
@@ -68,6 +68,18 @@ class TestPropertyDefinitionAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["property_type"] == "DateTime"
+ def test_warehouse_origin_provenance_is_exposed(self):
+ origin = {"source_id": "s1", "table_name": "github.issues", "column": "plan_tier"}
+ property = PropertyDefinition.objects.create(
+ team=self.team,
+ name="plan_tier",
+ type=PropertyDefinition.Type.PERSON,
+ warehouse_origin=origin,
+ )
+ response = self.client.get(f"/api/projects/{self.team.pk}/property_definitions/{property.id}")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["warehouse_origin"] == origin
+
def test_retrieve_with_non_uuid_id_returns_404(self):
# Links built without a saved definition id (e.g. pinned defaults) request
# `.../property_definitions/undefined` — that must 404, not 500 with a UUID ValueError.
diff --git a/posthog/taxonomy/property_definition_api.py b/posthog/taxonomy/property_definition_api.py
index 0a82b8cad18a..a8885e95b4df 100644
--- a/posthog/taxonomy/property_definition_api.py
+++ b/posthog/taxonomy/property_definition_api.py
@@ -479,6 +479,14 @@ ALWAYS_EXCLUDED_EVENT_PROPERTIES = set(
class PropertyDefinitionSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
+ warehouse_origin = serializers.JSONField(
+ read_only=True,
+ help_text=(
+ "Provenance for a person property populated from a data warehouse source "
+ "(source/table/column/last synced), or null. Read-only."
+ ),
+ )
+
class Meta:
model = PropertyDefinition
fields = (
@@ -489,6 +497,7 @@ class PropertyDefinitionSerializer(TaggedItemSerializerMixin, serializers.ModelS
"tags",
# This is a calculated property, set when property has been seen with the provided `event_names` query param events. NULL if no `event_names` provided
"is_seen_on_filtered_events",
+ "warehouse_origin",
)
def validate(self, data):
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
index 549e99341b52..c6cdc4e49497 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
@@ -24,7 +24,11 @@ import { urls } from 'scenes/urls'
import type { CustomPropertyOptionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
-import { CustomPropertySourceMode, customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'
+import {
+ CustomPropertySourceMode,
+ CustomPropertyTargetType,
+ customPropertyDefinitionsLogic,
+} from './customPropertyDefinitionsLogic'
import {
DISPLAY_TYPE_OPTIONS,
NEW_OPTION_ID_PREFIX,
@@ -38,6 +42,126 @@ const SOURCE_MODE_OPTIONS: { value: CustomPropertySourceMode; label: string }[]
{ value: 'workflow', label: 'Workflow' },
]
+const TARGET_TYPE_OPTIONS: { value: CustomPropertyTargetType; label: string }[] = [
+ { value: 'account', label: 'Account' },
+ { value: 'person', label: 'Person' },
+]
+
+// Person-target editor: pick a synced warehouse table, the distinct_id column, and the
+// column → person-property mappings. The binding + mappings are create-only on the backend, so
+// they're read-only once a source exists (only the key column + enabled switch stay editable).
+function PersonSourceEditor(): JSX.Element {
+ const { customPropertyForm, warehouseTables, warehouseTablesLoading, editingDefinition, columnMappingWarnings } =
+ useValues(customPropertyDefinitionsLogic)
+ const { setCustomPropertyFormValue } = useActions(customPropertyDefinitionsLogic)
+
+ const hasExistingSource = !!editingDefinition?.source
+ const noTables = !warehouseTablesLoading && warehouseTables.length === 0
+ const mappings = customPropertyForm.columnMappings
+ const setMappings = (next: typeof mappings): void => setCustomPropertyFormValue('columnMappings', next)
+
+ // 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) {
+ 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.
+ </LemonBanner>
+ )
+ }
+
+ return (
+ <>
+ {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 distinct ID column and toggle syncing.
+ </LemonBanner>
+ ) : (
+ <LemonField
+ name="warehouseTable"
+ label="Warehouse table"
+ help="Rows from this synced table are upserted onto matching people."
+ >
+ {({ value, onChange }) => (
+ <LemonSearchableSelect
+ value={value}
+ onChange={onChange}
+ options={warehouseTables.map((table) => ({ value: table.id, label: table.name }))}
+ loading={warehouseTablesLoading}
+ placeholder="Select a warehouse table"
+ fullWidth
+ />
+ )}
+ </LemonField>
+ )}
+ <LemonField
+ name="keyColumn"
+ label="Distinct ID column"
+ help="The column holding each row's distinct ID — used to match the person to update."
+ >
+ <LemonInput placeholder="e.g. distinct_id" fullWidth />
+ </LemonField>
+ {!hasExistingSource && (
+ <div className="flex flex-col gap-2">
+ <LemonLabel>Column mappings</LemonLabel>
+ <span className="text-secondary text-xs">
+ Map each warehouse column to the person property name it should set.
+ </span>
+ {mappings.map((mapping, index) => (
+ <div key={index} className="flex flex-col gap-1">
+ <div className="flex items-center gap-2">
+ <LemonInput
+ value={mapping.column}
+ onChange={(column) =>
+ setMappings(mappings.map((m, i) => (i === index ? { ...m, column } : m)))
+ }
+ placeholder="Warehouse column"
+ fullWidth
+ />
+ <span className="text-secondary">→</span>
+ <LemonInput
+ value={mapping.property}
+ onChange={(property) =>
+ setMappings(mappings.map((m, i) => (i === index ? { ...m, property } : m)))
+ }
+ placeholder="Person property"
+ fullWidth
+ />
+ <LemonButton
+ icon={<IconTrash />}
+ size="small"
+ tooltip="Remove mapping"
+ disabledReason={
+ mappings.length === 1 ? 'At least one mapping is required' : undefined
+ }
+ onClick={() => setMappings(mappings.filter((_, i) => i !== index))}
+ />
+ </div>
+ {columnMappingWarnings[index] && (
+ <span className="text-warning text-xs">{columnMappingWarnings[index]}</span>
+ )}
+ </div>
+ ))}
+ <LemonButton
+ type="secondary"
+ icon={<IconPlus />}
+ onClick={() => setMappings([...mappings, { column: '', property: '' }])}
+ >
+ Add mapping
+ </LemonButton>
+ </div>
+ )}
+ <LemonField name="isEnabled">
+ {({ value, onChange }) => (
+ <LemonSwitch checked={value} onChange={onChange} label="Sync enabled" bordered />
+ )}
+ </LemonField>
+ </>
+ )
+}
+
function CustomPropertyOptionsEditor(): JSX.Element {
const { customPropertyForm } = useValues(customPropertyDefinitionsLogic)
const { setCustomPropertyFormValue } = useActions(customPropertyDefinitionsLogic)
@@ -121,7 +245,7 @@ export function CustomPropertyModal(): JSX.Element {
} = useActions(customPropertyDefinitionsLogic)
const showBigNumberSwitch = isNumericDisplayType(customPropertyForm.displayType)
- const { sourceMode } = customPropertyForm
+ const { sourceMode, targetType } = customPropertyForm
const hasExistingSource = !!editingDefinition?.source
const noViews = !savedQueriesLoading && materializedViews.length === 0
@@ -138,14 +262,23 @@ export function CustomPropertyModal(): JSX.Element {
: option
)
+ // A new person source needs at least one complete column → property pair. The mapping rows
+ // aren't LemonFields, so this gates the submit button rather than showing a per-field error.
+ const missingPersonMapping =
+ targetType === 'person' &&
+ !hasExistingSource &&
+ !customPropertyForm.columnMappings.some((mapping) => mapping.column.trim() && mapping.property.trim())
+
const submitDisabledReason =
customPropertyForm.displayType === 'select' && customPropertyForm.options.length === 0
? 'Add at least one option'
- : sourceMode === 'data_warehouse' && noViews
- ? 'No materialized views are available'
- : sourceMode === 'workflow' && editingReferences.length === 0
- ? 'Create a workflow that updates this property first'
- : undefined
+ : missingPersonMapping
+ ? 'Map at least one column to a property'
+ : sourceMode === 'data_warehouse' && noViews
+ ? 'No materialized views are available'
+ : sourceMode === 'workflow' && editingReferences.length === 0
+ ? 'Create a workflow that updates this property first'
+ : undefined
return (
<LemonModal
@@ -180,6 +313,25 @@ export function CustomPropertyModal(): JSX.Element {
<LemonField name="description" label="Description">
<LemonTextArea placeholder="Optional description" minRows={2} />
</LemonField>
+ <LemonField
+ name="targetType"
+ label="Attach to"
+ help="Account properties describe a customer; person properties attach to individual people and are usable in feature flags, cohorts and insights."
+ >
+ {({ value, onChange }) => (
+ <LemonSegmentedButton
+ value={value}
+ onChange={onChange}
+ options={TARGET_TYPE_OPTIONS.map((option) => ({
+ ...option,
+ disabledReason: editingDefinition
+ ? "A property's target can't change after it's created"
+ : undefined,
+ }))}
+ fullWidth
+ />
+ )}
+ </LemonField>
<LemonField name="displayType" label="Type">
<LemonSelect options={DISPLAY_TYPE_OPTIONS} fullWidth />
</LemonField>
@@ -196,150 +348,167 @@ export function CustomPropertyModal(): JSX.Element {
</LemonField>
)}
{customPropertyForm.displayType === 'select' && <CustomPropertyOptionsEditor />}
- <LemonField name="sourceMode" label="Source">
- {({ value, onChange }) => (
- <LemonSegmentedButton value={value} onChange={onChange} options={sourceModeOptions} fullWidth />
- )}
- </LemonField>
- {hasExistingSource && sourceMode !== 'data_warehouse' && (
- <LemonBanner type="warning">
- Saving will remove this property's data warehouse sync. Values already synced will stay, but
- they'll stop updating automatically.
- </LemonBanner>
- )}
- {sourceMode === 'data_warehouse' &&
- (noViews ? (
- <LemonBanner type="info">
- No materialized views found. Create and materialize a view in the data warehouse first, then
- it can feed this property.
- </LemonBanner>
- ) : (
- <>
- <LemonField
- name="savedQuery"
- label="View"
- help="Values are pulled from this materialized view on each materialization, matched to accounts by external ID."
- >
- {({ value, onChange }) => (
- <LemonSearchableSelect
- value={value}
- onChange={(newValue) => {
- onChange(newValue)
- // Columns are view-specific, so a view change invalidates the picks.
- setCustomPropertyFormValue('sourceColumn', null)
- setCustomPropertyFormValue('keyColumn', null)
- }}
- options={materializedViews.map((view) => ({
- value: view.id,
- label: view.name,
- }))}
- loading={savedQueriesLoading}
- disabledReason={
- hasExistingSource ? 'The view is fixed once a sync is created' : undefined
- }
- placeholder="Select a materialized view"
- fullWidth
- />
- )}
- </LemonField>
- <LemonField
- name="sourceColumn"
- label="Value column"
- help="The column whose value is written to this property."
- >
- {({ value, onChange }) => (
- <LemonSearchableSelect
- value={value}
- onChange={onChange}
- options={selectedSourceColumns.map((column) => ({
- value: column,
- label: column,
- }))}
- loading={savedQueriesLoading}
- disabledReason={
- !customPropertyForm.savedQuery ? 'Select a view first' : undefined
- }
- placeholder="Column to read the value from"
- fullWidth
- />
- )}
- </LemonField>
- <LemonField
- name="keyColumn"
- label="Key column"
- help="The column matched against each account's external ID."
- >
- {({ value, onChange }) => (
- <LemonSearchableSelect
- value={value}
- onChange={onChange}
- options={selectedSourceColumns.map((column) => ({
- value: column,
- label: column,
- }))}
- loading={savedQueriesLoading}
- disabledReason={
- !customPropertyForm.savedQuery ? 'Select a view first' : undefined
- }
- placeholder="Column matching the account external ID"
- fullWidth
- />
- )}
- </LemonField>
- <LemonField name="isEnabled">
- {({ value, onChange }) => (
- <LemonSwitch checked={value} onChange={onChange} label="Sync enabled" bordered />
- )}
- </LemonField>
- </>
- ))}
- {sourceMode === 'workflow' && (
- <div className="flex flex-col gap-2">
- <div className="flex items-center justify-between">
- <span className="font-semibold">Workflows updating this property</span>
- <LemonButton
- size="small"
- icon={<IconRefresh />}
- tooltip="Refresh"
- onClick={loadDefinitions}
- loading={definitionsLoading}
- />
- </div>
- {editingReferences.length > 0 ? (
- <div className="flex flex-col gap-1">
- {editingReferences.map((reference) => (
- <div
- key={reference.id}
- className="flex items-center justify-between gap-2 border rounded p-2"
+ {targetType === 'person' && <PersonSourceEditor />}
+ {targetType === 'account' && (
+ <>
+ <LemonField name="sourceMode" label="Source">
+ {({ value, onChange }) => (
+ <LemonSegmentedButton
+ value={value}
+ onChange={onChange}
+ options={sourceModeOptions}
+ fullWidth
+ />
+ )}
+ </LemonField>
+ {hasExistingSource && sourceMode !== 'data_warehouse' && (
+ <LemonBanner type="warning">
+ Saving will remove this property's data warehouse sync. Values already synced will stay,
+ but they'll stop updating automatically.
+ </LemonBanner>
+ )}
+ {sourceMode === 'data_warehouse' &&
+ (noViews ? (
+ <LemonBanner type="info">
+ No materialized views found. Create and materialize a view in the data warehouse
+ first, then it can feed this property.
+ </LemonBanner>
+ ) : (
+ <>
+ <LemonField
+ name="savedQuery"
+ label="View"
+ help="Values are pulled from this materialized view on each materialization, matched to accounts by external ID."
+ >
+ {({ value, onChange }) => (
+ <LemonSearchableSelect
+ value={value}
+ onChange={(newValue) => {
+ onChange(newValue)
+ // Columns are view-specific, so a view change invalidates the picks.
+ setCustomPropertyFormValue('sourceColumn', null)
+ setCustomPropertyFormValue('keyColumn', null)
+ }}
+ options={materializedViews.map((view) => ({
+ value: view.id,
+ label: view.name,
+ }))}
+ loading={savedQueriesLoading}
+ disabledReason={
+ hasExistingSource
+ ? 'The view is fixed once a sync is created'
+ : undefined
+ }
+ placeholder="Select a materialized view"
+ fullWidth
+ />
+ )}
+ </LemonField>
+ <LemonField
+ name="sourceColumn"
+ label="Value column"
+ help="The column whose value is written to this property."
+ >
+ {({ value, onChange }) => (
+ <LemonSearchableSelect
+ value={value}
+ onChange={onChange}
+ options={selectedSourceColumns.map((column) => ({
+ value: column,
+ label: column,
+ }))}
+ loading={savedQueriesLoading}
+ disabledReason={
+ !customPropertyForm.savedQuery ? 'Select a view first' : undefined
+ }
+ placeholder="Column to read the value from"
+ fullWidth
+ />
+ )}
+ </LemonField>
+ <LemonField
+ name="keyColumn"
+ label="Key column"
+ help="The column matched against each account's external ID."
>
- <Link
- to={urls.workflow(reference.id, 'workflow')}
- target="_blank"
- targetBlankIcon
+ {({ value, onChange }) => (
+ <LemonSearchableSelect
+ value={value}
+ onChange={onChange}
+ options={selectedSourceColumns.map((column) => ({
+ value: column,
+ label: column,
+ }))}
+ loading={savedQueriesLoading}
+ disabledReason={
+ !customPropertyForm.savedQuery ? 'Select a view first' : undefined
+ }
+ placeholder="Column matching the account external ID"
+ fullWidth
+ />
+ )}
+ </LemonField>
+ <LemonField name="isEnabled">
+ {({ value, onChange }) => (
+ <LemonSwitch
+ checked={value}
+ onChange={onChange}
+ label="Sync enabled"
+ bordered
+ />
+ )}
+ </LemonField>
+ </>
+ ))}
+ {sourceMode === 'workflow' && (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <span className="font-semibold">Workflows updating this property</span>
+ <LemonButton
+ size="small"
+ icon={<IconRefresh />}
+ tooltip="Refresh"
+ onClick={loadDefinitions}
+ loading={definitionsLoading}
+ />
+ </div>
+ {editingReferences.length > 0 ? (
+ <div className="flex flex-col gap-1">
+ {editingReferences.map((reference) => (
+ <div
+ key={reference.id}
+ className="flex items-center justify-between gap-2 border rounded p-2"
+ >
+ <Link
+ to={urls.workflow(reference.id, 'workflow')}
+ target="_blank"
+ targetBlankIcon
+ >
+ {reference.name}
+ </Link>
+ <LemonTag>{reference.status}</LemonTag>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="border rounded p-4 flex flex-col items-center gap-2 text-center">
+ <span className="text-secondary">
+ No workflows update this property yet. Create one with an "Update account
+ property" action that sets this property — the editor opens in a new tab.
+ Once you save the workflow there, refresh this list.
+ </span>
+ <LemonButton
+ type="primary"
+ onClick={createWorkflowForProperty}
+ loading={newWorkflowUrlLoading}
>
- {reference.name}
- </Link>
- <LemonTag>{reference.status}</LemonTag>
+ Create workflow
+ </LemonButton>
</div>
- ))}
- </div>
- ) : (
- <div className="border rounded p-4 flex flex-col items-center gap-2 text-center">
- <span className="text-secondary">
- No workflows update this property yet. Create one with an "Update account property"
- action that sets this property — the editor opens in a new tab. Once you save the
- workflow there, refresh this list.
- </span>
- <LemonButton
- type="primary"
- onClick={createWorkflowForProperty}
- loading={newWorkflowUrlLoading}
- >
- Create workflow
- </LemonButton>
+ )}
</div>
)}
- </div>
+ </>
)}
</Form>
</LemonModal>
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
index 0d927cc03c1a..6adfa57dfc77 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
@@ -18,8 +18,18 @@ import { customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic
const DEFINITIONS_URL = '/api/projects/:team_id/custom_property_definitions/'
const DEFINITION_URL = '/api/projects/:team_id/custom_property_definitions/:id/'
const SAVED_QUERIES_URL = '/api/environments/:team_id/warehouse_saved_queries/'
+const WAREHOUSE_TABLES_URL = '/api/environments/:team_id/warehouse_tables/'
const SOURCES_URL = '/api/projects/:team_id/custom_property_sources/'
const SOURCE_URL = '/api/projects/:team_id/custom_property_sources/:id/'
+const PROPERTY_DEFINITIONS_URL = '/api/projects/:team_id/property_definitions/'
+
+// Loosely-typed warehouse table — the logic only reads id/name/external_schema.id.
+const buildTable = (overrides: Record<string, any> = {}): any => ({
+ id: 'table-1',
+ name: 'users',
+ external_schema: { id: 'schema-1', name: 'users' },
+ ...overrides,
+})
const buildSource = (overrides: Partial<CustomPropertySourceApi> = {}): CustomPropertySourceApi =>
({
@@ -66,6 +76,8 @@ const defaultMocks = (): Parameters<typeof useMocks>[0] => ({
get: {
[DEFINITIONS_URL]: { count: 1, results: [buildDefinition()] },
[SAVED_QUERIES_URL]: { count: 1, results: [buildView()] },
+ [WAREHOUSE_TABLES_URL]: { count: 1, results: [buildTable()] },
+ [PROPERTY_DEFINITIONS_URL]: { count: 1, results: [{ id: 'p1', name: 'existing_prop' }] },
},
post: {
[DEFINITIONS_URL]: buildDefinition({ id: 'def-2' }),
@@ -120,10 +132,13 @@ describe('customPropertyDefinitionsLogic', () => {
displayType: 'currency',
isBigNumber: true,
options: [],
+ targetType: 'account',
sourceMode: 'data_warehouse',
savedQuery: 'view-1',
sourceColumn: 'mrr',
keyColumn: 'org_id',
+ warehouseTable: null,
+ columnMappings: [{ column: '', property: '' }],
isEnabled: true,
})
})
@@ -277,6 +292,93 @@ describe('customPropertyDefinitionsLogic', () => {
})
})
+ it('creates a person-target definition and binds it to a warehouse schema', async () => {
+ let definitionBody: Record<string, any> | null = null
+ let sourceBody: Record<string, any> | null = null
+ useMocks({
+ ...defaultMocks(),
+ post: {
+ ...defaultMocks().post,
+ [DEFINITIONS_URL]: async ({ request }) => {
+ definitionBody = (await request.json()) as Record<string, any>
+ return buildDefinition({ id: 'def-2', target_type: 'person' })
+ },
+ [SOURCES_URL]: async ({ request }) => {
+ sourceBody = (await request.json()) as Record<string, any>
+ return buildSource()
+ },
+ },
+ })
+ mountLogic()
+ await expectLogic(logic, () => logic.actions.openCreateModal()).toDispatchActions([
+ 'loadWarehouseTablesSuccess',
+ ])
+ logic.actions.setCustomPropertyFormValues({
+ name: 'Plan tier',
+ targetType: 'person',
+ warehouseTable: 'table-1',
+ keyColumn: 'distinct_id',
+ columnMappings: [
+ { column: 'plan', property: 'plan_tier' },
+ // A half-filled row is dropped rather than sent.
+ { column: '', property: '' },
+ ],
+ isEnabled: true,
+ })
+
+ await expectLogic(logic, () => logic.actions.submitCustomPropertyForm()).toDispatchActions([
+ 'setEditingDefinition',
+ '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.
+ expect(sourceBody).toEqual({
+ definition: 'def-2',
+ external_data_schema: 'schema-1',
+ column_property_map: { plan: 'plan_tier' },
+ key_column: 'distinct_id',
+ is_enabled: true,
+ })
+ })
+
+ it('resolves the selected table schema id and serialized column map for the person source', async () => {
+ useMocks(defaultMocks())
+ mountLogic()
+ await expectLogic(logic, () => logic.actions.openCreateModal()).toDispatchActions([
+ 'loadWarehouseTablesSuccess',
+ ])
+ logic.actions.setCustomPropertyFormValues({
+ targetType: 'person',
+ warehouseTable: 'table-1',
+ columnMappings: [
+ { column: ' plan ', property: ' plan_tier ' },
+ { column: 'seats', property: '' },
+ ],
+ })
+ expect(logic.values.selectedWarehouseSchemaId).toBe('schema-1')
+ // Trims and drops incomplete pairs.
+ expect(logic.values.serializedColumnPropertyMap).toEqual({ plan: 'plan_tier' })
+ })
+
+ it('warns when a person mapping targets an identity or already-existing property', async () => {
+ useMocks(defaultMocks())
+ mountLogic()
+ await expectLogic(logic, () => logic.actions.openCreateModal()).toDispatchActions([
+ '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
+ ])
+ const warnings = logic.values.columnMappingWarnings
+ expect(warnings[0]).toBeNull()
+ expect(warnings[1]).toContain('identity property')
+ expect(warnings[2]).toContain('identity property')
+ expect(warnings[3]).toContain('already exists')
+ })
+
it('updates an existing source via PATCH without the create-only fields', async () => {
let patchedBody: Record<string, any> | null = null
useMocks({
@@ -299,6 +401,41 @@ describe('customPropertyDefinitionsLogic', () => {
expect(patchedBody).toEqual({ source_column: 'mrr', key_column: 'org_id', is_enabled: false })
})
+ it('saves an existing person source even when its warehouse table is no longer selectable', async () => {
+ // The table + column map are create-only and hidden on edit, so form validation must not
+ // require a re-selected warehouse table — only key_column and is_enabled stay editable.
+ let patchedBody: Record<string, any> | null = null
+ useMocks({
+ ...defaultMocks(),
+ get: { ...defaultMocks().get, [WAREHOUSE_TABLES_URL]: { count: 0, results: [] } },
+ patch: {
+ ...defaultMocks().patch,
+ [SOURCE_URL]: async ({ request }) => {
+ patchedBody = (await request.json()) as Record<string, any>
+ return buildSource()
+ },
+ },
+ })
+ 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' },
+ } as Partial<CustomPropertySourceApi>),
+ })
+ )
+ logic.actions.setCustomPropertyFormValue('isEnabled', false)
+
+ await expectLogic(logic, () => logic.actions.submitCustomPropertyForm()).toDispatchActions([
+ 'submitCustomPropertyFormSuccess',
+ ])
+ expect(patchedBody).toEqual({ key_column: 'distinct_id', is_enabled: false })
+ })
+
it('deletes the source when saving after switching away from data warehouse mode', async () => {
let sourceDeleted = false
useMocks({
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
index 22132575d3f6..53e3f1c3c2aa 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
@@ -8,7 +8,8 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'
-import type { DataWarehouseSavedQuery } from '~/types'
+import type { DataWarehouseSavedQuery, DataWarehouseTable, PropertyDefinition } from '~/types'
+import { PropertyDefinitionType } from '~/types'
import {
customPropertyDefinitionsCreate,
@@ -30,6 +31,14 @@ import type { customPropertyDefinitionsLogicType } from './customPropertyDefinit
import { NEW_OPTION_ID_PREFIX, isNumericDisplayType, optionLabelError } from './customPropertyTypes'
export type CustomPropertySourceMode = 'manual' | 'data_warehouse' | 'workflow'
+export type CustomPropertyTargetType = 'account' | 'person'
+
+// One warehouse-column → person-property pair in the person-target editor. Serialized to the
+// backend's `column_property_map` object ({column: property}) on save.
+export interface ColumnPropertyMapping {
+ column: string
+ property: string
+}
export interface CustomPropertyFormValues {
name: string
@@ -37,10 +46,16 @@ export interface CustomPropertyFormValues {
displayType: CustomPropertyDisplayTypeEnumApi
isBigNumber: boolean
options: CustomPropertyOptionApi[]
+ // 'account' feeds an account (group) property from a saved query; 'person' upserts warehouse
+ // columns onto person properties (usable in flags/cohorts/insights) from a raw synced table.
+ targetType: CustomPropertyTargetType
sourceMode: CustomPropertySourceMode
savedQuery: string | null
sourceColumn: string | null
keyColumn: string | null
+ // Person target: the warehouse table (its schema id backs the source) + the column mappings.
+ warehouseTable: string | null
+ columnMappings: ColumnPropertyMapping[]
isEnabled: boolean
}
@@ -50,10 +65,13 @@ const DEFAULT_FORM_VALUES: CustomPropertyFormValues = {
displayType: 'text',
isBigNumber: false,
options: [],
+ targetType: 'account',
sourceMode: 'manual',
savedQuery: null,
sourceColumn: null,
keyColumn: null,
+ warehouseTable: null,
+ columnMappings: [{ column: '', property: '' }],
isEnabled: true,
}
@@ -63,16 +81,20 @@ const serializeDefinition = ({
displayType,
isBigNumber,
options,
+ targetType,
}: CustomPropertyFormValues): {
name: string
description: string | null
display_type: CustomPropertyDisplayTypeEnumApi
+ target_type: CustomPropertyTargetType
is_big_number: boolean
options?: CustomPropertyOptionApi[]
} => ({
name: name.trim(),
description: description?.trim() || null,
display_type: displayType,
+ // Create-only on the backend; a definition's target doesn't change after creation.
+ target_type: targetType,
// The switch is hidden for non-numeric types, so never send a stale flag for them.
is_big_number: isNumericDisplayType(displayType) ? isBigNumber : false,
// Options only apply to select; the backend clears them for other types.
@@ -87,6 +109,22 @@ const serializeDefinition = ({
: {}),
})
+// Identity-critical person properties a warehouse source shouldn't silently overwrite. `$`-prefixed
+// props are also warned on (see columnMappingWarnings). Warn-only — the user can still proceed.
+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[] => {
+ if (!value || typeof value !== 'object') {
+ return [{ column: '', property: '' }]
+ }
+ const entries = Object.entries(value as Record<string, unknown>).map(([column, property]) => ({
+ column,
+ property: String(property),
+ }))
+ return entries.length ? entries : [{ column: '', property: '' }]
+}
+
const handleNameConflict = (error: unknown, setManualErrors: (errors: { name: string }) => void): boolean => {
if ((error as { status?: number })?.status !== 409) {
return false
@@ -158,6 +196,28 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
},
},
],
+ warehouseTables: [
+ [] as DataWarehouseTable[],
+ {
+ loadWarehouseTables: async (): Promise<DataWarehouseTable[]> => {
+ const response = await api.dataWarehouseTables.list()
+ // Only synced tables carry an external_schema, which is what a person source binds to.
+ return response.results.filter((table) => !!table.external_schema)
+ },
+ },
+ ],
+ personPropertyDefinitions: [
+ [] as PropertyDefinition[],
+ {
+ loadPersonPropertyDefinitions: async (): Promise<PropertyDefinition[]> => {
+ const response = await api.propertyDefinitions.list({
+ type: PropertyDefinitionType.Person,
+ limit: 1000,
+ })
+ return response.results
+ },
+ },
+ ],
newWorkflowUrl: [
null as string | null,
{
@@ -189,20 +249,31 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
name,
displayType,
options,
+ targetType,
sourceMode,
savedQuery,
sourceColumn,
keyColumn,
- }: CustomPropertyFormValues) => ({
- name: !name?.trim() ? 'Name is required' : undefined,
- options:
- displayType === 'select'
- ? options.map((_, index) => ({ label: optionLabelError(options, index) }))
- : undefined,
- savedQuery: sourceMode === 'data_warehouse' && !savedQuery ? 'Select a view' : undefined,
- sourceColumn: sourceMode === 'data_warehouse' && !sourceColumn ? 'Select the value column' : undefined,
- keyColumn: sourceMode === 'data_warehouse' && !keyColumn ? 'Select the key column' : undefined,
- }),
+ warehouseTable,
+ }: CustomPropertyFormValues) => {
+ const isPerson = targetType === 'person'
+ const isAccountWarehouse = !isPerson && sourceMode === 'data_warehouse'
+ // The table + column map are create-only, so only require them when creating a new
+ // person source — an existing source keeps only key_column and enabled editable.
+ const isNewPersonSource = isPerson && !values.editingDefinition?.source
+ return {
+ name: !name?.trim() ? 'Name is required' : undefined,
+ options:
+ !isPerson && displayType === 'select'
+ ? options.map((_, index) => ({ label: optionLabelError(options, index) }))
+ : undefined,
+ savedQuery: isAccountWarehouse && !savedQuery ? 'Select a view' : undefined,
+ sourceColumn: isAccountWarehouse && !sourceColumn ? 'Select the value column' : undefined,
+ keyColumn:
+ (isAccountWarehouse || isPerson) && !keyColumn?.trim() ? 'Enter the key column' : undefined,
+ warehouseTable: isNewPersonSource && !warehouseTable ? 'Select a warehouse table' : undefined,
+ }
+ },
submit: async (formValues: CustomPropertyFormValues) => {
const projectId = String(values.currentProjectId)
const editing = values.editingDefinition
@@ -217,9 +288,34 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
actions.setEditingDefinition(definition)
}
try {
- const { sourceMode, savedQuery, sourceColumn, keyColumn, isEnabled } = formValues
+ const { targetType, sourceMode, savedQuery, sourceColumn, keyColumn, isEnabled } = formValues
const existingSource = editing?.source ?? null
- if (sourceMode === 'data_warehouse' && savedQuery && sourceColumn && keyColumn) {
+ if (targetType === 'person') {
+ const schemaId = values.selectedWarehouseSchemaId
+ if (existingSource) {
+ // The binding + column map are create-only on the backend; only key_column
+ // and is_enabled are mutable on a person 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 (!keyColumn?.trim()) {
+ throw new Error('Enter the distinct ID column')
+ } else {
+ await customPropertySourcesCreate(projectId, {
+ definition: definition.id,
+ external_data_schema: schemaId,
+ column_property_map: values.serializedColumnPropertyMap,
+ key_column: keyColumn.trim(),
+ is_enabled: isEnabled,
+ })
+ }
+ } else if (sourceMode === 'data_warehouse' && savedQuery && sourceColumn && keyColumn) {
if (existingSource) {
// saved_query is create-only — only the mutable fields are sent on update.
await customPropertySourcesPartialUpdate(projectId, existingSource.id, {
@@ -258,6 +354,43 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
return (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,
+ ],
+ // The person-target column mappings as the backend's `column_property_map` object.
+ serializedColumnPropertyMap: [
+ (s) => [s.customPropertyForm],
+ (form: CustomPropertyFormValues): Record<string, string> =>
+ Object.fromEntries(
+ form.columnMappings
+ .filter((mapping) => mapping.column.trim() && mapping.property.trim())
+ .map((mapping) => [mapping.column.trim(), mapping.property.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: [
+ (s) => [s.customPropertyForm, s.personPropertyDefinitions],
+ (form: CustomPropertyFormValues, personPropertyDefinitions: PropertyDefinition[]): (string | null)[] => {
+ const existing = new Set(personPropertyDefinitions.map((definition) => definition.name))
+ return form.columnMappings.map((mapping) => {
+ const name = mapping.property.trim()
+ if (!name) {
+ return null
+ }
+ if (name.startsWith('$') || RESERVED_PERSON_PROPERTY_NAMES.has(name)) {
+ return `"${name}" is an identity property — writing to it may overwrite SDK-set values.`
+ }
+ if (existing.has(name)) {
+ return `A person property "${name}" already exists — this source will overwrite it.`
+ }
+ return null
+ })
+ },
+ ],
editingReferences: [
(s) => [s.definitions, s.editingDefinition],
(
@@ -276,15 +409,21 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
openCreateModal: () => {
actions.resetCustomPropertyForm()
actions.loadSavedQueries()
+ actions.loadWarehouseTables()
+ actions.loadPersonPropertyDefinitions()
},
openEditModal: ({ definition }) => {
actions.loadSavedQueries()
+ actions.loadWarehouseTables()
+ actions.loadPersonPropertyDefinitions()
+ const isPerson = definition.target_type === 'person'
actions.setCustomPropertyFormValues({
name: definition.name,
description: definition.description ?? '',
displayType: definition.display_type,
isBigNumber: definition.is_big_number ?? false,
options: definition.options ?? [],
+ targetType: isPerson ? 'person' : 'account',
sourceMode: definition.source
? 'data_warehouse'
: definition.references?.length
@@ -293,6 +432,12 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
savedQuery: 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,
+ columnMappings: isPerson
+ ? parseColumnPropertyMap(definition.source?.column_property_map)
+ : [{ column: '', property: '' }],
isEnabled: definition.source?.is_enabled ?? true,
})
},
@@ -357,6 +502,10 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.loadSavedQueries' })
lemonToast.error('Failed to load data warehouse views')
},
+ loadWarehouseTablesFailure: ({ error }) => {
+ posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.loadWarehouseTables' })
+ lemonToast.error('Failed to load data warehouse tables')
+ },
})),
afterMount(({ actions }) => {
actions.loadDefinitions()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a0f7f5e289c8..c5953ec4829b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20829,6 +20829,8 @@ export namespace Schemas {
readonly verified_by: UserBasic;
/** @nullable */
hidden?: boolean | null;
+ /** Provenance for a person property populated from a data warehouse source (source/table/column/last synced), or null. Read-only. */
+ readonly warehouse_origin: unknown;
}
export interface ErrorResponse {
@@ -41378,6 +41380,8 @@ export namespace Schemas {
readonly verified_by?: UserBasic;
/** @nullable */
hidden?: boolean | null;
+ /** Provenance for a person property populated from a data warehouse source (source/table/column/last synced), or null. Read-only. */
+ readonly warehouse_origin?: unknown;
}
/**