: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
feat(data-warehouse): checkpoint the Postgres keyset seek (#107082)
Tom Owersaf8bae00a31b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.pyindex dc059f8708ee..f662a5c014e2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py@@ -87,7 +87,7 @@ def _dispatch():objects.select_related.return_value.get.return_value = schemajob_objects.filter.return_value.first.return_value = job- return PostgresSource().source_for_pipeline(MagicMock(), inputs)+ return PostgresSource().source_for_pipeline(MagicMock(), MagicMock(), inputs)class TestBufferedDispatch:diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 4c5b93cd32af..68b95deac605 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -957,7 +957,13 @@ class ExternalDataJobWorkflow(PostHogWorkflow):is_resumable_source = Falseif source_type is not None:source = SourceRegistry.get_source(ExternalDataSourceType(source_type))- is_resumable_source = isinstance(source, ResumableSource)+ # The class can resume, and its mechanism covers a run of this shape. Both halves+ # matter: a class whose resume is narrower than itself would otherwise hand the+ # resumable allowance to every one of its runs, including the ones that restart from+ # row 0 on each of those extra attempts.+ is_resumable_source = isinstance(source, ResumableSource) and source.resume_covers_run(+ incremental_or_append=incremental_or_append+ )max_resumable_attempts = MAX_RESUMABLE_SOURCE_RETRIESmax_incremental_attempts = MAX_INCREMENTAL_SOURCE_RETRIESdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.pyindex ad1afac31d66..296de2cfb372 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@@ -499,6 +499,20 @@ class SimpleSource(_BaseSource[ConfigType], Generic[ConfigType]):class ResumableSource(_BaseSource[ConfigType], Generic[ConfigType, ResumableData]):"""Base class for sources that support resumable full-refresh imports."""+ def resume_covers_run(self, *, incremental_or_append: bool) -> bool:+ """Whether this source's resume mechanism covers a run of this shape.++ Only the retry budget reads this. A run it covers gets the resumable allowance, which is much+ larger than the incremental one and far larger than the full-load one, on the grounds that+ each attempt continues rather than restarting. A run it does not cover falls through to the+ ordinary budgets, because extra attempts would each redo the whole read.++ Default True: a REST source paginates the same way whichever sync type it runs. A source+ whose mechanism is narrower than its class — keyset seeking is a full-load path, and a seek+ gated behind a retry fallback covers almost nothing — narrows it here.+ """+ return True+def source_for_pipeline(self, config: ConfigType, resumable_source_manager: ResumableSourceManager[ResumableData], inputs: SourceInputs) -> SourceResponse:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/keyset.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/keyset.pyindex ad02980a1de6..1a83b7507872 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/keyset.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/keyset.py@@ -95,20 +95,28 @@ def keyset_last_key(state: KeysetResumeState | None, *, key_length: int) -> tuplreturn tuple(stored)-def keyset_key_of_last_row(table: pa.Table, keyset_columns: Sequence[str]) -> tuple[Any, ...]:- """The key tuple of the last row of `table`, which the next page seeks past.+def checked_keyset_key(key: tuple[Any, ...], keyset_columns: Sequence[str]) -> tuple[Any, ...]:+ """Return `key` unchanged, or raise `KeysetNullKeyError` if any part of it is NULL.++ Every predicate form compares as UNKNOWN against a NULL, so a single-column key would re-read the+ same page forever while a composite one would come back empty and silently truncate the load.+ See `KeysetNullKeyError`.- Raises `KeysetNullKeyError` if any part is NULL. Every predicate form compares as UNKNOWN against- a NULL, so a single-column key would re-read the same page forever while a composite one would- come back empty and silently truncate the load. See `KeysetNullKeyError`.+ Takes the values rather than the page, because a driver that seeks on an expression (Postgres+ leads an xmin seek with a cast cursor) has the key in its cursor row under an alias that the+ projected Arrow table does not carry."""- key = tuple(table.column(column)[-1].as_py() for column in keyset_columns)null_columns = [column for column, value in zip(keyset_columns, key) if value is None]if null_columns:raise KeysetNullKeyError(f"Keyset page ended on a NULL key for {null_columns}, so the walk cannot advance")return key+def keyset_key_of_last_row(table: pa.Table, keyset_columns: Sequence[str]) -> tuple[Any, ...]:+ """The key tuple of the last row of `table`, which the next page seeks past."""+ return checked_keyset_key(tuple(table.column(column)[-1].as_py() for column in keyset_columns), keyset_columns)++def is_orderable_keyset_type(arrow_type: pa.DataType) -> bool:"""Whether a column type gives a stable, unambiguous total order for keyset pagination.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.pyindex 63e097587dec..34387366cd74 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py@@ -1,3 +1,5 @@+import typing+import pytestfrom unittest.mock import MagicMock, patch@@ -5,10 +7,13 @@ import redis.exceptions as redis_exceptionsfrom posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import (ResumableSourceManager,resolve_resume_manager,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import KeysetResumeStatefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -157,3 +162,38 @@ class TestResumableSourceManager:redis.connection_pool.disconnect.assert_called_once()assert redis.delete.call_count == 2+++class TestResumeCoversRun:+ @staticmethod+ def _resume_state_of(source) -> type | None:+ """The state class a source checkpoints, read off its `ResumableSource[...]` base."""+ for base in getattr(type(source), "__orig_bases__", ()):+ if typing.get_origin(base) is ResumableSource:+ args = typing.get_args(base)+ if len(args) > 1:+ return args[1]+ return None++ def test_a_keyset_source_never_claims_the_resumable_budget_for_an_incremental_run(self):+ # Keyset seeking is a full-load path, so a keyset source's incremental runs resume from the+ # watermark like any other source's do. Covering them here hands every one the resumable+ # retry allowance — for the Postgres family that is most of the fleet, and the runs that+ # cannot resume redo the whole read on each of those extra attempts. Derived from the state+ # class so the next source to adopt `KeysetResumeState` is held to the same rule. Snowflake+ # is deliberately not caught: it checkpoints on the incremental field, so its resume does+ # cover incremental runs.+ keyset_sources = [+ source+ for source in SourceRegistry.get_all_sources().values()+ if isinstance(source, ResumableSource) and self._resume_state_of(source) is KeysetResumeState+ ]+ assert keyset_sources, "expected at least one source to checkpoint with KeysetResumeState"++ assert [s.source_type for s in keyset_sources if s.resume_covers_run(incremental_or_append=True)] == []++ def test_the_default_covers_every_run_of_any_other_resumable_source(self):+ # A REST source paginates the same way whichever sync type it runs, and Snowflake checkpoints+ # on its incremental field, so narrowing the default would cut their retry budgets.+ for incremental in (True, False):+ assert ResumableSource.resume_covers_run(MagicMock(), incremental_or_append=incremental) is Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.pyindex 69e78dde9a9e..f4452b6bd863 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py@@ -99,6 +99,12 @@ class MySQLSource(SSHTunnelMixin,ValidateDatabaseHostMixin,):+ def resume_covers_run(self, *, incremental_or_append: bool) -> bool:+ # Keyset seeking is a full-load path, and it is the default one here. An incremental run+ # resumes from its watermark like any non-resumable source's does, so it takes the+ # incremental retry budget rather than the much larger resumable one.+ return not incremental_or_append+@propertydef get_implementation(self) -> MySQLImplementation:return _MYSQL_IMPLEMENTATIONdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.pyindex 16cb2e0a0cba..0e1c23f4306a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py@@ -62,6 +62,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixopen_ssh_tunnel,pinned_host_kwargs,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (Column,Table,@@ -80,6 +81,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sqlfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.incremental import (IncrementalFieldFilter,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import (+ KeysetResumeState,+ checked_keyset_key,+ is_orderable_keyset_type,+ keyset_last_key,+ keyset_state,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates_psycopg import (and_join,render_psycopg_row_filter_conditions,@@ -2647,6 +2655,77 @@ def _has_duplicate_primary_keys(return False+@frozen+class PostgresKeyset:+ """Whether this run can seek, and whether it can persist where it got to.++ Two verdicts, because they are not the same question. `columns` says the read may page with a+ row-value seek instead of one server cursor — Postgres has done that since the read-replica+ recovery-conflict fallback, on any key type, because the key never leaves the process.+ `checkpointable` says the key may also be written to Redis and read back on another pod, which+ needs a type whose order cannot change underneath it and which the checkpoint can encode.++ `reason` is a stable token, never free text, so the ineligible share is countable from logs. That+ share is what decides whether widening the seek path past its current fallback is worth it.+ """++ columns: list[str] | None = None+ checkpointable: bool = False+ reason: str | None = None+++def resolve_postgres_keyset(+ *,+ primary_keys: list[str] | None,+ arrow_schema: pa.Schema,+ used_id_pk_fallback: bool,+ has_duplicate_primary_keys: bool,+ is_partitioned: bool,+ should_use_incremental_field: bool,+ is_xmin: bool,+ is_duckdb: bool,+ full_table: Table[PostgreSQLColumn],+) -> PostgresKeyset:+ """Decide how far this run can go: no seek, seek only, or seek plus a durable checkpoint."""+ if should_use_incremental_field:+ # Already resumable from its persisted watermark, and seeking would double the work.+ return PostgresKeyset(reason="incremental_sync")+ if is_xmin:+ # An xmin read appends deltas, so restarting it from key 0 would duplicate what it wrote.+ return PostgresKeyset(reason="xmin_sync")+ if is_duckdb:+ # Pages by LIMIT/OFFSET over an unordered query, so no page has an addressable position.+ return PostgresKeyset(reason="duckdb")+ if not primary_keys:+ return PostgresKeyset(reason="no_primary_key")+ if is_partitioned:+ # A parent's key is unique only within each child, so a seek across children can skip rows.+ return PostgresKeyset(reason="partitioned_parent")+ if used_id_pk_fallback and not (+ not has_duplicate_primary_keys and all(_column_is_not_null(full_table, key) for key in primary_keys)+ ):+ # An assumed `id` is neither unique nor NOT NULL until proven. A page boundary inside a run of+ # equal keys drops the rest of that run, and `key > last` never matches a NULL.+ return PostgresKeyset(reason="undeclared_key_not_seekable")++ missing = [key for key in primary_keys if key not in arrow_schema.names]+ if missing:+ # `resolve_table_projection` always retains the primary key, so this should be unreachable.+ # Were it reached, the SELECT would omit the key and the seek would fail looking it up in the+ # cursor description, so fall back to the server cursor rather than crash the read.+ return PostgresKeyset(reason=f"primary_key_not_projected:{missing[0]}")+ unorderable = [key for key in primary_keys if not is_orderable_keyset_type(arrow_schema.field(key).type)]+ if unorderable:+ # Seeking in-process on this key stays fine: one connection, one collation, one process. What+ # it cannot do is survive the trip through Redis, where the ordering assumption would have to+ # hold across a deploy rather than across a few minutes.+ return PostgresKeyset(+ columns=primary_keys,+ reason=f"non_orderable_type:{arrow_schema.field(unorderable[0]).type}",+ )+ return PostgresKeyset(columns=primary_keys, checkpointable=True)++@frozenclass _TableChunking:"""How much of a table one read pulls at a time.@@ -3373,6 +3452,7 @@ def postgres_source(xmin_num_wraparound: Optional[int] = None,byte_bounded_extraction: bool = False,activity_attempt: int = 1,+ resumable_source_manager: Optional[ResumableSourceManager[KeysetResumeState]] = None,) -> SourceResponse:table_name = table_names[0]if not table_name:@@ -3741,6 +3821,44 @@ def postgres_source()time.sleep(min(2 * setup_connection_dropped_errors, 30))+ # Resolved here, in setup scope, so the read path and the `SourceResponse` below cannot disagree+ # about whether this run seeks or checkpoints.+ keyset = resolve_postgres_keyset(+ primary_keys=primary_keys,+ arrow_schema=setup_projection.table.to_arrow_schema(),+ used_id_pk_fallback=used_id_pk_fallback,+ has_duplicate_primary_keys=has_duplicate_primary_keys,+ is_partitioned=is_partitioned,+ should_use_incremental_field=should_use_incremental_field,+ is_xmin=xmin_bounds is not None,+ is_duckdb=is_duckdb,+ full_table=full_table,+ )+ if keyset.reason is not None:+ # Logged for every run that can't checkpoint so the ineligible share, and its breakdown, is+ # measurable before the seek path is widened past its read-replica fallback.+ logger.info(f"Postgres keyset resume unavailable: reason={keyset.reason}")++ # A server cursor idles in an open transaction through every Delta merge, and a replica that+ # cancels reads during that idle kills each attempt at the same place — the cursor's order is+ # arbitrary, so nothing can resume past the first row and a restart repeats the failure. The seek+ # pages in autocommit, so nothing idles and a conflict resumes at the last key. Only from the+ # second attempt, so a replica that never cancels keeps its one consistent snapshot.+ takes_keyset_path = keyset.columns is not None and activity_attempt > 1 and using_read_replica+ can_checkpoint = resumable_source_manager is not None and keyset.checkpointable++ def keyset_resume_key(key_length: int) -> tuple[Any, ...] | None:+ if not can_checkpoint or resumable_source_manager is None or not resumable_source_manager.can_resume():+ return None+ resume_key = keyset_last_key(resumable_source_manager.load_state(), key_length=key_length)+ if resume_key is not None:+ logger.debug(f"Postgres keyset resume: {keyset.columns} > {resume_key}")+ return resume_key++ def keyset_checkpoint(last_key: tuple[Any, ...]) -> None:+ if can_checkpoint and resumable_source_manager is not None:+ resumable_source_manager.save_state(keyset_state(last_key))+def get_rows(chunk_size: int) -> Iterator[Any]:binary_reporter = BinaryColumnReporter(logger)with _tunnel_with_handshake_translation(tunnel) as (host, port):@@ -3856,6 +3974,8 @@ def postgres_source(*,from_recovery_conflict: bool = False,keyset_primary_keys: list[str] | None = None,+ checkpoint: Callable[[tuple[Any, ...]], None] | None = None,+ initial_last_key: tuple[Any, ...] | None = None,):# If the db is a read replica and we're running into `conflict with recovery errors,# we create a new query for each chunk. This is due to how the primary replicates@@ -3888,7 +4008,7 @@ def postgres_source(offset_paging_keys=primary_keys,)- last_key: tuple[Any, ...] | None = None+ last_key: tuple[Any, ...] | None = initial_last_key# An xmin read leads its seek with the cursor, which comes back under the projected# alias rather than a column name, so the two lists differ for it.keyset_result_columns: list[str] = []@@ -3975,11 +4095,13 @@ def postgres_source(if not rows or len(rows) == 0:break+ page_last_key = Noneif keyset_primary_keys is not None:key_positions = [column_names.index(key) for key in keyset_result_columns]- last_key = tuple(rows[-1][position] for position in key_positions)- else:- offset += len(rows)+ page_last_key = checked_keyset_key(+ tuple(rows[-1][position] for position in key_positions),+ keyset_result_columns,+ )yield table_from_iterator((dict(zip(column_names, row)) for row in rows),@@ -3988,6 +4110,20 @@ def postgres_source(binary_reporter=binary_reporter,)+ # Advance and checkpoint only once the consumer comes back for the next+ # page, never before the yield. An abandoned walk unwinds at the yield+ # above — `GeneratorExit` derives from `BaseException`, so none of the+ # handlers below catch it — which leaves the checkpoint on the last page+ # the consumer actually took. Publishing the key first would have a+ # drained worker commit a page it never read, skipping those rows for+ # good, because a resume appends rather than re-reading.+ if page_last_key is not None:+ last_key = page_last_key+ if checkpoint is not None:+ checkpoint(page_last_key)+ else:+ offset += len(rows)+successive_errors = 0successive_conn_errors = 0floor_retries = 0@@ -4161,40 +4297,26 @@ def postgres_source()return- # Seeking needs a key that is unique and never NULL. A page boundary inside a run of- # equal keys drops the rest of that run, and `key > last` never matches NULL, so a NULL- # row is dropped unless it lands on the first page. Postgres guarantees both for a- # declared primary key, so that needs no further check. The assumed `id` is neither- # until proven: its duplicate probe groups NULLs together, so one NULL row alone passes- # it, and the column has to be NOT NULL as well. A partitioned parent's key is unique- # only per child.- assumed_id_is_seekable = not has_duplicate_primary_keys and all(- _column_is_not_null(full_table, key) for key in primary_keys or []- )- keyset_primary_keys = (- primary_keys- if primary_keys and not is_partitioned and (not used_id_pk_fallback or assumed_id_is_seekable)- else None- )+ keyset_primary_keys = keyset.columns- # A server cursor idles in an open transaction through every Delta merge, and a replica- # that cancels reads during that idle kills each attempt at the same place. The handler- # below cannot resume past the first row, because the cursor's order is arbitrary, so- # it re-raises for a restart, and a restart on another cursor repeats the failure. The- # seek pages in autocommit, so nothing idles and a conflict resumes at the last key.- # Only from the second attempt, so a replica that never cancels keeps one snapshot.- if (- activity_attempt > 1- and using_read_replica- and keyset_primary_keys is not None- and not should_use_incremental_field- and xmin_bounds is None- ):+ # `takes_keyset_path` carries the reasoning, and the `SourceResponse` reads the same+ # variable so the two cannot disagree about whether this run resumes.+ if takes_keyset_path and keyset_primary_keys is not None:logger.debug(- f"Attempt {activity_attempt} of a full-table read on a read replica. Seeking from the "- f"start instead of reopening a server cursor. keys = {keyset_primary_keys}"+ f"Attempt {activity_attempt} of a full-table read on a read replica. Seeking "+ f"instead of reopening a server cursor. keys = {keyset_primary_keys}"+ )+ yield from offset_chunking(+ 0,+ chunk_size,+ keyset_primary_keys=keyset_primary_keys,+ checkpoint=keyset_checkpoint,+ initial_last_key=keyset_resume_key(len(keyset_primary_keys)),)- yield from offset_chunking(0, chunk_size, keyset_primary_keys=keyset_primary_keys)+ # Reached only when the walk read the table to the end. An abandoned generator+ # unwinds at its yield and leaves the checkpoint for the next pod to resume from.+ if can_checkpoint and resumable_source_manager is not None:+ resumable_source_manager.clear_state()returninitial_read_drop_retries = 0@@ -4375,6 +4497,10 @@ def postgres_source(xmin_ceiling_xid=xmin_bounds.upper if xmin_bounds is not None else None,xmin_ceiling_xid8=xmin_bounds.ceiling_xid8 if xmin_bounds is not None else None,xmin_num_wraparound=xmin_bounds.num_wraparound if xmin_bounds is not None else None,+ # Both halves, because a run that seeks without a persistable key still cannot hand its+ # position to another pod, and one that could checkpoint but reads through a server cursor+ # has no position to hand over. `supports_resume` defaults to True, so this must be explicit.+ supports_resume=can_checkpoint and takes_keyset_path,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex 80f4c1873941..dbd3daeafd47 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.naming_conventionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (FAST_RETURN_PROBE_TIMEOUT,FieldType,+ ResumableSource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (HOST_RESOLUTION_EXHAUSTED_MESSAGE,@@ -34,9 +35,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixValidateDatabaseHostMixin,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import resolve_detected_primary_keysfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import KeysetResumeStatefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.location import resolve_source_locationfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postgres import (@@ -372,11 +375,26 @@ _RECOVERY_CONFLICT_EXHAUSTED_MESSAGE = (@SourceRegistry.register-class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):+class PostgresSource(+ SQLSource[PostgresSourceConfig],+ ResumableSource[PostgresSourceConfig, KeysetResumeState],+ SSHTunnelMixin,+ ValidateDatabaseHostMixin,+):# xmin replication is Postgres-only; per-table availability is still decided by# `SourceSchema.supports_xmin` at discovery.supports_xmin = True+ def resume_covers_run(self, *, incremental_or_append: bool) -> bool:+ # Nothing yet. The seek that carries the checkpoint is still the read-replica retry fallback,+ # so almost no run reaches it, and handing the resumable retry allowance to every Postgres+ # full load would let one that cannot seek redo a multi-hour read 20 times over rather than+ # 3. Widen this to `not incremental_or_append` with the gate that makes seeking the default.+ return False++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KeysetResumeState]:+ return ResumableSourceManager[KeysetResumeState](inputs, KeysetResumeState)+def __init__(self, source_name: str = "Postgres"):super().__init__()self.source_name = source_name@@ -1868,6 +1886,8 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaitems=lambda: iter(()),primary_keys=schema.primary_key_columns,cdc_write_mode=first_lane.write_mode,+ # A change stream carries no seekable key, and `supports_resume` defaults to True.+ supports_resume=False,)if job is None:@@ -1917,9 +1937,16 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaprimary_keys=schema.primary_key_columns,cdc_write_mode=lanes[0].cdc_write_mode,lanes=lanes,+ # A change stream reads a buffer, not a keyed table, so there is no key to seek past.+ supports_resume=False,)- def source_for_pipeline(self, config: PostgresSourceConfig, inputs: SourceInputs) -> SourceResponse:+ def source_for_pipeline( # type: ignore[override]+ self,+ config: PostgresSourceConfig,+ resumable_source_manager: ResumableSourceManager[KeysetResumeState],+ inputs: SourceInputs,+ ) -> SourceResponse:from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import (CDCHandledExternally,@@ -1965,6 +1992,13 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDarequire_ssl = source_requires_ssl(schema.source, config)table_rebuild_pending = inputs.reset_pipeline or schema.delta_revive_required is not None+ # A rebuild empties the Delta table, so a checkpoint left from the previous run would have the+ # read resume mid-table and append into it — losing every row below the checkpoint silently.+ # Wider than the reset alone: a delta revive wipes the table too, and the pipeline skips its+ # own reset whenever it can resume.+ if table_rebuild_pending:+ resumable_source_manager.clear_state()+# Prefer the per-row `schema_metadata.source_schema` so multi-schema warehouse sources work# without needing to encode the schema in `config.schema`. Falls back to `config.schema` for# legacy single-schema warehouse sources whose rows haven't been reconciled yet.@@ -2000,6 +2034,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaxmin_num_wraparound=None if table_rebuild_pending else schema.xmin_num_wraparound,byte_bounded_extraction=inputs.byte_bounded_extraction,activity_attempt=inputs.activity_attempt,+ resumable_source_manager=resumable_source_manager,)except SqlclientUnableToEstablishSqlconnection as e:# A setup query (e.g. the duplicate-PK probe) touched a postgres_fdw foreign table and thediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.pyindex 051c0f00714f..6966b107f90f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py@@ -324,7 +324,7 @@ class TestPostgresSourceMetadataConnectionErrors:):mock_schema_model.objects.select_related.return_value.get.side_effect = original_errorwith pytest.raises(DjangoOperationalError) as exc_info:- source.source_for_pipeline(config, inputs)+ source.source_for_pipeline(config, MagicMock(), inputs)assert exc_info.value is original_error@@ -372,7 +372,7 @@ class TestPostgresSourceForeignServerConnectionError:):objects_mock.select_related.return_value.get.return_value = schema_modelwith pytest.raises(ForeignServerUnreachableError) as exc_info:- source.source_for_pipeline(config, inputs)+ source.source_for_pipeline(config, MagicMock(), inputs)error_msg = str(exc_info.value)non_retryable = source.get_non_retryable_errors()@@ -4175,11 +4175,11 @@ class TestChunkedRereadAfterRecoveryConflict:_XMIN_BOUNDS = XminBounds(lower=100, upper=300, ceiling_xid8=300, num_wraparound=0, wraparound_or_range=False)class _Scan:- def __init__(self, rows: list[tuple[int, ...]]):+ def __init__(self, rows: list[tuple[Any, ...]]):self._rows = rowsself._statements = 0- def rows_for(self, totally_ordered: bool) -> list[tuple[int, ...]]:+ def rows_for(self, totally_ordered: bool) -> list[tuple[Any, ...]]:if totally_ordered:return sorted(self._rows)self._statements += 1@@ -4187,10 +4187,11 @@ class TestChunkedRereadAfterRecoveryConflict:return self._rows[pivot:] + self._rows[:pivot]class _PageCursor:- def __init__(self, scan, column_names: list[str]):+ def __init__(self, scan, column_names: list[str], column_type: str):self.description = [_fake_column(name) for name in column_names]self._scan = scan- self._result: list[tuple[int, ...]] = []+ self._column_type = column_type+ self._result: list[tuple[Any, ...]] = []def execute(self, query, *args, **kwargs):text = query.as_string()@@ -4202,7 +4203,9 @@ class TestChunkedRereadAfterRecoveryConflict:rows = [row for row in rows if int(window.group(1)) <= row[0] < int(window.group(2))]seek = re.search(r"\) > \(([^)]*)\)", text)if seek:- rows = [row for row in rows if row[-1] > int(seek.group(1).split(", ")[-1])]+ raw_seek_value = seek.group(1).split(", ")[-1]+ seek_value = raw_seek_value.strip("'") if self._column_type == "text" else int(raw_seek_value)+ rows = [row for row in rows if row[-1] > seek_value]offset = re.search(r"OFFSET (\d+)", text)if offset:rows = rows[int(offset.group(1)) :]@@ -4274,23 +4277,29 @@ class TestChunkedRereadAfterRecoveryConflict:has_duplicate_pks: bool = False,is_xmin: bool = False,activity_attempt: int = 1,- ) -> list[int]:+ resumable_source_manager: Any = None,+ pages_to_take: int | None = None,+ arrow_schema: pa.Schema | None = None,+ column_type: str = "integer",+ ) -> list[int | str]:@contextmanagerdef fake_tunnel():yield ("localhost", 5432)fake_table = mock.Mock()- fake_table.to_arrow_schema.return_value = pa.schema([pa.field("id", pa.int64())])+ fake_table.to_arrow_schema.return_value = arrow_schema or pa.schema([pa.field("id", pa.int64())])fake_table.type = "table"# `nullable` is annotated `bool`, but `_get_table` really does pass the# information_schema "YES"/"NO" string for a table. That mismatch is the bug under test,# so the fake has to reproduce it rather than respect the annotation.fake_table.columns = [- PostgreSQLColumn(name="id", data_type="integer", nullable=nullable_value) # type: ignore[arg-type]+ PostgreSQLColumn(name="id", data_type=column_type, nullable=nullable_value) # type: ignore[arg-type]]fake_table.__contains__ = mock.Mock(return_value=has_id_column)- rows = self._XMIN_ROWS if is_xmin else self._ROWS+ rows: list[tuple[Any, ...]] = list(self._XMIN_ROWS if is_xmin else self._ROWS)+ if column_type == "text":+ rows = [(str(row[0]),) for row in rows]# `get_rows` inserts `_ph_xmin` ahead of the discovered columns, matching the SELECT.column_names = [XMIN_PROJECTED_COLUMN, "id"] if is_xmin else ["id"]scan = self._Scan(list(rows))@@ -4299,7 +4308,9 @@ class TestChunkedRereadAfterRecoveryConflict:module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"with (patch(f"{module}.psycopg.connect", return_value=connection),- patch(f"{module}.psycopg.Cursor", side_effect=lambda _conn: self._PageCursor(scan, column_names)),+ patch(+ f"{module}.psycopg.Cursor", side_effect=lambda _conn: self._PageCursor(scan, column_names, column_type)+ ),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=True),patch(f"{module}._is_duckdb_connection", return_value=False),@@ -4330,8 +4341,20 @@ class TestChunkedRereadAfterRecoveryConflict:is_xmin=is_xmin,xmin_last_value=self._XMIN_BOUNDS.lower if is_xmin else None,activity_attempt=activity_attempt,+ resumable_source_manager=resumable_source_manager,)- return [row["id"] for table in cast(Iterable[Any], response.items()) for row in table.to_pylist()]+ self.last_response = response+ pages = cast(Iterator[Any], iter(cast(Iterable[Any], response.items())))+ ids: list[int | str] = []+ taken = 0+ for table in pages:+ ids.extend(row["id"] for row in table.to_pylist())+ taken += 1+ if pages_to_take is not None and taken >= pages_to_take:+ # Abandon the walk the way a draining worker does, at the yield.+ pages.close() # type: ignore[attr-defined]+ break+ return ids@pytest.mark.parametrize("should_use_incremental_field,rows_before_conflict,nullable_value,primary_keys,has_id_column",@@ -4427,6 +4450,104 @@ class TestChunkedRereadAfterRecoveryConflict:message = str(exc_info.value)assert "no key that can resume a canceled read" in messageassert any(fragment in message for fragment in PostgresSource().get_non_retryable_errors())+ # The response is built before the read runs, so it exists even though draining raised. A+ # table with no seekable key has no position to hand another pod.+ assert self.last_response.supports_resume is False++ def test_an_abandoned_walk_does_not_checkpoint_the_page_it_parked_on(self):+ # The ordering rule, and the reason the checkpoint sits after the yield rather than next to+ # the `last_key` advance. A draining worker stops pulling mid-table, so the source parks at a+ # yield holding a page the consumer never took. Publishing that page's key would have the+ # next attempt seek past rows nothing wrote — and a resume appends rather than re-reading, so+ # those rows are gone for good.+ manager = MagicMock()+ manager.can_resume.return_value = False++ self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=0,+ primary_keys=["id"],+ activity_attempt=2,+ resumable_source_manager=manager,+ pages_to_take=1,+ )++ assert manager.save_state.call_count == 0+ # The walk never reached the end, so the next pod must still resume rather than start over.+ manager.clear_state.assert_not_called()++ def test_a_completed_walk_checkpoints_each_taken_page_then_clears(self):+ manager = MagicMock()+ manager.can_resume.return_value = False++ self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=0,+ primary_keys=["id"],+ activity_attempt=2,+ resumable_source_manager=manager,+ )++ assert manager.save_state.call_count > 0+ # The table is fully read, so the next scheduled sync starts at the top, not mid-table.+ manager.clear_state.assert_called_once()++ def test_a_seeking_run_reports_that_it_can_resume(self):+ manager = MagicMock()+ manager.can_resume.return_value = False++ self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=0,+ primary_keys=["id"],+ activity_attempt=2,+ resumable_source_manager=manager,+ )++ assert self.last_response.supports_resume is True++ @pytest.mark.parametrize(+ "kwargs,reason",+ [+ ({"should_use_incremental_field": True, "primary_keys": ["id"]}, "incremental_sync"),+ ({"should_use_incremental_field": False, "is_xmin": True, "primary_keys": ["id"]}, "xmin_sync"),+ ],+ ids=["incremental", "xmin"],+ )+ def test_a_run_that_cannot_seek_never_reports_resume(self, kwargs, reason):+ # `supports_resume` defaults to True on SourceResponse, so every one of these has to be set+ # down explicitly or the pipeline treats the run as resumable and suppresses its table reset.+ manager = MagicMock()+ manager.can_resume.return_value = False++ self._read_ids(+ rows_before_conflict=0,+ activity_attempt=2,+ resumable_source_manager=manager,+ **kwargs,+ )++ assert self.last_response.supports_resume is False++ def test_a_text_primary_key_seeks_but_never_checkpoints(self):+ # The collation decision. Ordering a text key is stable within one process, so the in-process+ # seek keeps working, but a checkpoint would have that ordering assumption hold across a+ # deploy instead of across minutes.+ manager = MagicMock()+ manager.can_resume.return_value = False++ self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=0,+ primary_keys=["id"],+ activity_attempt=2,+ resumable_source_manager=manager,+ arrow_schema=pa.schema([pa.field("id", pa.string())]),+ column_type="text",+ )++ assert self.last_response.supports_resume is False+ assert manager.save_state.call_count == 0class TestSafeCloseConnection:@@ -4522,7 +4643,7 @@ class TestPostgresSourceForPipelineSchemaResolution:objects_mock.select_related.return_value.get.return_value = schema_modelpostgres_source_mock.return_value = mock.MagicMock()- source.source_for_pipeline(config, inputs)+ source.source_for_pipeline(config, MagicMock(), inputs)assert postgres_source_mock.called, "postgres_source was not invoked"kwargs = postgres_source_mock.call_args.kwargs@@ -4531,6 +4652,43 @@ class TestPostgresSourceForPipelineSchemaResolution:f"expected table_names=['example_table'], got {kwargs['table_names']!r}")+ @pytest.mark.parametrize(+ "reset_pipeline,delta_revive_required,cleared",+ [(False, None, False), (True, None, True), (False, "corrupt-log", True)],+ ids=["steady_state_keeps_it", "reset_clears_it", "delta_revive_clears_it"],+ )+ def test_a_rebuild_of_the_table_clears_the_checkpoint(self, source, reset_pipeline, delta_revive_required, cleared):+ # Both rebuilds empty the Delta table, and the pipeline skips its own reset whenever it can+ # resume. A checkpoint surviving either one has the read restart mid-table and append into an+ # empty table, losing every row below the checkpoint with no error. The revive case has no+ # MySQL equivalent, which only clears on a reset.+ schema_model = self._make_schema_model("public.example_table")+ schema_model.delta_revive_required = delta_revive_required+ inputs = self._make_inputs("public.example_table")+ inputs.reset_pipeline = reset_pipeline+ config = self._make_config(schema=None)+ manager = MagicMock()++ with (+ mock.patch(+ "products.warehouse_sources.backend.models.external_data_schema.ExternalDataSchema.objects"+ ) as objects_mock,+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.postgres_source"+ ) as postgres_source_mock,+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.source_requires_ssl",+ return_value=False,+ ),+ mock.patch.object(source, "make_ssh_tunnel_func", return_value=lambda: None),+ ):+ objects_mock.select_related.return_value.get.return_value = schema_model+ postgres_source_mock.return_value = mock.MagicMock()++ source.source_for_pipeline(config, manager, inputs)++ assert manager.clear_state.called is cleared+def test_schema_metadata_wins_over_dotted_name_inference(self, source):# Metadata is the source of truth — explicit pin always beats name-splitting.schema_model = self._make_schema_model(@@ -4556,7 +4714,7 @@ class TestPostgresSourceForPipelineSchemaResolution:objects_mock.select_related.return_value.get.return_value = schema_modelpostgres_source_mock.return_value = mock.MagicMock()- source.source_for_pipeline(config, inputs)+ source.source_for_pipeline(config, MagicMock(), inputs)kwargs = postgres_source_mock.call_args.kwargsassert kwargs["schema"] == "real_schema"assert kwargs["table_names"] == ["real_table"]@@ -4594,7 +4752,7 @@ class TestPostgresSourceForPipelineSchemaResolution:objects_mock.select_related.return_value.get.return_value = schema_modelpostgres_source_mock.return_value = response- source.source_for_pipeline(config, inputs)+ source.source_for_pipeline(config, MagicMock(), inputs)assert response.name == NamingConvention.normalize_identifier("example_table"), (f"response.name must derive from s3_folder_name to keep Delta writes anchored to the "@@ -4631,7 +4789,7 @@ class TestPostgresSourceForPipelineSchemaResolution:objects_mock.select_related.return_value.get.return_value = schema_modelpostgres_source_mock.return_value = response- source.source_for_pipeline(config, inputs)+ source.source_for_pipeline(config, MagicMock(), inputs)assert response.name == NamingConvention.normalize_identifier("poblic.new_table")@@ -4657,7 +4815,7 @@ class TestPostgresSourceForPipelineSchemaResolution:objects_mock.select_related.return_value.get.return_value = schema_modelpostgres_source_mock.return_value = mock.MagicMock()- source.source_for_pipeline(config, inputs)+ source.source_for_pipeline(config, MagicMock(), inputs)kwargs = postgres_source_mock.call_args.kwargsassert kwargs["schema"] == "public"assert kwargs["table_names"] == ["example_table"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.pyindex c9d7d9edd6ea..0a6785796385 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py@@ -173,6 +173,7 @@ async def test_job_inputs_with_whitespace(activity_environment, team, **kwargs):xmin_num_wraparound=None,byte_bounded_extraction=False,activity_attempt=1,+ resumable_source_manager=mock.ANY,)@@ -228,6 +229,7 @@ async def test_postgres_source_without_ssh_tunnel(activity_environment, team, **xmin_num_wraparound=None,byte_bounded_extraction=False,activity_attempt=1,+ resumable_source_manager=mock.ANY,)@@ -295,6 +297,7 @@ async def test_postgres_source_with_ssh_tunnel_disabled(activity_environment, texmin_num_wraparound=None,byte_bounded_extraction=False,activity_attempt=1,+ resumable_source_manager=mock.ANY,)@@ -377,6 +380,7 @@ async def test_postgres_source_with_ssh_tunnel_enabled(activity_environment, teaxmin_num_wraparound=None,byte_bounded_extraction=False,activity_attempt=1,+ resumable_source_manager=mock.ANY,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_postgres_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_postgres_source.pyindex a9767ddd47de..2645feb14f47 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_postgres_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_postgres_source.py@@ -508,7 +508,7 @@ class TestSSLRequirement:"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.postgres_source") as mock_postgres_source:assert isinstance(postgres_source, SimpleSource)- postgres_source.source_for_pipeline(config, mock_inputs)+ postgres_source.source_for_pipeline(config, mock.MagicMock(), mock_inputs)mock_postgres_source.assert_called_once()call_kwargs = mock_postgres_source.call_args.kwargsassert call_kwargs["require_ssl"] is expected_require_ssl