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.

feat(data-warehouse): let a keyset checkpoint carry a composite key (#107063)

Tom Owers13514307b395
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index f11440e68c2d..37427fa2377e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -96,6 +96,22 @@ if TYPE_CHECKING:
PARQUET_COMPRESSION: ParquetCompression = "zstd"
+def should_coalesce_tables(*, resume_manager: ResumableSourceManager[Any] | None, is_webhook: bool) -> bool:
+ """Whether the batcher may merge small Arrow tables before staging a batch.
+
+ Coalescing keeps a driver's fetch size (e.g. a SQL cursor's 10k-row Arrow tables) from becoming
+ the queue's batch granularity, but it delays when a yielded table is persisted. So it has to stay
+ off for sources that treat a yield as durable: the webhook path deletes its staged S3 files right
+ after yielding, and a resume cursor commit assumes the write that preceded it drained every table
+ yielded so far.
+
+ Pass the *resolved* manager, never the raw one. A resumable source class whose current run cannot
+ resume commits no cursor, so it is free to coalesce — and reading the raw manager here would
+ switch coalescing off for every run of every such class, most of which never checkpoint.
+ """
+ return resume_manager is None and not is_webhook
+
+
class PipelineV3(Generic[ResumableData]):
_resource: SourceResponse
_resource_name: str
@@ -217,13 +233,6 @@ class PipelineV3(Generic[ResumableData]):
# A source can shrink the batcher chunk (e.g. document sources with large rows) so the
# source->Arrow conversion doesn't materialise an oversized table; None falls back to defaults.
- # Arrow coalescing keeps a driver's fetch size (e.g. a SQL cursor's 10k-row Arrow tables)
- # from becoming the queue's batch granularity, but it delays when a yielded table is
- # persisted, so it must stay off for sources that treat yield as durable: the webhook path
- # deletes its staged S3 files right after yielding, and the resume cursor commit after a
- # write assumes that write drained every table yielded so far. The resolved manager is what
- # decides that, not the raw one — a resumable source class whose current run can't resume
- # commits no cursor, so it can still coalesce.
self._batcher = Batcher(
self._logger,
chunk_size=source_response.chunk_size,
@@ -231,7 +240,9 @@ class PipelineV3(Generic[ResumableData]):
source_type=self._source.source_type if self._source else None,
team_id=self._job.team_id,
schema_name=self._schema.name,
- coalesce_tables=self._resumable_source_manager is None and not self._schema.is_webhook,
+ coalesce_tables=should_coalesce_tables(
+ resume_manager=self._resumable_source_manager, is_webhook=self._schema.is_webhook
+ ),
primary_keys=self._resource.primary_keys,
)
self._internal_schema = HogQLSchema()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index 67bcc3a986fb..340e53b1bc63 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -17,7 +17,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
LanedPipelineV3,
_LaneWriter,
)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import (
+ PipelineV3,
+ should_coalesce_tables,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
OutputLane,
@@ -888,6 +891,25 @@ async def _run_expecting(pipeline: PipelineV3, redis: MagicMock, exc: type[BaseE
await pipeline.run()
+class TestShouldCoalesceTables:
+ @pytest.mark.parametrize(
+ "resume_manager,is_webhook,expected",
+ [
+ # The case the resolved manager exists for: a resumable source class whose current run
+ # reports supports_resume=False resolves to no manager, commits no cursor, and so is free
+ # to coalesce. Reading the raw manager here switched coalescing off for every run of every
+ # resumable class instead.
+ (None, False, True),
+ (MagicMock(), False, False),
+ (None, True, False),
+ (MagicMock(), True, False),
+ ],
+ ids=["no_cursor_to_commit", "commits_a_cursor", "webhook", "webhook_and_cursor"],
+ )
+ def test_coalescing_is_off_exactly_when_a_yield_is_durable(self, resume_manager, is_webhook, expected):
+ assert should_coalesce_tables(resume_manager=resume_manager, is_webhook=is_webhook) is expected
+
+
class TestResumeCursorCommit:
@pytest.mark.parametrize(
"stage_before_yield,expected_committed",
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 1fbfd6591653..ad02980a1de6 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
@@ -21,7 +21,7 @@ so the ineligible share is measurable before the approach is extended to other d
from __future__ import annotations
import dataclasses
-from collections.abc import Callable, Iterator
+from collections.abc import Callable, Iterator, Sequence
from typing import Any
import pyarrow as pa
@@ -35,15 +35,78 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
)
+class KeysetNullKeyError(ValueError):
+ """A keyset page ended on a NULL key, so the walk has nothing to seek past.
+
+ `resolve_keyset_eligibility` only admits a database-declared primary key, which is `NOT NULL`
+ by definition, so reaching this means a driver decoded a NULL out of one anyway (MySQL's zero
+ dates, '0000-00-00', decode to `None`). Raised rather than tolerated because both alternatives
+ are worse: re-running the query without the seek predicate would re-read the same page forever,
+ and stopping the walk would silently truncate the load.
+ """
+
+
@frozen
class KeysetResumeState:
- """Checkpoint persisted between batches: the largest key value durably written so far.
+ """Checkpoint persisted between batches: the largest key durably written so far.
- `last_key` is the primary-key value of the last row in the last committed batch. The next batch
- reads ``WHERE pk > last_key``. `None` means "no batch committed yet" — start from the beginning.
+ The key is the primary-key value(s) of the last row in the last committed batch. The next batch
+ reads ``WHERE pk > <key>``. No key at all means "no batch committed yet" — start from the
+ beginning.
+
+ Two fields carry it, and single-column keys fill both. `last_keys` is the real one, holding the
+ whole key tuple for the dialects that seek on a composite key; `last_key` is the original
+ single-value field, kept so a rollback to a deploy that predates `last_keys` reads its checkpoint
+ rather than restarting the load. Build one with `keyset_state` and read it with `keyset_last_key`
+ rather than touching either field, so the pair cannot disagree.
"""
last_key: Any = None
+ last_keys: list[Any] | None = None
+
+
+def keyset_state(last_key: Sequence[Any]) -> KeysetResumeState:
+ """The checkpoint for `last_key`, a tuple of one value per key column."""
+ if not last_key:
+ raise ValueError("A keyset checkpoint needs at least one key value")
+ # The scalar field is what a deploy without `last_keys` reads. A composite key has nothing
+ # meaningful to put there — such a deploy also refuses composite keys, so it never looks.
+ return KeysetResumeState(
+ last_key=last_key[0] if len(last_key) == 1 else None,
+ last_keys=list(last_key),
+ )
+
+
+def keyset_last_key(state: KeysetResumeState | None, *, key_length: int) -> tuple[Any, ...] | None:
+ """The key to seek past, or `None` to start from the beginning.
+
+ JSON has no tuple, so a key persisted as one comes back as a list; this is where that is absorbed,
+ and every caller downstream gets a tuple.
+
+ A stored key whose length doesn't match `key_length` returns `None`. The table's primary key
+ changed since the checkpoint was written, and seeking on a mismatched tuple would compare the
+ wrong columns — re-reading the table is the only safe reading of that state.
+ """
+ if state is None:
+ return None
+ stored = state.last_keys if state.last_keys else ([state.last_key] if state.last_key is not None else None)
+ if not stored or len(stored) != key_length:
+ return None
+ return tuple(stored)
+
+
+def keyset_key_of_last_row(table: pa.Table, keyset_columns: Sequence[str]) -> tuple[Any, ...]:
+ """The key tuple of the last row of `table`, which the next page seeks past.
+
+ Raises `KeysetNullKeyError` if any part is NULL. Every predicate form compares as UNKNOWN against
+ a NULL, so a single-column key would re-read the same page forever while a composite one would
+ come back empty and silently truncate the load. See `KeysetNullKeyError`.
+ """
+ key = tuple(table.column(column)[-1].as_py() for column in keyset_columns)
+ null_columns = [column for column, value in zip(keyset_columns, key) if value is None]
+ if null_columns:
+ raise KeysetNullKeyError(f"Keyset page ended on a NULL key for {null_columns}, so the walk cannot advance")
+ return key
def is_orderable_keyset_type(arrow_type: pa.DataType) -> bool:
@@ -62,17 +125,6 @@ def is_orderable_keyset_type(arrow_type: pa.DataType) -> bool:
return pa.types.is_integer(arrow_type) or pa.types.is_date(arrow_type) or pa.types.is_timestamp(arrow_type)
-class KeysetNullKeyError(ValueError):
- """A keyset page ended on a NULL key, so the walk has nothing to seek past.
-
- `resolve_keyset_eligibility` only admits a database-declared primary key, which is `NOT NULL`
- by definition, so reaching this means a driver decoded a NULL out of one anyway (MySQL's zero
- dates, '0000-00-00', decode to `None`). Raised rather than tolerated because both alternatives
- are worse: re-running the query without the seek predicate would re-read the same page forever,
- and stopping the walk would silently truncate the load.
- """
-
-
@dataclasses.dataclass(frozen=True)
class KeysetEligibility:
"""Whether this run can keyset-resume, and if not, why.
@@ -175,13 +227,9 @@ def iter_keyset_pages(
yield table
- last_value = table.column(keyset_column)[-1].as_py()
- if last_value is None:
- # Never fall through to another query: with `last_value` back to None the next page
- # would carry no seek predicate and return this same page again, indefinitely.
- raise KeysetNullKeyError(
- f"Keyset page for '{keyset_column}' ended on a NULL key, so the walk cannot advance"
- )
+ # 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])
if checkpoint is not None:
checkpoint(last_value)
if table.num_rows < chunk_size:
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 f692e31473d4..d6c0ed8cb1ee 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
@@ -17,6 +17,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
KeysetResumeState,
is_orderable_keyset_type,
iter_keyset_pages,
+ keyset_key_of_last_row,
+ keyset_last_key,
+ keyset_state,
resolve_keyset_eligibility,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.query_builder import SelectQueryBuilder
@@ -86,6 +89,74 @@ def test_an_eligible_key_type_can_always_be_checkpointed(arrow_type, last_key):
assert restored.last_key is not None
+class TestKeysetCheckpointState:
+ """`keyset_state` and `keyset_last_key` are the only sanctioned way to build and read the pair."""
+
+ def test_a_single_column_key_fills_both_fields(self):
+ # `last_key` is what a deploy predating `last_keys` reads. Writing only `last_keys` would make
+ # a rollback drop every in-flight checkpoint and restart those loads from row 0.
+ assert keyset_state((7,)) == KeysetResumeState(last_key=7, last_keys=[7])
+
+ def test_a_composite_key_leaves_the_single_value_field_empty(self):
+ # There is no honest scalar for a composite key. A deploy that can't read `last_keys` also
+ # refuses composite keys, so it never seeks on this state.
+ assert keyset_state((7, "b")) == KeysetResumeState(last_key=None, last_keys=[7, "b"])
+
+ def test_a_key_from_an_older_deploy_still_resumes(self):
+ # Forward compatibility: state written before `last_keys` existed carries only the scalar.
+ assert keyset_last_key(KeysetResumeState(last_key=7), key_length=1) == (7,)
+
+ def test_a_key_comes_back_as_a_tuple_after_its_json_round_trip(self):
+ # JSON has no tuple, so Redis hands back a list. Callers compare and unpack tuples.
+ assert keyset_last_key(KeysetResumeState(last_keys=[7, "b"]), key_length=2) == (7, "b")
+
+ @pytest.mark.parametrize(
+ "state,key_length",
+ [
+ (KeysetResumeState(last_keys=[7]), 2),
+ (KeysetResumeState(last_keys=[7, "b"]), 1),
+ (KeysetResumeState(last_key=7), 2),
+ ],
+ )
+ def test_a_key_of_the_wrong_width_restarts_rather_than_seeking(self, state, key_length):
+ # The table's primary key changed since the checkpoint. Seeking on it would compare the wrong
+ # columns, so the load has to start again.
+ assert keyset_last_key(state, key_length=key_length) is None
+
+ @pytest.mark.parametrize("state", [None, KeysetResumeState(), KeysetResumeState(last_keys=[])])
+ def test_no_checkpoint_starts_from_the_beginning(self, state):
+ assert keyset_last_key(state, key_length=1) is None
+
+
+class TestKeysetKeyOfLastRow:
+ @pytest.mark.parametrize(
+ "table,columns,expected",
+ [
+ (pa.table({"id": [1, 2]}), ["id"], (2,)),
+ (pa.table({"a": [1, 1], "b": ["x", "y"]}), ["a", "b"], (1, "y")),
+ # Column order follows the key, not the table.
+ (pa.table({"a": [1], "b": ["x"]}), ["b", "a"], ("x", 1)),
+ ],
+ )
+ def test_reads_the_key_of_the_final_row(self, table, columns, expected):
+ assert keyset_key_of_last_row(table, columns) == expected
+
+ @pytest.mark.parametrize(
+ "table,columns",
+ [
+ (pa.table({"id": [1, None]}), ["id"]),
+ (pa.table({"a": [1, 1], "b": ["x", None]}), ["a", "b"]), # NULL in the trailing column
+ (pa.table({"a": [1, None], "b": ["x", "y"]}), ["a", "b"]), # NULL in the leading column
+ ],
+ )
+ def test_any_null_part_stops_the_walk(self, table, columns):
+ # A composite key fails worse than a single one: both `(a, NULL) > (x, y)` and `b > NULL`
+ # evaluate to UNKNOWN, so the next page comes back empty and truncates the load silently
+ # rather than looping. Raising is the only option that neither truncates nor spins.
+ with pytest.raises(KeysetNullKeyError):
+ keyset_key_of_last_row(table, columns)
+
+
@pytest.mark.parametrize(
"primary_keys,incremental,declared,expected_column,expected_reason",
[
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 3bb228c5a03f..15cbf0073285 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
@@ -86,6 +86,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import (
KeysetResumeState,
iter_keyset_pages,
+ keyset_last_key,
+ keyset_state,
resolve_keyset_eligibility,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.location import (
@@ -1794,10 +1796,10 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
manager = resumable_source_manager
def _keyset_get_rows() -> Iterator[Any]:
- initial_last_value = None
state = manager.load_state() if manager.can_resume() else None
- if state is not None:
- initial_last_value = state.last_key
+ resume_key = keyset_last_key(state, key_length=1)
+ initial_last_value = resume_key[0] if resume_key is not None else None
+ if initial_last_value is not None:
logger.debug(f"MySQL keyset resume: {keyset_column} > {initial_last_value}")
# Autocommit: each page is its own transaction, so the load never holds a read view
@@ -1830,7 +1832,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
return table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)
def _checkpoint(last_key: Any) -> None:
- manager.save_state(KeysetResumeState(last_key=last_key))
+ manager.save_state(keyset_state((last_key,)))
yield from iter_keyset_pages(
builder=_QUERY_BUILDER,