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): map every warehouse column in one action (#84079)

Tom Owers71bade73248a
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 985aa770aac3..9ab817a24a92 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -1837,13 +1837,22 @@ def _fail_created_runs(team_id: int, source_ids: list[Any], error: str) -> None:
def _start_backfill(team_id: int, binding: "WarehouseBinding", trigger: str) -> None:
"""Start the person-property backfill workflow. Failure must not fail the originating write."""
created_source_ids: list[Any] = []
+ # The temporal client is heavy; keep it off the CA facade import (django.setup) path. Imported
+ # before the try so the except clause below can name WarehouseBindingMissingError even when an
+ # earlier line raises.
+ from products.warehouse_sources.backend.facade.temporal import ( # noqa: PLC0415
+ WarehouseBindingMissingError,
+ start_person_property_backfill,
+ )
+
try:
# Placeholder rows before starting, so the activity always finds a running row to reconcile.
created_source_ids = _create_running_runs(team_id, binding, trigger)
- # The temporal client is heavy; keep it off the CA facade import (django.setup) path.
- from products.warehouse_sources.backend.facade.temporal import start_person_property_backfill # noqa: PLC0415
-
start_person_property_backfill(team_id=team_id, binding=binding, trigger=trigger)
+ except WarehouseBindingMissingError:
+ # The warehouse object was deleted between saving the source and this deferred start. There is
+ # nothing to back-fill, so reconcile the placeholders without capturing it as an error.
+ _fail_created_runs(team_id, created_source_ids, "The warehouse table or view for this source no longer exists.")
except Exception as e:
# The workflow never started, so nothing will reconcile the placeholders — fail them here.
_fail_created_runs(team_id, created_source_ids, "Failed to start backfill")
@@ -1976,10 +1985,19 @@ def trigger_person_property_backfill(
_assert_warehouse_editor(team_id, binding, user_access_control)
# Placeholder rows before starting, so the activity always finds a running row to reconcile.
created_source_ids = _create_running_runs(team_id, binding, trigger)
- from products.warehouse_sources.backend.facade.temporal import start_person_property_backfill # noqa: PLC0415
+ from products.warehouse_sources.backend.facade.temporal import ( # noqa: PLC0415
+ WarehouseBindingMissingError,
+ start_person_property_backfill,
+ )
try:
return start_person_property_backfill(team_id=team_id, binding=binding, trigger=trigger)
+ except WarehouseBindingMissingError:
+ # The warehouse table or view was deleted after the placeholders were created; reconcile them
+ # so the source isn't stuck 'running', and report an invalid source (→ 400) rather than a
+ # coalesced run for a table that is gone.
+ _fail_created_runs(team_id, created_source_ids, "The warehouse table or view for this source no longer exists.")
+ return None
except Exception:
# The workflow never started; reconcile the placeholders so the source isn't stuck 'running'
# with its trigger disabled, then surface the error to the caller.
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 16b2508b3be1..eb46b31c36a9 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
@@ -324,6 +324,23 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):
run = CustomPropertySyncRun.objects.unscoped().get(source_id=source.id)
assert run.status == "failed" and run.error == "Failed to start sync"
+ @patch("products.customer_analytics.backend.facade.api.person_properties_flag_enabled", return_value=True)
+ def test_backfill_fails_its_run_when_the_warehouse_object_is_gone(self, _flag):
+ # Deleting the source's warehouse object soft-deletes the schema but leaves the source's binding,
+ # so the backfill can't resolve a table. Without failing the placeholder it just created, the run
+ # would sit 'running' until the stale-run sweep, and the trigger would report a coalesced run for a
+ # table that no longer exists (returning False → 'already_running') instead of an invalid source.
+ source = self._create(user_access_control=self._uac(allowed=True))
+ ExternalDataSchema.objects.filter(id=self.schema.id).update(deleted=True)
+
+ result = api.trigger_person_property_backfill(
+ team_id=self.team.id, source_id=source.id, user_access_control=self._uac(allowed=True)
+ )
+
+ assert result is None
+ run = CustomPropertySyncRun.objects.unscoped().get(source_id=source.id)
+ assert run.status == "failed" and run.finished_at is not None
+
@parameterized.expand(
[
("stale", api.STALE_RUNNING_RUN_AFTER + timedelta(minutes=1), "failed"),
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
index 13d95e481365..b7c9debae02f 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
@@ -173,8 +173,9 @@ function PersonSourceEditor(): JSX.Element {
selectedTableColumns,
selectedTableColumnsLoading,
hasWarehouseSourceOptions,
+ mappableColumns,
} = useValues(customPropertyDefinitionsLogic)
- const { setCustomPropertyFormValue, loadSelectedTableColumns, loadWarehouseTables } =
+ const { setCustomPropertyFormValue, loadSelectedTableColumns, loadWarehouseTables, mapAllColumns } =
useActions(customPropertyDefinitionsLogic)
const { groupTypes, groupTypesLoading } = useValues(groupsModel)
@@ -203,6 +204,19 @@ function PersonSourceEditor(): JSX.Element {
</span>
),
}))
+ const keyColumnLabel = isGroup ? 'group key column' : 'distinct ID column'
+ // Bulk mapping needs the key column chosen first, since that is what it excludes. Naming the
+ // reason in the disabled state keeps a wide table from being mapped with its identifier in it.
+ const mapAllDisabledReason = !customPropertyForm.warehouseSource
+ ? 'Select a table or view first'
+ : selectedTableColumnsLoading
+ ? 'Loading columns'
+ : !customPropertyForm.keyColumn?.trim()
+ ? `Choose the ${keyColumnLabel} first`
+ : !mappableColumns.length
+ ? 'Every column is mapped already'
+ : undefined
+ const warningCount = columnMappingWarnings.filter(Boolean).length
const groupTypeOptions = Array.from(groupTypes.values()).map((groupType) => ({
value: groupType.group_type_index,
label: groupType.name_singular || groupType.group_type,
@@ -391,13 +405,32 @@ function PersonSourceEditor(): JSX.Element {
)}
</div>
))}
- <LemonButton
- type="secondary"
- icon={<IconPlus />}
- onClick={() => setMappings([...mappings, { column: '', property: '', description: '' }])}
- >
- Add mapping
- </LemonButton>
+ {warningCount > 0 && (
+ <span className="text-warning text-xs">
+ {warningCount === 1
+ ? '1 mapped property needs a look before you save.'
+ : `${warningCount} mapped properties need a look before you save.`}
+ </span>
+ )}
+ <div className="flex items-center gap-2">
+ <LemonButton
+ type="secondary"
+ icon={<IconPlus />}
+ onClick={() => setMappings([...mappings, { column: '', property: '', description: '' }])}
+ >
+ Add mapping
+ </LemonButton>
+ <LemonButton type="secondary" onClick={mapAllColumns} disabledReason={mapAllDisabledReason}>
+ {mappableColumns.length > 0
+ ? `Map ${mappableColumns.length} more columns`
+ : 'Map all columns'}
+ </LemonButton>
+ </div>
+ <span className="text-secondary text-xs">
+ Mapping every column keeps the warehouse column names. The {keyColumnLabel} is left out, because
+ its values identify the {entityLabel} rather than describing it. Nothing is saved until you
+ create the property, so you can edit or remove any row first.
+ </span>
</div>
)}
<LemonField
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 e27b259defbf..dfd9d027f233 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
@@ -393,6 +393,88 @@ describe('customPropertyDefinitionsLogic', () => {
expect(logic.values.serializedColumnDescriptions).toEqual({ plan: 'The plan tier' })
})
+ describe('mapping every column at once', () => {
+ const openWithColumns = async (formValues: Record<string, any>): Promise<void> => {
+ // oxlint-disable-next-line react-hooks/rules-of-hooks
+ useMocks(defaultMocks())
+ mountLogic()
+ await expectLogic(logic, () => logic.actions.openCreateModal()).toDispatchActions([
+ 'loadSavedQueriesSuccess',
+ ])
+ logic.actions.setCustomPropertyFormValues({ targetType: 'person', ...formValues })
+ await expectLogic(logic, () =>
+ logic.actions.loadSelectedTableColumns({ source: 'view:view-1' })
+ ).toDispatchActions(['loadSelectedTableColumnsSuccess'])
+ }
+
+ const mapAll = async (formValues: Record<string, any>): Promise<void> => {
+ await openWithColumns(formValues)
+ logic.actions.mapAllColumns()
+ }
+
+ it('maps every column but the key column, keeping the warehouse names', async () => {
+ // The whole point of the action: a wide table should not have to be mapped by hand, and the
+ // key column must not become a property, since its values identify the person.
+ await mapAll({ keyColumn: 'org_id' })
+
+ expect(logic.values.customPropertyForm.columnMappings).toEqual([
+ { column: 'mrr', property: 'mrr', description: '' },
+ ])
+ expect(logic.values.serializedColumnPropertyMap).toEqual({ mrr: 'mrr' })
+ })
+
+ it('keeps rows the user already started and never duplicates their columns', async () => {
+ // Bulk mapping on top of hand-entered work must not discard a renamed property or map the
+ // same column twice.
+ await mapAll({
+ keyColumn: 'org_id',
+ columnMappings: [{ column: 'mrr', property: 'monthly_revenue', description: '' }],
+ })
+
+ expect(logic.values.customPropertyForm.columnMappings).toEqual([
+ { column: 'mrr', property: 'monthly_revenue', description: '' },
+ ])
+ })
+
+ it('keeps a started row that has a property but no column yet', async () => {
+ // A property typed before its column, or left after a source switch clears columns but keeps
+ // the name, must not be discarded by the bulk map.
+ await mapAll({
+ keyColumn: 'org_id',
+ columnMappings: [{ column: '', property: 'monthly_revenue', description: '' }],
+ })
+
+ expect(logic.values.customPropertyForm.columnMappings).toEqual([
+ { column: '', property: 'monthly_revenue', description: '' },
+ { column: 'mrr', property: 'mrr', description: '' },
+ ])
+ })
+
+ it('offers nothing to map once every column is spoken for', async () => {
+ await mapAll({ keyColumn: 'org_id' })
+ expect(logic.values.mappableColumns).toEqual([])
+ })
+
+ it('never serializes the key column as a property, even after the key changes', async () => {
+ // Bulk mapping excludes whatever key column is set at the time, but the key can change
+ // afterwards. The column_property_map is create-only, so writing the new identifier column as
+ // a property would be unrecoverable, and it must be dropped from the payload.
+ await mapAll({ keyColumn: 'org_id' })
+ expect(logic.values.serializedColumnPropertyMap).toEqual({ mrr: 'mrr' })
+
+ logic.actions.setCustomPropertyFormValue('keyColumn', 'mrr')
+
+ expect(logic.values.serializedColumnPropertyMap).toEqual({})
+ })
+
+ it('leaves the key column mappable until one is chosen', async () => {
+ // The button is gated on this in the modal — without a key column the action would map the
+ // identifier as a property.
+ await openWithColumns({ keyColumn: '' })
+ expect(logic.values.mappableColumns.map((column) => column.name)).toEqual(['org_id', 'mrr'])
+ })
+ })
+
it('binds a person source to a materialized view when one is picked', async () => {
let sourceBody: Record<string, any> | null = null
useMocks({
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
index 3dbd845e2628..6331969f90fb 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
@@ -247,6 +247,7 @@ export interface customPropertyDefinitionsLogicValues {
hasWarehouseSourceOptions: boolean | null
isCustomPropertyFormSubmitting: boolean
isCustomPropertyFormValid: boolean
+ mappableColumns: WarehouseColumn[]
materializedViews: DataWarehouseSavedQuery[]
modalVisible: boolean
newWorkflowUrl: string | null
@@ -407,6 +408,9 @@ export interface customPropertyDefinitionsLogicActions {
search?: string
}
}
+ mapAllColumns: () => {
+ value: true
+ }
openCreateModal: (
targetType?: CustomPropertyTargetType,
lockTargetType?: boolean
@@ -504,6 +508,10 @@ export interface customPropertyDefinitionsLogicMeta {
materializedViews: DataWarehouseSavedQuery[],
customPropertyForm: CustomPropertyFormValues
) => ProfileSourceBinding | null
+ mappableColumns: (
+ selectedTableColumns: WarehouseColumn[],
+ customPropertyForm: CustomPropertyFormValues
+ ) => WarehouseColumn[]
serializedColumnPropertyMap: (customPropertyForm: CustomPropertyFormValues) => Record<string, string>
serializedColumnDescriptions: (customPropertyForm: CustomPropertyFormValues) => Record<string, string>
columnMappingWarnings: (
@@ -556,6 +564,10 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
setTargetTypeFilter: (targetTypeFilter: CustomPropertyTargetTypeFilter) => ({ targetTypeFilter }),
setEditingDefinition: (definition: CustomPropertyDefinitionApi) => ({ definition }),
+ // Fill a mapping row for every column the source exposes that isn't mapped yet. A wide table
+ // is the common case for this feature, and adding twenty rows by hand is the friction it
+ // exists to remove.
+ mapAllColumns: true,
// Person sources only. triggerSync re-runs the underlying warehouse sync; triggerBackfill
// starts a full-table backfill. add/removeTriggeringSource drive the per-row double-submit
// guard, keyed by source so triggering one row never re-enables another's in-flight button.
@@ -1015,28 +1027,57 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
return schemaId ? { field: 'external_data_schema', id: schemaId } : null
},
],
- // The person-target column mappings as the backend's `column_property_map` object.
+ // Columns a bulk map would add: everything the source exposes except the key column, whose
+ // values identify the person or group rather than describing it, and columns already mapped.
+ mappableColumns: [
+ (s) => [s.selectedTableColumns, s.customPropertyForm],
+ (selectedTableColumns: WarehouseColumn[], form: CustomPropertyFormValues): WarehouseColumn[] => {
+ const keyColumn = form.keyColumn?.trim()
+ const alreadyMapped = new Set(
+ form.columnMappings.map((mapping) => mapping.column.trim()).filter(Boolean)
+ )
+ return selectedTableColumns.filter(
+ (column) => column.name !== keyColumn && !alreadyMapped.has(column.name)
+ )
+ },
+ ],
+ // The person-target column mappings as the backend's `column_property_map` object. The key
+ // column is never mapped: its values identify the person/group. Bulk mapping already excludes
+ // the key column, but the key can be changed afterwards, and the map is create-only, so a key
+ // column left in a row here would be written as a property with no way to undo it.
serializedColumnPropertyMap: [
(s) => [s.customPropertyForm],
- (form: CustomPropertyFormValues): Record<string, string> =>
- Object.fromEntries(
+ (form: CustomPropertyFormValues): Record<string, string> => {
+ const keyColumn = form.keyColumn?.trim()
+ return Object.fromEntries(
form.columnMappings
- .filter((mapping) => mapping.column.trim() && mapping.property.trim())
+ .filter(
+ (mapping) =>
+ mapping.column.trim() && mapping.property.trim() && mapping.column.trim() !== keyColumn
+ )
.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.
+ // description}), only for complete mappings that carry a non-empty description. The key column
+ // is excluded alongside its property, so both stay consistent.
serializedColumnDescriptions: [
(s) => [s.customPropertyForm],
- (form: CustomPropertyFormValues): Record<string, string> =>
- Object.fromEntries(
+ (form: CustomPropertyFormValues): Record<string, string> => {
+ const keyColumn = form.keyColumn?.trim()
+ return Object.fromEntries(
form.columnMappings
.filter(
- (mapping) => mapping.column.trim() && mapping.property.trim() && mapping.description.trim()
+ (mapping) =>
+ mapping.column.trim() &&
+ mapping.property.trim() &&
+ mapping.description.trim() &&
+ mapping.column.trim() !== keyColumn
)
.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.
@@ -1091,6 +1132,29 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
],
}),
listeners(({ actions, values, cache }) => ({
+ mapAllColumns: () => {
+ if (!values.mappableColumns.length) {
+ return
+ }
+ // Rows the user already started are kept, and the columns behind them are excluded from
+ // mappableColumns, so a bulk map never duplicates or discards hand-entered work. A row
+ // counts as started if it holds a column, property, or description, so a property typed
+ // before its column (including one left after a source switch clears columns but keeps
+ // the name) survives. Only fully empty placeholder rows drop out.
+ const started = values.customPropertyForm.columnMappings.filter(
+ (mapping) => mapping.column.trim() || mapping.property.trim() || mapping.description.trim()
+ )
+ actions.setCustomPropertyFormValue('columnMappings', [
+ ...started,
+ ...values.mappableColumns.map((column) => ({
+ column: column.name,
+ // Same name on both sides: it is what the per-row picker already seeds, and a
+ // rename is a decision for the person, not a default worth guessing at.
+ property: column.name,
+ description: column.description ?? '',
+ })),
+ ])
+ },
openCreateModal: ({ targetType }) => {
actions.resetCustomPropertyForm()
if (targetType) {
diff --git a/products/customer_analytics/skills/setting-up-warehouse-properties/SKILL.md b/products/customer_analytics/skills/setting-up-warehouse-properties/SKILL.md
new file mode 100644
index 000000000000..d3ebfb51a6ad
--- /dev/null
+++ b/products/customer_analytics/skills/setting-up-warehouse-properties/SKILL.md
@@ -0,0 +1,135 @@
+---
+name: setting-up-warehouse-properties
+description: >
+ Populate person or group properties from a data warehouse table or materialized view, so warehouse columns
+ become properties usable in feature flags, cohorts, and insights. Use when the user wants to "sync my Postgres
+ columns to person properties", "map a warehouse table to people", "replace our daily identify cron", "update
+ person properties from the warehouse", or asks for reverse ETL into PostHog. Covers picking the table and the
+ identifier column, proposing a whole-table column mapping in one call, excluding identity and reserved
+ properties, checking collisions with properties that already exist, and running the first backfill.
+---
+
+# Setting up warehouse properties
+
+Warehouse properties write columns from a warehouse table or materialized view onto matching people or groups,
+on the schedule that table already syncs on. They replace a cron that sends `$set` identify events.
+
+The mapping is the whole job. Most tables worth mapping are wide, so the work is deciding which columns become
+properties and what they are called — not making many API calls. **One source carries the entire mapping**:
+`custom-property-sources-create` takes the complete `column_property_map` in a single request, so never loop
+per column.
+
+## When to use this skill
+
+- "Sync my `postgres.customer_attributes` columns to person properties"
+- "We send a daily identify job from our warehouse, can PostHog pull it instead?"
+- "Map this table to people" / "reverse ETL into PostHog"
+- The user is looking at Data → Warehouse properties and wants a whole table mapped
+
+Use `setting-up-a-data-warehouse-source` instead when the table is not in the warehouse yet. This skill starts
+once the data is syncing.
+
+## Tools
+
+| Tool | Purpose |
+| ------------------------------------ | ---------------------------------------------------------------------------------------------------- |
+| `external-data-schemas-list` | Find a synced table and its schema id (the `external_data_schema` binding); columns are omitted here |
+| `external-data-schemas-retrieve` | Read one synced table's columns and types by schema id |
+| `view-list` | Find a materialized view and its column schema (the `saved_query` binding) |
+| `view-get` | Read one materialized view's columns and types by id |
+| `custom-property-definitions-list` | See what warehouse properties already exist for the team |
+| `custom-property-definitions-create` | Create the definition the source attaches to (`target_type: person` or `group`) |
+| `custom-property-sources-create` | Bind the definition to the table, carrying the whole `column_property_map` |
+| `custom-property-sources-backfill` | Populate historical rows after creating the mapping |
+| `custom-property-sources-runs-list` | Check the run funnel after a sync or backfill |
+| `custom-property-sources-sync` | Run the underlying table now |
+
+Person and group targets need the `warehouse-person-properties` feature. A group target additionally needs the
+`group:write` scope; without it, `custom-property-sources-create` refuses the group definition.
+
+## The flow
+
+### 1. Find the table and its columns
+
+For a synced table, `external-data-schemas-list` gives you the schema id (the `external_data_schema` binding), and
+`external-data-schemas-retrieve` returns that schema's columns and types.
+
+For a materialized view, `view-list` finds the view and its column schema, and `view-get` returns one view's columns
+by id; a view binds by `saved_query` instead, and must already be materialized, since an unmaterialized view has no
+data to read and the create call rejects it.
+
+### 2. Pick the identifier column, and say why it matters
+
+Ask which column holds the PostHog **distinct ID** (person targets) or the **group key** (group targets). This is
+the single most common reason a mapping silently does nothing, so do not guess it from a name like `id` or
+`user_id` without confirming.
+
+Two properties of the sync are worth stating plainly before the user commits:
+
+- It **only updates people or groups that already exist** in PostHog. Rows that match nobody are skipped, and
+ the run reports them as `skipped_missing_person`. It does not create people.
+- **Null values are skipped, not written.** A column that is null for a row leaves that property as it was. If
+ the user expects a null to clear a property, warehouse properties will not do it.
+
+### 3. Propose the mapping before creating anything
+
+Build the full `column_property_map` — `{warehouse_column: property_name}` — and show it to the user for
+approval. Default to **the same name on both sides**; a rename is the user's call, not a guess worth making.
+
+Exclude from the proposal, and say what you excluded:
+
+- **The identifier column.** Its values identify the person, they do not describe them.
+- **Anything `$`-prefixed, and `email`, `name`, `username`.** These are identity properties the SDKs set, and
+ writing them from the warehouse can overwrite what PostHog already knows.
+- **Columns that would be sensitive as a person property.** Password hashes, tokens, internal audit columns, and
+ anything the user would not want visible in the person profile UI. Flag them rather than dropping them
+ silently, since only the user knows their schema.
+
+Then check collisions: read the existing person properties and call out any mapped name that already exists,
+because the sync will overwrite it on every run. `custom-property-definitions-list` shows the warehouse
+properties already configured, so you can also spot a table that is already mapped.
+
+Wide tables are exactly when this matters — a twenty-column table proposed as a bare list is not reviewable.
+Group the proposal into what will be mapped, what you excluded and why, and what collides.
+
+### 4. Create it
+
+Create the definition first, then the source:
+
+1. `custom-property-definitions-create` with `target_type: person` (or `group` plus `group_type_index`),
+ `display_type: text`, and a name describing the group of properties, not one column — the definition is the row
+ the user sees in the UI. `display_type` is required by the API; use `text` for person and group targets, where it
+ is ignored (it only drives how an account property renders, since profile properties are written as raw `$set` /
+ `$group_set` values).
+2. `custom-property-sources-create` with the definition id, exactly one of `external_data_schema` or
+ `saved_query`, the whole `column_property_map`, and `key_column` set to the identifier from step 2.
+
+The mapping and the binding are **create-only**. To change which columns are mapped, delete the property and
+create it again — so it is worth getting the proposal right rather than iterating on a live mapping.
+
+### 5. Backfill and verify
+
+Creating an enabled source starts a backfill automatically. For an existing mapping, `custom-property-sources-backfill`
+reads the whole table and populates historical rows; it coalesces if one is already running.
+
+Then read `custom-property-sources-runs-list` and walk the funnel, which is where a mapping that "did nothing"
+explains itself:
+
+| Stage | Zero here means |
+| ----------- | -------------------------------------------------------------------------------- |
+| `rows_read` | Nothing was staged — the table has not synced since the mapping was created |
+| `changed` | Every value already matches what was last sent; a re-run is expected to be quiet |
+| `existing` | No row's identifier matched a person or group — usually the wrong key column |
+| `produced` | Nothing reached capture; check `skipped_missing_person` |
+
+A run that reads rows but shows `existing: 0` is the wrong-key-column case almost every time.
+
+## Notes that save a round trip
+
+- The sync follows the **table's own schedule**. It is not separately schedulable, so "how often does this
+ update" is answered by the table's sync frequency.
+- A source that fails repeatedly is **disabled automatically** after five consecutive failures. Re-enabling it
+ resets the streak and triggers a fresh backfill.
+- "Sync now" runs the underlying table, which for a synced table is a real, billable warehouse sync, and for a
+ materialized view is a materialization. It is not a cheap no-op — do not call it to "check" a mapping when
+ `custom-property-sources-runs-list` answers the question for free.
diff --git a/products/warehouse_sources/backend/facade/temporal.py b/products/warehouse_sources/backend/facade/temporal.py
index a18c0e157a26..92e4362da6a5 100644
--- a/products/warehouse_sources/backend/facade/temporal.py
+++ b/products/warehouse_sources/backend/facade/temporal.py
@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.person_property_tr
ExternalDataSchemaSyncPausedError,
SavedQueryNotFoundError,
SavedQueryNotOnV2ScheduleError,
+ WarehouseBindingMissingError,
start_person_property_backfill,
trigger_saved_query_materialization,
trigger_schema_sync,
@@ -57,6 +58,7 @@ __all__ = [
"PersonPropertyRowSink",
"SavedQueryNotFoundError",
"SavedQueryNotOnV2ScheduleError",
+ "WarehouseBindingMissingError",
"load_all_sources",
"prepare_s3_files_for_querying",
"start_person_property_backfill",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.py
index 5e77435b0344..b1b3ee96f07d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_triggers.py
@@ -59,6 +59,12 @@ class SavedQueryNotOnV2ScheduleError(Exception):
per-query data-modeling schedule, whose workflow never stages person-property rows."""
+class WarehouseBindingMissingError(Exception):
+ """Raised by ``start_person_property_backfill`` when the binding's warehouse object (schema or
+ view) no longer resolves. A caller that created placeholder run rows before starting must fail
+ them on this, so they don't sit 'running' until the stale-run sweep clears them hours later."""
+
+
def trigger_schema_sync(*, team_id: int, schema_id: str) -> None:
"""Trigger the underlying warehouse schema's Temporal schedule — a real, billable sync. The normal
incremental person-property child runs off it, so this doubles as person-property "sync now".
@@ -86,12 +92,14 @@ def trigger_schema_sync(*, team_id: int, schema_id: str) -> None:
def start_person_property_backfill(*, team_id: int, binding: WarehouseBinding, trigger: str) -> bool:
"""Start the per-table backfill workflow. One workflow per ``{team, binding}`` (id-keyed), so
concurrent triggers for the same table coalesce: returns False (does not raise) when one is
- already running. Also returns False when the warehouse object no longer exists."""
+ already running. Raises ``WarehouseBindingMissingError`` when the warehouse object no longer
+ exists, kept distinct from the coalesced False so the caller can fail the run rows it created
+ rather than reporting a coalesced run for a table that is gone."""
log = logger.bind(team_id=team_id, binding_kind=binding.kind, binding_id=binding.id, trigger=trigger)
inputs = _backfill_inputs(team_id, binding, trigger)
if inputs is None:
- log.warning("person-property backfill not started: warehouse table no longer exists")
- return False
+ log.warning("person-property backfill not started: warehouse object no longer exists")
+ raise WarehouseBindingMissingError
workflow_id = f"{BACKFILL_WORKFLOW_NAME}-{team_id}-{binding.id}"
return _start_backfill_workflow(inputs, workflow_id)