Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(data-warehouse): bound SQL extraction batches by bytes (#85711)

Daniel RC5755587b1466
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/byte_bounded_extraction_flag.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/byte_bounded_extraction_flag.py
new file mode 100644
index 000000000000..530083eeff63
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/byte_bounded_extraction_flag.py
@@ -0,0 +1,44 @@
+import posthoganalytics
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.team.team import Team
+
+BYTE_BOUNDED_EXTRACTION_FLAG = "warehouse-byte-bounded-extraction"
+
+
+def is_byte_bounded_extraction_enabled(team_id: int, source_type: str) -> bool:
+ """Gate for bounding extraction batches by accumulated bytes rather than a sampled row count.
+
+ `source_type` rides along as a person property so the rollout widens one driver at a time
+ from the flag itself. The drivers differ in what a smaller fetch costs them — a Postgres
+ server cursor pays a round trip per fetch where MySQL reads from an unbuffered stream — so
+ they are worth validating separately.
+
+ Fails closed: any error means "off", which keeps the row-count batching.
+ """
+ try:
+ team = Team.objects.only("uuid", "organization_id").get(id=team_id)
+ except Team.DoesNotExist:
+ return False
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ BYTE_BOUNDED_EXTRACTION_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/sql/batching.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/batching.py
new file mode 100644
index 000000000000..e36684c1c386
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/batching.py
@@ -0,0 +1,225 @@
+"""Byte-bounded batching for SQL extraction.
+
+Every SQL driver reads its table the same way: ask the cursor for `chunk_size` rows, turn
+them into one Arrow table, repeat. `chunk_size` is derived from a sampled row size (a p95 of
+`octet_length` over a 1% sample, see `SQLSourceImplementation.get_chunk_size`), so the row
+count only bounds memory while every row is close to that sample. On a table whose row sizes
+span orders of magnitude — a `bytea` column holding multi-MB blobs next to rows that are a few
+hundred bytes — the sample says nothing about the heavy region, and the same row count fetches
+gigabytes there. That is an extraction-side OOM the pipeline's own buffer accounting never
+sees, because the pod dies before a single Arrow table reaches it.
+
+What actually bounds memory here is the fetch, not the flush. `fetch(n)` materialises all `n`
+rows before it returns — for a Postgres server cursor that is a `FETCH FORWARD n` whose whole
+result libpq buffers client-side — so a page is resident in full before any batch is yielded.
+The old loop asked for `chunk_size` rows however wide they were, which is precisely how a heavy
+region became gigabytes. Two bounds, then, doing two different jobs:
+
+* `max_page_rows` bounds one fetch, so what is resident before the first yield is bounded. This
+ is the memory bound. Callers that can measure their own rows pass a size derived from that
+ measurement; the rest take `MAX_FETCH_PAGE_ROWS`.
+* the byte budget bounds one batch, so what the caller materialises into Arrow stays bounded
+ whatever the row count works out to. This is not a memory bound on its own.
+
+Peak residency is therefore one page or one batch, not their sum: a batch that leaves no room
+for another page is flushed before that page is fetched.
+
+The residual exposure is one fetch: a region can only be measured once some of it has been
+read, so an abrupt jump in row size is paid for at whatever page size preceded it. What keeps
+that page small enough to survive is `max_page_rows` — either a driver's own measurement of its
+widest row, or `MAX_FETCH_PAGE_ROWS` when it has none. A single row larger than the budget is
+yielded on its own, the same way `_split_table` yields a lone oversized row.
+
+`byte_bounded` carries the rollout gate. With it off nothing is measured and both bounds come
+off `max_rows` alone, which is the fetch-a-chunk-and-yield-it loop every driver ran before.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
+from datetime import date, datetime, time
+from decimal import Decimal
+from itertools import islice
+from typing import Any, TypeVar
+from uuid import UUID
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_TABLE_SIZE_BYTES
+
+RowT = TypeVar("RowT")
+
+# Payload a batch may accumulate before it is flushed. The same budget the row-count estimate
+# was derived from, so a table of evenly sized rows keeps batching exactly as it did before.
+EXTRACT_BATCH_MAX_BYTES = DEFAULT_TABLE_SIZE_BYTES
+
+# Default rows per fetch for a driver that passes no `max_page_rows` of its own. A fetch is the
+# window in which row sizes are still unmeasured, so it caps a heavy region nothing warned us
+# about — the estimate below can only react one fetch late. Low because it is free to be: these
+# drivers read from a result stream the server is already pushing, so a smaller fetch costs no
+# round trip. A driver that pays per fetch should measure its widest row and pass a cap instead
+# (Postgres does), rather than take this one.
+MAX_FETCH_PAGE_ROWS = 1_000
+
+# Stand-in for anything whose payload isn't its length: ints, dates, decimals, UUIDs. Wrong in
+# both directions by a few bytes, which is irrelevant next to the columns this exists to catch.
+_SCALAR_VALUE_BYTES = 16
+
+# Types whose payload is that stand-in, so a column of them never needs measuring. Exact classes
+# rather than an isinstance check: this is per column of per row of every sync.
+_FIXED_WIDTH_TYPES = frozenset({int, float, bool, Decimal, datetime, date, time, UUID})
+
+
+def estimate_row_bytes(row: Any) -> int:
+ """Rough payload of one driver row, in bytes."""
+ return sum(_value_bytes(value) for value in row)
+
+
+def _measure_plan(row: Any) -> tuple[tuple[int, ...], int]:
+ """Which of a row's columns are worth measuring, and what the rest weigh together.
+
+ This runs on every row of every sync, so the per-column type dispatch is worth hoisting out
+ of the row loop: a SQL column's type does not change between rows, and the fixed-width ones
+ (numbers, timestamps, uuids) contribute a constant that can be added in one go. Measuring
+ every column instead is several times the cost, for columns that cannot vary in size.
+
+ Being wrong here is one-directional. A `None` says nothing about its column's type, so it
+ counts as worth measuring — that only costs a `len` on a value that turns out to be narrow.
+ """
+ measured = tuple(index for index, value in enumerate(row) if value.__class__ not in _FIXED_WIDTH_TYPES)
+ return measured, (len(row) - len(measured)) * _SCALAR_VALUE_BYTES
+
+
+def _planned_row_bytes(row: Any, measured: tuple[int, ...], fixed_bytes: int) -> int:
+ total = fixed_bytes
+ for index in measured:
+ value = row[index]
+ total += _str_bytes(value) if value.__class__ is str else _value_bytes(value)
+ return total
+
+
+def _str_bytes(value: str) -> int:
+ """Encoded size of a text value, without encoding one that does not need it.
+
+ `len` counts code points, so a CJK or emoji column measures a third to a quarter of what it
+ weighs. `isascii` reads a flag the interpreter already keeps, so plain text stays one `len`.
+ """
+ return len(value) if value.isascii() else len(value.encode())
+
+
+def _value_bytes(value: Any) -> int:
+ value_type = type(value)
+ if value_type is str:
+ return _str_bytes(value)
+ if value_type is bytes:
+ return len(value)
+ if value is None:
+ return 0
+ if isinstance(value, bytearray):
+ return len(value)
+ if isinstance(value, memoryview):
+ return value.nbytes
+ if isinstance(value, Mapping):
+ return sum(_value_bytes(key) + _value_bytes(item) for key, item in value.items())
+ if isinstance(value, list | tuple | set | frozenset):
+ return sum(_value_bytes(item) for item in value)
+ return _SCALAR_VALUE_BYTES
+
+
+def _page_rows(largest_row_bytes: int, *, max_rows: int, max_bytes: int | None, max_page_rows: int) -> int:
+ ceiling = min(max_rows, max_page_rows)
+ if max_bytes is None or largest_row_bytes <= 0:
+ return ceiling
+ return max(1, min(ceiling, max_bytes // largest_row_bytes))
+
+
+def fetch_row_batches(
+ fetch: Callable[[int], Sequence[RowT] | None],
+ *,
+ max_rows: int,
+ byte_bounded: bool,
+ max_bytes: int | None = None,
+ max_page_rows: int | None = None,
+) -> Iterator[list[RowT]]:
+ """Yield row batches bounded by `max_rows`, and by accumulated bytes when `byte_bounded`.
+
+ `fetch(n)` returns up to `n` rows, and an empty sequence (or None, which some DB-API
+ drivers return instead) once the result set is drained — `cursor.fetchmany` for a driver,
+ `iter_row_batches` for an already-streaming source.
+ Under `byte_bounded` it is called with a page size derived from the widest row 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 that holds either way, for a driver whose own
+ limits cap a single fetch.
+ """
+ budget = (EXTRACT_BATCH_MAX_BYTES if max_bytes is None else max_bytes) if byte_bounded else None
+ page_ceiling = max_page_rows or (MAX_FETCH_PAGE_ROWS if byte_bounded else max_rows)
+
+ batch: list[RowT] = []
+ batch_bytes = 0
+ largest_row_bytes = 0
+ page_rows = _page_rows(0, max_rows=max_rows, max_bytes=budget, max_page_rows=page_ceiling)
+
+ while True:
+ page = fetch(page_rows)
+ if not page:
+ break
+
+ widest_in_page = 0
+ page_bytes = 0
+ measured, fixed_bytes = _measure_plan(page[0]) if budget is not None else ((), 0)
+ for row in page:
+ row_bytes = _planned_row_bytes(row, measured, fixed_bytes) if budget is not None else 0
+ widest_in_page = max(widest_in_page, row_bytes)
+ page_bytes += row_bytes
+ # Flush *before* appending whatever would overflow, never after, or a nearly full
+ # batch could still take a further full-sized row (mirrors the repartition rewrite).
+ if batch and budget is not None and batch_bytes + row_bytes > budget:
+ yield batch
+ batch = []
+ batch_bytes = 0
+ batch.append(row)
+ batch_bytes += row_bytes
+ # The row bound needs no lookahead, so hand a full batch over as it completes rather
+ # than holding it back for a row that may be an error or the end of the result set.
+ if len(batch) >= max_rows:
+ yield batch
+ batch = []
+ batch_bytes = 0
+
+ # 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 budget is not None and batch_bytes + page_bytes > budget:
+ yield batch
+ 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)
+ page_rows = _page_rows(largest_row_bytes, max_rows=max_rows, max_bytes=budget, max_page_rows=page_ceiling)
+
+ if batch:
+ yield batch
+
+
+def iter_row_batches(
+ rows: Iterable[RowT],
+ *,
+ max_rows: int,
+ byte_bounded: bool,
+ max_bytes: int | None = None,
+ max_page_rows: int | None = None,
+) -> Iterator[list[RowT]]:
+ """`fetch_row_batches` over rows that already arrive one at a time (e.g. libpq row mode)."""
+ row_iterator = iter(rows)
+ return fetch_row_batches(
+ lambda n: list(islice(row_iterator, n)),
+ max_rows=max_rows,
+ byte_bounded=byte_bounded,
+ max_bytes=max_bytes,
+ max_page_rows=max_page_rows,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_byte_bounded_extraction_flag.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_byte_bounded_extraction_flag.py
new file mode 100644
index 000000000000..3fe86564be91
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_byte_bounded_extraction_flag.py
@@ -0,0 +1,32 @@
+import pytest
+from unittest.mock import patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.byte_bounded_extraction_flag import (
+ is_byte_bounded_extraction_enabled,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.byte_bounded_extraction_flag"
+
+
+class TestByteBoundedExtractionFlagFailsClosed:
+ def test_flag_service_error_returns_false(self):
+ with (
+ patch(f"{_MODULE}.Team") as team_cls,
+ patch(f"{_MODULE}.posthoganalytics.feature_enabled", side_effect=RuntimeError("flags endpoint down")),
+ ):
+ team_cls.objects.get.return_value.uuid = "u"
+ assert is_byte_bounded_extraction_enabled(1, "MySQL") is False
+
+ @pytest.mark.django_db
+ def test_missing_team_returns_false(self):
+ assert is_byte_bounded_extraction_enabled(999999999, "MySQL") is False
+
+ def test_source_type_reaches_the_flag_for_per_driver_targeting(self):
+ with (
+ patch(f"{_MODULE}.Team") as team_cls,
+ patch(f"{_MODULE}.posthoganalytics.feature_enabled", return_value=True) as feature_enabled,
+ ):
+ team_cls.objects.get.return_value.uuid = "u"
+ assert is_byte_bounded_extraction_enabled(1, "MySQL") is True
+
+ assert feature_enabled.call_args.kwargs["person_properties"]["source_type"] == "MySQL"
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.py
new file mode 100644
index 000000000000..7b7739931cf4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_sql_batching.py
@@ -0,0 +1,194 @@
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from typing import Any
+from uuid import UUID
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import (
+ MAX_FETCH_PAGE_ROWS,
+ _measure_plan,
+ _planned_row_bytes,
+ estimate_row_bytes,
+ fetch_row_batches,
+ iter_row_batches,
+)
+
+
+class _FakeCursor:
+ def __init__(self, rows: list[Any]) -> None:
+ self.rows = list(rows)
+ self.page_sizes: list[int] = []
+
+ def fetchmany(self, size: int) -> list[Any]:
+ self.page_sizes.append(size)
+ page, self.rows = self.rows[:size], self.rows[size:]
+ return page
+
+
+def _narrow(count: int) -> list[tuple[int, str]]:
+ return [(index, "s") for index in range(count)]
+
+
+def _wide(count: int, *, value_bytes: int, start: int = 0) -> list[tuple[int, str]]:
+ return [(index, "x" * value_bytes) for index in range(start, start + count)]
+
+
+class TestEstimateRowBytes:
+ @parameterized.expand(
+ [
+ ("text", ("abcd",), 4),
+ ("binary", (b"abcdef",), 6),
+ ("memoryview", (memoryview(b"abcdef"),), 6),
+ ("null_costs_nothing", (None,), 0),
+ ("scalars_are_a_constant", (1, 2), 32),
+ ("nested_json", ({"k": "vvvv"},), 5),
+ ("array", ([b"ab", b"cd"],), 4),
+ # `len` would call these 4, 6 and 2, so a table of them would overrun the budget by
+ # the encoding width rather than by a rounding error.
+ ("accented_text", ("café",), 5),
+ ("cjk_text", ("这是一个测试",), 18),
+ ("emoji_text", ("🎉🎊",), 8),
+ ("non_ascii_inside_json", ({"k": "café"},), 6),
+ ]
+ )
+ def test_measures_the_payload_that_matters(self, _name: str, row: tuple, expected: int) -> None:
+ assert estimate_row_bytes(row) == expected
+
+
+class TestMeasurePlan:
+ @parameterized.expand(
+ [
+ ("text_and_numbers", (1, "abcd", 2.5, b"xy")),
+ ("all_fixed_width", (1, 2.5, True, datetime(2026, 8, 20), Decimal("1.5"), UUID(int=1))),
+ ("all_variable", ("abcd", b"xy", {"k": "vv"}, ["a", "b"])),
+ ("nulls", (None, "abcd", None)),
+ ("non_ascii", (1, "café", "这是一个测试")),
+ ]
+ )
+ def test_matches_measuring_every_column(self, _name: str, row: tuple) -> None:
+ assert _planned_row_bytes(row, *_measure_plan(row)) == estimate_row_bytes(row)
+
+ def test_a_column_null_in_the_planning_row_is_still_measured(self) -> None:
+ # A None says nothing about its column's type. Skipping it would stop measuring a text
+ # column that happens to be null in the row the plan came from — the byte bound would
+ # then silently miss exactly the values it exists to catch.
+ measured, _ = _measure_plan((1, None))
+
+ assert _planned_row_bytes((1, "x" * 4096), measured, 16) == 4096 + 16
+
+
+class TestFetchRowBatches:
+ def test_batches_on_the_row_count_when_rows_are_evenly_sized(self) -> None:
+ cursor = _FakeCursor(_narrow(250))
+
+ batches = list(fetch_row_batches(cursor.fetchmany, byte_bounded=True, max_rows=100, max_bytes=1_000_000))
+
+ assert [len(batch) for batch in batches] == [100, 100, 50]
+
+ def test_flushes_early_once_the_byte_budget_is_reached(self) -> None:
+ cursor = _FakeCursor(_wide(40, value_bytes=1024))
+
+ batches = list(fetch_row_batches(cursor.fetchmany, byte_bounded=True, max_rows=10_000, max_bytes=8 * 1024))
+
+ assert all(sum(estimate_row_bytes(row) for row in batch) <= 8 * 1024 for batch in batches)
+ assert sum(len(batch) for batch in batches) == 40
+
+ def test_keeps_every_row_in_order_across_a_size_cliff(self) -> None:
+ rows = _narrow(50) + _wide(50, value_bytes=4096, start=50)
+ cursor = _FakeCursor(list(rows))
+
+ batches = list(fetch_row_batches(cursor.fetchmany, byte_bounded=True, max_rows=1_000, max_bytes=16 * 1024))
+
+ assert [row for batch in batches for row in batch] == rows
+
+ def test_yields_an_oversized_row_on_its_own(self) -> None:
+ rows = [(0, "s"), (1, "x" * 4096), (2, "s")]
+ cursor = _FakeCursor(rows)
+
+ batches = list(fetch_row_batches(cursor.fetchmany, byte_bounded=True, max_rows=1_000, max_bytes=1_024))
+
+ assert batches == [[rows[0]], [rows[1]], [rows[2]]]
+
+ def test_shrinks_the_fetch_page_once_wide_rows_appear(self) -> None:
+ cursor = _FakeCursor(_narrow(MAX_FETCH_PAGE_ROWS) + _wide(2_000, value_bytes=1024, start=MAX_FETCH_PAGE_ROWS))
+
+ list(fetch_row_batches(cursor.fetchmany, byte_bounded=True, max_rows=1_000_000, max_bytes=8 * 1024))
+
+ assert cursor.page_sizes[0] == MAX_FETCH_PAGE_ROWS
+ assert cursor.page_sizes[-1] <= 8
+
+ def test_recovers_the_fetch_page_after_a_lone_wide_row(self) -> None:
+ # A single outlier must not pin the read to tiny pages for the millions of rows behind it.
+ cursor = _FakeCursor([(0, "x" * 65_536), *_narrow(20_000)])
+
+ list(fetch_row_batches(cursor.fetchmany, byte_bounded=True, max_rows=1_000_000, max_bytes=64 * 1024))
+
+ assert min(cursor.page_sizes) == 1
+ assert cursor.page_sizes[-1] == MAX_FETCH_PAGE_ROWS
+
+ @parameterized.expand(
+ [
+ # A page wider than the batch would over-fetch; Redshift rejects it outright on a
+ # single-node cluster, where the caller's own cap is the only thing keeping the
+ # server cursor usable.
+ ("batch_size", {"max_rows": 4}, 4),
+ ("caller_cap", {"max_rows": 1_000, "max_page_rows": 3}, 3),
+ ]
+ )
+ def test_page_never_exceeds_the_lowest_ceiling(self, _name: str, kwargs: dict, expected: int) -> None:
+ cursor = _FakeCursor(_narrow(10))
+
+ list(fetch_row_batches(cursor.fetchmany, byte_bounded=True, max_bytes=1_000_000, **kwargs))
+
+ assert set(cursor.page_sizes) == {expected}
+
+
+class TestPageAlignedFlush:
+ def test_a_batch_never_spans_a_fetch_once_pages_are_large(self) -> None:
+ # A batch carried across a fetch is resident alongside the page that lands next, so the
+ # two peak together. Pages of ~1 KiB rows against a 12 KB budget: each page nearly fills
+ # a batch on its own, so carrying the remainder would double residency for one more row.
+ cursor = _FakeCursor(_wide(50, value_bytes=1000))
+
+ batches = list(
+ fetch_row_batches(cursor.fetchmany, byte_bounded=True, max_rows=1_000, max_bytes=12_000, max_page_rows=10)
+ )
+
+ assert [len(batch) for batch in batches] == [10, 10, 10, 10, 10]
+
+ def test_small_pages_still_coalesce_across_fetches(self) -> None:
+ # The other half: a driver reading 1000 narrow rows at a time must not yield a batch per
+ # fetch just because the page boundary arrived.
+ cursor = _FakeCursor(_narrow(100))
+
+ batches = list(
+ fetch_row_batches(cursor.fetchmany, byte_bounded=True, max_rows=1_000, max_bytes=12_000, max_page_rows=10)
+ )
+
+ assert [len(batch) for batch in batches] == [100]
+
+
+class TestByteBoundedOff:
+ def test_batches_and_fetches_on_the_row_count_alone(self) -> None:
+ # The rollout gate has to leave the old loop exactly as it was: one fetch of the chunk
+ # size, one batch per fetch, whatever the rows weigh.
+ cursor = _FakeCursor(_wide(250, value_bytes=4096))
+
+ batches = list(fetch_row_batches(cursor.fetchmany, byte_bounded=False, max_rows=100, max_bytes=8 * 1024))
+
+ assert [len(batch) for batch in batches] == [100, 100, 50]
+ assert set(cursor.page_sizes) == {100}
+
+
+class TestIterRowBatches:
+ def test_batches_an_already_streaming_source(self) -> None:
+ rows = _narrow(5)
+
+ assert list(iter_row_batches(iter(rows), byte_bounded=True, max_rows=2, max_bytes=1_000_000)) == [
+ rows[0:2],
+ rows[2:4],
+ rows[4:5],
+ ]
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 1d1a3f56304f..0cd32080dc45 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
@@ -120,3 +120,6 @@ class SourceInputs:
# (flag on + parents verified synced). Evaluated once by the run-time gate in
# `import_data_activity_sync` so sources don't re-evaluate the feature flag per run.
fanout_warehouse_reuse: bool = False
+ # 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
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
index d9ae7570bdfe..27bec1fa00ca 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
@@ -44,6 +44,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
project_arrow_columns,
render_named_conditions,
)
+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.implementation import (
SourceMetadata,
SQLSourceImplementation,
@@ -957,11 +958,9 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
column_names = [column[0] for column in cursor.description or []]
- while True:
- rows = cursor.fetchmany(chunk_size)
- if not rows:
- break
-
+ for rows in fetch_row_batches(
+ cursor.fetchmany, max_rows=chunk_size, byte_bounded=inputs.byte_bounded_extraction
+ ):
yield table_from_iterator(
(dict(zip(column_names, row)) for row in rows),
arrow_schema,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py
index 3dd756ed2be1..8c25bb090537 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
@@ -57,6 +57,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
compute_projected_columns,
project_arrow_columns,
)
+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.implementation import (
SourceMetadata,
SQLSourceImplementation,
@@ -1539,12 +1540,9 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
# the query actually returned instead of failing the batch build.
read_schema = restrict_schema_to_columns(arrow_schema, column_names)
- while True:
- # use chunk_size to fetch rows instead of DEFAULT_CHUNK_SIZE
- batch = ss_cursor.fetchmany(chunk_size)
- if not batch:
- break
-
+ for batch in fetch_row_batches(
+ ss_cursor.fetchmany, max_rows=chunk_size, byte_bounded=inputs.byte_bounded_extraction
+ ):
yield table_from_iterator(
(dict(zip(column_names, row)) for row in batch),
read_schema,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py
index 17e7970c37aa..62e1f8c2040d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py
@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
ValidatedRowFilter,
compute_projected_columns,
)
+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.predicates_psycopg import (
and_join,
render_psycopg_row_filter_conditions,
@@ -372,6 +373,8 @@ def iterate_date_windows(
chunk_size: int,
arrow_schema: pa.Schema,
logger: FilteringBoundLogger,
+ byte_bounded: bool = False,
+ fetch_rows: int | None = None,
initial_window: timedelta | int | float | None = None,
max_window_multiplier: int = 30,
min_window_divisor: int = 10,
@@ -445,10 +448,9 @@ def iterate_date_windows(
cur.execute(query)
columns = [c.name for c in cur.description or []]
window_schema = restrict_schema_to_columns(arrow_schema, columns)
- while True:
- rows = cur.fetchmany(chunk_size)
- if not rows:
- break
+ for rows in fetch_row_batches(
+ cur.fetchmany, max_rows=chunk_size, byte_bounded=byte_bounded, max_page_rows=fetch_rows
+ ):
rows_this_window += len(rows)
yield table_from_iterator(
(dict(zip(columns, r)) for r in rows),
@@ -602,6 +604,8 @@ def iterate_partitions(
chunk_size: int,
arrow_schema: pa.Schema,
logger: FilteringBoundLogger,
+ byte_bounded: bool = False,
+ fetch_rows: int | None = None,
incremental_field: Optional[str] = None,
incremental_field_type: Optional[IncrementalFieldType] = None,
db_incremental_field_last_value: Any = None,
@@ -642,10 +646,9 @@ def iterate_partitions(
cur.execute(query)
columns = [c.name for c in cur.description or []]
partition_schema = restrict_schema_to_columns(arrow_schema, columns)
- while True:
- rows = cur.fetchmany(chunk_size)
- if not rows:
- break
+ for rows in fetch_row_batches(
+ cur.fetchmany, max_rows=chunk_size, byte_bounded=byte_bounded, max_page_rows=fetch_rows
+ ):
rows_this_partition += len(rows)
yield table_from_iterator(
(dict(zip(columns, r)) for r in rows),
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 ccb595ac5e1c..de108da3eba6 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
@@ -32,6 +32,7 @@ from structlog.types import FilteringBoundLogger
from posthog.hogql.database.schema.duckdb_table_functions import is_dangerous_table_function
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.psycopg_helpers import resolve_psycopg_hostaddr_with_timeout
@@ -65,6 +66,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
ValidatedRowFilter,
compute_projected_columns,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import (
+ EXTRACT_BATCH_MAX_BYTES,
+ fetch_row_batches,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import (
SQLSourceImplementation,
)
@@ -105,6 +110,17 @@ SYNC_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 mins
METADATA_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 mins
+# Rows the row-size probe aims to measure. Enough for a stable p95 and a meaningful widest row,
+# few enough that `octet_length(t::text)` — which de-toasts every value — stays cheap on a table
+# whose values are megabytes each.
+SIZE_SAMPLE_TARGET_ROWS = 1000
+# Ceiling on rows measured when the catalog estimate is stale enough to over-sample. Reaching it
+# reintroduces the head bias `_size_sample_percent` exists to remove, so keep it well clear of
+# the target rather than close to it.
+SIZE_SAMPLE_MAX_ROWS = 5000
+# A sample can ask for arbitrarily few of a huge table's pages, but not for none of them.
+MIN_SIZE_SAMPLE_PERCENT = 0.0001
+
# Alias for the projected `xmin` system column on xmin syncs. `SELECT *` never returns system
# columns, so it must be projected explicitly; the alias also names the ORDER BY / WHERE cursor.
XMIN_PROJECTED_COLUMN = "_ph_xmin"
@@ -2015,6 +2031,7 @@ def _build_query(
db_incremental_field_last_value: Optional[Any],
add_sampling: Optional[bool] = False,
*,
+ sample_percent: Optional[float] = None,
upper_bound_inclusive: Optional[Any] = None,
enabled_columns: Optional[list[str]] = None,
primary_keys: Optional[list[str]] = None,
@@ -2041,10 +2058,19 @@ def _build_query(
cols=select_clause, table=sql.Identifier(schema, table_name)
)
else:
- query = sql.SQL("SELECT {cols} FROM {table} TABLESAMPLE SYSTEM (1)").format(
- cols=select_clause, table=sql.Identifier(schema, table_name)
+ # A percentage sized to the table returns roughly the target row count from pages
+ # spread across all of it. The fixed 1% below needs `LIMIT` to stay affordable, and
+ # a sample scan reads blocks in physical order, so that pairing only ever measures
+ # the front of the table — blind to a region that widens later, which is exactly
+ # the shape that makes a row-count batch unsafe.
+ query = sql.SQL("SELECT {cols} FROM {table} TABLESAMPLE SYSTEM ({percent})").format(
+ cols=select_clause,
+ table=sql.Identifier(schema, table_name),
+ percent=sql.Literal(sample_percent if sample_percent is not None else 1),
)
- return query + sql.SQL(" LIMIT 1000")
+ if sample_percent is not None:
+ return query + sql.SQL(" LIMIT {limit}").format(limit=sql.Literal(SIZE_SAMPLE_MAX_ROWS))
+ return query + sql.SQL(" LIMIT {limit}").format(limit=sql.Literal(SIZE_SAMPLE_TARGET_ROWS))
query = sql.SQL("SELECT {cols} FROM {table}").format(
cols=select_clause, table=sql.Identifier(schema, table_name)
@@ -2091,9 +2117,17 @@ def _build_query(
last_value=sql.Literal(db_incremental_field_last_value),
)
else:
+ # Sized like the full-refresh sample, but never below the fixed 1% this has always
+ # drawn. A small table is one page, and a 1% page sample misses it ~99 times in 100,
+ # so an incremental sync of one measures nothing and has to guess at its row size.
+ # Raising the floor only ever draws more pages; a table big enough for the estimate
+ # to fall under 1% keeps exactly the sample it has today, where the slice it filters
+ # to is the part the estimate cannot speak for.
query = sql.SQL(
- "SELECT {cols} FROM {schema}.{table} TABLESAMPLE SYSTEM (1) WHERE {incremental_field} {op} {last_value}"
+ "SELECT {cols} FROM {schema}.{table} TABLESAMPLE SYSTEM ({percent}) "
+ "WHERE {incremental_field} {op} {last_value}"
).format(
+ percent=sql.Literal(max(sample_percent, 1.0) if sample_percent is not None else 1),
cols=select_clause,
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
@@ -2375,7 +2409,84 @@ def _has_duplicate_primary_keys(
return False
-def _get_table_chunk_size(cursor: psycopg.Cursor, inner_query: sql.Composed, logger: FilteringBoundLogger) -> int:
+@frozen
+class _TableChunking:
+ """How much of a table one read pulls at a time.
+
+ Two row counts with two different jobs. `batch_rows` sizes what the pipeline receives, from
+ the sample's p95. `fetch_rows` sizes a single `FETCH`, from the sample's p99 — a `FETCH` is
+ materialised whole, so it has to be sized for the rows a heavy page is made of rather than
+ for the table's typical row.
+ """
+
+ batch_rows: int
+ fetch_rows: int
+
+
+def _fetch_rows_for(batch_rows: int, wide_row_bytes: int | None) -> int:
+ """Rows per `FETCH` that the sample's p99 row says fit in one batch budget.
+
+ The p99 and not the widest row. A `FETCH` is sized for what a page of rows weighs, and one
+ outlier says nothing about that — sizing off the maximum lets a single freak row hold the
+ whole table to tiny fetches, since this becomes a hard ceiling the reader's own high-water
+ mark can shrink below but never grow above. At the p99 a table only fetches small when wide
+ rows are common enough to actually fill a page, which is the case that kills the pod.
+
+ No usable measurement keeps the whole-batch `FETCH` this driver has always issued, leaving
+ the shrink to the reader's running high-water mark. That is the pre-existing exposure,
+ never a new one.
+ """
+ if not wide_row_bytes or wide_row_bytes <= 0:
+ return batch_rows
+ return max(1, min(batch_rows, EXTRACT_BATCH_MAX_BYTES // wide_row_bytes))
+
+
+def _estimated_row_count(
+ cursor: psycopg.Cursor, schema: str, table_name: str, logger: FilteringBoundLogger
+) -> int | None:
+ """Catalog row estimate for one table, or None when neither source has run yet.
+
+ `reltuples` is -1 on a table ANALYZE has never touched, and the stats collector's
+ `n_live_tup` is 0 on a fresh standby, so both are checked before giving up.
+ """
+ try:
+ cursor.execute(
+ sql.SQL("""
+ SELECT c.reltuples, s.n_live_tup
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid
+ WHERE n.nspname = {schema} AND c.relname = {table}
+ """).format(schema=sql.Literal(schema), table=sql.Literal(table_name))
+ )
+ row = cursor.fetchone()
+ if row is None:
+ return None
+ reltuples, n_live_tup = row
+ for estimate in (reltuples, n_live_tup):
+ if estimate is not None and estimate > 0:
+ return int(estimate)
+ return None
+ except Exception as e:
+ logger.debug(f"_estimated_row_count: Error: {e}", exc_info=e)
+ return None
+
+
+def _size_sample_percent(row_estimate: int | None) -> float | None:
+ """Percentage of pages to sample so about `SIZE_SAMPLE_TARGET_ROWS` rows come back.
+
+ None when the catalog cannot say how big the table is; the caller keeps the fixed 1% sample.
+ """
+ if not row_estimate or row_estimate <= 0:
+ return None
+ if row_estimate <= SIZE_SAMPLE_TARGET_ROWS:
+ return 100.0
+ return max(MIN_SIZE_SAMPLE_PERCENT, 100.0 * SIZE_SAMPLE_TARGET_ROWS / row_estimate)
+
+
+def _get_table_chunk_size(
+ cursor: psycopg.Cursor, inner_query: sql.Composed, logger: FilteringBoundLogger
+) -> _TableChunking:
# Under autocommit each statement is its own transaction — a failure can't poison
# subsequent commands, so no SAVEPOINT is needed. When called inside a shared
# transaction (e.g. tests or future callers), wrap in a SAVEPOINT so that a
@@ -2387,8 +2498,16 @@ def _get_table_chunk_size(cursor: psycopg.Cursor, inner_query: sql.Composed, log
cursor.execute("SAVEPOINT _chunk_size_probe")
savepoint_active = True
+ # The extra percentile and the maximum ride along on rows the p95 already materialised,
+ # so both cost nothing to learn. The p99 sizes a `FETCH`, because that is the row size a
+ # page of rows is actually made of; the maximum is logged rather than used, since one
+ # outlier row characterises no page (see `_fetch_rows_for`).
query = sql.SQL("""
- SELECT percentile_cont(0.95) within group (order by subquery.row_size) FROM (
+ SELECT
+ percentile_cont(0.95) within group (order by subquery.row_size),
+ percentile_cont(0.99) within group (order by subquery.row_size),
+ max(subquery.row_size)
+ FROM (
SELECT octet_length(t::text) as row_size FROM ({}) as t
) as subquery
""").format(inner_query)
@@ -2405,15 +2524,33 @@ def _get_table_chunk_size(cursor: psycopg.Cursor, inner_query: sql.Composed, log
if row is None:
logger.debug(f"_get_table_chunk_size: No results returned. Using DEFAULT_CHUNK_SIZE={DEFAULT_CHUNK_SIZE}")
- chunk_size = DEFAULT_CHUNK_SIZE
- else:
- row_size_bytes = row[0] or 1
- chunk_size = int(DEFAULT_TABLE_SIZE_BYTES / row_size_bytes)
- logger.debug(
- f"_get_table_chunk_size: row_size_bytes={row_size_bytes}. DEFAULT_TABLE_SIZE_BYTES={DEFAULT_TABLE_SIZE_BYTES}. Using CHUNK_SIZE={chunk_size}"
- )
-
- return chunk_size
+ return _TableChunking(batch_rows=DEFAULT_CHUNK_SIZE, fetch_rows=DEFAULT_CHUNK_SIZE)
+
+ # A sample that measured nothing returns NULL percentiles: an empty table, or a
+ # never-analyzed one, which draws no catalog estimate and so falls back to a fixed 1%
+ # of pages that a small table usually misses entirely. Reading that as a one-byte row
+ # derives a chunk of 150 million, and a chunk is what sizes the `FETCH` when no page cap
+ # applies — so the read asks for the whole table in one page on exactly the tables whose
+ # row size is unknown. This stays off the gate: it is a defect in the arithmetic, not
+ # behavior worth preserving, and every other SQL source already floors this case.
+ row_size_bytes = row[0]
+ if not row_size_bytes:
+ logger.debug(f"_get_table_chunk_size: Nothing measured. Using DEFAULT_CHUNK_SIZE={DEFAULT_CHUNK_SIZE}")
+ return _TableChunking(batch_rows=DEFAULT_CHUNK_SIZE, fetch_rows=DEFAULT_CHUNK_SIZE)
+ wide_row_bytes = int(row[1]) if row[1] else None
+ largest_row_bytes = int(row[2]) if row[2] else None
+ # A row wider than the whole budget floors the division to zero, and a zero-row chunk
+ # reads `FETCH FORWARD 0` — an empty page the loop cannot tell from the end of the
+ # result set, so the table syncs as empty. One row per batch is what such a table can
+ # actually do; the sibling `SQLSourceImplementation.get_chunk_size` already floors it.
+ batch_rows = max(1, int(DEFAULT_TABLE_SIZE_BYTES / row_size_bytes))
+ chunking = _TableChunking(batch_rows=batch_rows, fetch_rows=_fetch_rows_for(batch_rows, wide_row_bytes))
+ logger.debug(
+ f"_get_table_chunk_size: row_size_bytes={row_size_bytes}. wide_row_bytes={wide_row_bytes}. "
+ f"largest_row_bytes={largest_row_bytes}. DEFAULT_TABLE_SIZE_BYTES={DEFAULT_TABLE_SIZE_BYTES}. "
+ f"Using CHUNK_SIZE={chunking.batch_rows}, FETCH_ROWS={chunking.fetch_rows}"
+ )
+ return chunking
except Exception as e:
# Best-effort: any failure (including a statement_timeout / QueryCanceled) falls back to
# DEFAULT_CHUNK_SIZE. The estimation query wraps the sample in `octet_length(t::text)`,
@@ -2432,7 +2569,7 @@ def _get_table_chunk_size(cursor: psycopg.Cursor, inner_query: sql.Composed, log
logger.debug(f"_get_table_chunk_size: Failed to rollback savepoint: {rollback_error}")
logger.debug(f"_get_table_chunk_size: Error: {e}. Using DEFAULT_CHUNK_SIZE={DEFAULT_CHUNK_SIZE}", exc_info=e)
- return DEFAULT_CHUNK_SIZE
+ return _TableChunking(batch_rows=DEFAULT_CHUNK_SIZE, fetch_rows=DEFAULT_CHUNK_SIZE)
def _role_subject_to_rls(cursor: psycopg.Cursor, schema: str, table_name: str, logger: FilteringBoundLogger) -> bool:
@@ -3003,6 +3140,7 @@ def postgres_source(
is_xmin: bool = False,
xmin_last_value: Optional[int] = None,
xmin_num_wraparound: Optional[int] = None,
+ byte_bounded_extraction: bool = False,
) -> SourceResponse:
table_name = table_names[0]
if not table_name:
@@ -3171,6 +3309,9 @@ def postgres_source(
incremental_field_type,
db_incremental_field_last_value,
add_sampling=True,
+ sample_percent=_size_sample_percent(
+ _estimated_row_count(cursor, schema, table_name, logger)
+ ),
enabled_columns=enabled_columns,
primary_keys=primary_keys,
xmin_bounds=xmin_bounds,
@@ -3208,10 +3349,19 @@ def postgres_source(
)
logger.debug("Getting table chunk size...")
if chunk_size_override is not None:
- chunk_size = chunk_size_override
+ chunking = _TableChunking(
+ batch_rows=chunk_size_override, fetch_rows=chunk_size_override
+ )
logger.debug(f"Using chunk_size_override: {chunk_size_override}")
else:
- chunk_size = _get_table_chunk_size(cursor, inner_query_with_limit, logger)
+ chunking = _get_table_chunk_size(cursor, inner_query_with_limit, logger)
+ chunk_size = chunking.batch_rows
+ # The page cap only exists to bound what one `FETCH` materialises, so
+ # it belongs behind the same gate as the byte bound it serves. Applied
+ # with the gate off it shrinks the fetch without ever flushing a batch:
+ # the read pays a round trip per page and still accumulates the whole
+ # table, which is worse than the single full-size fetch it replaced.
+ fetch_page_rows = chunking.fetch_rows if byte_bounded_extraction else None
logger.debug("Getting rows to sync...")
# For partitioned tables without an incremental cursor (initial
@@ -3662,6 +3812,8 @@ def postgres_source(
table_name=table_name,
child_partitions=child_partitions,
chunk_size=chunk_size,
+ byte_bounded=byte_bounded_extraction,
+ fetch_rows=fetch_page_rows,
arrow_schema=arrow_schema,
logger=logger,
incremental_field=incremental_field,
@@ -3699,6 +3851,8 @@ def postgres_source(
db_incremental_field_last_value=db_incremental_field_last_value,
child_partitions=child_partitions,
chunk_size=chunk_size,
+ byte_bounded=byte_bounded_extraction,
+ fetch_rows=fetch_page_rows,
arrow_schema=arrow_schema,
logger=logger,
using_read_replica=using_read_replica,
@@ -3742,13 +3896,17 @@ def postgres_source(
column_names = [column.name for column in cursor.description or []]
read_schema = restrict_schema_to_columns(arrow_schema, column_names)
- while True:
- rows = cursor.fetchmany(chunk_size)
- if not rows:
- break
-
+ for rows in fetch_row_batches(
+ cursor.fetchmany,
+ max_rows=chunk_size,
+ byte_bounded=byte_bounded_extraction,
+ max_page_rows=fetch_page_rows,
+ ):
dicts = [dict(zip(column_names, row)) for row in rows]
- del rows
+ # The batcher still holds this list, so only clearing it in place
+ # frees the tuples before the Arrow build. `del` would drop the
+ # local name and leave the batcher's reference holding the rows.
+ rows.clear()
yield table_from_iterator(
iter(dicts), read_schema, primary_keys=primary_keys, binary_reporter=binary_reporter
)
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 0572351b6423..360549e5e107 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
@@ -1474,6 +1474,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
is_xmin=schema.is_xmin,
xmin_last_value=schema.xmin_last_value,
xmin_num_wraparound=schema.xmin_num_wraparound,
+ byte_bounded_extraction=inputs.byte_bounded_extraction,
)
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 94e4e3b078f8..001abd9c5f58 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
@@ -30,8 +30,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
QueryTimeoutException,
TemporaryFileSizeExceedsLimitException,
)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_CHUNK_SIZE
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import (
+ DEFAULT_CHUNK_SIZE,
+ DEFAULT_TABLE_SIZE_BYTES,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import table_payload_bytes
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import batching
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (
ColumnTypeCategory,
ValidatedRowFilter,
@@ -63,6 +68,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
_SSH_HANDSHAKE_EOF_ERROR,
FORCE_UTF8_CLIENT_ENCODING,
METADATA_STATEMENT_TIMEOUT_MS,
+ MIN_SIZE_SAMPLE_PERCENT,
+ SIZE_SAMPLE_MAX_ROWS,
+ SIZE_SAMPLE_TARGET_ROWS,
SSL_REQUIRED_AFTER_DATE,
XMIN_PROJECTED_COLUMN,
JsonAsStringLoader,
@@ -84,6 +92,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
_connect_to_postgres,
_connect_with_dropped_retry,
_connect_with_options_fallback,
+ _fetch_rows_for,
_get_estimated_row_count_for_partitioned_table,
_get_partition_settings,
_get_partition_settings_for_partitioned_table,
@@ -114,7 +123,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
_safe_close_connection,
_schema_discovery_timeout_error,
_schemas_from_conn,
+ _size_sample_percent,
_statement_timeout_as_non_retryable,
+ _TableChunking,
_tunnel_with_handshake_translation,
_xmin_capable_tables_from_conn,
filter_postgres_incremental_fields,
@@ -1768,7 +1779,7 @@ class TestSetupStatementTimeoutUnsupported:
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=100),
+ patch(f"{module}._get_table_chunk_size", return_value=_TableChunking(batch_rows=100, fetch_rows=100)),
patch(f"{module}._get_rows_to_sync", return_value=0),
patch(f"{module}._role_subject_to_rls", return_value=False),
patch(f"{module}._get_partition_settings", return_value=None),
@@ -2791,7 +2802,7 @@ class TestServerCursorStatementTimeout:
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=100),
+ patch(f"{module}._get_table_chunk_size", return_value=_TableChunking(batch_rows=100, fetch_rows=100)),
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),
@@ -2914,7 +2925,7 @@ class TestServerCursorCloseStatementTimeout:
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=100),
+ patch(f"{module}._get_table_chunk_size", return_value=_TableChunking(batch_rows=100, fetch_rows=100)),
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),
@@ -3029,7 +3040,7 @@ class TestGetRowsSkipsServerCursorForDuckDB:
patch(f"{module}._is_duckdb_connection", return_value=True),
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=100),
+ patch(f"{module}._get_table_chunk_size", return_value=_TableChunking(batch_rows=100, fetch_rows=100)),
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),
@@ -3171,7 +3182,7 @@ class TestOffsetChunkingConnectRecoveryConflict:
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=1000),
+ 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),
@@ -3240,7 +3251,7 @@ class TestOffsetChunkingConnectTimeout:
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=1000),
+ 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),
@@ -3354,7 +3365,7 @@ class TestOffsetChunkingRecoveryConflictTimeout:
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=1000),
+ 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),
@@ -5492,12 +5503,49 @@ class TestGetTableChunkSize:
with autocommit_pg_connection.cursor() as cursor:
inner_query = sql.SQL("SELECT * FROM does_not_exist_chunk_probe").format()
- chunk_size = _get_table_chunk_size(cast(Any, cursor), inner_query, logger)
+ chunk_size = _get_table_chunk_size(cast(Any, cursor), inner_query, logger).batch_rows
assert chunk_size == DEFAULT_CHUNK_SIZE
cursor.execute("SELECT 1")
assert cursor.fetchone()[0] == 1
+ @pytest.mark.django_db
+ def test_common_wide_rows_shrink_the_fetch_without_shrinking_the_batch(self):
+ # Wide rows sitting between the p95 and the p99: too rare to move the batch, common
+ # enough to fill a FETCH.
+ logger = structlog.get_logger()
+
+ with django_connection.cursor() as dj_cursor:
+ dj_cursor.execute("CREATE TEMP TABLE wide_rows (id int, payload text)")
+ dj_cursor.execute("INSERT INTO wide_rows SELECT g, 'x' FROM generate_series(1, 200) g")
+ dj_cursor.execute(
+ "INSERT INTO wide_rows SELECT g, repeat('x', 1024 * 1024) FROM generate_series(201, 206) g"
+ )
+
+ chunking = _get_table_chunk_size(cast(Any, dj_cursor), sql.SQL("SELECT * FROM wide_rows").format(), logger)
+
+ # The p95 still sees a narrow row, so the batch stays large; the FETCH does not.
+ assert chunking.batch_rows > 100_000
+ assert chunking.fetch_rows < 200
+
+ @pytest.mark.django_db
+ def test_a_lone_wide_row_does_not_shrink_the_fetch(self):
+ # One outlier among two hundred cannot fill a page, and the FETCH cap is a ceiling the
+ # reader can never grow back above — so pricing the whole table off it would strand every
+ # later fetch at a handful of rows for one row's sake.
+ logger = structlog.get_logger()
+
+ with django_connection.cursor() as dj_cursor:
+ dj_cursor.execute("CREATE TEMP TABLE lone_wide_row (id int, payload text)")
+ dj_cursor.execute("INSERT INTO lone_wide_row SELECT g, 'x' FROM generate_series(1, 200) g")
+ dj_cursor.execute("INSERT INTO lone_wide_row VALUES (201, repeat('x', 1024 * 1024))")
+
+ chunking = _get_table_chunk_size(
+ cast(Any, dj_cursor), sql.SQL("SELECT * FROM lone_wide_row").format(), logger
+ )
+
+ assert chunking.fetch_rows == chunking.batch_rows
+
@pytest.mark.django_db
def test_statement_timeout_falls_back_without_poisoning_transaction(self):
# The estimation query wraps the sample in octet_length(t::text), which can exceed the
@@ -5511,13 +5559,136 @@ class TestGetTableChunkSize:
dj_cursor.execute("SET LOCAL statement_timeout = '100ms'")
inner_query = sql.SQL("SELECT pg_sleep(3) AS c").format()
- chunk_size = _get_table_chunk_size(cast(Any, dj_cursor), inner_query, logger)
+ chunk_size = _get_table_chunk_size(cast(Any, dj_cursor), inner_query, logger).batch_rows
assert chunk_size == DEFAULT_CHUNK_SIZE
# Savepoint rollback leaves the connection usable for the rest of setup.
dj_cursor.execute("SELECT 1")
assert dj_cursor.fetchone()[0] == 1
+ class _ProbeCursor:
+ def __init__(self, row):
+ self._row = row
+ self.connection = mock.Mock(autocommit=True)
+
+ def execute(self, *args, **kwargs):
+ return None
+
+ def fetchall(self):
+ return []
+
+ def fetchone(self):
+ return self._row
+
+ def test_a_row_wider_than_the_budget_still_reads_one_row_at_a_time(self):
+ # Flooring the division to zero reads `FETCH FORWARD 0`, and an empty page is
+ # indistinguishable from the end of the result set — the table would sync as empty.
+ wider_than_the_budget = float(DEFAULT_TABLE_SIZE_BYTES * 2)
+ cursor = self._ProbeCursor((wider_than_the_budget, wider_than_the_budget, int(wider_than_the_budget)))
+
+ chunking = _get_table_chunk_size(cast(Any, cursor), sql.SQL("SELECT 1").format(), structlog.get_logger())
+
+ assert chunking.batch_rows == 1
+ assert chunking.fetch_rows == 1
+
+ def test_a_sample_that_measured_nothing_falls_back(self):
+ # NULL percentiles mean no row was measured, not that rows are one byte wide. Reading
+ # that as a size derives a 150-million-row chunk, and with no page cap in play the chunk
+ # is what sizes the FETCH, so the read asks for the whole table in one page.
+ cursor = self._ProbeCursor((None, None, None))
+
+ chunking = _get_table_chunk_size(cast(Any, cursor), sql.SQL("SELECT 1").format(), structlog.get_logger())
+
+ assert chunking == _TableChunking(batch_rows=DEFAULT_CHUNK_SIZE, fetch_rows=DEFAULT_CHUNK_SIZE)
+
+
+class TestSizeSamplePercent:
+ @parameterized.expand(
+ [
+ ("no_estimate", None, None),
+ ("zero_estimate", 0, None),
+ ("smaller_than_the_target", 400, 100.0),
+ ("large_table", 2_000_000, 0.05),
+ ("beyond_the_floor", 10_000_000_000, MIN_SIZE_SAMPLE_PERCENT),
+ ]
+ )
+ def test_scales_the_sample_to_the_table(self, _name, row_estimate, expected):
+ assert _size_sample_percent(row_estimate) == expected
+
+
+class TestFetchRowsFor:
+ @parameterized.expand(
+ [
+ # Nothing measured has to leave the whole-batch FETCH alone, or every table pays
+ # round trips for a risk only some of them carry.
+ ("unmeasured", None, 100_000, 100_000),
+ ("zero", 0, 100_000, 100_000),
+ # A uniform table's p99 is close to its p95, so the FETCH barely moves.
+ ("uniform_rows", 2 * 1024, 100_000, 76_800),
+ # Wide rows common enough to fill a page are what the cap exists for.
+ ("wide_rows", 3 * 1024 * 1024, 100_000, 50),
+ ("wider_than_the_budget", 400 * 1024 * 1024, 100_000, 1),
+ ]
+ )
+ def test_derives_the_fetch_from_the_p99_row(self, _name, wide_row_bytes, batch_rows, expected):
+ assert _fetch_rows_for(batch_rows, wide_row_bytes) == expected
+
+
+class TestSamplingQuery:
+ def _sampling_query(self, sample_percent):
+ return _build_query(
+ "public",
+ "events",
+ False,
+ "table",
+ None,
+ None,
+ None,
+ add_sampling=True,
+ sample_percent=sample_percent,
+ ).as_string()
+
+ def test_a_sized_sample_is_not_truncated_to_the_head_of_the_table(self):
+ # A sample scan reads blocks in physical order, so a target-sized LIMIT over a fixed 1%
+ # only ever measures the front of the table — blind to a region that widens later.
+ query = self._sampling_query(0.05)
+
+ assert "TABLESAMPLE SYSTEM (0.05)" in query
+ assert f"LIMIT {SIZE_SAMPLE_MAX_ROWS}" in query
+
+ def test_falls_back_to_the_fixed_sample_without_an_estimate(self):
+ query = self._sampling_query(None)
+
+ assert "TABLESAMPLE SYSTEM (1)" in query
+ assert f"LIMIT {SIZE_SAMPLE_TARGET_ROWS}" in query
+
+ def _incremental_sampling_query(self, sample_percent):
+ return _build_query(
+ "public",
+ "events",
+ True,
+ "table",
+ "id",
+ IncrementalFieldType.Integer,
+ 0,
+ add_sampling=True,
+ sample_percent=sample_percent,
+ ).as_string()
+
+ @parameterized.expand(
+ [
+ # A small table is one page, and a 1% page sample misses it ~99 times in 100, so the
+ # sync measures nothing and has to guess at its row size.
+ ("small_table_is_measured_whole", 100.0, "TABLESAMPLE SYSTEM (100.0)"),
+ # Below the floor the sample stays what it has always been, because the estimate
+ # describes the table and the query reads a slice of it.
+ ("large_table_keeps_the_fixed_sample", 0.05, "TABLESAMPLE SYSTEM (1.0)"),
+ ("no_estimate_keeps_the_fixed_sample", None, "TABLESAMPLE SYSTEM (1)"),
+ ]
+ )
+ def test_the_incremental_sample_never_draws_fewer_pages_than_before(self, _name, sample_percent, expected):
+ assert expected in self._incremental_sampling_query(sample_percent)
+
class TestGetRowsToSync:
# Mirrors a misconfigured incremental field: COUNT(*) over a column that doesn't exist.
@@ -7108,6 +7279,7 @@ class _FakeCursor:
self._executed = True
def fetchmany(self, n: int):
+ self.owner.owner.fetch_sizes.append(n)
if not self._executed:
return []
batch, self._rows_remaining = self._rows_remaining[:n], self._rows_remaining[n:]
@@ -7149,6 +7321,7 @@ class _FakeConnectionFactory:
self.script = script
self.connections_opened = 0
self.connections: list[_FakeConnection] = []
+ self.fetch_sizes: list[int] = []
def __call__(self) -> _FakeConnection:
self.connections_opened += 1
@@ -7183,6 +7356,7 @@ def _run_windows(script, **overrides):
"db_incremental_field_last_value": date(2026, 1, 1),
"child_partitions": [],
"chunk_size": 1000,
+ "byte_bounded": False,
"arrow_schema": _arrow_schema(),
"logger": structlog.get_logger(),
"initial_window": timedelta(days=1),
@@ -7375,6 +7549,9 @@ class TestIterateDateWindowsFake:
_run_windows(
script=script,
child_partitions=[child],
+ # One row per batch, so the row really is out before the drop: rows read into the
+ # batcher but not yet yielded are discarded with the failed window and re-read.
+ chunk_size=1,
is_connection_dropped=_is_connection_dropped_error,
)
@@ -7983,7 +8160,7 @@ class TestGetRowsInitialReadDropRetry:
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=100),
+ patch(f"{module}._get_table_chunk_size", return_value=_TableChunking(batch_rows=100, fetch_rows=100)),
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),
@@ -8131,7 +8308,7 @@ class TestGetRowsInitialReadLockTimeoutRetry:
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=100),
+ patch(f"{module}._get_table_chunk_size", return_value=_TableChunking(batch_rows=100, fetch_rows=100)),
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),
@@ -8295,7 +8472,7 @@ class TestPartitionIterationConnectRetry:
patch(f"{module}._is_partitioned_table", return_value=True),
patch(f"{module}.list_child_partitions", return_value=[child]),
patch(f"{module}.get_partition_strategy", return_value=partition_strategy),
- patch(f"{module}._get_table_chunk_size", return_value=1000),
+ 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),
@@ -8322,3 +8499,188 @@ class TestPartitionIterationConnectRetry:
# 1 setup + 2 per-window/per-partition connects (1 dropped commit + 1 success).
assert connect_mock.call_count == 3
assert sum(table.num_rows for table in tables) == 3
+
+
+class TestExtractionByteBounds:
+ """Extraction batches must be bounded by accumulated bytes, not by a sampled row count.
+
+ The chunk size is derived from a p95 `octet_length` sample, so on a table whose row
+ sizes span orders of magnitude a fixed row count buys no memory bound at all: a heavy
+ region fetches the same row count and materialises gigabytes.
+ """
+
+ BUDGET = 8 * 1024
+ BLOB = "x" * 1024
+
+ def _schema(self) -> pa.Schema:
+ fields: list[pa.Field] = [pa.field("id", pa.int64()), pa.field("val", pa.string())]
+ return pa.schema(fields)
+
+ def _child(self) -> ChildPartition:
+ return ChildPartition(
+ oid=1,
+ schema="public",
+ name="p",
+ partbound="FOR VALUES FROM ('2026-01-01') TO ('2026-01-02')",
+ )
+
+ def test_batches_flush_on_the_byte_budget_not_the_row_count(self):
+ rows = [(i, "s") for i in range(200)] + [(i, self.BLOB) for i in range(200, 400)]
+
+ with patch.object(batching, "EXTRACT_BATCH_MAX_BYTES", self.BUDGET):
+ tables, _ = _run_windows(
+ script=[list(rows)],
+ child_partitions=[self._child()],
+ chunk_size=400,
+ byte_bounded=True,
+ arrow_schema=self._schema(),
+ )
+
+ assert sum(table.num_rows for table in tables) == 400
+ assert [value for table in tables for value in table.column("val").to_pylist()] == [row[1] for row in rows]
+ # A blob row costs ~1 KiB, so a batch that respects an 8 KiB budget holds a handful of
+ # them — never the whole 400-row chunk.
+ oversized = [table.num_rows for table in tables if table_payload_bytes(table) > self.BUDGET]
+ assert oversized == []
+
+ def test_gate_off_keeps_the_row_count_batching(self):
+ rows = [(i, self.BLOB) for i in range(400)]
+
+ with patch.object(batching, "EXTRACT_BATCH_MAX_BYTES", self.BUDGET):
+ tables, factory = _run_windows(
+ script=[list(rows)],
+ child_partitions=[self._child()],
+ chunk_size=400,
+ byte_bounded=False,
+ arrow_schema=self._schema(),
+ )
+
+ assert [table.num_rows for table in tables] == [400]
+ assert set(factory.fetch_sizes) == {400}
+
+ def test_fetch_pages_shrink_once_wide_rows_appear(self):
+ rows = [(i, "s") for i in range(1000)] + [(i, self.BLOB) for i in range(1000, 2000)]
+
+ with patch.object(batching, "EXTRACT_BATCH_MAX_BYTES", self.BUDGET):
+ _, factory = _run_windows(
+ script=[list(rows)],
+ child_partitions=[self._child()],
+ chunk_size=100_000,
+ byte_bounded=True,
+ arrow_schema=self._schema(),
+ )
+
+ # Once a 1 KiB row has been seen, a page of the sampled row count would hold ~100 MiB.
+ assert max(factory.fetch_sizes[-3:]) <= self.BUDGET // len(self.BLOB) + 1
+
+
+class TestFetchPageGate:
+ """The page cap is the byte bound's own instrument, so the rollout gate has to hold it back too.
+
+ Left applied with the gate off it shrinks the `FETCH` without ever flushing a batch: the read
+ pays a round trip per page and still accumulates the whole table into one batch, which is
+ strictly worse than the single full-size fetch it replaced.
+ """
+
+ class _Cursor:
+ def __init__(self, *, named: bool, rows: list, fetch_sizes: list[int]):
+ self._named = named
+ self._rows = list(rows) if named else []
+ self._fetch_sizes = fetch_sizes
+ col = mock.Mock()
+ col.name = "id"
+ self.description = [col]
+
+ def execute(self, *args, **kwargs):
+ return None
+
+ def fetchmany(self, n):
+ if not self._named:
+ return []
+ self._fetch_sizes.append(n)
+ batch, self._rows = self._rows[:n], self._rows[n:]
+ return batch
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ class _Connection:
+ def __init__(self, rows, fetch_sizes):
+ self.autocommit = False
+ self.closed = False
+ self.broken = False
+ self.adapters = mock.Mock()
+ self._rows = rows
+ self._fetch_sizes = fetch_sizes
+
+ def cursor(self, *args, **kwargs):
+ return TestFetchPageGate._Cursor(named="name" in kwargs, rows=self._rows, fetch_sizes=self._fetch_sizes)
+
+ def commit(self):
+ return None
+
+ def close(self):
+ self.closed = True
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def _fetch_sizes(self, *, byte_bounded: bool) -> list[int]:
+ from contextlib import contextmanager
+
+ @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 = []
+ fake_table.__contains__ = mock.Mock(return_value=False)
+
+ fetch_sizes: list[int] = []
+ rows = [(i,) for i in range(20)]
+
+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"
+ with (
+ patch(f"{module}.psycopg.connect", return_value=self._Connection(rows, fetch_sizes)),
+ patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(named=False, rows=[], fetch_sizes=[])),
+ patch(f"{module}._get_table", return_value=fake_table),
+ patch(f"{module}._is_read_replica", return_value=False),
+ 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=7)),
+ patch(f"{module}._get_rows_to_sync", return_value=20),
+ patch(f"{module}._role_subject_to_rls", return_value=False),
+ patch(f"{module}._get_partition_settings", return_value=None),
+ ):
+ 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,
+ byte_bounded_extraction=byte_bounded,
+ )
+ list(cast(Iterable[Any], response.items()))
+
+ return fetch_sizes
+
+ def test_gate_off_fetches_the_whole_chunk(self):
+ assert set(self._fetch_sizes(byte_bounded=False)) == {1000}
+
+ def test_gate_on_fetches_the_measured_page(self):
+ assert max(self._fetch_sizes(byte_bounded=True)) == 7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
index fd7c86f6cc59..e6d3adaf8374 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
@@ -49,6 +49,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
compute_projected_columns,
project_arrow_columns,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import (
+ fetch_row_batches,
+ iter_row_batches,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import (
SourceMetadata,
SQLSourceImplementation,
@@ -523,17 +527,17 @@ def _stream_rows_as_arrow_batches(
chunk_size: int,
arrow_schema: pa.Schema,
*,
+ byte_bounded: bool = False,
primary_keys: list[str] | None = None,
binary_reporter: BinaryColumnReporter | None = None,
) -> Iterator[pa.Table]:
- """Yield one Arrow table per `chunk_size` rows, reading rows straight off the wire.
+ """Yield one Arrow table per `chunk_size` rows (or per byte budget), reading rows off the wire.
`stream()` puts libpq in single-row (or chunked-row) mode: no cursor is declared, so the
per-node cap on cursor data never applies, and no result set is buffered into the worker
either. Those were the two ways a large table could not be read.
"""
column_names: list[str] = []
- pending: list[Any] = []
def to_arrow(rows: list[Any]) -> pa.Table:
return table_from_iterator(
@@ -543,17 +547,13 @@ def _stream_rows_as_arrow_batches(
binary_reporter=binary_reporter,
)
- for row in cursor.stream(query, size=_libpq_rows_per_chunk()):
+ for rows in iter_row_batches(
+ cursor.stream(query, size=_libpq_rows_per_chunk()), max_rows=chunk_size, byte_bounded=byte_bounded
+ ):
if not column_names:
# Only described once the first result arrives, so it can't be read before the loop.
column_names = [column.name for column in cursor.description or []]
- pending.append(row)
- if len(pending) >= chunk_size:
- yield to_arrow(pending)
- pending = []
-
- if pending:
- yield to_arrow(pending)
+ yield to_arrow(rows)
def _fetch_arrow_batches(
@@ -562,19 +562,19 @@ def _fetch_arrow_batches(
arrow_schema: pa.Schema,
fetch_size: int | None = None,
*,
+ byte_bounded: bool = False,
primary_keys: list[str] | None = None,
binary_reporter: BinaryColumnReporter | None = None,
) -> Iterator[pa.Table]:
- """Yield one Arrow table per `chunk_size` rows drawn from an already-executed `cursor`.
+ """Yield one Arrow table per `chunk_size` rows (or per byte budget) from an executed `cursor`.
- `fetch_size` decouples the per-`FETCH` page from the Arrow batch: rows accumulate across
- pages until `chunk_size` is reached. Redshift caps a single `FETCH` on a single-node cluster
- (see `REDSHIFT_SINGLE_NODE_FETCH_LIMIT`) far below the chunk sizes we target, so paging is
- the only way to keep the server cursor and still write batches the Delta writer sizes well.
- Defaults to `chunk_size`, i.e. one `FETCH` per Arrow table.
+ `fetch_size` caps the per-`FETCH` page independently of the Arrow batch: rows accumulate
+ across pages until `chunk_size` is reached. Redshift caps a single `FETCH` on a single-node
+ cluster (see `REDSHIFT_SINGLE_NODE_FETCH_LIMIT`) far below the chunk sizes we target, so
+ paging is the only way to keep the server cursor and still write batches the Delta writer
+ sizes well. Defaults to `chunk_size`, i.e. one `FETCH` per Arrow table.
"""
column_names = [column.name for column in cursor.description or []]
- page_size = fetch_size or chunk_size
def to_arrow(rows: list[Any]) -> pa.Table:
return table_from_iterator(
@@ -584,21 +584,10 @@ def _fetch_arrow_batches(
binary_reporter=binary_reporter,
)
- pending: list[Any] = []
- while True:
- rows = cursor.fetchmany(page_size)
- if not rows:
- break
-
- pending.extend(rows)
- # Overshoots by at most `page_size - 1` rows, which is bounded and far below the byte
- # budget `chunk_size` was derived from.
- if len(pending) >= chunk_size:
- yield to_arrow(pending)
- pending = []
-
- if pending:
- yield to_arrow(pending)
+ for rows in fetch_row_batches(
+ cursor.fetchmany, max_rows=chunk_size, byte_bounded=byte_bounded, max_page_rows=fetch_size or chunk_size
+ ):
+ yield to_arrow(rows)
def _stream_arrow_batches(
@@ -609,6 +598,7 @@ def _stream_arrow_batches(
cursor_name: str,
logger: FilteringBoundLogger,
*,
+ byte_bounded: bool = False,
primary_keys: list[str] | None = None,
) -> Iterator[pa.Table]:
"""Stream `query` as Arrow tables, holding only `chunk_size` rows in the worker at a time.
@@ -641,6 +631,7 @@ def _stream_arrow_batches(
query,
chunk_size,
arrow_schema,
+ byte_bounded=byte_bounded,
primary_keys=primary_keys,
binary_reporter=binary_reporter,
):
@@ -668,6 +659,7 @@ def _stream_arrow_batches(
chunk_size,
arrow_schema,
fetch_size,
+ byte_bounded=byte_bounded,
primary_keys=primary_keys,
binary_reporter=binary_reporter,
):
@@ -1667,6 +1659,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
arrow_schema,
f"posthog_{inputs.team_id}_{schema}.{table_name}",
logger,
+ byte_bounded=inputs.byte_bounded_extraction,
primary_keys=primary_keys,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
index a426273f5c54..b9f68e89bf42 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
@@ -733,7 +733,7 @@ class TestFetchArrowBatches:
tables = list(_fetch_arrow_batches(cursor, 5, _STREAM_SCHEMA, fetch_size=2))
- assert _ids(tables) == [[1, 2, 3, 4, 5, 6], [7]]
+ assert _ids(tables) == [[1, 2, 3, 4, 5], [6, 7]]
assert [c.args[0] for c in cursor.fetchmany.call_args_list] == [2, 2, 2, 2, 2]
def test_fetches_a_whole_chunk_at_a_time_by_default(self):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index 8d6843f0655d..0d1fde15661b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -85,7 +85,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.reg
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClient as PostHogRESTClient,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import XminBounds
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import (
+ XminBounds,
+ _TableChunking,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (
BALANCE_TRANSACTION_RESOURCE_NAME as STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,
CHARGE_RESOURCE_NAME as STRIPE_CHARGE_RESOURCE_NAME,
@@ -1770,7 +1773,7 @@ async def test_delta_no_merging_on_first_sync(team, postgres_config, postgres_co
# Set up merge mock chain (needed for v3 where batch 1 merges into the table created by batch 0)
mock_merge.return_value.when_matched_update_all.return_value.when_not_matched_insert_all.return_value.execute.return_value = {}
- mock_chunk_size.return_value = 1
+ mock_chunk_size.return_value = _TableChunking(batch_rows=1, fetch_rows=1)
await _run(
team=team,
schema_name="test_table",
@@ -1859,6 +1862,11 @@ async def test_delta_no_merging_on_first_sync_uncapped_chunk_size(
"INSERT INTO {schema}.test_table (id) VALUES (2)".format(schema=postgres_config["schema"])
)
await postgres_connection.commit()
+ # Without stats the row-size probe has no catalog estimate, falls back to sampling 1% of
+ # pages, and on a one-page table draws nothing 99 times in 100 — which lands on the
+ # unmeasurable-sample path instead of the uncapped chunk this test is about.
+ await postgres_connection.execute("ANALYZE {schema}.test_table".format(schema=postgres_config["schema"]))
+ await postgres_connection.commit()
with (
mock.patch(
@@ -1967,7 +1975,7 @@ async def test_delta_no_merging_on_first_sync_after_reset(team, postgres_config,
):
mock_merge.return_value.when_matched_update_all.return_value.when_not_matched_insert_all.return_value.execute.return_value = {}
- mock_chunk_size.return_value = 1
+ mock_chunk_size.return_value = _TableChunking(batch_rows=1, fetch_rows=1)
await _execute_run(
str(uuid.uuid4()),
ExternalDataWorkflowInputs(
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 3182e2b9cc16..92d3513cd15c 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
@@ -118,6 +118,7 @@ async def test_job_inputs_with_whitespace(activity_environment, team, **kwargs):
is_xmin=False,
xmin_last_value=None,
xmin_num_wraparound=None,
+ byte_bounded_extraction=False,
)
@@ -171,6 +172,7 @@ async def test_postgres_source_without_ssh_tunnel(activity_environment, team, **
is_xmin=False,
xmin_last_value=None,
xmin_num_wraparound=None,
+ byte_bounded_extraction=False,
)
@@ -236,6 +238,7 @@ async def test_postgres_source_with_ssh_tunnel_disabled(activity_environment, te
is_xmin=False,
xmin_last_value=None,
xmin_num_wraparound=None,
+ byte_bounded_extraction=False,
)
@@ -316,6 +319,7 @@ async def test_postgres_source_with_ssh_tunnel_enabled(activity_environment, tea
is_xmin=False,
xmin_last_value=None,
xmin_num_wraparound=None,
+ byte_bounded_extraction=False,
)
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 e3defe0e28d3..352531151814 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
@@ -62,6 +62,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
SimpleSource,
error_message_matches,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.byte_bounded_extraction_flag import (
+ is_byte_bounded_extraction_enabled,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_reuse_flag import (
is_fanout_warehouse_reuse_enabled,
)
@@ -424,6 +427,9 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
fanout_warehouse_reuse = await _warehouse_parent_reuse_available(
new_source, schema, inputs.source_id, inputs.team_id, logger
)
+ byte_bounded_extraction = await database_sync_to_async_pool(is_byte_bounded_extraction_enabled)(
+ inputs.team_id, str(source_type)
+ )
# INFO so it's visible without DEBUG: confirms which parent-source path a fan-out
# child took, and doubles as rollout-adoption telemetry. Only fan-out children
# (schemas with required parents) log it; every other schema stays quiet.
@@ -461,6 +467,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
# A schema-level override (user-managed) wins over the source pin.
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,
)
try: