: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
fix(warehouse-sources): size keyset pages by the average row, halve after a worker death (#113751)
Daniel RC5de65a8834f1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.pyindex 2e70b9259196..32f47930a86b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py@@ -291,6 +291,24 @@ def report_heartbeat_timeout(inputs: "ImportDataActivityInputs", logger: Filterilogger.debug(f"Error while reporting heartbeat timeout: {e}", exc_info=e)+def count_worker_deaths(inputs: "ImportDataActivityInputs", logger: FilteringBoundLogger) -> int:+ """Times a worker died on this run without raising. `report_heartbeat_timeout` records each one."""+ try:+ from products.warehouse_sources.backend.models.oom_event import ( # noqa: PLC0415 — Django models must not be imported at this activity module's load time+ ExternalDataSchemaOOMEvent,+ )++ return (+ ExternalDataSchemaOOMEvent.objects.for_team(inputs.team_id)+ .filter(schema_id=inputs.schema_id, run_id=inputs.run_id)+ .count()+ )+ except Exception as e:+ # The count only makes a read more careful, so a read of it that fails must not fail the sync.+ logger.debug(f"Could not count worker deaths for schema {inputs.schema_id}: {e}", exc_info=e)+ return 0++async def handle_non_retryable_error(team_id: int,source_id: str,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.pyindex 681c0a2acb0e..483032ffbc52 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.eNON_RETRYABLE_ERROR_RETRY_LIMIT,UNREADABLE_JOB_INPUTS_MESSAGE,_get_redis,+ count_worker_deaths,finalize_desc_sort_incremental_value,handle_corrupted_delta_log,handle_non_retryable_error,@@ -324,6 +325,21 @@ class TestReportHeartbeatTimeoutRecording(BaseTest):assert event.self_phase is None and event.self_peak_buffer_bytes is Noneassert event.self_report_age_at_death_seconds is None+ def test_counts_the_deaths_of_this_run_only(self) -> None:+ schema = self._schema()+ other_schema = self._schema()+ events = ExternalDataSchemaOOMEvent.objects.for_team(self.team.pk)+ for schema_id, run_id in [+ (schema.id, "run-1"),+ (schema.id, "run-1"),+ (schema.id, "run-0"),+ (other_schema.id, "run-1"),+ ]:+ events.create(team_id=self.team.pk, schema_id=schema_id, run_id=run_id)+ inputs = MagicMock(team_id=self.team.pk, schema_id=schema.id, run_id="run-1")++ assert count_worker_deaths(inputs, MagicMock()) == 2+def test_row_snapshots_workload_evidence_without_co_tenant_identifiers(self) -> None:# The whole point of the stack: the dead attempt's own self-report and its pod's aggregates# must survive onto the durable row (the Redis source expires in hours), and nothing on thediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/batching.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/batching.pyindex 3eea1bbf58ea..98cc0c62892e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/batching.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/batching.py@@ -128,22 +128,38 @@ def _page_rows(largest_row_bytes: int, *, max_rows: int, max_bytes: int, max_pagreturn max(1, min(ceiling, max_bytes // largest_row_bytes))+def page_rows_after_worker_deaths(page_rows: int, worker_deaths: int) -> int:+ """The page ceiling for a run whose worker has died `worker_deaths` times.++ A page that is too large does not raise. The kernel kills the worker, and the next attempt+ reads the same rows again at the same size. Each death halves the page for the rest of the run.+ """+ return max(1, page_rows >> min(worker_deaths, 30))++def fetch_row_batches(fetch: Callable[[int], Sequence[RowT] | None],*,max_rows: int,max_bytes: int | None = None,max_page_rows: int | None = None,+ size_pages_by_average: bool = False,) -> Iterator[list[RowT]]:"""Yield row batches bounded by `max_rows` and by accumulated bytes.`fetch(n)` returns up to `n` rows, and an empty sequence (or None, which some DB-APIdrivers return instead) once the result set is drained — `cursor.fetchmany` for a driver,`iter_row_batches` for an already-streaming source.- It is called with a page size derived from the widest row seen so far, never with+ It is called with a page size derived from the rows seen so far, never with`max_rows` outright, so the caller's chunk size bounds the batch and not the fetch.`max_page_rows` is a caller-imposed ceiling, for a driver whose own limits cap a single fetch.++ `size_pages_by_average` is for a driver that pays a query and a round trip per fetch. The+ default sizes a page as if every row were as wide as the widest row seen, which costs a+ streaming driver nothing. A paging driver pays for it on every table that mixes narrow rows+ with an occasional wide one: its pages stay small for the whole read. With this set, a page is+ sized from the average row of the pages before it, so only a run of wide rows shrinks it."""budget = EXTRACT_BATCH_MAX_BYTES if max_bytes is None else max_bytespage_ceiling = max_page_rows or MAX_FETCH_PAGE_ROWS@@ -151,10 +167,12 @@ def fetch_row_batches(batch: list[RowT] = []batch_bytes = 0largest_row_bytes = 0+ average_row_bytes = 0page_rows = _page_rows(0, max_rows=max_rows, max_bytes=budget, max_page_rows=page_ceiling)while True:- page = fetch(page_rows)+ requested_rows = page_rows+ page = fetch(requested_rows)if not page:break@@ -180,23 +198,32 @@ def fetch_row_batches(batch = []batch_bytes = 0+ # Halving rather than forgetting: a table with one outsized row among millions would+ # otherwise stay stuck on tiny pages for the rest of the read, and one that has genuinely+ # widened re-shrinks on its very next page anyway.+ largest_row_bytes = max(widest_in_page, largest_row_bytes // 2)+ # The average halves too. A short page of narrow rows inside a run of wide rows would+ # otherwise send the next page back to the ceiling, into the wide rows that follow.+ average_row_bytes = max(-(-page_bytes // len(page)), average_row_bytes // 2)+ row_bytes_for_next_page = average_row_bytes if size_pages_by_average else largest_row_bytes+ page_rows = _page_rows(row_bytes_for_next_page, max_rows=max_rows, max_bytes=budget, max_page_rows=page_ceiling)+# Hand over a batch that leaves no room for another page rather than holding it while that# page lands. A batch carried across a fetch is resident *alongside* it, so the two peak- # together; flushing here makes residency one or the other. The next page is sized from- # the same estimate as the one just read, which is what makes its size predictable enough- # to budget for. Below that, a batch still spans as many fetches as it takes to fill —- # a driver reading 1000 rows at a time would otherwise yield a batch per fetch.- if batch and batch_bytes + page_bytes > budget:+ # together; flushing here makes residency one or the other. The widest-row estimate sizes+ # the next page like the one just read, so that page predicts it. The average can grow the+ # next page, so there the prediction is the page it is about to ask for. A driver that+ # returned fewer rows than it was asked for has a limit of its own, and the prediction+ # keeps to that limit, or every one of its short pages would become a batch. Below that, a+ # batch still spans as many fetches as it takes to fill — a driver reading 1000 rows at a+ # time would otherwise yield a batch per fetch.+ next_page_rows = page_rows if len(page) >= requested_rows else min(page_rows, len(page))+ next_page_bytes = next_page_rows * average_row_bytes if size_pages_by_average else page_bytes+ if batch and batch_bytes + next_page_bytes > budget:yield batchbatch = []batch_bytes = 0- # Halving rather than forgetting: a table with one outsized row among millions would- # otherwise stay stuck on tiny pages for the rest of the read, and one that has genuinely- # widened re-shrinks on its very next page anyway.- largest_row_bytes = max(widest_in_page, largest_row_bytes // 2)- page_rows = _page_rows(largest_row_bytes, max_rows=max_rows, max_bytes=budget, max_page_rows=page_ceiling)-if batch:yield batchdiff --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 0ef805231049..3d7a3cba4605 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@@ -28,7 +28,10 @@ import pyarrow as pafrom posthog.dataclasses import frozen-from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import fetch_row_batches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import (+ fetch_row_batches,+ page_rows_after_worker_deaths,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import ValidatedRowFilterfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.query_builder import (SafeSQL,@@ -212,6 +215,7 @@ def iter_keyset_pages(enabled_columns: list[str] | None = None,primary_keys: list[str] | None = None,row_filters: list[ValidatedRowFilter] | None = None,+ worker_deaths: int = 0,) -> Iterator[pa.Table]:"""Yield a table as successive Arrow batches, read by keyset pages that seek on `keyset_column`.@@ -224,8 +228,8 @@ def iter_keyset_pages(A page and a batch are not the same rows. `chunk_size` only bounds memory while every row is closeto the sampled row size, so the pages go through `fetch_row_batches`: a page asks for fewer rows- once the walk reads a wide row, and a batch closes on its byte budget. A batch can therefore end- inside a page, or hold several pages.+ once the walk reads a run of wide rows, and a batch closes on its byte budget. A batch can+ therefore end inside a page, or hold several pages.`checkpoint` records the last key of a batch once the consumer has come back for the next one.Generator laziness is what makes that the right moment: the call happens after the consumer has@@ -278,7 +282,12 @@ def iter_keyset_pages(# A page is one query and one round trip, so the page ceiling is the chunk size and not the lower# default that suits a driver reading from an open result stream.- for rows in fetch_row_batches(fetch_page, max_rows=chunk_size, max_page_rows=chunk_size):+ for rows in fetch_row_batches(+ fetch_page,+ max_rows=chunk_size,+ max_page_rows=page_rows_after_worker_deaths(chunk_size, worker_deaths),+ size_pages_by_average=True,+ ):table = to_table(columns, rows)yield tablediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_keyset.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_keyset.pyindex e778326c7ab9..ab905b2ffcc1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_keyset.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_keyset.py@@ -206,10 +206,11 @@ def _to_table(columns: list[str], rows) -> pa.Table:class _FakePages:# Serves a fixed dataset back through keyset SQL: parses `id > N` out of the built SQL, applies# the LIMIT, and records every query so the walk itself can be asserted.- def __init__(self, all_ids: list[int], chunk_size: int, body: str = "row"):+ def __init__(self, all_ids: list[int], chunk_size: int, body: str = "row", wide_ids: frozenset[int] = frozenset()):self.all_ids = sorted(all_ids)self.chunk_size = chunk_sizeself.body = body+ self.wide_ids = wide_idsself.queries: list[str] = []self.limits: list[int] = []@@ -222,7 +223,9 @@ class _FakePages:page = remaining[: min(limit, self.chunk_size)]if not page:return None- return KeysetPage(columns=["id", "body"], rows=[(i, self.body) for i in page])+ return KeysetPage(+ columns=["id", "body"], rows=[(i, "x" * 200 if i in self.wide_ids else self.body) for i in page]+ )def test_iter_keyset_pages_walks_whole_table_in_order():@@ -427,3 +430,45 @@ def test_a_batch_that_ends_inside_a_page_checkpoints_its_own_last_row():assert first.column("id").to_pylist() == [1, 2]assert second.column("id").to_pylist() == [3, 4]assert saved == [2]+++def test_an_occasional_wide_row_does_not_shrink_the_pages():+ pages = _FakePages(all_ids=list(range(1, 41)), chunk_size=10, wide_ids=frozenset({5, 15, 25, 35}))++ with patch.object(batching, "EXTRACT_BATCH_MAX_BYTES", 1_000):+ tables = list(+ iter_keyset_pages(+ builder=_BUILDER,+ schema="db",+ table_name="t",+ keyset_column="id",+ chunk_size=10,+ run_page=pages.run_page,+ to_table=_to_table,+ initial_last_value=None,+ )+ )++ assert [v.as_py() for table in tables for v in table.column("id")] == list(range(1, 41))+ assert set(pages.limits) == {10}+++def test_each_worker_death_halves_the_pages():+ pages = _FakePages(all_ids=list(range(1, 9)), chunk_size=8)++ tables = list(+ iter_keyset_pages(+ builder=_BUILDER,+ schema="db",+ table_name="t",+ keyset_column="id",+ chunk_size=8,+ run_page=pages.run_page,+ to_table=_to_table,+ initial_last_value=None,+ worker_deaths=2,+ )+ )++ assert [v.as_py() for table in tables for v in table.column("id")] == list(range(1, 9))+ assert set(pages.limits) == {2}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_sql_batching.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_sql_batching.pyindex e9571530ed69..884c6360e1d5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_sql_batching.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_sql_batching.py@@ -145,6 +145,58 @@ class TestFetchRowBatches:assert set(cursor.page_sizes) == {expected}+ def test_average_sizing_keeps_its_page_through_an_occasional_wide_row(self) -> None:+ rows = [(index, "x" * 4096 if index % 100 == 0 else "s") for index in range(1_000)]+ cursor = _FakeCursor(list(rows))++ batches = list(+ fetch_row_batches(+ cursor.fetchmany,+ max_rows=10_000,+ max_bytes=64 * 1024,+ max_page_rows=100,+ size_pages_by_average=True,+ )+ )++ assert [row for batch in batches for row in batch] == rows+ assert set(cursor.page_sizes) == {100}++ def test_average_sizing_shrinks_the_page_in_a_run_of_wide_rows(self) -> None:+ rows = _narrow(200) + _wide(200, value_bytes=1024, start=200)+ cursor = _FakeCursor(list(rows))++ batches = list(+ fetch_row_batches(+ cursor.fetchmany,+ max_rows=10_000,+ max_bytes=8 * 1024,+ max_page_rows=100,+ size_pages_by_average=True,+ )+ )++ assert [row for batch in batches for row in batch] == rows+ assert cursor.page_sizes[0] == 100+ assert cursor.page_sizes[-1] <= 8++ def test_average_sizing_stays_small_past_a_narrow_row_inside_a_run_of_wide_rows(self) -> None:+ rows = [(index, "s" if index % 3 == 2 else "x" * 1200) for index in range(400)]+ cursor = _FakeCursor(list(rows))++ batches = list(+ fetch_row_batches(+ cursor.fetchmany,+ max_rows=10_000,+ max_bytes=1_000,+ max_page_rows=100,+ size_pages_by_average=True,+ )+ )++ assert [row for batch in batches for row in batch] == rows+ assert set(cursor.page_sizes[1:]) == {1}+class TestPageAlignedFlush:def test_a_batch_never_spans_a_fetch_once_pages_are_large(self) -> None:@@ -166,6 +218,21 @@ class TestPageAlignedFlush:assert [len(batch) for batch in batches] == [100]+ def test_a_driver_that_caps_its_own_pages_still_fills_batches_under_average_sizing(self) -> None:+ cursor = _FakeCursor(_wide(2_000, value_bytes=84))++ batches = list(+ fetch_row_batches(+ lambda requested_rows: cursor.fetchmany(min(requested_rows, 50)),+ max_rows=10_000,+ max_bytes=100_000,+ max_page_rows=5_000,+ size_pages_by_average=True,+ )+ )++ assert [len(batch) for batch in batches] == [1_000, 1_000]+class TestIterRowBatches:def test_batches_an_already_streaming_source(self) -> None: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.pyindex 296c8aa63989..a5d4cefd91f2 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,6 +170,9 @@ class SourceInputs:# 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+ # Times a worker died on this run without raising, which is what a page too large for its+ # memory looks like. A source that pages can read smaller pages after one.+ worker_deaths: int = 0# Set for a source that implements `CursorSource`. It holds the cursor stored by the last# successful run, or no cursor when this run rebuilds the table.source_cursor: Optional[SourceCursorManager[Any]] = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.pyindex 79b8baf1439d..bd3b15856356 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py@@ -2055,6 +2055,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conenabled_columns=projection.enabled_columns,primary_keys=primary_keys,row_filters=row_filters,+ worker_deaths=inputs.worker_deaths,)# Only reached when the walk exhausted the table. An abandoned generator (drainingdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.pyindex b5595e5bcb78..3fd56cb7244c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py@@ -938,8 +938,10 @@ class TestKeysetReadPath:return mock_connect, cursor, plan_check@staticmethod- def _keyset_source(manager):- source = MySQLImplementation().build_pipeline(_make_config(), _make_inputs(), resumable_source_manager=manager)+ def _keyset_source(manager, **inputs):+ source = MySQLImplementation().build_pipeline(+ _make_config(), _make_inputs(**inputs), resumable_source_manager=manager+ )assert source.supports_resume is Truereturn source@@ -996,6 +998,14 @@ class TestKeysetReadPath:assert manager.save_state.call_count == 1manager.clear_state.assert_not_called()+ def test_a_worker_death_halves_the_pages(self, keyset_mocks):+ _, cursor, _ = keyset_mocks+ cursor.fetchall.side_effect = [[(1,)], []]++ list(cast(Generator, self._keyset_source(self._fake_manager(), worker_deaths=1).items()))++ assert "LIMIT 1" in cursor.execute.call_args_list[0].args[0]+def test_resumes_from_the_persisted_checkpoint(self, keyset_mocks):manager = self._fake_manager()manager.can_resume.return_value = Truediff --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 2ef1eb08a058..9a9a6ce269ed 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@@ -75,6 +75,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sqlfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import (EXTRACT_BATCH_MAX_BYTES,fetch_row_batches,+ page_rows_after_worker_deaths,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import (SQLSourceImplementation,@@ -3642,6 +3643,7 @@ def postgres_source(is_xmin: bool = False,xmin_cursor: Optional[SourceCursorManager[XminCursor]] = None,activity_attempt: int = 1,+ worker_deaths: int = 0,resumable_source_manager: Optional[ResumableSourceManager[KeysetResumeState]] = None,) -> SourceResponse:table_name = table_names[0]@@ -4442,10 +4444,18 @@ def postgres_source(try:# A page is one statement and it is resident in full, so it is sized like any# other fetch. A batch then spans as many pages as its byte budget holds.+ # A seek page is also a round trip, so only a run of wide rows shrinks it, and+ # a worker death halves it. A LIMIT/OFFSET walk is the fallback on a replica+ # that cancels reads, and it scans its whole offset on every page, so it keeps+ # the more careful sizing and its page.+ seeks = keyset_primary_keys is not Nonefor rows in fetch_row_batches(fetch_page,max_rows=chunk_size,- max_page_rows=fetch_page_rows,+ max_page_rows=(+ page_rows_after_worker_deaths(fetch_page_rows, worker_deaths) if seeks else fetch_page_rows+ ),+ size_pages_by_average=seeks,):batch_last_key = keyset_key_of(rows[-1]) if keyset_primary_keys is not None else Nonediff --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 3e2bba491e83..f7784c98eaa0 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@@ -2259,6 +2259,7 @@ class PostgresSource(is_xmin=schema.is_xmin,xmin_cursor=self.get_cursor_manager(inputs) if schema.is_xmin else None,activity_attempt=inputs.activity_attempt,+ worker_deaths=inputs.worker_deaths,resumable_source_manager=resumable_source_manager,)except SqlclientUnableToEstablishSqlconnection as e: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 b8268edc2dea..289a4e427ec8 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@@ -4360,6 +4360,8 @@ class TestChunkedRereadAfterRecoveryConflict:chunking: _TableChunking | None = None,lock_timeout_before_each_page: bool = False,page_error: BaseException | None = None,+ text_ids: list[str] | None = None,+ worker_deaths: int = 0,) -> list[int | str]:@contextmanagerdef fake_tunnel():@@ -4378,7 +4380,7 @@ class TestChunkedRereadAfterRecoveryConflict: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]+ rows = [(text_id,) for text_id in text_ids] if text_ids else [(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))@@ -4425,6 +4427,7 @@ class TestChunkedRereadAfterRecoveryConflict:team_id=1,is_xmin=is_xmin,activity_attempt=activity_attempt,+ worker_deaths=worker_deaths,resumable_source_manager=resumable_source_manager,)self.last_response = response@@ -4714,6 +4717,42 @@ class TestChunkedRereadAfterRecoveryConflict:# Once a page shows what a row weighs, a page holds no more than one batch budget.assert self.last_scan.limits[-1] == 2+ @parameterized.expand(+ [+ ("seek_walk_halves_its_pages", False, 2),+ # A LIMIT/OFFSET walk starts again from the first row and scans its offset on every page.+ ("offset_walk_keeps_its_pages", True, 4),+ ]+ )+ def test_page_size_after_a_worker_death(self, _name, should_use_incremental_field, expected_limit):+ ids = self._read_ids(+ should_use_incremental_field=should_use_incremental_field,+ rows_before_conflict=0,+ primary_keys=["id"],+ chunking=_TableChunking(batch_rows=6, fetch_rows=4),+ worker_deaths=1,+ )++ assert ids == [row[0] for row in self._ROWS]+ assert max(self.last_scan.limits) == expected_limit++ def test_one_wide_row_does_not_shrink_the_seek_pages(self):+ text_ids = ["a", "b", "c" + "x" * 200, "d", "e", "f"]++ with patch.object(batching, "EXTRACT_BATCH_MAX_BYTES", 300):+ ids = self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=0,+ primary_keys=["id"],+ arrow_schema=pa.schema([pa.field("id", pa.string())]),+ column_type="text",+ text_ids=text_ids,+ chunking=_TableChunking(batch_rows=6, fetch_rows=2),+ )++ assert ids == text_ids+ assert set(self.last_scan.limits) == {2}+def test_a_batch_that_ends_inside_a_page_checkpoints_its_own_last_row(self):# The first page reads rows 1 to 4, and the byte budget closes the first batch after row 2.# A checkpoint on the read position would resume past rows 3 and 4, which nothing wrote.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 11b22e811417..cac3f76d07ce 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@@ -56,6 +56,7 @@ from products.warehouse_sources.backend.temporal.data_imports.metrics import (get_worker_shutdown_handoff_metric,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (+ count_worker_deaths,handle_non_retryable_error,report_heartbeat_timeout,reset_pipeline_requested,@@ -669,6 +670,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,activity_attempt=current_import_attempt(),+ worker_deaths=await asyncio.to_thread(count_worker_deaths, inputs, logger),source_cursor=source_cursor_manager,)