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.

fix(warehouse-sources): ask for a key only where discovery reads one (#101895)

Daniel RCa65a9ac3bdab
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 5db41b43d0ca..9576c897e39b 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6595,6 +6595,7 @@ export type SchemaIncrementalFieldsResponse = {
supports_webhooks: boolean
available_columns: AvailableColumn[]
detected_primary_keys: string[] | null
+ primary_key_detection_supported?: boolean
cdc_available?: boolean
xmin_available?: boolean
}
@@ -6638,6 +6639,7 @@ export interface ExternalDataSourceSyncSchema {
primary_key_columns: string[] | null
available_columns: AvailableColumn[]
detected_primary_keys: string[] | null
+ primary_key_detection_supported?: boolean
/**
* For sources that gate read access by scope (e.g. Stripe restricted API keys), the
* reason this endpoint is currently unreachable. `null`/undefined = endpoint is
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
index f02ace0afc4b..9bf1a8ef9a3e 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
@@ -487,6 +487,9 @@ function SyncMethodSection({ sourceId, schema }: { sourceId: string; schema: Ext
}}
availableColumns={schemaIncrementalFields.available_columns ?? []}
detectedPrimaryKeys={schemaIncrementalFields.detected_primary_keys ?? null}
+ primaryKeyDetectionSupported={
+ schemaIncrementalFields.primary_key_detection_supported ?? false
+ }
primaryKeyLocked={!!schema.table && !!schema.primary_key_columns?.length}
onClose={() => {}}
onSave={persistSyncMethod}
diff --git a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx
index db359dce2cfe..484ef76646ed 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx
@@ -35,11 +35,11 @@ describe('SyncMethodForm', () => {
})
it.each([
- ['no key, columns known', null, true, 'Select primary key columns, or use full table replication instead'],
- ['no key, columns unknown', null, false, undefined],
- ['key picked, columns known', ['id'], true, undefined],
- ])('requires a merge key for incremental: %s', (_, mergeKey, columnsKnown, expected) => {
- expect(getSaveDisabledReason('incremental', 'updated_at', null, mergeKey, columnsKnown)).toBe(expected)
+ ['no key, key required', null, true, 'Select primary key columns, or use full table replication instead'],
+ ['no key, source declares its own key', null, false, undefined],
+ ['key picked, key required', ['id'], true, undefined],
+ ])('requires a merge key for incremental: %s', (_, mergeKey, keyRequired, expected) => {
+ expect(getSaveDisabledReason('incremental', 'updated_at', null, mergeKey, keyRequired)).toBe(expected)
})
it.each([
diff --git a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
index 85febfcb732a..9a4aec2756b8 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
@@ -99,6 +99,7 @@ interface SyncMethodFormProps {
) => void
availableColumns?: AvailableColumn[]
detectedPrimaryKeys?: string[] | null
+ primaryKeyDetectionSupported?: boolean
primaryKeyLocked?: boolean
saveButtonIsLoading?: boolean
isNewSource?: boolean
@@ -136,7 +137,7 @@ export const getSaveDisabledReason = (
incrementalField: string | null,
appendField: string | null,
mergeKey: string[] | null,
- columnsKnown: boolean
+ keyRequired: boolean
): string | undefined => {
if (!syncType) {
return 'You must select a sync method before saving'
@@ -148,9 +149,7 @@ export const getSaveDisabledReason = (
// An incremental sync merges rows on a key. Saved without one, the table syncs once and then
// fails on every later run, so the key is required here rather than at the first merge.
- // Only when the columns are known: without them the picker is empty, and the source
- // resolves its key at sync time instead.
- if (syncType === 'incremental' && columnsKnown && !mergeKey?.length) {
+ if (syncType === 'incremental' && keyRequired && !mergeKey?.length) {
return 'Select primary key columns, or use full table replication instead'
}
@@ -196,6 +195,7 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormPro
onSave,
availableColumns,
detectedPrimaryKeys,
+ primaryKeyDetectionSupported,
primaryKeyLocked,
saveButtonIsLoading,
isNewSource,
@@ -210,8 +210,12 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormPro
const columns = availableColumns ?? schema.available_columns ?? []
const resolvedDetectedPks = detectedPrimaryKeys ?? schema.detected_primary_keys ?? null
- // With no column list there is nothing to pick from, and the key resolves at sync time.
- const keyResolvable = columns.length === 0 || !!(schema.primary_key_columns?.length || resolvedDetectedPks?.length)
+ // A key is only asked for when the source reads keys off the table and the columns are
+ // known. A source that declares its key in code resolves it at sync time, and with no
+ // column list there is nothing to pick from.
+ const keyRequired =
+ (primaryKeyDetectionSupported ?? schema.primary_key_detection_supported ?? false) && columns.length > 0
+ const keyResolvable = !keyRequired || !!(schema.primary_key_columns?.length || resolvedDetectedPks?.length)
const defaultField = schema.incremental_field ?? schema.incremental_fields[0]?.field ?? null
@@ -656,7 +660,7 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormPro
incrementalFieldValue,
appendFieldValue,
primaryKeyColumns.length ? primaryKeyColumns : resolvedDetectedPks,
- columns.length > 0
+ keyRequired
)
const saveDisabledReason = validationDisabledReason ?? (!isDirty ? 'No changes to save' : undefined)
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index 687ff9c7b33f..f66d4a56a9c8 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -921,9 +921,13 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
# key leaves the same unmergeable table as never setting one.
requested_keys = data["primary_key_columns"] if "primary_key_columns" in data else None
merge_keys = requested_keys if "primary_key_columns" in data else instance.primary_key_columns
- # Only when the schema's columns are known. Without them there is nothing to say the
- # table has no key, and the sync-time guard still covers it.
- if known_columns and not merge_keys and "id" not in column_names:
+ # Only for a source that reads keys off the table, and only when the schema's columns
+ # are known. A source that declares its key in code never needs one here, and without
+ # columns there is nothing to say the table has none; the sync-time guard covers both.
+ source_detects_keys = SourceRegistry.get_source(
+ ExternalDataSourceType(instance.source.source_type)
+ ).detects_primary_keys
+ if source_detects_keys and known_columns and not merge_keys and "id" not in column_names:
raise ValidationError(
f"'{instance.name}' has no primary key to sync incrementally on. "
"Set primary_key_columns for it, or choose full_refresh."
@@ -2061,13 +2065,10 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# job_inputs is an EncryptedJSONField: booleans round-trip as "True"/"False"
# strings, so bool(...) would treat "False" as truthy. str_to_bool decodes both.
source_cdc_enabled = str_to_bool(source.job_inputs.get("cdc_enabled"))
+ source_impl = SourceRegistry.get_source(ExternalDataSourceType(source.source_type))
cdc_available = schema.supports_cdc if is_cdc_enabled_for_team(self.team) and source_cdc_enabled else None
# xmin is source-capability-gated, mirroring the database_schema endpoint.
- xmin_available = (
- schema.supports_xmin
- if SourceRegistry.get_source(ExternalDataSourceType(source.source_type)).supports_xmin
- else None
- )
+ xmin_available = schema.supports_xmin if source_impl.supports_xmin else None
data = {
"incremental_fields": schema.incremental_fields,
@@ -2083,6 +2084,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
for col_name, col_type, nullable in schema.columns
],
"detected_primary_keys": schema.detected_primary_keys,
+ "primary_key_detection_supported": source_impl.detects_primary_keys,
}
return Response(status=status.HTTP_200_OK, data=data)
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
index c33f81ab601b..6d2388cac169 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
@@ -442,6 +442,7 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
for col_name, col_type, nullable in schema.columns
],
"detected_primary_keys": schema.detected_primary_keys,
+ "primary_key_detection_supported": source.detects_primary_keys,
"permission_error": endpoint_permissions.get(schema.name),
"rls_warning": schema.rls_warning,
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py
index b969d06464b0..da97fe003a63 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py
@@ -135,6 +135,9 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Val
# Lets users pick which columns to sync (and, in the wizard, surfaces the
# row-filter editor that shares the same column-selection modal).
supports_column_selection: bool = True
+ # Discovery reads the merge key off the table's sorting key, so a table without one has
+ # nothing to merge on and is asked for a key like any SQL source.
+ detects_primary_keys: bool = True
supports_row_filters: bool = True
api_docs_url = "https://clickhouse.com/docs"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index b97cb2eb296d..b2b667e2ee69 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -141,6 +141,11 @@ class _BaseSource(ABC, Generic[ConfigType]):
# silently sync unfiltered rows.
supports_row_filters: bool = False
+ # `True` only for sources whose discovery reads primary keys off the table itself, so an
+ # incremental table with none found has nothing to merge on. Sources left `False` declare
+ # the key in code at sync time, and are never asked for one.
+ detects_primary_keys: bool = False
+
# `True` for sources whose HogQL tables use a PostHog-managed canonical schema
# (`external_table_definitions`) — Stripe, Paddle, Zendesk. Their query exposes a fixed
# field set (and powers revenue analytics), so the physical column set must stay complete.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py
index 0af722c1c451..9fde6afb7502 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py
@@ -58,6 +58,7 @@ class SQLSource(SimpleSource[ConfigType], Generic[ConfigType]):
supports_column_selection: bool = True
supports_row_filters: bool = True
+ detects_primary_keys: bool = True
@property
@abstractmethod
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
index ce2e255f632f..3744fa52bcaa 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
@@ -123,6 +123,7 @@ class TestExternalDataSchema(APIBaseTest):
"webhook_only": False,
"available_columns": [],
"detected_primary_keys": None,
+ "primary_key_detection_supported": False,
}
@parameterized.expand(
@@ -341,6 +342,7 @@ class TestExternalDataSchema(APIBaseTest):
{"field": "id", "label": "id", "type": "integer", "nullable": True},
],
"detected_primary_keys": ["id"],
+ "primary_key_detection_supported": True,
}
@parameterized.expand(
@@ -603,6 +605,36 @@ class TestExternalDataSchema(APIBaseTest):
("columns_unknown", [], None, None, True, ""),
("clearing_an_existing_key", [{"name": "amount"}], ["order_id"], [], False, "no primary key"),
("key_naming_a_missing_column", [{"name": "amount"}], None, ["nope"], False, "no column named"),
+ (
+ "source_declares_its_key_in_code",
+ [{"name": "amount"}],
+ None,
+ None,
+ True,
+ "",
+ "full_refresh",
+ ExternalDataSourceType.STRIPE,
+ ),
+ (
+ "clickhouse_without_a_sorting_key_is_refused",
+ [{"name": "amount"}],
+ None,
+ None,
+ False,
+ "no primary key",
+ "full_refresh",
+ ExternalDataSourceType.CLICKHOUSE,
+ ),
+ (
+ "clickhouse_with_a_key_passes",
+ [{"name": "amount"}, {"name": "event_id"}],
+ None,
+ ["event_id"],
+ True,
+ "",
+ "full_refresh",
+ ExternalDataSourceType.CLICKHOUSE,
+ ),
("already_incremental_reenable_passes", [{"name": "amount"}], None, None, True, "", "incremental"),
(
"already_incremental_clearing_key_is_refused",
@@ -624,10 +656,11 @@ class TestExternalDataSchema(APIBaseTest):
expected_ok: bool,
expected_error: str,
initial_sync_type: str = "full_refresh",
+ source_type: str = ExternalDataSourceType.POSTGRES,
) -> None:
source = ExternalDataSource.objects.create(
team=self.team,
- source_type=ExternalDataSourceType.STRIPE,
+ source_type=source_type,
job_inputs={"auth_method": {"selection": "api_key", "stripe_secret_key": "123"}},
)
schema = ExternalDataSchema.objects.create(
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 01bd578891bb..487ce03e7bcb 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -133,7 +133,8 @@ def _configure_source_mock_versioning(mock_get_source) -> None:
attributes real values: the create path persists `default_version` into the `api_version`
column, and the serializer renders `get_version_deprecation` into the response. The create path
also reads `max_instances_per_team` to enforce the per-team source limit — leave it unset so the
- limit check is skipped rather than comparing against a MagicMock.
+ limit check is skipped rather than comparing against a MagicMock. `database_schema` renders
+ `detects_primary_keys` straight into the response, where a MagicMock does not serialize.
The update path also asks the source whether an edit introduces a new connection host or leaves
row-backed credentials preserved; a bare MagicMock returns truthy for both, which would wrongly
@@ -142,6 +143,7 @@ def _configure_source_mock_versioning(mock_get_source) -> None:
mock_get_source.return_value.get_version_deprecation.return_value = None
mock_get_source.return_value.max_instances_per_team = None
mock_get_source.return_value.connection_host_fields = []
+ mock_get_source.return_value.detects_primary_keys = False
mock_get_source.return_value.server_managed_job_input_fields.return_value = []
mock_get_source.return_value.job_inputs_add_connection_host.return_value = False
mock_get_source.return_value.has_preserved_row_backed_credentials.return_value = False
@@ -5566,6 +5568,7 @@ class TestExternalDataSource(APIBaseTest):
SourceSchema(name="table_1", supports_incremental=False, supports_append=False, row_count=42)
]
mock_source.get_endpoint_permissions.return_value = {}
+ mock_source.detects_primary_keys = False
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_sources/database_schema/",
@@ -5662,6 +5665,7 @@ class TestExternalDataSource(APIBaseTest):
{"field": "id", "label": "id", "type": "integer", "nullable": True},
],
"detected_primary_keys": ["id"],
+ "primary_key_detection_supported": True,
"permission_error": None,
"rls_warning": None,
}
@@ -5740,6 +5744,7 @@ class TestExternalDataSource(APIBaseTest):
{"field": "id", "label": "id", "type": "integer", "nullable": True},
],
"detected_primary_keys": ["id"],
+ "primary_key_detection_supported": True,
"permission_error": None,
"rls_warning": None,
}