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(warehouse-sources): bound mysql keyset pages by bytes (#112525)

Daniel RCd29888d3f0d3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/keyset.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/keyset.py
index 1a83b7507872..0ef805231049 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,6 +28,7 @@ import pyarrow as pa
from 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.predicates import ValidatedRowFilter
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.query_builder import (
SafeSQL,
@@ -189,6 +190,14 @@ def resolve_keyset_eligibility(
return KeysetEligibility(column=key)
+@frozen
+class KeysetPage:
+ """One keyset page as the driver returned it."""
+
+ columns: list[str]
+ rows: Sequence[Sequence[Any]]
+
+
def iter_keyset_pages(
*,
builder: SelectQueryBuilder,
@@ -196,49 +205,84 @@ def iter_keyset_pages(
table_name: str,
keyset_column: str,
chunk_size: int,
- run_page: Callable[[SafeSQL], pa.Table | None],
+ run_page: Callable[[SafeSQL], KeysetPage | None],
+ to_table: Callable[[list[str], list[Sequence[Any]]], pa.Table],
initial_last_value: Any | None,
checkpoint: Callable[[Any], None] | None = None,
enabled_columns: list[str] | None = None,
primary_keys: list[str] | None = None,
row_filters: list[ValidatedRowFilter] | None = None,
) -> Iterator[pa.Table]:
- """Yield successive keyset pages of a table as Arrow tables, seeking on `keyset_column`.
+ """Yield a table as successive Arrow batches, read by keyset pages that seek on `keyset_column`.
Each page is an independent bounded query (``… WHERE pk > :last ORDER BY pk ASC LIMIT n``) — no
server-side streaming cursor is held, so the read survives being resumed on another pod. `run_page`
- is the driver's executor: it runs one `SafeSQL` and returns the page as an Arrow table (or `None`
- when the page is empty). `initial_last_value` seeds the seek from a persisted checkpoint (or `None`
- to start at the beginning). Pagination advances on the last (largest) key of each page; a short
- page ends the walk.
+ is the driver's executor: it runs one `SafeSQL` and returns the rows of the page (or `None` when
+ the page is empty). `to_table` builds the Arrow table of one batch. `initial_last_value` seeds the
+ seek from a persisted checkpoint (or `None` to start at the beginning). Pagination advances on the
+ last (largest) key of each page; a short page ends the walk.
+
+ A page and a batch are not the same rows. `chunk_size` only bounds memory while every row is close
+ to 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.
- `checkpoint` records the last key of a page once the consumer has come back for the next one.
+ `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
- taken the page, not when it was read, so an abandoned walk leaves the checkpoint on the last page
- the consumer actually received rather than one the source had merely queued up.
+ taken the batch, not when it was read, so an abandoned walk leaves the checkpoint on the last batch
+ the consumer actually received rather than one the source had merely queued up. The key is the
+ last row of that batch and not the read position, which can already be past rows that wait for
+ the next batch.
"""
last_value = initial_last_value
- while True:
- page_sql = builder.select_keyset(
- schema=schema,
- table_name=table_name,
- keyset_column=keyset_column,
- keyset_last_value=last_value,
- limit=chunk_size,
- enabled_columns=enabled_columns,
- primary_keys=primary_keys,
- row_filters=row_filters,
+ last_read_key: tuple[Any, ...] | None = None
+ columns: list[str] = []
+ exhausted = False
+
+ def fetch_page(requested_rows: int) -> Sequence[Sequence[Any]]:
+ nonlocal last_value, last_read_key, columns, exhausted
+ if exhausted:
+ return []
+ if last_read_key is not None:
+ # Never fall through to another query on a NULL key: with `last_value` back to None the
+ # next page would carry no seek predicate and return the same page again, indefinitely.
+ (last_value,) = checked_keyset_key(last_read_key, [keyset_column])
+
+ page = run_page(
+ builder.select_keyset(
+ schema=schema,
+ table_name=table_name,
+ keyset_column=keyset_column,
+ keyset_last_value=last_value,
+ limit=requested_rows,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ row_filters=row_filters,
+ )
)
- table = run_page(page_sql)
- if table is None or table.num_rows == 0:
- break
+ if page is None or not page.rows:
+ return []
+
+ rows = page.rows
+ if not columns:
+ columns = list(page.columns)
+ elif page.columns != columns:
+ # One batch can hold rows from several pages, and it reads every row with the columns of
+ # the first page.
+ positions = [page.columns.index(name) if name in page.columns else None for name in columns]
+ rows = [tuple(row[position] if position is not None else None for position in positions) for row in rows]
+
+ last_read_key = (rows[-1][columns.index(keyset_column)],)
+ exhausted = len(rows) < requested_rows
+ return rows
+
+ # 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):
+ table = to_table(columns, rows)
yield table
- # Never fall through to another query on a NULL key: with `last_value` back to None the next
- # page would carry no seek predicate and return this same page again, indefinitely.
- (last_value,) = keyset_key_of_last_row(table, [keyset_column])
+ (batch_last_value,) = keyset_key_of_last_row(table, [keyset_column])
if checkpoint is not None:
- checkpoint(last_value)
- if table.num_rows < chunk_size:
- break
+ checkpoint(batch_last_value)
diff --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.py
index d6c0ed8cb1ee..eb47d32bf012 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
@@ -9,11 +9,13 @@ from unittest.mock import MagicMock, patch
import pyarrow as pa
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import batching
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.identifiers import (
BacktickIdentifierQuoter,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import (
KeysetNullKeyError,
+ KeysetPage,
KeysetResumeState,
is_orderable_keyset_type,
iter_keyset_pages,
@@ -196,26 +198,30 @@ def test_resolve_keyset_eligibility(primary_keys, incremental, declared, expecte
_BUILDER = SelectQueryBuilder(quoter=BacktickIdentifierQuoter())
-def _fake_table(ids: list[int]) -> pa.Table:
- return pa.table({"id": ids, "body": [f"row-{i}" for i in ids]})
+def _to_table(columns: list[str], rows) -> pa.Table:
+ return pa.table({column: [row[index] for row in rows] for index, column in enumerate(columns)})
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):
+ def __init__(self, all_ids: list[int], chunk_size: int, body: str = "row"):
self.all_ids = sorted(all_ids)
self.chunk_size = chunk_size
+ self.body = body
self.queries: list[str] = []
+ self.limits: list[int] = []
def run_page(self, page_sql):
self.queries.append(page_sql.sql)
after = page_sql.params.get("keyset_value") if isinstance(page_sql.params, dict) else None
+ limit = int(page_sql.sql.rsplit("LIMIT ", 1)[1])
+ self.limits.append(limit)
remaining = [i for i in self.all_ids if after is None or i > after]
- page = remaining[: self.chunk_size]
+ page = remaining[: min(limit, self.chunk_size)]
if not page:
return None
- return _fake_table(page)
+ return KeysetPage(columns=["id", "body"], rows=[(i, self.body) for i in page])
def test_iter_keyset_pages_walks_whole_table_in_order():
@@ -228,6 +234,7 @@ def test_iter_keyset_pages_walks_whole_table_in_order():
keyset_column="id",
chunk_size=3,
run_page=pages.run_page,
+ to_table=_to_table,
initial_last_value=None,
)
)
@@ -248,6 +255,7 @@ def test_iter_keyset_pages_seeks_from_initial_value():
keyset_column="id",
chunk_size=10,
run_page=pages.run_page,
+ to_table=_to_table,
initial_last_value=3,
)
)
@@ -265,6 +273,7 @@ def test_iter_keyset_pages_stops_immediately_when_empty():
keyset_column="id",
chunk_size=5,
run_page=pages.run_page,
+ to_table=_to_table,
initial_last_value=None,
)
)
@@ -283,6 +292,7 @@ def test_iter_keyset_pages_full_page_then_empty_terminates():
keyset_column="id",
chunk_size=2,
run_page=pages.run_page,
+ to_table=_to_table,
initial_last_value=None,
)
)
@@ -303,6 +313,7 @@ def test_checkpoint_records_each_page_only_once_the_consumer_takes_the_next():
keyset_column="id",
chunk_size=2,
run_page=pages.run_page,
+ to_table=_to_table,
initial_last_value=None,
checkpoint=saved.append,
)
@@ -327,6 +338,7 @@ def test_checkpoint_is_optional():
keyset_column="id",
chunk_size=5,
run_page=pages.run_page,
+ to_table=_to_table,
initial_last_value=None,
)
)
@@ -344,7 +356,7 @@ def test_null_page_boundary_raises_instead_of_replaying_the_page():
def run_page(page_sql):
queries.append(page_sql.sql)
- return pa.table({"id": pa.array([1, None], type=pa.int64())})
+ return KeysetPage(columns=["id"], rows=[(1,), (None,)])
walk = iter_keyset_pages(
builder=_BUILDER,
@@ -353,6 +365,7 @@ def test_null_page_boundary_raises_instead_of_replaying_the_page():
keyset_column="id",
chunk_size=2,
run_page=run_page,
+ to_table=_to_table,
initial_last_value=None,
)
@@ -362,3 +375,54 @@ def test_null_page_boundary_raises_instead_of_replaying_the_page():
next(walk)
assert len(queries) == 1 # crucially, no second query was ever issued
+
+
+# An id measures 16 bytes and the body 24, so an 80-byte budget holds two rows per batch.
+_WIDE_BODY = "x" * 24
+_TWO_ROW_BUDGET = 80
+
+
+def test_a_page_asks_for_fewer_rows_once_the_walk_reads_wide_rows():
+ pages = _FakePages(all_ids=[1, 2, 3, 4, 5, 6, 7, 8], chunk_size=4, body=_WIDE_BODY)
+
+ with patch.object(batching, "EXTRACT_BATCH_MAX_BYTES", _TWO_ROW_BUDGET):
+ tables = list(
+ iter_keyset_pages(
+ builder=_BUILDER,
+ schema="db",
+ table_name="t",
+ keyset_column="id",
+ chunk_size=4,
+ 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")] == [1, 2, 3, 4, 5, 6, 7, 8]
+ assert max(table.num_rows for table in tables) == 2
+ assert pages.limits[0] == 4
+ assert set(pages.limits[1:]) == {2}
+
+
+def test_a_batch_that_ends_inside_a_page_checkpoints_its_own_last_row():
+ pages = _FakePages(all_ids=[1, 2, 3, 4], chunk_size=4, body=_WIDE_BODY)
+ saved: list[int] = []
+
+ with patch.object(batching, "EXTRACT_BATCH_MAX_BYTES", _TWO_ROW_BUDGET):
+ walk = iter_keyset_pages(
+ builder=_BUILDER,
+ schema="db",
+ table_name="t",
+ keyset_column="id",
+ chunk_size=4,
+ run_page=pages.run_page,
+ to_table=_to_table,
+ initial_last_value=None,
+ checkpoint=saved.append,
+ )
+ first, second = next(walk), next(walk)
+
+ assert first.column("id").to_pylist() == [1, 2]
+ assert second.column("id").to_pylist() == [3, 4]
+ assert saved == [2]
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 8b15836380e8..2548899e5928 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
@@ -20,7 +20,7 @@ import time
import socket
import datetime
import collections
-from collections.abc import Callable, Iterator
+from collections.abc import Callable, Iterator, Sequence
from contextlib import ExitStack, contextmanager
from typing import Any, TypeVar
@@ -86,6 +86,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
IncrementalFieldFilter,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import (
+ KeysetPage,
KeysetResumeState,
iter_keyset_pages,
keyset_last_key,
@@ -1929,7 +1930,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
arrow_schema = projection.table.to_arrow_schema()
plan_checked = False
- def _run_page(page_sql: SafeSQL) -> pa.Table | None:
+ def _run_page(page_sql: SafeSQL) -> KeysetPage | None:
nonlocal plan_checked
with connection.cursor() as cursor:
# Check the first page that actually seeks — page 1 has no `pk >`
@@ -1943,8 +1944,10 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
rows = cursor.fetchall()
if not rows:
return None
- column_names = [column[0] for column in cursor.description or []]
- return table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)
+ return KeysetPage(columns=[column[0] for column in cursor.description or []], rows=rows)
+
+ def _to_table(column_names: list[str], rows: list[Sequence[Any]]) -> pa.Table:
+ return table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)
def _checkpoint(last_key: Any) -> None:
manager.save_state(keyset_state((last_key,)))
@@ -1956,6 +1959,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
keyset_column=keyset_column,
chunk_size=chunk_size,
run_page=_run_page,
+ to_table=_to_table,
initial_last_value=initial_last_value,
checkpoint=_checkpoint,
enabled_columns=projection.enabled_columns,