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(data-warehouse): let users set a primary key on a keyless incremental table (#78210)

Tom Owerseec1caf8e8b4
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
index 7dacaeee5662..78a090071e78 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
@@ -479,7 +479,7 @@ function SyncMethodSection({ sourceId, schema }: { sourceId: string; schema: Ext
}}
availableColumns={schemaIncrementalFields.available_columns ?? []}
detectedPrimaryKeys={schemaIncrementalFields.detected_primary_keys ?? null}
- primaryKeyLocked={!!schema.table}
+ primaryKeyLocked={!!schema.table && !!schema.primary_key_columns?.length}
onClose={() => {}}
onSave={persistSyncMethod}
/>
diff --git a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
index 6326e83a5dce..7d8fea2e97d7 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
@@ -203,9 +203,9 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormPro
)
const [incrementalFieldValue, setIncrementalFieldValue] = useState(defaultField)
const [appendFieldValue, setAppendFieldValue] = useState(defaultField)
- // Prefill detected PKs only when the selector is editable. For locked schemas
- // (already synced) the backend rejects any PK diff, so prefilling from detected
- // would silently turn unrelated edits into "Primary key cannot be changed" errors.
+ // Prefill detected PKs only when the selector is editable. A locked schema already has a key
+ // the backend refuses to swap, so prefilling from detected would silently turn unrelated edits
+ // into "Primary key cannot be changed" errors.
const [primaryKeyColumns, setPrimaryKeyColumns] = useState<string[]>(
schema.primary_key_columns ?? (primaryKeyLocked ? [] : (resolvedDetectedPks ?? []))
)
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 bccc0d4f21a7..4f54b2e8dafb 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -795,8 +795,12 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
if "primary_key_columns" in data:
new_pk = data.get("primary_key_columns")
old_pk = instance.sync_type_config.get("primary_key_columns")
+ # Only swapping an established key breaks merge identity against already-synced
+ # rows. A keyless incremental table can't merge at all, and picking its first key
+ # is the fix we tell the user to apply, so don't block that.
if (
resulting_sync_type == ExternalDataSchema.SyncType.INCREMENTAL
+ and old_pk
and new_pk != old_pk
and instance.table is not None
):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index 673bac0bfc60..27dc86410524 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.l
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
BillingLimitsWillBeReachedException,
DuplicatePrimaryKeysException,
+ MissingPrimaryKeysException,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (
is_transient_object_store_error,
@@ -301,6 +302,8 @@ async def persist_primary_keys(
def validate_incremental_sync(
is_incremental: bool,
resource: SourceResponse,
+ *,
+ is_first_sync: bool = True,
) -> None:
# Check for duplicate primary keys
if is_incremental and resource.has_duplicate_primary_keys:
@@ -309,6 +312,13 @@ def validate_incremental_sync(
f"has a unique primary key. Primary keys being used are: {resource.primary_keys}"
)
+ # The Delta merge needs a key to match rows on, so a keyless incremental table fails once a
+ # table already exists. Raise before extraction rather than letting the writer hit it mid-load:
+ # on pipeline v3 the write happens in the load consumer, which can only fail the job, so the
+ # schema is never paused and the same doomed run repeats on every schedule.
+ if is_incremental and not is_first_sync and not resource.primary_keys:
+ raise MissingPrimaryKeysException()
+
async def setup_row_tracking_with_billing_check(
team_id: int,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
index 09b92b4825ab..339834d6bec3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
@@ -12,12 +12,17 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEvent
+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
handle_corrupted_delta_log,
handle_reset_or_full_refresh,
persist_primary_keys,
report_heartbeat_timeout,
resolve_primary_keys,
+ validate_incremental_sync,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ MissingPrimaryKeysException,
)
from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException
@@ -436,3 +441,41 @@ class TestHandleResetOrFullRefresh:
helper.reset_table.assert_awaited_once()
schema.refresh_from_db()
assert "reset_pipeline" not in schema.sync_type_config
+
+
+class TestValidateIncrementalSync:
+ @parameterized.expand(
+ [
+ # The failure this guard exists for: a keyless incremental table can never merge into
+ # the Delta table that an earlier run already wrote.
+ ("keyless_incremental_after_first_sync_raises", True, False, None, True),
+ # The first run writes the whole table, so it doesn't need a merge key. Raising here
+ # would break every initial sync of a keyless table.
+ ("keyless_incremental_first_sync_allowed", True, True, None, False),
+ # Full refresh overwrites, so it never merges on a key.
+ ("keyless_full_refresh_allowed", False, False, None, False),
+ ("incremental_with_key_allowed", True, False, ["id"], False),
+ ]
+ )
+ def test_missing_primary_keys(
+ self,
+ _name: str,
+ is_incremental: bool,
+ is_first_sync: bool,
+ primary_keys: list[str] | None,
+ expect_raise: bool,
+ ):
+ resource = MagicMock(primary_keys=primary_keys, has_duplicate_primary_keys=False)
+
+ if not expect_raise:
+ validate_incremental_sync(is_incremental, resource, is_first_sync=is_first_sync)
+ return
+
+ with pytest.raises(MissingPrimaryKeysException):
+ validate_incremental_sync(is_incremental, resource, is_first_sync=is_first_sync)
+
+ def test_message_stays_classified_as_non_retryable(self):
+ # The message is what pauses the schema: without a matching Any_Source_Errors entry the
+ # run is retried on every schedule even though only the user can resolve it.
+ message = str(MissingPrimaryKeysException())
+ assert [key for key in Any_Source_Errors if key in message]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
index b6295b0bcdc2..0ab11f75d0f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
@@ -67,6 +67,19 @@ class DuplicatePrimaryKeysException(Exception):
pass
+# Matched as a substring by the shared non-retryable classification (`Any_Source_Errors`) and by the
+# v3 load consumer, so both keep recognizing the condition — keep the wording in step with them.
+MISSING_PRIMARY_KEYS_ERROR = "Primary key required for incremental syncs"
+
+
+class MissingPrimaryKeysException(Exception):
+ """An incremental table has no primary key to merge on, so it can't be merged into the
+ already-written Delta table. Permanent until the user picks a key or switches the sync type."""
+
+ def __init__(self, message: str = MISSING_PRIMARY_KEYS_ERROR) -> None:
+ super().__init__(message)
+
+
class QueryTimeoutException(Exception):
pass
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
index eb03a3d857eb..76535119e469 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
@@ -14,6 +14,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.sync import database_sync_to_async_pool
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ MissingPrimaryKeysException,
align_incoming_decimals_to_delta,
first_per_pk_table,
normalize_column_name,
@@ -320,7 +321,7 @@ class DeltaWriter:
if write_type == "incremental" and delta_table is not None and not is_first_sync:
if not primary_keys or len(primary_keys) == 0:
- raise Exception("Primary key required for incremental syncs")
+ raise MissingPrimaryKeysException()
# The merge casts every source column to its stored column type; a scale-heavy decimal
# column (e.g. decimal128(38, 32)) overflows that cast on larger values. Align to the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
index 7e00696ae7db..1777da42b9bb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
@@ -166,7 +166,11 @@ class PipelineNonDLT(Generic[ResumableData]):
await reset_rows_synced_if_needed(self._job, self._is_incremental, self._reset_pipeline, should_resume)
- validate_incremental_sync(self._is_incremental, self._resource)
+ validate_incremental_sync(
+ self._is_incremental,
+ self._resource,
+ is_first_sync=self._table is None or self._reset_pipeline,
+ )
await persist_primary_keys(self._schema, self._resource, self._is_incremental, self._logger)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index badbfb5244b4..06bbd2a1f377 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -268,7 +268,11 @@ class PipelineV3(Generic[ResumableData]):
await reset_rows_synced_if_needed(self._job, self._is_incremental, self._reset_pipeline, should_resume)
- validate_incremental_sync(self._is_incremental, self._resource)
+ validate_incremental_sync(
+ self._is_incremental,
+ self._resource,
+ is_first_sync=self._table is None or self._reset_pipeline,
+ )
await persist_primary_keys(self._schema, self._resource, self._is_incremental, self._logger)
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 70a6f2edca5c..91c354c9df92 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
@@ -1607,7 +1607,15 @@ class TestExternalDataSchema(APIBaseTest):
assert schema.sync_type_config.get("primary_key_columns") == ["_id", "source_id"]
assert schema.primary_key_columns == ["_id", "source_id"]
- def test_update_schema_rejects_primary_key_change_with_existing_data(self):
+ @parameterized.expand(
+ [
+ ("swapping_an_established_key_is_rejected", ["id"], 400, ["id"]),
+ ("setting_the_first_key_is_allowed", None, 200, ["_id"]),
+ ]
+ )
+ def test_update_schema_primary_key_change_with_existing_data(
+ self, _name: str, stored_pk: list[str] | None, expected_status: int, expected_pk: list[str]
+ ):
source = ExternalDataSource.objects.create(
team=self.team, source_type=ExternalDataSourceType.STRIPE, job_inputs={"stripe_secret_key": "123"}
)
@@ -1622,7 +1630,8 @@ class TestExternalDataSchema(APIBaseTest):
sync_type_config={
"incremental_field": "created",
"incremental_field_type": "integer",
- "primary_key_columns": ["id"],
+ "incremental_field_last_value": 1,
+ **({"primary_key_columns": stored_pk} if stored_pk else {}),
},
table=table,
)
@@ -1637,7 +1646,10 @@ class TestExternalDataSchema(APIBaseTest):
},
)
- assert response.status_code == 400
+ assert response.status_code == expected_status
+
+ schema.refresh_from_db()
+ assert schema.sync_type_config.get("primary_key_columns") == expected_pk
def test_update_schema_primary_key_columns_not_reset_on_full_refresh(self):
source = ExternalDataSource.objects.create(