: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
chore(data-warehouse): remove the postgres keyset full-load flag (#110625)
Tom Owersa38215fba472
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/source.pyindex 49d24e313785..61d836729330 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/source.py@@ -47,7 +47,7 @@ class AttioSource(ResumableSource[AttioSourceConfig, AttioResumeConfig]):self,*,incremental_or_append: bool,- keyset_full_load_enabled: bool = False,+ keyset_full_load_enabled: bool = True,schema_name: str | None = None,) -> bool:endpoint = ATTIO_ENDPOINTS.get(schema_name or "")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.pyindex cb0655926d3a..a7bac3630c63 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@@ -503,7 +503,7 @@ class ResumableSource(_BaseSource[ConfigType], Generic[ConfigType, ResumableDataself,*,incremental_or_append: bool,- keyset_full_load_enabled: bool = False,+ keyset_full_load_enabled: bool = True,schema_name: str | None = None,) -> bool:"""Whether this source's resume mechanism covers a run of this shape.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.pydeleted file mode 100644index 182f20f45bf5..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/keyset_full_load_flag.py+++ /dev/null@@ -1,64 +0,0 @@-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 Falsediff --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 8ca881abe94a..63e4a2dc9044 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,7 +15,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res)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-from products.warehouse_sources.backend.types import ExternalDataSourceType@frozen@@ -199,29 +198,31 @@ 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: 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"-covered = [source.source_type- for source in keyset_sources- if source.resume_covers_run(incremental_or_append=True, keyset_full_load_enabled=True)+ for source in self._keyset_sources()+ if source.resume_covers_run(incremental_or_append=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)+ def test_a_keyset_source_covers_its_full_loads(self):+ # The other half of the rule above. A full load seeks and checkpoints, so each extra attempt+ # continues the read instead of restarting it, which is what the resumable allowance pays for.+ not_covered = [+ source.source_type+ for source in self._keyset_sources()+ if not source.resume_covers_run(incremental_or_append=False)+ ]+ assert not_covered == []- 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 _keyset_sources(self) -> list[ResumableSource]:+ 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"+ return keyset_sourcesdef 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 checkpointsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.pyindex e1f3bb57d072..a7e7f19d9582 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@@ -170,9 +170,8 @@ 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+ # Compatibility switch for activity payloads recorded before keyset full loads became unconditional.+ keyset_full_load: bool = True# 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 = 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/source.pyindex e66b5cf7a1d0..460242b7cea0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/source.py@@ -64,7 +64,7 @@ class IntercomSource(ResumableSource[IntercomSourceConfig, IntercomResumeConfig]self,*,incremental_or_append: bool,- keyset_full_load_enabled: bool = False,+ keyset_full_load_enabled: bool = True,schema_name: str | None = None,) -> bool:# The companies Scroll API cannot preserve a cursor across worker hand-offs.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.pyindex 42598dc2e6d3..3d7182f03e3c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py@@ -448,7 +448,7 @@ class MongoDBSource(ResumableSource[MongoDBSourceConfig, MongoResumeConfig], Valself,*,incremental_or_append: bool,- keyset_full_load_enabled: bool = False,+ keyset_full_load_enabled: bool = True,schema_name: str | None = None,) -> bool:# The `_id` checkpoint covers only a full refresh. An incremental or append run restarts fromdiff --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 d401ba9a7e8c..4ff6113147a7 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@@ -103,7 +103,7 @@ class MySQLSource(self,*,incremental_or_append: bool,- keyset_full_load_enabled: bool = False,+ keyset_full_load_enabled: bool = True,schema_name: str | None = None,) -> bool:# Keyset seeking is a full-load path, and it is the default one here. An incremental rundiff --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 e30f207a1191..3db90c0521d9 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@@ -3565,7 +3565,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,+ keyset_full_load_enabled: bool = True,) -> SourceResponse:table_name = table_names[0]if not table_name:@@ -3954,17 +3954,14 @@ def postgres_source(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.+ # Logged for every run that can't checkpoint, so the ineligible share and its breakdown by+ # reason stay measurable.logger.info(f"Postgres keyset resume unavailable: reason={keyset.reason}")- # 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. 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.+ # New full loads over a seekable key page by keyset, which lets a drained worker resume rather+ # than restart the read. A False value can only come from an activity payload recorded before+ # rollout completed; honoring it keeps that activity on one cursor mode across worker versions.+ # The read-replica retry fallback remains unchanged for those old payloads.takes_keyset_path = keyset.columns is not None and (keyset_full_load_enabled or (activity_attempt > 1 and using_read_replica))@@ -4452,8 +4449,8 @@ def postgres_source(# 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 "- f"instead of reopening a server cursor. keys = {keyset_primary_keys}"+ f"Full-table read by keyset seek instead of a server cursor. attempt={activity_attempt} "+ f"keys = {keyset_primary_keys}")yield from offset_chunking(0,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 4aeef22cab90..386ab135db4c 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@@ -415,13 +415,11 @@ class PostgresSource(self,*,incremental_or_append: bool,- keyset_full_load_enabled: bool = False,+ keyset_full_load_enabled: bool = True,schema_name: str | None = None,) -> 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.+ # Old activity payloads that recorded False keep the server-cursor path during the rolling+ # deploy, so only keyset full loads receive the resumable retry budget.return not incremental_or_append and keyset_full_load_enableddef get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KeysetResumeState]: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.pyindex 696c801c7f7c..aebbe01aec94 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@@ -91,6 +91,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.pNetworkAsStringLoader,PostgresDiscoveredSchema,PostgresImplementation,+ PostgresKeyset,PostgreSQLColumn,RangeAsStringLoader,SafeDateLoader,@@ -156,6 +157,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.sfrom products.warehouse_sources.backend.types import IncrementalFieldType+def server_cursor_path():+ # Every full load over a seekable key reads by keyset seek. These tests cover the server-cursor+ # path, which still serves a table without one, so they make the table ineligible to seek.+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.resolve_postgres_keyset",+ return_value=PostgresKeyset(reason="no_primary_key"),+ ):+ yield++class TestSafeDateLoader:@pytest.fixturedef loader(self):@@ -2161,6 +2173,9 @@ class TestSetupStatementTimeoutUnsupported:def fetchmany(self, _n: int):return []+ def fetchall(self):+ return []+def fetchone(self):return None@@ -2236,6 +2251,7 @@ class TestSetupStatementTimeoutUnsupported:assert list(cast(Iterable[Any], response.items())) == [][email protected]("server_cursor_path")class TestPostgresSourceSyncAllProjection:"""Sync-all names the discovered columns rather than rendering `SELECT *`.@@ -3485,6 +3501,7 @@ class TestStatementTimeoutAsNonRetryable:)[email protected]("server_cursor_path")class TestServerCursorStatementTimeout:"""The main server-cursor streaming path in `get_rows` must not leak a raw,retryable QueryCanceled when a FETCH hits the statement_timeout — it must map@@ -3604,6 +3621,7 @@ class TestServerCursorStatementTimeout:assert expected_substr in str(exc_info.value)[email protected]("server_cursor_path")class TestServerCursorCloseStatementTimeout:"""Closing the `get_rows` generator (the sync finished, or the activity was cancelled) tearsdown the open server cursor; that teardown round-trip can itself hit the statement_timeout and@@ -3928,10 +3946,9 @@ class TestOffsetChunkingConnectRecoveryConflict:def connect_side_effect(*args, **kwargs):connect_calls["n"] += 1- # Calls 1 (setup), 2 (catalog re-read before streaming) and 3 (initial server-cursor- # read) succeed; the offset-chunking bootstrap connect hits the recovery conflict- # twice before succeeding.- if connect_calls["n"] in (4, 5):+ # Calls 1 (setup) and 2 (catalog re-read before streaming) succeed. The keyset read's+ # first connect hits the recovery conflict twice before succeeding.+ if connect_calls["n"] in (3, 4):raise connect_errorreturn connection@@ -3966,9 +3983,8 @@ class TestOffsetChunkingConnectRecoveryConflict:# Before the fix the connect-time conflict escaped offset_chunking and raised here.list(cast(Iterable[Any], response.items()))- # 1 setup + 1 catalog re-read + 1 initial read + 3 offset-chunking connects (2 conflicts- # + 1 success).- assert connect_mock.call_count == 6+ # 1 setup + 1 catalog re-read + 3 keyset-read connects (2 conflicts + 1 success).+ assert connect_mock.call_count == 5class TestOffsetChunkingConnectTimeout:@@ -3996,10 +4012,9 @@ class TestOffsetChunkingConnectTimeout:def connect_side_effect(*args, **kwargs):connect_calls["n"] += 1- # Calls 1 (setup), 2 (catalog re-read before streaming) and 3 (initial server-cursor- # read) succeed; the offset-chunking bootstrap connect times out twice before- # succeeding.- if connect_calls["n"] in (4, 5):+ # Calls 1 (setup) and 2 (catalog re-read before streaming) succeed. The keyset read's+ # first connect times out twice before succeeding.+ if connect_calls["n"] in (3, 4):raise psycopg.errors.ConnectionTimeout("connection timeout expired")return connection@@ -4037,128 +4052,8 @@ class TestOffsetChunkingConnectTimeout:# Before the fix the connect-time timeout escaped offset_chunking and raised here.list(cast(Iterable[Any], response.items()))- # 1 setup + 1 catalog re-read + 1 initial read + 3 offset-chunking connects (2 timeouts- # + 1 success).- assert connect_mock.call_count == 6---class TestOffsetChunkingRecoveryConflictTimeout:- """When a read replica cancels the initial read with a recovery conflict, `get_rows` falls- back to offset chunking. If a chunk then exhausts the 10-min statement_timeout, a full-table- sync used to re-raise the raw, retryable QueryCanceled — so Temporal re-read from the start- into the same conflicting, overloaded replica every attempt. The fallback must instead surface- a non-retryable QueryTimeoutException with actionable replica guidance.- """-- class _NamedCursor:- def __init__(self):- col = mock.Mock()- col.name = "id"- self.description = [col]-- def execute(self, *args, **kwargs):- raise psycopg.errors.SerializationFailure("canceling statement due to conflict with recovery")-- def fetchmany(self, _n):- return []-- def __enter__(self):- return self-- def __exit__(self, *args):- return False-- class _OffsetCursor:- def __init__(self):- col = mock.Mock()- col.name = "id"- self.description = [col]-- def execute(self, *args, **kwargs):- raise psycopg.errors.QueryCanceled("canceling statement due to statement timeout")-- def fetchall(self):- return []-- def __enter__(self):- return self-- def __exit__(self, *args):- return False-- class _Connection:- def __init__(self):- self.autocommit = False- self.closed = False- self.broken = False- self.adapters = mock.Mock()-- def cursor(self, *args, **kwargs):- if "name" in kwargs:- return TestOffsetChunkingRecoveryConflictTimeout._NamedCursor()- return mock.MagicMock()-- def commit(self):- return None-- def close(self):- self.closed = True-- def __enter__(self):- return self-- def __exit__(self, *args):- return False-- def test_statement_timeout_in_recovery_conflict_fallback_is_non_retryable(self):- @contextmanager- def 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.type = "table"- fake_table.columns = [PostgreSQLColumn(name="id", data_type="integer", nullable=False)]- fake_table.__contains__ = mock.Mock(return_value=False)-- module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"- with (- patch(f"{module}.psycopg.connect", return_value=self._Connection()),- patch(f"{module}.psycopg.Cursor", side_effect=lambda _conn: self._OffsetCursor()),- 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),- patch(f"{module}._get_primary_keys", return_value=["id"]),- patch(f"{module}._is_partitioned_table", return_value=False),- patch(f"{module}._get_table_chunk_size", return_value=_TableChunking(batch_rows=1000, fetch_rows=1000)),- patch(f"{module}._get_rows_to_sync", return_value=10),- patch(f"{module}._role_subject_to_rls", return_value=False),- patch(f"{module}._get_partition_settings", return_value=None),- patch(f"{module}.time.sleep"),- ):- response = postgres_source(- tunnel=lambda: fake_tunnel(),- user="u",- password="p",- database="db",- sslmode="prefer",- schema="public",- table_names=["companies"],- should_use_incremental_field=False,- logger=structlog.get_logger(),- db_incremental_field_last_value=None,- team_id=1,- )- with pytest.raises(QueryTimeoutException) as exc_info:- list(cast(Iterable[Any], response.items()))-- message = str(exc_info.value)- assert "max_standby_streaming_delay" in message- # Unlike a raw QueryCanceled, QueryTimeoutException is classified non-retryable. It's matched- # by class name in the Temporal-wrapped error string (see external_data_job.py), so the- # non-retryable signal here is the type name, not the message text.- non_retryable = PostgresSource().get_non_retryable_errors()- assert type(exc_info.value).__name__ in non_retryable+ # 1 setup + 1 catalog re-read + 3 keyset-read connects (2 timeouts + 1 success).+ assert connect_mock.call_count == 5def _fake_column(name: str):@@ -4288,10 +4183,10 @@ class TestChunkedRereadAfterRecoveryConflict:is_xmin: bool = False,activity_attempt: int = 1,resumable_source_manager: Any = None,+ keyset_full_load_enabled: bool = True,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]:@contextmanagerdef fake_tunnel():@@ -4411,10 +4306,6 @@ class TestChunkedRereadAfterRecoveryConflict:assert sorted(ids) == [1, 2, 3, 4, 5, 6]- def test_full_refresh_stays_retryable_when_rows_are_already_written(self):- with pytest.raises(psycopg.errors.SerializationFailure):- self._read_ids(should_use_incremental_field=False, rows_before_conflict=2, primary_keys=["id"])-def test_retried_full_refresh_seeks_instead_of_reopening_the_cursor(self):# The first attempt re-raised past its first row, so a second server cursor conflicts at the# same place. The named cursor here would raise again after two rows; the seek never opens it.@@ -4560,10 +4451,9 @@ class TestChunkedRereadAfterRecoveryConflict:assert self.last_response.supports_resume is Falseassert 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.+ def test_the_first_attempt_seeks_and_checkpoints(self):+ # A full load pages and checkpoints from its first attempt, so a drained worker resumes+ # rather than restarting the read.manager = MagicMock()manager.can_resume.return_value = False@@ -4573,15 +4463,12 @@ class TestChunkedRereadAfterRecoveryConflict:primary_keys=["id"],activity_attempt=1,resumable_source_manager=manager,- keyset_full_load_enabled=True,)assert self.last_response.supports_resume is Trueassert 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.+ def test_an_old_flag_off_activity_keeps_the_server_cursor(self):manager = MagicMock()manager.can_resume.return_value = False@@ -4595,11 +4482,11 @@ class TestChunkedRereadAfterRecoveryConflict:)assert self.last_response.supports_resume is False- assert manager.save_state.call_count == 0+ manager.save_state.assert_not_called()- 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.+ def test_an_incremental_run_does_not_seek(self):+ # Seeking is 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@@ -4609,7 +4496,6 @@ class TestChunkedRereadAfterRecoveryConflict:primary_keys=["id"],activity_attempt=1,resumable_source_manager=manager,- keyset_full_load_enabled=True,)assert self.last_response.supports_resume is False@@ -4625,7 +4511,6 @@ class TestChunkedRereadAfterRecoveryConflict: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@@ -9780,6 +9665,7 @@ class TestGetRowsInitialConnectRetry:dj_cursor.execute(f"DROP TABLE IF EXISTS {table_name}")[email protected]("server_cursor_path")class TestGetRowsInitialReadDropRetry:# Regression: the main server-cursor read wrapped only the *connect* in# _connect_with_dropped_retry, so a transient drop during the server-cursor DECLARE@@ -9918,6 +9804,7 @@ class TestGetRowsInitialReadDropRetry:self._run(connect_side_effect)[email protected]("server_cursor_path")class TestGetRowsInitialReadLockTimeoutRetry:# Regression: a source-side lock_timeout hit while opening the server-cursor DECLARE# (cursor.execute) raises psycopg.errors.LockNotAvailable, which subclasses OperationalError and@@ -10284,6 +10171,7 @@ class TestExtractionByteBounds:assert max(factory.fetch_sizes[-3:]) <= self.BUDGET // len(self.BLOB) + 1[email protected]("server_cursor_path")class TestFetchPageGate:"""The page cap is the byte bound's own instrument, so the rollout gate has to hold it back too.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singular/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/source.pyindex b84dd341a976..e858e3e22b2a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/singular/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/source.py@@ -81,7 +81,7 @@ class SingularSource(ResumableSource[SingularSourceConfig, SingularResumeConfig]self,*,incremental_or_append: bool,- keyset_full_load_enabled: bool = False,+ keyset_full_load_enabled: bool = True,schema_name: str | None = None,) -> bool:# A lookup table is one request, so a retry has nothing to continue from.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.pyindex 57d6c0bacabd..2b13225f97f4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py@@ -68,7 +68,7 @@ class ZendeskSource(ResumableSource[ZendeskSourceConfig, ZendeskResumeConfig]):self,*,incremental_or_append: bool,- keyset_full_load_enabled: bool = False,+ keyset_full_load_enabled: bool = True,schema_name: str | None = None,) -> bool:endpoint = ZENDESK_ENDPOINTS.get(schema_name or "")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 02da25e53447..d684e387b9e4 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@@ -179,7 +179,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,+ keyset_full_load_enabled=True,)@@ -235,7 +235,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,+ keyset_full_load_enabled=True,)@@ -303,7 +303,7 @@ async def test_postgres_source_with_ssh_tunnel_disabled(activity_environment, tebyte_bounded_extraction=False,activity_attempt=1,resumable_source_manager=mock.ANY,- keyset_full_load_enabled=False,+ keyset_full_load_enabled=True,)@@ -386,7 +386,7 @@ async def test_postgres_source_with_ssh_tunnel_enabled(activity_environment, teabyte_bounded_extraction=False,activity_attempt=1,resumable_source_manager=mock.ANY,- keyset_full_load_enabled=False,+ keyset_full_load_enabled=True,)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.pyindex 909cbfa15d11..24b5b1048b7e 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,9 +47,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repfrom 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_operationfrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.check_billing_limits import (billing_limit_reached,@@ -332,12 +329,10 @@ 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+ # Always True for new jobs so workers from either release seek during a rolling deploy. The new+ # workflow also preserves an explicit False from an older recorded result. Remove after this+ # release is fully deployed.+ keyset_full_load_enabled: bool = True# 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@@ -494,7 +489,6 @@ 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.pyindex f578a268ae59..a227a6d50122 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@@ -117,9 +117,10 @@ 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+ # Fixed for the job lifetime so activity retries cannot switch cursor modes while old and new+ # workers overlap. Defaults True for new payloads; an old payload that recorded False keeps the+ # server-cursor path on both worker versions. Remove after this release is fully deployed.+ keyset_full_load_enabled: bool = True@propertydef properties_to_log(self) -> dict[str, Any]:@@ -131,7 +132,6 @@ 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,}