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): probe the key an incremental sync merges on (#99515)

Daniel RC6f26b83599c3
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index df7bcf7c5f58..d1148dfe94ef 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -239,7 +239,7 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
# See `sources/common/history_window.py`. A column rather than a `sync_type_config` key
# because it has to outlive a reset, and clearing that blob is what a reset is for.
history_start = models.DateTimeField(null=True, blank=True)
- # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "xmin_last_value": int, "xmin_ceiling": int, "xmin_num_wraparound": int, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str }, "repartition_rewrite": { "temp_uri": str, "rows_written": int, "target": dict } }
+ # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "verified_primary_keys": list[str] | None, "xmin_last_value": int, "xmin_ceiling": int, "xmin_num_wraparound": int, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str }, "repartition_rewrite": { "temp_uri": str, "rows_written": int, "target": dict } }
sync_type_config = models.JSONField(
default=dict,
blank=True,
@@ -625,6 +625,14 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
return None
+ @property
+ def verified_primary_keys(self) -> list[str] | None:
+ """The key a full-table probe proved unique, so later runs only probe what they read."""
+ if self.sync_type_config:
+ return self.sync_type_config.get("verified_primary_keys", None)
+
+ return None
+
@property
def incremental_sync_blocked(self) -> str | None:
"""Why the last run proved this schema's incremental sync can never succeed, if it did."""
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 8faac65f4369..2aa159564ef0 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
@@ -32,6 +32,7 @@ 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.primary_keys import resolve_merge_keys
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.metadata import (
extract_available_column_names,
)
@@ -304,18 +305,11 @@ def resolve_primary_keys(
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)
- # Case-insensitive: engines like Snowflake uppercase unquoted identifiers, so the column
- # arrives as `ID`. Return the actual stored casing — the merge indexes batches by real name.
- id_column = next(
- (name for name in extract_available_column_names(schema.schema_metadata) if name.lower() == "id"), None
+ return resolve_merge_keys(
+ schema.primary_key_columns,
+ resource.primary_keys,
+ extract_available_column_names(schema.schema_metadata),
)
- if id_column is not None:
- return [id_column]
- return None
async def persist_primary_keys(
@@ -323,6 +317,16 @@ async def persist_primary_keys(
resource: SourceResponse,
is_incremental: bool,
logger: FilteringBoundLogger,
+) -> None:
+ await _persist_detected_primary_keys(schema, resource, is_incremental, logger)
+ await persist_verified_primary_keys(schema, resource, logger)
+
+
+async def _persist_detected_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).
@@ -362,6 +366,34 @@ async def persist_primary_keys(
await logger.aexception("Failed to persist detected primary keys into sync_type_config")
+async def persist_verified_primary_keys(
+ schema: "ExternalDataSchema",
+ resource: SourceResponse,
+ logger: FilteringBoundLogger,
+) -> None:
+ """Record the key a full-table probe proved unique, so later runs only probe what they read.
+
+ Best-effort: losing this costs another full probe next run, not correctness.
+ """
+ verified = resource.verified_primary_keys
+ if not verified or list(verified) == list(schema.verified_primary_keys or []):
+ return
+
+ 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,
+ updates={"verified_primary_keys": list(verified)},
+ )
+ schema.sync_type_config = config
+ except Exception:
+ await logger.aexception("Failed to persist verified 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/sources/common/primary_keys.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/primary_keys.py
new file mode 100644
index 000000000000..927589596a45
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/primary_keys.py
@@ -0,0 +1,56 @@
+"""Which key an incremental sync merges on, and when that key has to be proven unique."""
+
+from collections.abc import Iterable, Sequence
+
+
+def resolve_merge_keys(
+ persisted_keys: Sequence[str] | None,
+ detected_keys: Sequence[str] | None,
+ available_columns: Iterable[str],
+) -> list[str] | None:
+ """The key the merge will match rows on.
+
+ A persisted key is the customer's own choice (or an earlier detection) and always wins, so the
+ merge key stays stable across runs when live detection is flaky. `id` is the last resort, which
+ is a guess rather than a constraint, so `should_probe_for_duplicates` treats it as unverified.
+
+ Matched case-insensitively because engines like Snowflake uppercase unquoted identifiers, but
+ the column's stored casing is returned: the merge indexes batches by the real name.
+ """
+ if persisted_keys:
+ return list(persisted_keys)
+ if detected_keys:
+ return list(detected_keys)
+ id_column = next((name for name in available_columns if name.lower() == "id"), None)
+ return [id_column] if id_column is not None else None
+
+
+def should_probe_for_duplicates(
+ merge_keys: Sequence[str] | None,
+ declared_keys: Sequence[str] | None,
+ *,
+ constraints_enforced: bool,
+) -> bool:
+ """Whether the merge key still has to be proven unique against the source.
+
+ Only one thing makes a probe unnecessary: the engine enforces the constraint the key comes
+ from. A key the customer picked, and the `id` guess, carry no such guarantee on any engine, and
+ on an engine that records constraints without enforcing them (Redshift, BigQuery, ClickHouse)
+ neither does a declared one.
+ """
+ if not merge_keys:
+ return False
+ if not constraints_enforced or not declared_keys:
+ return True
+ return list(merge_keys) != list(declared_keys)
+
+
+def needs_full_probe(merge_keys: Sequence[str], verified_keys: Sequence[str] | None) -> bool:
+ """Whether this run has to scan the whole table rather than the rows it is about to read.
+
+ A key is proven once: scanning the whole table on every run costs a full GROUP BY per sync,
+ which on a large table outlives the statement timeout. Afterwards each run only has to prove
+ the rows it brings in, because a duplicate among those is what a merge cannot resolve. A key
+ that was never proven, or one that replaced the proven key, starts again from the whole table.
+ """
+ return list(merge_keys) != list(verified_keys or [])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_primary_keys.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_primary_keys.py
new file mode 100644
index 000000000000..462f6c8837eb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_primary_keys.py
@@ -0,0 +1,67 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.primary_keys import (
+ needs_full_probe,
+ resolve_merge_keys,
+ should_probe_for_duplicates,
+)
+
+
+class TestResolveMergeKeys(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("stored_wins_over_detection", ["order_id"], ["id"], ["id", "order_id"], ["order_id"]),
+ ("detection_when_nothing_stored", None, ["id"], ["id"], ["id"]),
+ ("id_is_the_last_resort", None, None, ["id", "name"], ["id"]),
+ ("id_matched_case_insensitively", None, None, ["ID", "NAME"], ["ID"]),
+ ("no_key_at_all", None, None, ["name"], None),
+ ]
+ )
+ def test_precedence(
+ self,
+ _name: str,
+ persisted: list[str] | None,
+ detected: list[str] | None,
+ columns: list[str],
+ expected: list[str] | None,
+ ) -> None:
+ assert resolve_merge_keys(persisted, detected, columns) == expected
+
+
+class TestShouldProbeForDuplicates(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("enforced_declared_key_is_already_unique", ["id"], ["id"], True, False),
+ ("unenforced_declared_key_proves_nothing", ["id"], ["id"], False, True),
+ ("customer_key_is_not_a_constraint", ["email"], ["id"], True, True),
+ ("id_guess_is_not_a_constraint", ["id"], None, True, True),
+ ("nothing_to_probe", None, ["id"], False, False),
+ ]
+ )
+ def test_gate(
+ self,
+ _name: str,
+ merge_keys: list[str] | None,
+ declared_keys: list[str] | None,
+ constraints_enforced: bool,
+ expected: bool,
+ ) -> None:
+ assert (
+ should_probe_for_duplicates(merge_keys, declared_keys, constraints_enforced=constraints_enforced)
+ is expected
+ )
+
+
+class TestNeedsFullProbe(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("never_verified", ["id"], None, True),
+ ("verified_the_same_key", ["id"], ["id"], False),
+ ("verified_a_different_key", ["order_id"], ["id"], True),
+ ("verified_a_narrower_key", ["tenant", "id"], ["id"], True),
+ ]
+ )
+ def test_cadence(self, _name: str, merge_keys: list[str], verified: list[str] | None, expected: bool) -> None:
+ assert needs_full_probe(merge_keys, verified) is expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
index c88fc4224836..34bc282da541 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
@@ -62,6 +62,9 @@ class SourceResponse:
rows_to_sync: Optional[int] = None
has_duplicate_primary_keys: Optional[bool] = None
"""Whether incremental tables have non-unique primary keys"""
+ verified_primary_keys: Optional[list[str]] = None
+ """The key this run proved unique across the whole table, persisted so later runs only have to
+ prove the rows they bring in."""
webhook_only: bool = False
"""Webhook-fed resource whose poll path does no backfill: after a wipe the poll cannot
rebuild the table, so a requested pipeline reset preserves the Delta table and resumes
@@ -112,6 +115,11 @@ class SourceInputs:
last_synced_at: Optional[datetime.datetime] = None
enabled_columns: Optional[list[str]] = None
row_filters: Optional[list[ValidatedRowFilter]] = None
+ # The schema's stored primary key and the key a full probe last proved unique. A source that
+ # merges on an unenforced key needs both: the first is the key it will merge on, the second
+ # says whether that key still has to be proven against the whole table.
+ primary_keys: Optional[list[str]] = None
+ verified_primary_keys: Optional[list[str]] = None
# Multi-schema import context, read by `resolve_source_location`.
schema_metadata: Optional[dict[str, Any]] = None
s3_folder_name: Optional[str] = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
index b65813245f62..b92c0c8cea75 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
@@ -46,6 +46,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mix
open_ssh_tunnel,
pinned_host_kwargs,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.primary_keys import (
+ needs_full_probe,
+ resolve_merge_keys,
+ should_probe_for_duplicates,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
Column,
Table,
@@ -864,6 +869,10 @@ class QualifiedRelation:
name: str
+# (incremental field, comparison operator, last synced value) — the rows a run is about to read.
+type IncrementalProbeWindow = tuple[str, str, str | int | float | None]
+
+
@frozen
class RedshiftTableSetup:
"""Everything `build_pipeline` learns about a table before it can stream rows."""
@@ -875,6 +884,7 @@ class RedshiftTableSetup:
rows_to_sync: int
partition_settings: PartitionSettings | None
duplicate_primary_keys: bool
+ verified_primary_keys: list[str] | None
class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycopg.Connection, Any]):
@@ -1415,6 +1425,49 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
logger.warning(_no_primary_key_warning(cursor, schema, table_name, table_type))
return None
+ @staticmethod
+ def _duplicate_primary_keys_query(
+ schema: str,
+ table_name: str,
+ primary_keys: list[str],
+ incremental_window: Optional[IncrementalProbeWindow],
+ row_filters: Optional[list[ValidatedRowFilter]],
+ ) -> sql.Composed:
+ table = sql.Identifier(schema, table_name)
+ filter_conditions = render_psycopg_row_filter_conditions(row_filters or [])
+ key_columns = [sql.Identifier(key) for key in primary_keys]
+
+ conditions = list(filter_conditions)
+ if incremental_window is not None:
+ field, operator, last_value = incremental_window
+ # The candidate set is this run's rows; the count below spans the whole table.
+ candidates = sql.SQL("SELECT DISTINCT {cols} FROM {table} WHERE {field} {op} {value}").format(
+ cols=sql.SQL(", ").join(key_columns),
+ table=table,
+ field=sql.Identifier(field),
+ op=sql.SQL(operator),
+ value=sql.Literal(last_value),
+ )
+ if filter_conditions:
+ candidates = candidates + sql.SQL(" AND ") + and_join(filter_conditions)
+ # `IN` never matches a key holding NULL, so a nullable key would go unprobed.
+ # GROUP BY treats NULLs as equal, and the merge sees them the same way.
+ key_matches: list[sql.Composable] = [
+ sql.SQL("(t.{key} = c.{key} OR (t.{key} IS NULL AND c.{key} IS NULL))").format(key=key)
+ for key in key_columns
+ ]
+ conditions.append(
+ sql.SQL("EXISTS (SELECT 1 FROM ({candidates}) AS c WHERE {matches})").format(
+ candidates=candidates, matches=and_join(key_matches)
+ )
+ )
+
+ query = sql.SQL("SELECT {cols} FROM {table} AS t").format(cols=sql.SQL(", ").join(key_columns), table=table)
+ if conditions:
+ query = query + sql.SQL(" WHERE ") + and_join(conditions)
+ group_by = sql.SQL(", ").join(sql.SQL(str(i + 1)) for i, _ in enumerate(primary_keys))
+ return query + sql.SQL(" GROUP BY {group} HAVING COUNT(*) > 1 LIMIT 1").format(group=group_by)
+
def has_duplicate_primary_keys(
self,
cursor: psycopg.Cursor,
@@ -1422,25 +1475,23 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
table_name: str,
primary_keys: list[str] | None,
logger: FilteringBoundLogger,
- ) -> bool:
+ incremental_window: Optional[IncrementalProbeWindow] = None,
+ row_filters: Optional[list[ValidatedRowFilter]] = None,
+ ) -> bool | None:
+ """Whether the key repeats. None when the check could not run, which is not the same as
+ proving the key unique.
+
+ `incremental_window` narrows which keys are examined to the ones this run reads, but each
+ of those keys is still counted across the whole table: a row that repeats a key synced by
+ an earlier run is exactly the case a merge cannot resolve. Row filters are applied on both
+ sides, because a key only has to be unique among the rows extraction actually reads.
+ """
if not primary_keys or len(primary_keys) == 0:
return False
try:
- sql_query = cast(
- LiteralString,
- f"""
- SELECT {", ".join(["{}" for _ in primary_keys])}
- FROM {{}}.{{}}
- GROUP BY {", ".join([str(i + 1) for i, _ in enumerate(primary_keys)])}
- HAVING COUNT(*) > 1
- LIMIT 1
- """,
- )
- query = sql.SQL(sql_query).format(
- *[sql.Identifier(key) for key in primary_keys],
- sql.Identifier(schema),
- sql.Identifier(table_name),
+ query = self._duplicate_primary_keys_query(
+ schema, table_name, primary_keys, incremental_window, row_filters
)
_explain_query(cursor, query, logger)
logger.debug(f"Running query: {query.as_string()}")
@@ -1464,9 +1515,9 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
# to error tracking. Mirrors the graceful-skip probes elsewhere in this driver.
if "system requested abort" in str(e):
logger.debug(f"has_duplicate_primary_keys: query aborted by Redshift, skipping check: {e}")
- return False
+ return None
capture_exception(e)
- return False
+ return None
def get_table_metadata(
self,
@@ -1765,10 +1816,13 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
if primary_keys:
logger.debug(f"Found primary keys: {primary_keys}")
- # Resolve PKs before projection so SELECT and Arrow schema agree.
- if primary_keys is None and "id" in full_table:
- logger.debug("Falling back to ['id'] for primary keys...")
- primary_keys = ["id"]
+ # Resolve PKs before projection so SELECT and Arrow schema agree. The
+ # stored key wins here for the same reason it wins in the pipeline: it is
+ # what the merge runs on, so it is what the probe below has to check.
+ declared_keys = primary_keys
+ primary_keys = resolve_merge_keys(
+ inputs.primary_keys, declared_keys, [column.name for column in full_table.columns]
+ )
projection = _resolve_projection(full_table, primary_keys)
table = projection.table
@@ -1824,12 +1878,54 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
else None
)
duplicate_primary_keys = False
- if primary_keys == ["id"] and "id" in full_table:
- # Only check dupes when we fell back to the `id` PK above.
- logger.debug("Checking duplicate primary keys...")
- duplicate_primary_keys = self.has_duplicate_primary_keys(
- cursor, schema, table_name, primary_keys, logger
+ verified_primary_keys: list[str] | None = None
+ # Redshift records primary key constraints without enforcing them, so no
+ # key here is unique until this proves it.
+ if should_probe_for_duplicates(primary_keys, declared_keys, constraints_enforced=False):
+ assert primary_keys is not None
+ # A run with no stored cursor re-reads the whole table (a reset, or the
+ # first sync), so a window would describe rows the run is not limited to.
+ full_probe = (
+ needs_full_probe(primary_keys, inputs.verified_primary_keys)
+ or not should_use_incremental_field
+ or incremental_field is None
+ or db_incremental_field_last_value is None
+ )
+ window: IncrementalProbeWindow | None = (
+ None
+ if full_probe or incremental_field is None
+ else (
+ incremental_field,
+ incremental_type_to_operator(incremental_field_type)
+ if incremental_field_type
+ else ">",
+ db_incremental_field_last_value,
+ )
)
+ logger.debug(f"Checking duplicate primary keys (full_probe={full_probe})...")
+ try:
+ probed = self.has_duplicate_primary_keys(
+ cursor,
+ schema,
+ table_name,
+ primary_keys,
+ logger,
+ incremental_window=window,
+ row_filters=row_filters,
+ )
+ except psycopg.errors.QueryCanceled:
+ # A full scan of a large table can outlive the statement timeout.
+ # Failing the sync here would stop a table that syncs today, so the
+ # key stays unverified and the next run scans for it again.
+ logger.warning(
+ f"Duplicate primary key check timed out for {schema}.{table_name}; "
+ "the key stays unverified"
+ )
+ else:
+ duplicate_primary_keys = probed is True
+ # Only a check that ran proves anything.
+ if full_probe and probed is False:
+ verified_primary_keys = primary_keys
except psycopg.errors.QueryCanceled:
if should_use_incremental_field:
raise QueryTimeoutException(
@@ -1844,6 +1940,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
rows_to_sync=rows_to_sync,
partition_settings=partition_settings,
duplicate_primary_keys=duplicate_primary_keys,
+ verified_primary_keys=verified_primary_keys,
)
# A fresh connection can still drop before setup finishes (network blip, cluster
@@ -1856,6 +1953,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
rows_to_sync = setup.rows_to_sync
partition_settings = setup.partition_settings
duplicate_primary_keys = setup.duplicate_primary_keys
+ verified_primary_keys = setup.verified_primary_keys
def _refreshed_projection(connection: psycopg.Connection) -> TableProjection[RedshiftColumn]:
"""Re-read the catalog on the streaming connection, right before the read query.
@@ -1914,4 +2012,5 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
partition_size=partition_settings.partition_size if partition_settings else None,
rows_to_sync=rows_to_sync,
has_duplicate_primary_keys=duplicate_primary_keys,
+ verified_primary_keys=verified_primary_keys,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
index b19afd21df03..567485697342 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
@@ -936,14 +936,80 @@ class TestHasDuplicatePrimaryKeys:
cursor.fetchone.return_value = None
assert impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger) is False
- def test_returns_false_on_exception(self, impl, cursor, logger):
+ def test_returns_inconclusive_on_exception(self, impl: Any, cursor: Any, logger: Any) -> None:
cursor.execute.side_effect = RuntimeError("boom")
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.capture_exception"
) as mock_capture:
- assert impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger) is False
+ assert impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger) is None
mock_capture.assert_called_once()
+ def test_window_limits_the_scan_to_the_rows_this_run_reads(self, impl: Any, cursor: Any, logger: Any) -> None:
+ cursor.fetchone.return_value = None
+
+ impl.has_duplicate_primary_keys(
+ cursor, "public", "t", ["id"], logger, incremental_window=("updated_at", ">", "2026-01-01")
+ )
+
+ executed = cursor.execute.call_args.args[0].as_string()
+ assert '"updated_at" > ' in executed
+
+ def test_window_counts_its_keys_across_the_whole_table(self, impl: Any, cursor: Any, logger: Any) -> None:
+ cursor.fetchone.return_value = None
+
+ impl.has_duplicate_primary_keys(
+ cursor, "public", "t", ["id"], logger, incremental_window=("updated_at", ">", "2026-01-01")
+ )
+
+ executed = cursor.execute.call_args.args[0].as_string()
+ assert "EXISTS (SELECT 1 FROM (SELECT DISTINCT" in executed
+ assert executed.index("GROUP BY") > executed.index("EXISTS (SELECT 1 FROM (SELECT DISTINCT")
+
+ def test_window_matches_a_null_key_as_well(self, impl: Any, cursor: Any, logger: Any) -> None:
+ cursor.fetchone.return_value = None
+ impl.has_duplicate_primary_keys(
+ cursor, "public", "t", ["id", "region"], logger, incremental_window=("updated_at", ">", "2026-01-01")
+ )
+ executed = cursor.execute.call_args.args[0].as_string()
+ assert '(t."id" = c."id" OR (t."id" IS NULL AND c."id" IS NULL))' in executed
+ assert '(t."region" = c."region" OR (t."region" IS NULL AND c."region" IS NULL))' in executed
+ assert " IN (" not in executed
+
+ def test_row_filters_bound_both_sides_of_the_check(self, impl: Any, cursor: Any, logger: Any) -> None:
+ cursor.fetchone.return_value = None
+
+ impl.has_duplicate_primary_keys(
+ cursor,
+ "public",
+ "t",
+ ["id"],
+ logger,
+ incremental_window=("updated_at", ">", "2026-01-01"),
+ row_filters=[
+ ValidatedRowFilter(column="tenant", operator="=", value="acme", category=ColumnTypeCategory.STRING)
+ ],
+ )
+
+ executed = cursor.execute.call_args.args[0].as_string()
+ assert executed.count('"tenant"') == 2
+
+ def test_an_aborted_check_is_inconclusive_not_clean(self, impl: Any, cursor: Any, logger: Any) -> None:
+ cursor.execute.side_effect = psycopg.errors.InternalError_("system requested abort")
+
+ assert impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger) is None
+
+ def test_no_window_scans_the_whole_table(self, impl: Any, cursor: Any, logger: Any) -> None:
+ cursor.fetchone.return_value = None
+
+ impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger)
+
+ assert "WHERE" not in cursor.execute.call_args.args[0].as_string()
+
+ def test_query_canceled_is_propagated(self, impl: Any, cursor: Any, logger: Any) -> None:
+ cursor.execute.side_effect = psycopg.errors.QueryCanceled("canceling statement due to statement timeout")
+ with pytest.raises(psycopg.errors.QueryCanceled):
+ impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger)
+
def test_operational_error_is_propagated(self, impl, cursor, logger):
# A connection-level failure (e.g. the SSL connection dropping mid-query) means the probe
# never ran — swallowing it as "no duplicate keys" would be a false negative, so it must
@@ -958,7 +1024,7 @@ class TestHasDuplicatePrimaryKeys:
impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger)
mock_capture.assert_not_called()
- def test_system_requested_abort_is_not_reported(self, impl, cursor, logger):
+ def test_system_requested_abort_is_not_reported(self, impl: Any, cursor: Any, logger: Any) -> None:
# Redshift WLM/QMR aborts (code 1020, "system requested abort") surface as `InternalError_`
# and are expected, non-actionable noise — skip gracefully without reporting to error tracking.
abort_message = (
@@ -969,7 +1035,7 @@ class TestHasDuplicatePrimaryKeys:
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.capture_exception"
) as mock_capture:
- assert impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger) is False
+ assert impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger) is None
mock_capture.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index ad59abe17bf5..687c9b8919e3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -532,6 +532,8 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
reset_pipeline=reset_pipeline,
enabled_columns=schema.enabled_columns,
row_filters=row_filters,
+ primary_keys=schema.primary_key_columns,
+ verified_primary_keys=schema.verified_primary_keys,
schema_metadata=schema.schema_metadata,
s3_folder_name=schema.resolved_s3_folder_name,
# A schema-level override (user-managed) wins over the source pin.