:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): require a key before a table syncs incrementally (#99664)
Daniel RC9450a5b67d53
diff --git a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsxindex b5552a546cb8..db359dce2cfe 100644--- a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx@@ -1,7 +1,7 @@import { ExternalDataSourceSyncSchema } from '~/types'import { SyncTypeLabelMap } from '../../../utils'-import { shouldOfferXmin } from './SyncMethodForm'+import { getInitialRadioState, getSaveDisabledReason, shouldOfferXmin } from './SyncMethodForm'const baseSchema: ExternalDataSourceSyncSchema = {table: 'orders',@@ -33,4 +33,19 @@ describe('SyncMethodForm', () => {it('exposes a label for the xmin sync type', () => {expect(SyncTypeLabelMap.xmin).toBe('xmin')})++ 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)+ })++ it.each([+ ['key resolvable', true, 'incremental'],+ ['keyless with columns known', false, 'append'],+ ])('preselects incremental only when the key resolves: %s', (_, keyResolvable, expected) => {+ expect(getInitialRadioState({ ...baseSchema, xmin_available: false }, true, true, keyResolvable)).toBe(expected)+ })})diff --git a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsxindex 2cfa72967ce0..85febfcb732a 100644--- a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx@@ -131,10 +131,12 @@ const getCdcSyncSupported = (export const shouldOfferXmin = (schema: ExternalDataSourceSyncSchema): boolean =>!schema.webhook_only && !!schema.xmin_available-const getSaveDisabledReason = (+export const getSaveDisabledReason = (syncType: 'full_refresh' | 'incremental' | 'append' | 'webhook' | 'cdc' | 'xmin' | undefined,incrementalField: string | null,- appendField: string | null+ appendField: string | null,+ mergeKey: string[] | null,+ columnsKnown: boolean): string | undefined => {if (!syncType) {return 'You must select a sync method before saving'@@ -144,15 +146,24 @@ const getSaveDisabledReason = (return 'You must select an incremental field'}+ // 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) {+ return 'Select primary key columns, or use full table replication instead'+ }+if (syncType === 'append' && !appendField) {return 'You must select an append field'}}-const getInitialRadioState = (+export const getInitialRadioState = (schema: ExternalDataSourceSyncSchema,incrementalSyncSupported: boolean,- appendSyncSupported: boolean+ appendSyncSupported: boolean,+ keyResolvable: boolean): 'full_refresh' | 'incremental' | 'append' | 'webhook' | 'cdc' | 'xmin' => {if (schema.sync_type) {return schema.sync_type@@ -167,7 +178,9 @@ const getInitialRadioState = (if (schema.cdc_available) {return 'cdc'}- if (incrementalSyncSupported) {+ // Offering incremental to a table with no key only leads to a sync that fails on its second+ // run, so a keyless table falls through to a method it can actually run.+ if (incrementalSyncSupported && keyResolvable) {return 'incremental'}if (appendSyncSupported) {@@ -197,11 +210,13 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormProconst 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)const defaultField = schema.incremental_field ?? schema.incremental_fields[0]?.field ?? nullconst [radioValue, setRadioValue] = useState(() =>- getInitialRadioState(schema, !incrementalSyncSupported.disabled, !appendSyncSupported.disabled)+ getInitialRadioState(schema, !incrementalSyncSupported.disabled, !appendSyncSupported.disabled, keyResolvable))const [incrementalFieldValue, setIncrementalFieldValue] = useState(defaultField)const [appendFieldValue, setAppendFieldValue] = useState(defaultField)@@ -219,7 +234,14 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormProconst [lookbackUnit, setLookbackUnit] = useState<LookbackUnit>(initialLookback.unit)useEffect(() => {- setRadioValue(getInitialRadioState(schema, !incrementalSyncSupported.disabled, !appendSyncSupported.disabled))+ setRadioValue(+ getInitialRadioState(+ schema,+ !incrementalSyncSupported.disabled,+ !appendSyncSupported.disabled,+ keyResolvable+ )+ )setIncrementalFieldValue(defaultField)setAppendFieldValue(defaultField)setPrimaryKeyColumns(schema.primary_key_columns ?? (primaryKeyLocked ? [] : (resolvedDetectedPks ?? [])))@@ -629,7 +651,13 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormProreturn false})()- const validationDisabledReason = getSaveDisabledReason(radioValue, incrementalFieldValue, appendFieldValue)+ const validationDisabledReason = getSaveDisabledReason(+ radioValue,+ incrementalFieldValue,+ appendFieldValue,+ primaryKeyColumns.length ? primaryKeyColumns : resolvedDetectedPks,+ columns.length > 0+ )const saveDisabledReason = validationDisabledReason ?? (!isDirty ? 'No changes to save' : undefined)const handleSave = (): void => {diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex 8fd449645086..687ff9c7b33f 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -901,6 +901,39 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers"Include sync_type in the same request to change the sync type.")+ # An incremental sync merges rows on a primary key. A schema saved without one syncs once+ # and then fails on every later run, so the switch is refused rather than accepted and+ # broken at the second sync. `id` counts, because discovery falls back to it.+ # Only the request that makes the table incremental, or edits its key, is judged. A table+ # already incremental keeps taking unrelated edits and a re-enable after a fix at the source.+ switches_to_incremental = (+ resulting_sync_type == ExternalDataSchema.SyncType.INCREMENTAL+ and instance.sync_type != ExternalDataSchema.SyncType.INCREMENTAL+ )+ if switches_to_incremental or (+ resulting_sync_type == ExternalDataSchema.SyncType.INCREMENTAL and "primary_key_columns" in data+ ):+ metadata = instance.schema_metadata or {}+ metadata_columns = metadata.get("columns") if isinstance(metadata, dict) else None+ known_columns = metadata_columns if isinstance(metadata_columns, list) else []+ column_names = {str(column.get("name", "")).lower() for column in known_columns if isinstance(column, dict)}+ # The key this request leaves in force, not the one it replaces: clearing an existing+ # 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:+ raise ValidationError(+ f"'{instance.name}' has no primary key to sync incrementally on. "+ "Set primary_key_columns for it, or choose full_refresh."+ )+ # Only the names this request supplies. A key stored against older metadata must not+ # block an edit that leaves it alone.+ unknown_keys = [key for key in (requested_keys or []) if str(key).lower() not in column_names]+ if column_names and unknown_keys:+ raise ValidationError(f"'{instance.name}' has no column named {', '.join(unknown_keys)} to merge on.")+trigger_refresh = False# Update the validated_data with incremental fieldsif resulting_sync_type in incremental_style_types:diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.pyindex daf704e62a0b..b2df97840339 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py@@ -1426,6 +1426,32 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):schema_name = schema.get("name")source_schema = source_schemas_by_name.get(schema_name)+ # An incremental sync merges rows on a primary key. Created without one, the table+ # syncs once (the first write overwrites) and then fails on every later run, so the+ # configuration is refused here rather than at the second sync.+ # Only for a table discovery introspected. A source that reports no columns here+ # (a managed REST source, say) resolves its key at sync time instead, so the absence+ # of a detected key says nothing about whether the merge has one. `id` counts for the+ # same reason it does at sync time: resolution falls back to it.+ introspected_columns = (source_schema.columns if source_schema else None) or []+ has_id_column = any(str(column[0]).lower() == "id" for column in introspected_columns)+ if (+ should_sync+ and sync_type == "incremental"+ and not primary_key_columns+ and introspected_columns+ and not source_schema.detected_primary_keys # type: ignore[union-attr]+ and not has_id_column+ ):+ new_source_model.delete()+ return Response(+ data={+ "message": f"Table '{schema_name}' has no primary key to sync incrementally on. "+ "Set primary_key_columns for it, or choose full_refresh."+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+metadata_source_catalog: str | Nonemetadata_source_schema: str | Nonemetadata_source_table_name: str | Nonediff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.pyindex 07d2d01e2c33..ce2e255f632f 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@@ -588,6 +588,89 @@ class TestExternalDataSchema(APIBaseTest):assert schema.sync_type_config.get("reset_pipeline") is Noneassert schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH+ @parameterized.expand(+ [+ ("no_key_and_no_id_column", [{"name": "amount"}], None, None, False, "no primary key"),+ ("id_column_is_the_fallback", [{"name": "id"}, {"name": "amount"}], None, None, True, ""),+ (+ "key_supplied_in_the_request",+ [{"name": "amount"}, {"name": "order_id"}],+ None,+ ["order_id"],+ True,+ "",+ ),+ ("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"),+ ("already_incremental_reenable_passes", [{"name": "amount"}], None, None, True, "", "incremental"),+ (+ "already_incremental_clearing_key_is_refused",+ [{"name": "amount"}],+ ["order_id"],+ [],+ False,+ "no primary key",+ "incremental",+ ),+ ]+ )+ def test_switching_to_incremental_requires_a_key_the_merge_can_use(+ self,+ _name: str,+ columns: list[dict[str, str]],+ persisted_keys: list[str] | None,+ requested_keys: list[str] | None,+ expected_ok: bool,+ expected_error: str,+ initial_sync_type: str = "full_refresh",+ ) -> None:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type=ExternalDataSourceType.STRIPE,+ job_inputs={"auth_method": {"selection": "api_key", "stripe_secret_key": "123"}},+ )+ schema = ExternalDataSchema.objects.create(+ name="orders",+ team=self.team,+ source=source,+ should_sync=False,+ sync_type=initial_sync_type,+ sync_type_config={+ **({"primary_key_columns": persisted_keys} if persisted_keys else {}),+ "schema_metadata": {"columns": columns},+ },+ )+ payload: dict[str, Any] = {"should_sync": True}+ if initial_sync_type != "incremental":+ payload.update(+ {"sync_type": "incremental", "incremental_field": "created_at", "incremental_field_type": "datetime"}+ )+ if requested_keys is not None:+ payload["primary_key_columns"] = requested_keys++ with (+ mock.patch(+ "products.warehouse_sources.backend.presentation.views.external_data_schema.trigger_external_data_workflow"+ ),+ mock.patch(+ "products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",+ return_value=False,+ ),+ mock.patch(+ "products.warehouse_sources.backend.presentation.views.external_data_schema.sync_external_data_job_workflow"+ ),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}", data=payload+ )++ if expected_ok:+ assert response.status_code == 200, response.content+ else:+ assert response.status_code == 400, response.content+ assert expected_error in str(response.json()).lower()+def test_update_schema_sync_type_is_logged_to_activity(self):source = ExternalDataSource.objects.create(team=self.team,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.pyindex b1ec7483723d..01bd578891bb 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@@ -2379,6 +2379,7 @@ class TestExternalDataSource(APIBaseTest):supports_incremental=False,supports_append=False,columns=[("something", "DATE", False)],+ detected_primary_keys=["something"],)],),@@ -4833,6 +4834,71 @@ class TestExternalDataSource(APIBaseTest):assert ExternalDataSource.objects.filter(team_id=self.team.pk).count() == 0mock_setup_cdc_resources.assert_not_called()+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")+ def test_create_rejects_incremental_for_a_table_with_no_key_to_merge_on(self, mock_get_source):+ _configure_source_mock_versioning(mock_get_source)+ source_mock = mock_get_source.return_value+ source_mock.validate_config.return_value = (True, [])+ parsed_config = Mock()+ parsed_config.schema = "public"+ parsed_config.to_dict.return_value = {+ "host": "localhost",+ "port": 5432,+ "database": "app",+ "user": "user",+ "password": "pass",+ "schema": "public",+ }+ source_mock.parse_config.return_value = parsed_config+ source_mock.validate_credentials.return_value = (True, None)+ source_mock.get_schemas.return_value = [+ SourceSchema(+ name="events",+ supports_incremental=True,+ supports_append=True,+ columns=[("amount", "integer", False), ("updated_at", "timestamp", False)],+ foreign_keys=[],+ incremental_fields=[+ {+ "label": "updated_at",+ "type": IncrementalFieldType.Timestamp,+ "field": "updated_at",+ "field_type": IncrementalFieldType.Timestamp,+ "nullable": False,+ }+ ],+ detected_primary_keys=None,+ ),+ ]++ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/",+ data={+ "source_type": "Postgres",+ "payload": {+ "host": "localhost",+ "port": 5432,+ "database": "app",+ "user": "user",+ "password": "pass",+ "schema": "public",+ "schemas": [+ {+ "name": "events",+ "should_sync": True,+ "sync_type": "incremental",+ "incremental_field": "updated_at",+ "incremental_field_type": "timestamp",+ },+ ],+ },+ },+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "no primary key" in response.json()["message"].lower()+ assert ExternalDataSource.objects.filter(team_id=self.team.pk).count() == 0+@parameterized.expand([# Frontend sends null when the user leaves the PK selector empty — backend falls@@ -4841,8 +4907,8 @@ class TestExternalDataSource(APIBaseTest):("fallback_to_detected", None, ["id"], ["id"]),# User explicitly overrides — caller value wins, detected is ignored.("explicit_wins_over_detected", ["custom_pk"], ["id"], ["custom_pk"]),- # Nothing detected and nothing provided — key omitted from sync_type_config- # entirely (preserves pre-existing behaviour for tables without a PK).+ # Nothing detected and nothing provided, but the table has an `id` column, which is+ # what resolution falls back to — so the key is omitted here and found at sync time.("both_absent_omits_key", None, None, None),])