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.

feat(data-warehouse): put the Postgres keyset seek behind a rollout flag (#107133)

Tom Owers53011c8268fb
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.py
index f8fe1162c491..2933c10867df 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
@@ -893,6 +893,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
statistics_needed = False
person_property_sync_enabled = False
fast_return_eligible = False
+ keyset_full_load_enabled = False
scheduled_full_refresh = False
repartition_needed = True
billing_limit_checked = False
@@ -909,6 +910,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
statistics_needed = create_job_result.statistics_needed
person_property_sync_enabled = create_job_result.person_property_sync_enabled
fast_return_eligible = create_job_result.fast_return_eligible
+ keyset_full_load_enabled = create_job_result.keyset_full_load_enabled
scheduled_full_refresh = create_job_result.scheduled_full_refresh
repartition_needed = create_job_result.repartition_needed
billing_limit_checked = create_job_result.billing_limit_checked
@@ -979,6 +981,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
reset_pipeline=inputs.reset_pipeline,
fast_return_eligible=fast_return_eligible,
scheduled_full_refresh=scheduled_full_refresh,
+ keyset_full_load_enabled=keyset_full_load_enabled,
)
is_resumable_source = False
@@ -989,7 +992,8 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
# 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
+ incremental_or_append=incremental_or_append,
+ keyset_full_load_enabled=keyset_full_load_enabled,
)
max_resumable_attempts = MAX_RESUMABLE_SOURCE_RETRIES
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index 296de2cfb372..2b0728bdb0d8 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,7 +499,7 @@ 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:
+ def resume_covers_run(self, *, incremental_or_append: bool, keyset_full_load_enabled: bool = False) -> 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
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/keyset_full_load_flag.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/keyset_full_load_flag.py
new file mode 100644
index 000000000000..182f20f45bf5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/keyset_full_load_flag.py
@@ -0,0 +1,64 @@
+from django.db import InterfaceError, OperationalError
+
+import structlog
+import posthoganalytics
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.team.team import Team
+from posthog.temporal.common.utils import retry_on_db_connection_drop
+
+logger = structlog.get_logger(__name__)
+
+KEYSET_FULL_LOAD_FLAG = "warehouse-postgres-keyset-full-load"
+
+
+def is_keyset_full_load_enabled(team_id: int, source_type: str) -> bool:
+ """Gate for reading a full load with keyset pages instead of one server cursor.
+
+ The two reads see the table differently. A server cursor pins one snapshot for its whole life,
+ so the load reflects a single instant; keyset pages read in autocommit, so each page sees a
+ fresher one. Rows inserted or updated ahead of the cursor become visible, which a full refresh
+ already tolerates. A primary key that *moves* does not: shifted forward past the cursor its row
+ is read twice, shifted backward it is never read. That is why this is staged rather than flipped.
+
+ `source_type` rides along as a person property so Postgres, Supabase, Neon and PlanetScale widen
+ independently. They run the same code but not the same servers, and a managed provider's idle
+ and lock timeouts are its own.
+
+ Fails closed: any error means "off", which keeps the server cursor.
+ """
+ try:
+ team = retry_on_db_connection_drop(lambda: Team.objects.only("uuid", "organization_id").get(id=team_id))
+ except Team.DoesNotExist:
+ return False
+ except (OperationalError, InterfaceError) as e:
+ # Already retried once. A second one is an app-DB connectivity blip, not a bug in this gate,
+ # so it shouldn't page anyone — matching `is_byte_bounded_extraction_enabled`.
+ logger.warning(
+ "is_keyset_full_load_enabled: transient app-DB error, failing closed",
+ error=str(e),
+ exc_info=True,
+ )
+ return False
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ KEYSET_FULL_LOAD_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ person_properties={"team_id": str(team.id), "source_type": source_type},
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ capture_exception(e)
+ return False
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.py
index 34387366cd74..e5c136d95102 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
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import KeysetResumeState
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.types import ExternalDataSourceType
@frozen
@@ -183,14 +184,29 @@ class TestResumeCoversRun:
# 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 = [
+ keyset_sources: list[ResumableSource] = [
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)] == []
+ covered = [
+ source.source_type
+ for source in keyset_sources
+ if source.resume_covers_run(incremental_or_append=True, keyset_full_load_enabled=True)
+ ]
+ assert covered == []
+
+ def test_a_full_load_the_flag_has_not_reached_is_not_covered(self):
+ # A full load only resumes once the flag turns seeking on for it. Covering it before then
+ # hands the resumable allowance to a run that still restarts, so each extra attempt redoes
+ # the whole read.
+ postgres = SourceRegistry.get_source(ExternalDataSourceType.POSTGRES)
+ assert isinstance(postgres, ResumableSource)
+
+ assert postgres.resume_covers_run(incremental_or_append=False, keyset_full_load_enabled=False) is False
+ assert postgres.resume_covers_run(incremental_or_append=False, keyset_full_load_enabled=True) is 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
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 33fe86d92042..9f611b8161f8 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
@@ -163,6 +163,9 @@ class SourceInputs:
# True when extraction batches should be bounded by accumulated bytes rather than by the
# sampled row count alone. Evaluated once per run alongside `fanout_warehouse_reuse`.
byte_bounded_extraction: bool = False
+ # True when a full load may page with keyset seeks by default, rather than only as the
+ # read-replica retry fallback. Evaluated once per run alongside `byte_bounded_extraction`.
+ keyset_full_load: bool = False
# Temporal's attempt number for this activity, starting at 1. A source can read a retry
# differently from a first run, because the first run has already shown what fails.
activity_attempt: int = 1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py
index f4452b6bd863..1cdcc58610cc 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,7 +99,7 @@ class MySQLSource(
SSHTunnelMixin,
ValidateDatabaseHostMixin,
):
- def resume_covers_run(self, *, incremental_or_append: bool) -> bool:
+ def resume_covers_run(self, *, incremental_or_append: bool, keyset_full_load_enabled: bool = False) -> 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.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index 0e1c23f4306a..03b9613ad597 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
@@ -154,6 +154,11 @@ _MAX_READ_RECOVERY_CONFLICT_RETRIES = 10
# A shorter query holds its snapshot for less time, lowering the odds the replica cancels it.
_MIN_RECOVERY_CONFLICT_CHUNK_SIZE = 100
+# A seek takes ACCESS SHARE once per page rather than once per read, so it meets a concurrent
+# ACCESS EXCLUSIVE (a DDL, a VACUUM FULL) far more often than a server cursor does. Blocking is
+# transient, so retry the page rather than fail the run; past this the lock is someone's problem.
+_MAX_KEYSET_PAGE_LOCK_RETRIES = 5
+
# Bounded in-process retries for a transient connection drop hit *during* the setup metadata
# probes (not just the initial connect). Mirrors `_connect_with_dropped_retry`'s default; past
# this the drop is treated as sustained and re-raised for Temporal to retry the whole activity.
@@ -732,6 +737,23 @@ def _full_table_timeout_error() -> Exception:
)
+def _keyset_page_timeout_error(keyset_primary_keys: list[str]) -> Exception:
+ """Build the timeout error for a keyset page cancelled by the statement_timeout.
+
+ A seek page reads a bounded `LIMIT n`, so exhausting a 10-minute timeout on one says the plan is
+ wrong, not that the table is large — `_full_table_timeout_error` would tell the customer to make
+ each run read less, which they already are. The usual cause is the walk not being served by the
+ primary-key index, so name that instead. Plain retryable Exception, matching that function: a
+ later attempt resumes at the last committed key rather than starting over.
+ """
+ keys = ", ".join(keyset_primary_keys)
+ return Exception(
+ f"Reading one page of this table hit your database's statement timeout. Each page reads a "
+ f"bounded range of ({keys}) and orders by it, so check that an index on ({keys}) serves that "
+ f"order — a row filter on another indexed column can pull the planner off it."
+ )
+
+
def _raised_while_closing_generator(error: BaseException) -> bool:
"""True when `error` surfaced while the row generator was being closed.
@@ -2509,6 +2531,32 @@ def _explain_query(cursor: psycopg.Cursor, query: sql.Composed, logger: Filterin
logger.debug(f"EXPLAIN raised an exception: {e}")
+def _check_keyset_page_plan(cursor: psycopg.Cursor, query: sql.Composed, logger: FilteringBoundLogger) -> None:
+ """Warn when a keyset page is not reading an index in key order.
+
+ A seek page is only cheap when the planner answers it as an index scan on the key: one descent,
+ then `LIMIT n` rows already in `ORDER BY` order. A row filter gives it another choice — take that
+ filter's index, lose the ordering, and sort the matched set — and the sort runs *per page*,
+ turning one table scan into thousands. A sequential scan is the same trap by another route.
+
+ Diagnostics only: log a stable token so the bad-plan rate is countable, and let the page run. It
+ is what says whether widening the seek past the flag is safe.
+ """
+ try:
+ cursor.execute(sql.SQL("EXPLAIN {}").format(query))
+ plan = "\n".join(str(column) for row in cursor.fetchall() for column in row)
+ except Exception as e:
+ # Best-effort, exactly like `_explain_query`: a failed EXPLAIN must never fail the page.
+ logger.debug(f"Keyset EXPLAIN raised an exception: {e}")
+ return
+
+ # Only the outermost node matters — a sort *under* a LIMIT is the per-page cost this looks for,
+ # and a seq scan means the key's index was not used at all.
+ problems = [marker for marker in ("Seq Scan", "Sort ", "Sort\n", "Incremental Sort") if marker in plan]
+ if problems:
+ logger.warning(f"Keyset page not served by an index scan in key order: reason=bad_keyset_plan found={problems}")
+
+
def _get_primary_keys(
cursor: psycopg.Cursor, schema: str, table_name: str, logger: FilteringBoundLogger
) -> list[str] | None:
@@ -3453,6 +3501,7 @@ def postgres_source(
byte_bounded_extraction: bool = False,
activity_attempt: int = 1,
resumable_source_manager: Optional[ResumableSourceManager[KeysetResumeState]] = None,
+ keyset_full_load_enabled: bool = False,
) -> SourceResponse:
table_name = table_names[0]
if not table_name:
@@ -3839,12 +3888,16 @@ def postgres_source(
# 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
+ # Two ways in. The flag makes seeking the default for a full load, which is what lets a drained
+ # worker resume rather than restart the read. The second arm is the original fallback, unchanged:
+ # 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
+ # arbitrary, so nothing can resume past the first row and a restart repeats the failure. Seeking
+ # pages in autocommit, so nothing idles and a conflict resumes at the last key. Leaving that arm
+ # conditioned on the second attempt is what makes a flag-off deploy read exactly as it does now.
+ takes_keyset_path = keyset.columns is not None and (
+ keyset_full_load_enabled or (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:
@@ -4040,6 +4093,8 @@ def postgres_source(
successive_errors = 0
successive_conn_errors = 0
floor_retries = 0
+ lock_retries = 0
+ plan_checked = False
# Open lazily inside the loop so a recovery conflict (or connection drop) raised by
# the connect itself is caught by the handlers below. A hot standby can cancel the
# connection's own startup with "conflict with recovery" when we reconnect
@@ -4087,6 +4142,11 @@ def postgres_source(
with psycopg.Cursor(connection) as cursor:
query_with_limit_sql = build_page_query()
logger.debug(f"Postgres query: {query_with_limit_sql}")
+ # Check the first page that actually seeks. Page 1 carries no `key >`
+ # predicate, so its plan says nothing about how the walk behaves.
+ if keyset_primary_keys is not None and last_key is not None and not plan_checked:
+ plan_checked = True
+ _check_keyset_page_plan(cursor, query_with_limit_sql, logger)
cursor.execute(query_with_limit_sql)
column_names = [column.name for column in cursor.description or []]
@@ -4168,7 +4228,26 @@ def postgres_source(
"max_standby_streaming_delay or enable hot_standby_feedback on the replica, "
"or sync from the primary database instead."
) from e
+ if keyset_primary_keys is not None:
+ raise _keyset_page_timeout_error(keyset_primary_keys) from e
raise _full_table_timeout_error() from e
+ except psycopg.errors.LockNotAvailable as e:
+ # A server cursor takes ACCESS SHARE once, at its DECLARE. A seek walk takes
+ # it per page, so its cumulative chance of landing on a concurrent ACCESS
+ # EXCLUSIVE is far higher. Without this clause `LockNotAvailable` reaches the
+ # dropped-connection handler as an `OperationalError`, matches neither of its
+ # predicates, and fails the whole activity. Retrying the same page is safe
+ # because `last_key` does not advance until after the page is yielded.
+ _safe_close_connection(connection)
+ lock_retries += 1
+ if lock_retries > _MAX_KEYSET_PAGE_LOCK_RETRIES:
+ raise
+ logger.debug(
+ f"Keyset page blocked on a lock ({e}). Retrying the same page "
+ f"({lock_retries}/{_MAX_KEYSET_PAGE_LOCK_RETRIES})"
+ )
+ time.sleep(min(2 * lock_retries, 30))
+ continue
except _CONNECTION_DROPPED_ERROR_TYPES as e:
if _is_recovery_conflict_error(e):
# A recovery conflict raised by the (re)connect itself surfaces as a plain
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.py
index dbd3daeafd47..1c833416363d 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
@@ -385,12 +385,12 @@ class PostgresSource(
# `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 resume_covers_run(self, *, incremental_or_append: bool, keyset_full_load_enabled: bool = False) -> bool:
+ # Both halves. Keyset seeking is a full-load path, so an incremental or xmin run resumes from
+ # its watermark and keeps the incremental budget. And a full load only resumes once the flag
+ # reaches it — before that it still restarts, so the resumable allowance would buy it nothing
+ # and would cost a whole re-read on each extra attempt.
+ return not incremental_or_append and keyset_full_load_enabled
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KeysetResumeState]:
return ResumableSourceManager[KeysetResumeState](inputs, KeysetResumeState)
@@ -2035,6 +2035,7 @@ class PostgresSource(
byte_bounded_extraction=inputs.byte_bounded_extraction,
activity_attempt=inputs.activity_attempt,
resumable_source_manager=resumable_source_manager,
+ keyset_full_load_enabled=inputs.keyset_full_load,
)
except SqlclientUnableToEstablishSqlconnection as e:
# A setup query (e.g. the duplicate-PK probe) touched a postgres_fdw foreign table and the
diff --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.py
index 6966b107f90f..3ebe88cf8866 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
@@ -47,6 +47,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mix
_resolve_hostaddr_with_timeout,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import batching
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import KeysetResumeState
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (
ColumnTypeCategory,
ValidatedRowFilter,
@@ -102,6 +103,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
_build_count_query,
_build_query,
_capture_xmin_ceiling,
+ _check_keyset_page_plan,
_connect_to_postgres,
_connect_with_dropped_retry,
_fetch_rows_for,
@@ -4281,6 +4283,7 @@ class TestChunkedRereadAfterRecoveryConflict:
pages_to_take: int | None = None,
arrow_schema: pa.Schema | None = None,
column_type: str = "integer",
+ keyset_full_load_enabled: bool = False,
) -> list[int | str]:
@contextmanager
def fake_tunnel():
@@ -4342,6 +4345,7 @@ class TestChunkedRereadAfterRecoveryConflict:
xmin_last_value=self._XMIN_BOUNDS.lower if is_xmin else None,
activity_attempt=activity_attempt,
resumable_source_manager=resumable_source_manager,
+ keyset_full_load_enabled=keyset_full_load_enabled,
)
self.last_response = response
pages = cast(Iterator[Any], iter(cast(Iterable[Any], response.items())))
@@ -4549,6 +4553,115 @@ class TestChunkedRereadAfterRecoveryConflict:
assert self.last_response.supports_resume is False
assert manager.save_state.call_count == 0
+ def test_the_flag_makes_the_first_attempt_seek_and_resume(self):
+ # What the flag buys: the first attempt pages and checkpoints, so a drained worker resumes
+ # rather than restarting. Without it the seek waits for a second attempt against a replica,
+ # which is a slice too small to matter.
+ 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=1,
+ resumable_source_manager=manager,
+ keyset_full_load_enabled=True,
+ )
+
+ assert self.last_response.supports_resume is True
+ assert manager.save_state.call_count > 0
+
+ def test_the_first_attempt_does_not_seek_with_the_flag_off(self):
+ # The regression guard for the rollout: a flag-off deploy has to read exactly as it does now,
+ # so nothing changes for the fleet until the flag reaches a team.
+ 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=1,
+ resumable_source_manager=manager,
+ keyset_full_load_enabled=False,
+ )
+
+ assert self.last_response.supports_resume is False
+ assert manager.save_state.call_count == 0
+
+ def test_the_flag_does_not_make_an_incremental_run_seek(self):
+ # The flag widens the full-load path only. An incremental run already resumes from its
+ # watermark, and seeking it would read the table twice.
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ self._read_ids(
+ should_use_incremental_field=True,
+ rows_before_conflict=2,
+ primary_keys=["id"],
+ activity_attempt=1,
+ resumable_source_manager=manager,
+ keyset_full_load_enabled=True,
+ )
+
+ assert self.last_response.supports_resume is False
+
+ def test_a_resumed_run_seeks_past_the_persisted_checkpoint(self):
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = KeysetResumeState(last_key=2, last_keys=[2])
+
+ ids = self._read_ids(
+ should_use_incremental_field=False,
+ rows_before_conflict=0,
+ primary_keys=["id"],
+ activity_attempt=1,
+ resumable_source_manager=manager,
+ keyset_full_load_enabled=True,
+ )
+
+ # Rows at or below the checkpoint are never re-read, which is what makes a resumed load
+ # append-safe: the pipeline appends after batch 0 rather than overwriting.
+ assert ids and all(isinstance(row_id, int) and row_id > 2 for row_id in ids)
+
+
+class TestCheckKeysetPagePlan:
+ """The signal that says whether widening the seek is safe for a table."""
+
+ @pytest.mark.parametrize(
+ "plan,warns",
+ [
+ ("Limit (cost=0.29..8.31 rows=2)\n -> Index Scan using companies_pkey on companies", False),
+ ("Limit\n -> Index Only Scan using companies_pkey on companies", False),
+ # A row filter pulled the planner onto another index, so the page cannot read in key
+ # order and sorts the matched set — once per page, not once per load.
+ ("Limit\n -> Sort (cost=1.0..2.0)\n -> Index Scan using idx_status", True),
+ ("Limit\n -> Incremental Sort\n -> Index Scan using idx_status", True),
+ # The key's index was not used at all.
+ ("Limit\n -> Seq Scan on companies (cost=0.00..1.00)", True),
+ ],
+ ids=["index_scan", "index_only_scan", "sort", "incremental_sort", "seq_scan"],
+ )
+ def test_warns_only_when_the_page_is_not_an_index_scan_in_key_order(self, plan, warns):
+ cursor = mock.MagicMock()
+ cursor.fetchall.return_value = [(line,) for line in plan.split("\n")]
+ logger = mock.MagicMock()
+
+ _check_keyset_page_plan(cursor, sql.SQL("SELECT 1"), logger) # type: ignore[arg-type]
+
+ assert logger.warning.called is warns
+
+ def test_swallows_an_explain_failure(self):
+ # Diagnostics must never fail the page that follows.
+ cursor = mock.MagicMock()
+ cursor.execute.side_effect = psycopg.errors.InsufficientPrivilege("nope")
+ logger = mock.MagicMock()
+
+ _check_keyset_page_plan(cursor, sql.SQL("SELECT 1"), logger) # type: ignore[arg-type]
+
+ assert logger.warning.called is False
+
class TestSafeCloseConnection:
def test_none_is_a_noop(self):
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.py
index 0a6785796385..22219e785fd6 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
@@ -174,6 +174,7 @@ async def test_job_inputs_with_whitespace(activity_environment, team, **kwargs):
byte_bounded_extraction=False,
activity_attempt=1,
resumable_source_manager=mock.ANY,
+ keyset_full_load_enabled=False,
)
@@ -230,6 +231,7 @@ async def test_postgres_source_without_ssh_tunnel(activity_environment, team, **
byte_bounded_extraction=False,
activity_attempt=1,
resumable_source_manager=mock.ANY,
+ keyset_full_load_enabled=False,
)
@@ -298,6 +300,7 @@ async def test_postgres_source_with_ssh_tunnel_disabled(activity_environment, te
byte_bounded_extraction=False,
activity_attempt=1,
resumable_source_manager=mock.ANY,
+ keyset_full_load_enabled=False,
)
@@ -381,6 +384,7 @@ async def test_postgres_source_with_ssh_tunnel_enabled(activity_environment, tea
byte_bounded_extraction=False,
activity_attempt=1,
resumable_source_manager=mock.ANY,
+ keyset_full_load_enabled=False,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
index b0af05cda586..60fb0330da01 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
@@ -47,6 +47,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
get_v3_pipeline_lock_holder,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.keyset_full_load_flag import (
+ is_keyset_full_load_enabled,
+)
from products.warehouse_sources.backend.temporal.data_imports.util import retry_internal_db_operation
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.check_billing_limits import (
billing_limit_reached,
@@ -329,6 +332,12 @@ class CreateExternalDataJobModelActivityOutputs:
# Computed here because this activity already resolves the repair gates the decision needs.
# Defaults False so a payload from a worker that predates the field takes the full path.
fast_return_eligible: bool = False
+ # True when this team and source may read a full load with keyset pages. The retry budget needs it
+ # because the resumable allowance only earns itself on a run that actually resumes, and the read
+ # path decides that from the same flag. Evaluated here because the budget is set when the import
+ # activity is scheduled, before that activity can evaluate anything. Defaults False so an older
+ # payload keeps the smaller budget.
+ keyset_full_load_enabled: bool = False
# The workflow hands this to the import, which resets only while the schema is still due. Nothing is
# stored on the schema, so a run that stops before the wipe leaves no reset behind for later runs.
scheduled_full_refresh: bool = False
@@ -490,6 +499,7 @@ def create_external_data_job_model_activity(
statistics_needed=statistics_needed,
person_property_sync_enabled=person_property_sync_enabled,
fast_return_eligible=fast_return_eligible,
+ keyset_full_load_enabled=is_keyset_full_load_enabled(inputs.team_id, str(source.source_type)),
scheduled_full_refresh=scheduled_full_refresh,
repartition_needed=repartition_needed,
billing_limit_checked=True,
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 1453442e8a6d..95e1589f52b5 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
@@ -109,6 +109,9 @@ class ImportDataActivityInputs:
fast_return_eligible: bool = False
# Kept apart from `reset_pipeline`, which every retry would read again and wipe the table again.
scheduled_full_refresh: bool = False
+ # Fixed for the job lifetime so a flag change between activity attempts cannot mix a stale
+ # keyset checkpoint with a server-cursor retry that reset the destination table.
+ keyset_full_load_enabled: bool = False
@property
def properties_to_log(self) -> dict[str, Any]:
@@ -120,6 +123,7 @@ class ImportDataActivityInputs:
"reset_pipeline": self.reset_pipeline,
"fast_return_eligible": self.fast_return_eligible,
"scheduled_full_refresh": self.scheduled_full_refresh,
+ "keyset_full_load_enabled": self.keyset_full_load_enabled,
}
@@ -548,6 +552,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
api_version=new_source.resolve_api_version(schema.api_version or model.pipeline.api_version),
fanout_warehouse_reuse=fanout_warehouse_reuse,
byte_bounded_extraction=byte_bounded_extraction,
+ keyset_full_load=inputs.keyset_full_load_enabled,
activity_attempt=activity.info().attempt if activity.in_activity() else 1,
)