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): stop intermittent snowflake incremental PK crash (#70543)

Kyle Swank96d364198890
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 ecf33bf8cfe7..3f534ceb5819 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
@@ -28,6 +28,9 @@ from products.warehouse_sources.backend.temporal.data_imports.row_tracking impor
increment_rows,
will_hit_billing_limit,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.metadata import (
+ extract_available_column_names,
+)
from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException
if TYPE_CHECKING:
@@ -227,6 +230,69 @@ async def reset_rows_synced_if_needed(
await database_sync_to_async_pool(job.save)(update_fields=["rows_synced", "updated_at"])
+def resolve_primary_keys(
+ schema: "ExternalDataSchema",
+ resource: SourceResponse,
+) -> list[str] | None:
+ """Resolve the primary keys for an incremental merge with a stable precedence.
+
+ 1. Persisted `sync_type_config["primary_key_columns"]` (a user override or an earlier
+ detection) — always wins.
+ 2. Otherwise the keys the source detected live this run.
+ 3. Otherwise fall back to an `id` column when the schema has one — mirroring the discovery
+ path, which sync-time driver detection (e.g. a flaky Snowflake `SHOW PRIMARY KEYS`) lacks.
+
+ Returns None when no key can be resolved, so the keyless-table guardrail still fires.
+ """
+ if schema.primary_key_columns:
+ return schema.primary_key_columns
+ if resource.primary_keys:
+ return list(resource.primary_keys)
+ if "id" in extract_available_column_names(schema.schema_metadata):
+ return ["id"]
+ return None
+
+
+async def persist_primary_keys(
+ schema: "ExternalDataSchema",
+ resource: SourceResponse,
+ is_incremental: bool,
+ logger: FilteringBoundLogger,
+) -> None:
+ """Persist a freshly resolved primary key so future runs stop depending on flaky live
+ detection (e.g. a Snowflake `SHOW PRIMARY KEYS` that intermittently returns nothing).
+
+ Only fills an empty stored value — never overwrites a user override — and checks again
+ inside the row lock so a concurrent API edit isn't clobbered. Best-effort: a failure here
+ must not fail an otherwise successful sync.
+ """
+ if not is_incremental or schema.primary_key_columns:
+ return
+ primary_keys = resource.primary_keys
+ if not primary_keys:
+ return
+
+ resolved = list(primary_keys)
+
+ def _set_if_absent(config: dict[str, Any]) -> None:
+ if not config.get("primary_key_columns"):
+ config["primary_key_columns"] = resolved
+
+ from products.warehouse_sources.backend.models.external_data_schema import ( # noqa: PLC0415 — Django model import kept off this activity module's load path
+ update_sync_type_config_keys,
+ )
+
+ try:
+ config = await database_sync_to_async_pool(update_sync_type_config_keys)(
+ schema.id,
+ schema.team_id,
+ mutate=_set_if_absent,
+ )
+ schema.sync_type_config = config
+ except Exception:
+ await logger.aexception("Failed to persist detected primary keys into sync_type_config")
+
+
def validate_incremental_sync(
is_incremental: bool,
resource: SourceResponse,
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 2e1b9be74787..5fb0ea6709ad 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
@@ -15,13 +15,113 @@ from products.warehouse_sources.backend.models.oom_event import ExternalDataSche
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,
run_pre_write_defensive_compact,
)
_EXTRACT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract"
+class TestResolvePrimaryKeys:
+ @parameterized.expand(
+ [
+ # A persisted key (user override or earlier detection) always wins over live detection.
+ ("persisted_wins_over_live", ["user_pk"], ["live_pk"], {"columns": [{"name": "id"}]}, ["user_pk"]),
+ # No persisted key -> use what the source detected live this run.
+ ("live_used_when_no_persisted", None, ["live_pk"], {"columns": [{"name": "id"}]}, ["live_pk"]),
+ # Neither persisted nor live, but the table has `id` -> mirror the discovery-time fallback.
+ ("id_fallback_when_neither", None, None, {"columns": [{"name": "id"}, {"name": "name"}]}, ["id"]),
+ # Nothing to fall back on -> None, so the keyless-table guardrail still fires.
+ ("none_when_no_id_and_nothing_else", None, None, {"columns": [{"name": "name"}]}, None),
+ ]
+ )
+ def test_precedence(
+ self,
+ _name: str,
+ persisted: list[str] | None,
+ live: list[str] | None,
+ schema_metadata: dict,
+ expected: list[str] | None,
+ ):
+ schema = MagicMock(primary_key_columns=persisted, schema_metadata=schema_metadata)
+ resource = MagicMock(primary_keys=live)
+ assert resolve_primary_keys(schema, resource) == expected
+
+
+class TestPersistPrimaryKeys:
+ @parameterized.expand(
+ [
+ # name, is_incremental, persisted_pk, resource_pks, db_config_before, expected_written (None = no write attempted)
+ # Full-refresh schemas don't merge on a PK — never touch sync_type_config.
+ ("skips_when_not_incremental", False, None, ["id"], {}, None),
+ # A stored PK is already the source of truth — nothing to backfill.
+ ("skips_when_already_persisted", True, ["existing"], ["id"], {}, None),
+ # No resolvable PK -> leave it empty so the keyless-table guardrail still fires.
+ ("skips_when_no_resolved_pk", True, None, None, {}, None),
+ # The fix: an incremental schema with no stored PK backfills the resolved one.
+ ("backfills_when_incremental_and_empty", True, None, ["id"], {}, {"primary_key_columns": ["id"]}),
+ # A concurrent API edit that landed a PK first must not be clobbered inside the lock.
+ (
+ "does_not_clobber_concurrent_write",
+ True,
+ None,
+ ["id"],
+ {"primary_key_columns": ["already"]},
+ {"primary_key_columns": ["already"]},
+ ),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_persists_only_when_incremental_and_empty(
+ self,
+ _name: str,
+ is_incremental: bool,
+ persisted: list[str] | None,
+ resource_pks: list[str] | None,
+ db_config_before: dict,
+ expected_written: dict | None,
+ ):
+ schema = MagicMock(id="s1", team_id=1, primary_key_columns=persisted)
+ resource = MagicMock(primary_keys=resource_pks)
+
+ captured: dict = {}
+
+ def fake_pool(fn):
+ async def _call(schema_id, team_id, *, mutate=None, **kwargs):
+ config = dict(db_config_before)
+ if mutate is not None:
+ mutate(config)
+ captured["config"] = config
+ return config
+
+ return _call
+
+ with patch(f"{_EXTRACT_MODULE}.database_sync_to_async_pool", fake_pool):
+ await persist_primary_keys(schema, resource, is_incremental, AsyncMock())
+
+ assert captured.get("config") == expected_written
+
+ @pytest.mark.asyncio
+ async def test_persistence_failure_does_not_raise(self):
+ # Best-effort: a DB failure while backfilling the PK must not fail an otherwise good sync.
+ schema = MagicMock(id="s1", team_id=1, primary_key_columns=None)
+ resource = MagicMock(primary_keys=["id"])
+ logger = AsyncMock()
+
+ def fake_pool(fn):
+ async def _call(*args, **kwargs):
+ raise RuntimeError("pooler dropped the connection")
+
+ return _call
+
+ with patch(f"{_EXTRACT_MODULE}.database_sync_to_async_pool", fake_pool):
+ await persist_primary_keys(schema, resource, True, logger)
+
+ logger.aexception.assert_awaited_once()
+
+
class TestRunPreWriteDefensiveCompact:
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
index 8254b2bafdc7..1a5c210f8d59 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
@@ -30,7 +30,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.e
finalize_desc_sort_incremental_value,
handle_corrupted_delta_log,
handle_reset_or_full_refresh,
+ persist_primary_keys,
reset_rows_synced_if_needed,
+ resolve_primary_keys,
run_pre_write_defensive_compact,
setup_row_tracking_with_billing_check,
should_check_shutdown,
@@ -170,9 +172,10 @@ class PipelineNonDLT(Generic[ResumableData]):
self._resource = source_response
self._resource_name = source_response.name
- # Allow user-specified primary keys to override auto-detected ones
- if schema.primary_key_columns:
- self._resource.primary_keys = schema.primary_key_columns
+ # Persisted PK (user override or earlier detection) > live-detected > `id` fallback. Keeps
+ # the merge key stable across runs when live detection (e.g. Snowflake SHOW PRIMARY KEYS)
+ # intermittently returns nothing.
+ self._resource.primary_keys = resolve_primary_keys(schema, self._resource)
self._job = job
self._reset_pipeline = reset_pipeline
@@ -225,6 +228,8 @@ class PipelineNonDLT(Generic[ResumableData]):
validate_incremental_sync(self._is_incremental, self._resource)
+ await persist_primary_keys(self._schema, self._resource, self._is_incremental, self._logger)
+
await setup_row_tracking_with_billing_check(
self._job.team_id,
self._schema,
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 762764933782..180147edcaae 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
@@ -32,7 +32,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.e
finalize_desc_sort_incremental_value,
handle_corrupted_delta_log,
handle_reset_or_full_refresh,
+ persist_primary_keys,
reset_rows_synced_if_needed,
+ resolve_primary_keys,
run_pre_write_defensive_compact,
setup_row_tracking_with_billing_check,
should_check_shutdown,
@@ -119,9 +121,10 @@ class PipelineV3(Generic[ResumableData]):
self._resource = source_response
self._resource_name = source_response.name
- # Allow user-specified primary keys to override auto-detected ones
- if schema.primary_key_columns:
- self._resource.primary_keys = schema.primary_key_columns
+ # Persisted PK (user override or earlier detection) > live-detected > `id` fallback. Keeps
+ # the merge key stable across runs when live detection (e.g. Snowflake SHOW PRIMARY KEYS)
+ # intermittently returns nothing.
+ self._resource.primary_keys = resolve_primary_keys(schema, self._resource)
self._job = job
self._reset_pipeline = reset_pipeline
@@ -258,6 +261,8 @@ class PipelineV3(Generic[ResumableData]):
validate_incremental_sync(self._is_incremental, self._resource)
+ await persist_primary_keys(self._schema, self._resource, self._is_incremental, self._logger)
+
await setup_row_tracking_with_billing_check(
self._job.team_id,
self._schema,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
index 1a875b62ce02..f0b9933f1a23 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
@@ -518,8 +518,27 @@ class SnowflakeImplementation(
fully qualified `database.schema.table` reference, so this method
takes `database` in addition to schema/table_name — the only
driver to do so.
+
+ Permission- and session-sensitive, like the schema-level
+ `get_primary_keys`: some roles can't see PK metadata and the `SHOW`
+ can transiently fail or return nothing. Swallow a failing `SHOW` and
+ return None so the pipeline falls back to a persisted or `id`-column
+ primary key instead of crashing an incremental merge. A missing
+ `column_name` still raises — that's a driver shape change, not a
+ transient issue, and it's worth surfacing.
"""
- cursor.execute("SHOW PRIMARY KEYS IN IDENTIFIER(%s)", (f"{database}.{schema}.{table_name}",))
+ try:
+ cursor.execute("SHOW PRIMARY KEYS IN IDENTIFIER(%s)", (f"{database}.{schema}.{table_name}",))
+ except Exception as e:
+ structlog.get_logger().warning(
+ "Failed to detect primary key for Snowflake table",
+ database=database,
+ schema=schema,
+ table_name=table_name,
+ exc_info=e,
+ )
+ capture_exception(e)
+ return None
column_index = next((i for i, row in enumerate(cursor.description) if row.name == "column_name"), -1)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
index f9554446baf3..c1c4d4bcca3d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
@@ -557,6 +557,12 @@ class TestGetPrimaryKeysForTable:
with pytest.raises(ValueError, match="column_name"):
impl.get_primary_keys_for_table(cursor, "DB", "PUBLIC", "t")
+ def test_returns_none_when_show_fails(self, impl, cursor):
+ # A transient/permission SHOW failure must degrade to None so the pipeline falls back to a
+ # persisted or `id`-column PK, instead of crashing the incremental merge intermittently.
+ cursor.execute.side_effect = Exception("does not exist or not authorized")
+ assert impl.get_primary_keys_for_table(cursor, "DB", "PUBLIC", "t") is None
+
class TestGetRowsToSync:
def test_returns_count(self, impl, cursor, logger):