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): stop offset resume duplicating and skipping rows (#93392)

posthog[bot]10e6e5f4f717
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 467213b397ed..b51ef5d282b4 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
@@ -2069,6 +2069,18 @@ def build_incremental_condition(
)
+def _offset_paging_tiebreak(keys: list[str]) -> sql.Composed:
+ """Trailing ORDER BY terms that make an offset-paged read totally ordered.
+
+ `LIMIT/OFFSET` paging issues one statement per chunk, so every chunk re-evaluates the ORDER BY
+ from scratch. Any order that leaves rows tied lets Postgres return the tied rows in a different
+ sequence per chunk, and the pages then overlap and skip. A full-table scan has no ORDER BY at
+ all, `xmin` repeats across every row one transaction wrote, and an incremental cursor repeats
+ across rows sharing a timestamp, so each needs the primary key appended to break the ties.
+ """
+ return sql.SQL(", ").join(sql.SQL("{col} ASC").format(col=sql.Identifier(key)) for key in keys)
+
+
def _build_query(
schema: str,
table_name: str,
@@ -2085,6 +2097,7 @@ def _build_query(
primary_keys: Optional[list[str]] = None,
row_filters: Optional[list[ValidatedRowFilter]] = None,
xmin_bounds: Optional[XminBounds] = None,
+ offset_paging_keys: Optional[list[str]] = None,
) -> sql.Composed:
projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
select_clause: sql.Composable = (
@@ -2096,7 +2109,13 @@ def _build_query(
if xmin_bounds is not None:
return _build_xmin_query(
- schema, table_name, select_clause, xmin_bounds, row_filter_conditions, add_sampling=bool(add_sampling)
+ schema,
+ table_name,
+ select_clause,
+ xmin_bounds,
+ row_filter_conditions,
+ add_sampling=bool(add_sampling),
+ offset_paging_keys=offset_paging_keys,
)
if not should_use_incremental_field:
@@ -2125,6 +2144,8 @@ def _build_query(
)
if row_filter_conditions:
query = query + sql.SQL(" WHERE ") + and_join(row_filter_conditions)
+ if offset_paging_keys:
+ query = query + sql.SQL(" ORDER BY ") + _offset_paging_tiebreak(offset_paging_keys)
return query
if incremental_field is None or incremental_field_type is None:
@@ -2185,7 +2206,17 @@ def _build_query(
if row_filter_conditions:
query = query + sql.SQL(" AND ") + and_join(row_filter_conditions)
- return query + sql.SQL(" ORDER BY {field} ASC").format(field=sql.Identifier(incremental_field))
+ ordered = query + sql.SQL(" ORDER BY {field} ASC").format(field=sql.Identifier(incremental_field))
+ tiebreak = [key for key in offset_paging_keys or [] if key != incremental_field]
+ if tiebreak:
+ ordered = ordered + sql.SQL(", ") + _offset_paging_tiebreak(tiebreak)
+ return ordered
+
+
+# The `xmin` system column cast to a sortable, comparable integer, because no ordering operators
+# exist on raw `xid`. The window predicate, the projection and the seek must all compare the same
+# expression, so they share this one.
+_XMIN_CURSOR = sql.SQL("xmin::text::bigint")
def _xmin_predicate(bounds: XminBounds) -> sql.Composed:
@@ -2193,7 +2224,7 @@ def _xmin_predicate(bounds: XminBounds) -> sql.Composed:
if bounds.full_scan:
# No window is safe across wraparound epochs (see `_capture_xmin_ceiling`), so read it all.
return sql.SQL("TRUE").format()
- xmin_expr = sql.SQL("xmin::text::bigint")
+ xmin_expr = _XMIN_CURSOR
if bounds.wraparound_or_range:
return sql.SQL("({xmin} >= {lo} OR {xmin} < {hi})").format(
xmin=xmin_expr, lo=sql.Literal(bounds.lower), hi=sql.Literal(bounds.upper)
@@ -2211,11 +2242,12 @@ def _build_xmin_query(
row_filter_conditions: list[sql.Composable],
*,
add_sampling: bool,
+ offset_paging_keys: Optional[list[str]] = None,
) -> sql.Composed:
# `_ph_xmin` is force-projected (system columns never come back from `SELECT *`) and kept out of
# `compute_projected_columns` so it can't collide with the user's incremental-field machinery.
- select = sql.SQL("xmin::text::bigint AS {alias}, {cols}").format(
- alias=sql.Identifier(XMIN_PROJECTED_COLUMN), cols=select_clause
+ select = sql.SQL("{cursor} AS {alias}, {cols}").format(
+ cursor=_XMIN_CURSOR, alias=sql.Identifier(XMIN_PROJECTED_COLUMN), cols=select_clause
)
query = sql.SQL("SELECT {cols} FROM {table} WHERE {predicate}").format(
cols=select, table=sql.Identifier(schema, table_name), predicate=_xmin_predicate(bounds)
@@ -2223,8 +2255,11 @@ def _build_xmin_query(
if row_filter_conditions:
query = query + sql.SQL(" AND ") + and_join(row_filter_conditions)
- # ORDER BY the cast cursor so the offset-resume path stays correct on a connection drop.
- ordered = query + sql.SQL(" ORDER BY xmin::text::bigint ASC")
+ # The cast cursor orders the read, but every row one transaction wrote shares it, so an
+ # offset-paged read needs the tiebreak below before its order survives per-chunk re-evaluation.
+ ordered = query + sql.SQL(" ORDER BY {cursor} ASC").format(cursor=_XMIN_CURSOR)
+ if offset_paging_keys:
+ ordered = ordered + sql.SQL(", ") + _offset_paging_tiebreak(offset_paging_keys)
if add_sampling:
return ordered + sql.SQL(" LIMIT 1000")
return ordered
@@ -2258,22 +2293,35 @@ def _build_keyset_query(
incremental_field: Optional[str] = None,
enabled_columns: Optional[list[str]] = None,
row_filters: Optional[list[ValidatedRowFilter]] = None,
+ xmin_bounds: Optional[XminBounds] = None,
) -> sql.Composed:
- """One page of a full-table read, seeking past the last primary key already read.
+ """One page of a full-table or xmin read, seeking past the last key already read.
A full-table read has no ORDER BY, so LIMIT/OFFSET cannot page it: every page is its own scan
and may come back in a different order, which both repeats and drops rows. Ordering by the
primary key gives the pages one sequence to walk, and seeking past the last key keeps each page
an index range scan. The key must be unique, or a page boundary inside a run of equal keys
drops the rest of that run.
+
+ An xmin read does order itself, but every row one transaction wrote carries the same `xmin`, so
+ a bulk-loaded table is one long run of equal keys. Its cursor therefore leads the primary key in
+ the seek instead of replacing it, which makes the pair unique again.
"""
projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
select_clause: sql.Composable = (
sql.SQL("*") if projected is None else sql.SQL(", ").join(sql.Identifier(c) for c in projected)
)
- key_columns = sql.SQL(", ").join(sql.Identifier(key) for key in primary_keys)
+ key_expressions: list[sql.Composable] = [sql.Identifier(key) for key in primary_keys]
+ if xmin_bounds is not None:
+ select_clause = sql.SQL("{cursor} AS {alias}, {cols}").format(
+ cursor=_XMIN_CURSOR, alias=sql.Identifier(XMIN_PROJECTED_COLUMN), cols=select_clause
+ )
+ key_expressions.insert(0, _XMIN_CURSOR)
+ key_columns = sql.SQL(", ").join(key_expressions)
conditions = render_psycopg_row_filter_conditions(row_filters or [])
+ if xmin_bounds is not None:
+ conditions.insert(0, _xmin_predicate(xmin_bounds))
if after is not None:
conditions.append(
sql.SQL("({keys}) > ({values})").format(
@@ -3735,9 +3783,19 @@ def postgres_source(
primary_keys=primary_keys,
row_filters=row_filters,
xmin_bounds=xmin_bounds,
+ offset_paging_keys=primary_keys,
)
last_key: tuple[Any, ...] | None = None
+ # An xmin read leads its seek with the cursor, which comes back under the projected
+ # alias rather than a column name, so the two lists differ for it.
+ keyset_result_columns: list[str] = []
+ if keyset_primary_keys is not None:
+ keyset_result_columns = (
+ [XMIN_PROJECTED_COLUMN, *keyset_primary_keys]
+ if xmin_bounds is not None
+ else keyset_primary_keys
+ )
def build_page_query() -> sql.Composed:
if keyset_primary_keys is not None:
@@ -3749,6 +3807,7 @@ def postgres_source(
incremental_field=incremental_field,
enabled_columns=enabled_columns,
row_filters=row_filters,
+ xmin_bounds=xmin_bounds,
)
return page + sql.SQL(" LIMIT {limit}").format(limit=sql.Literal(chunk_size))
return query + sql.SQL(" LIMIT {limit} OFFSET {offset}").format(
@@ -3815,7 +3874,7 @@ def postgres_source(
break
if keyset_primary_keys is not None:
- key_positions = [column_names.index(key) for key in keyset_primary_keys]
+ key_positions = [column_names.index(key) for key in keyset_result_columns]
last_key = tuple(rows[-1][position] for position in key_positions)
else:
offset += len(rows)
@@ -4069,28 +4128,32 @@ def postgres_source(
except psycopg.errors.SerializationFailure as e:
# If we hit a SerializationFailure and we're reading from a read replica, we fallback to offset chunking
if using_read_replica and "conflict with recovery" in "".join(e.args):
- # Paging by OFFSET needs a query that orders its rows, the precondition the
+ # Paging by OFFSET needs a query whose order is total, the precondition the
# connection-dropped handler below also enforces. A full-table read orders
- # nothing, so seek on the primary key instead, and only from the start,
- # because rows already yielded are already written.
- if not should_use_incremental_field and xmin_bounds is None:
- if keyset_primary_keys is None:
- raise _unorderable_read_abort_error(schema, table_name) from e
- if offset > 0:
+ # nothing, and an xmin read orders on a cursor that every row of one
+ # transaction shares, so both seek on the primary key instead. Seeking can
+ # only start from the top, because rows already yielded are already written.
+ if not should_use_incremental_field:
+ if keyset_primary_keys is not None and offset == 0:
+ logger.debug(
+ f"Falling back to keyset chunking for table due to SerializationFailure error: {e}."
+ )
+ yield from offset_chunking(
+ 0,
+ chunk_size,
+ from_recovery_conflict=True,
+ keyset_primary_keys=keyset_primary_keys,
+ )
+ return
+ # An xmin read still has its cursor to page on, and it appends, so
+ # restarting it would duplicate the rows it already wrote. Keep paging.
+ if xmin_bounds is None:
+ if keyset_primary_keys is None:
+ raise _unorderable_read_abort_error(schema, table_name) from e
# Retryable, so Temporal restarts the read and the load overwrites
# from the first batch. The next attempt can conflict before any row
# is out, where seeking takes over.
raise
- logger.debug(
- f"Falling back to keyset chunking for table due to SerializationFailure error: {e}."
- )
- yield from offset_chunking(
- 0,
- chunk_size,
- from_recovery_conflict=True,
- keyset_primary_keys=keyset_primary_keys,
- )
- return
logger.debug(
f"Falling back to offset chunking for table due to SerializationFailure error: {e}."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
index 49f0473ddfbb..ad2e842bbc34 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
@@ -3422,6 +3422,12 @@ class TestOffsetChunkingRecoveryConflictTimeout:
assert type(exc_info.value).__name__ in non_retryable
+def _fake_column(name: str):
+ column = mock.Mock()
+ column.name = name
+ return column
+
+
class TestChunkedRereadAfterRecoveryConflict:
"""A read replica cancelling the initial read with "conflict with recovery" routes `get_rows`
into a chunked re-read. Paging by LIMIT/OFFSET is only correct when the query orders its rows:
@@ -3433,34 +3439,41 @@ class TestChunkedRereadAfterRecoveryConflict:
"""
_CONFLICT = "canceling statement due to conflict with recovery"
- _ROWS: list[tuple[int]] = [(1,), (2,), (3,), (4,), (5,), (6,)]
+ _ROWS: list[tuple[int, ...]] = [(1,), (2,), (3,), (4,), (5,), (6,)]
+ # An xmin read projects the cursor ahead of the row. One bulk load gives every row the same
+ # cursor, and the trailing row sits below the window a resumed page still has to apply.
+ _XMIN_ROWS: list[tuple[int, ...]] = [(200, 1), (200, 2), (200, 3), (200, 4), (200, 5), (200, 6), (50, 7)]
+ _XMIN_BOUNDS = XminBounds(lower=100, upper=300, ceiling_xid8=300, num_wraparound=0, wraparound_or_range=False)
class _Scan:
- def __init__(self, rows: list[tuple[int]]):
+ def __init__(self, rows: list[tuple[int, ...]]):
self._rows = rows
self._statements = 0
- def rows_for(self, ordered: bool) -> list[tuple[int]]:
- if ordered:
+ def rows_for(self, totally_ordered: bool) -> list[tuple[int, ...]]:
+ if totally_ordered:
return sorted(self._rows)
self._statements += 1
pivot = self._statements % len(self._rows)
return self._rows[pivot:] + self._rows[:pivot]
class _PageCursor:
- def __init__(self, scan):
- column = mock.Mock()
- column.name = "id"
- self.description = [column]
+ def __init__(self, scan, column_names: list[str]):
+ self.description = [_fake_column(name) for name in column_names]
self._scan = scan
- self._result: list[tuple[int]] = []
+ self._result: list[tuple[int, ...]] = []
def execute(self, query, *args, **kwargs):
text = query.as_string()
- rows = self._scan.rows_for("ORDER BY" in text)
- seek = re.search(r'\("id"\) > \((\d+)\)', text)
+ # Only an ORDER BY that reaches the primary key is total. Anything short of it leaves
+ # rows tied, and each page is its own statement, so the pages overlap and skip.
+ rows = self._scan.rows_for('"id"' in text.partition("ORDER BY")[2])
+ window = re.search(r"xmin::text::bigint >= (\d+) AND xmin::text::bigint < (\d+)", text)
+ if window:
+ rows = [row for row in rows if int(window.group(1)) <= row[0] < int(window.group(2))]
+ seek = re.search(r"\) > \(([^)]*)\)", text)
if seek:
- rows = [row for row in rows if row[0] > int(seek.group(1))]
+ rows = [row for row in rows if row[-1] > int(seek.group(1).split(", ")[-1])]
offset = re.search(r"OFFSET (\d+)", text)
if offset:
rows = rows[int(offset.group(1)) :]
@@ -3477,10 +3490,8 @@ class TestChunkedRereadAfterRecoveryConflict:
return False
class _NamedCursor:
- def __init__(self, rows_before_conflict: int, scan):
- column = mock.Mock()
- column.name = "id"
- self.description = [column]
+ def __init__(self, rows_before_conflict: int, scan, column_names: list[str]):
+ self.description = [_fake_column(name) for name in column_names]
self._pending = scan.rows_for(True)[:rows_before_conflict]
def execute(self, *args, **kwargs):
@@ -3532,6 +3543,7 @@ class TestChunkedRereadAfterRecoveryConflict:
nullable_value: bool | str = False,
has_id_column: bool = False,
has_duplicate_pks: bool = False,
+ is_xmin: bool = False,
) -> list[int]:
@contextmanager
def fake_tunnel():
@@ -3548,13 +3560,16 @@ class TestChunkedRereadAfterRecoveryConflict:
]
fake_table.__contains__ = mock.Mock(return_value=has_id_column)
- scan = self._Scan(list(self._ROWS))
- connection = self._Connection(self._NamedCursor(rows_before_conflict, scan))
+ rows = self._XMIN_ROWS if is_xmin else self._ROWS
+ # `get_rows` inserts `_ph_xmin` ahead of the discovered columns, matching the SELECT.
+ column_names = [XMIN_PROJECTED_COLUMN, "id"] if is_xmin else ["id"]
+ scan = self._Scan(list(rows))
+ connection = self._Connection(self._NamedCursor(rows_before_conflict, scan, column_names))
module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"
with (
patch(f"{module}.psycopg.connect", return_value=connection),
- patch(f"{module}.psycopg.Cursor", side_effect=lambda _conn: self._PageCursor(scan)),
+ patch(f"{module}.psycopg.Cursor", side_effect=lambda _conn: self._PageCursor(scan, column_names)),
patch(f"{module}._get_table", return_value=fake_table),
patch(f"{module}._is_read_replica", return_value=True),
patch(f"{module}._is_duckdb_connection", return_value=False),
@@ -3562,7 +3577,8 @@ class TestChunkedRereadAfterRecoveryConflict:
patch(f"{module}._has_duplicate_primary_keys", return_value=has_duplicate_pks),
patch(f"{module}._is_partitioned_table", return_value=False),
patch(f"{module}._get_table_chunk_size", return_value=_TableChunking(batch_rows=2, fetch_rows=2)),
- patch(f"{module}._get_rows_to_sync", return_value=len(self._ROWS)),
+ patch(f"{module}._get_rows_to_sync", return_value=len(rows)),
+ patch(f"{module}._capture_xmin_ceiling", return_value=self._XMIN_BOUNDS),
patch(f"{module}._role_subject_to_rls", return_value=False),
patch(f"{module}._get_partition_settings", return_value=None),
patch(f"{module}.time.sleep"),
@@ -3581,6 +3597,8 @@ class TestChunkedRereadAfterRecoveryConflict:
logger=structlog.get_logger(),
db_incremental_field_last_value=0 if should_use_incremental_field else None,
team_id=1,
+ is_xmin=is_xmin,
+ xmin_last_value=self._XMIN_BOUNDS.lower if is_xmin else None,
)
return [row["id"] for table in cast(Iterable[Any], response.items()) for row in table.to_pylist()]
@@ -3616,6 +3634,18 @@ class TestChunkedRereadAfterRecoveryConflict:
assert sorted(ids) == [row[0] for row in self._ROWS]
+ def test_xmin_reread_seeks_past_the_cursor_and_the_key(self):
+ # One bulk load shares a single xmin, so ordering on the cursor alone leaves the whole
+ # table tied. Row 7 is below the window, so a page that drops the predicate surfaces it.
+ ids = self._read_ids(
+ should_use_incremental_field=False,
+ rows_before_conflict=0,
+ primary_keys=["id"],
+ is_xmin=True,
+ )
+
+ assert sorted(ids) == [1, 2, 3, 4, 5, 6]
+
def test_full_refresh_stays_retryable_when_rows_are_already_written(self):
with pytest.raises(psycopg.errors.SerializationFailure):
self._read_ids(should_use_incremental_field=False, rows_before_conflict=2, primary_keys=["id"])
@@ -5091,6 +5121,47 @@ class TestBuildQuery:
assert "'2024-01-01'" in rendered
assert "ORDER BY" in rendered
+ # Offset paging re-evaluates the ORDER BY once per chunk, so anything short of a total order
+ # lets tied rows come back in a different sequence per chunk and the pages overlap and skip.
+ @pytest.mark.parametrize(
+ "offset_paging_keys,expected_suffix",
+ [
+ # The healthy server-cursor read streams one consistent snapshot and must stay unordered.
+ (None, None),
+ (["id"], 'ORDER BY "id" ASC'),
+ (["tenant_id", "id"], 'ORDER BY "tenant_id" ASC, "id" ASC'),
+ ],
+ )
+ def test_full_scan_offset_paging_order(self, offset_paging_keys, expected_suffix):
+ query = _build_query("public", "users", False, "table", None, None, None, offset_paging_keys=offset_paging_keys)
+ rendered = self._render(query).rstrip()
+ if expected_suffix is None:
+ assert "ORDER BY" not in rendered
+ else:
+ assert rendered.endswith(expected_suffix)
+
+ @pytest.mark.parametrize(
+ "offset_paging_keys,expected_suffix",
+ [
+ (None, 'ORDER BY "created_at" ASC'),
+ (["id"], 'ORDER BY "created_at" ASC, "id" ASC'),
+ # A cursor that is itself the primary key is already total, so it must not repeat.
+ (["created_at"], 'ORDER BY "created_at" ASC'),
+ ],
+ )
+ def test_incremental_offset_paging_order(self, offset_paging_keys, expected_suffix):
+ query = _build_query(
+ "public",
+ "events",
+ True,
+ "table",
+ "created_at",
+ IncrementalFieldType.Timestamp,
+ "2024-01-01",
+ offset_paging_keys=offset_paging_keys,
+ )
+ assert self._render(query).rstrip().endswith(expected_suffix)
+
def test_incremental_raises_without_field(self):
with pytest.raises(ValueError, match="incremental_field and incremental_field_type can't be None"):
_build_query("public", "events", True, "table", None, None, None)
@@ -5488,6 +5559,29 @@ class TestBuildXminQuery:
assert "SELECT COUNT(*)" in rendered
assert "xmin::text::bigint >= 100 AND xmin::text::bigint < 5000" in rendered
+ # Every row one transaction wrote shares an xmin, so the cursor alone leaves huge ties — a
+ # bulk-loaded table can be a single group. Offset paging needs the primary key to break them.
+ @pytest.mark.parametrize(
+ "offset_paging_keys,expected_suffix",
+ [
+ (None, "ORDER BY xmin::text::bigint ASC"),
+ (["id"], 'ORDER BY xmin::text::bigint ASC, "id" ASC'),
+ ],
+ )
+ def test_offset_paging_breaks_xmin_ties(self, offset_paging_keys, expected_suffix):
+ query = _build_query(
+ "public",
+ "users",
+ False,
+ "table",
+ None,
+ None,
+ None,
+ xmin_bounds=self._bounds(),
+ offset_paging_keys=offset_paging_keys,
+ )
+ assert self._render(query).rstrip().endswith(expected_suffix)
+
class TestCaptureXminCeiling:
def _cursor(self, *, server_version: int, ceiling_xid8: int, ceiling_xid: int) -> MagicMock: