:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): resumable keyset full loads for MySQL (#73177)
Tom Owers354e289aebd7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.pyindex 255360514608..6793e9aead51 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py@@ -62,7 +62,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (validate_schema_and_update_table,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import (+ ResumableSourceManager,+ resolve_resume_manager,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (ResumableData,SourceResponse,@@ -132,7 +135,7 @@ class PipelineNonDLT(Generic[ResumableData]):self._delta_table_ref = DeltaTableRef(self._resource_name, self._job, self._logger, is_first_sync=self._table is None)- self._resumable_source_manager = resumable_source_manager+ self._resumable_source_manager = resolve_resume_manager(resumable_source_manager, self._resource)# 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.self._batcher = Batcher(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.pyindex 520add8451f5..f11440e68c2d 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@@ -79,7 +79,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineS3BatchWriter,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer import ParquetCompression-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import (+ ResumableSourceManager,+ resolve_resume_manager,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (ResumableData,SourceResponse,@@ -195,7 +198,8 @@ class PipelineV3(Generic[ResumableData]):self._uses_delta_write_column_selection = source_uses_delta_write_column_selection(models.source.source_type)self._observed_columns: dict[str, dict[str, Any]] = {}- is_resume = resumable_source_manager is not None and resumable_source_manager.can_resume()+ self._resumable_source_manager = resolve_resume_manager(resumable_source_manager, self._resource)+ is_resume = self._resumable_source_manager is not None and self._resumable_source_manager.can_resume()self._producer_kwargs: dict[str, Any] = {"sync_type": sync_type,@@ -211,14 +215,15 @@ class PipelineV3(Generic[ResumableData]):self._s3_batch_writer, resource_name=self._resource_name, cdc_write_mode=self._resource.cdc_write_mode)- self._resumable_source_manager = resumable_source_manager# 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.+ # 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,@@ -226,7 +231,7 @@ 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=resumable_source_manager is None and not self._schema.is_webhook,+ coalesce_tables=self._resumable_source_manager is None and not self._schema.is_webhook,primary_keys=self._resource.primary_keys,)self._internal_schema = HogQLSchema()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.pyindex 364ce6995901..702baee35726 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py@@ -14,7 +14,11 @@ from structlog.types import FilteringBoundLoggerfrom posthog.redis import get_client-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import ResumableData, SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (+ ResumableData,+ SourceInputs,+ SourceResponse,+)class ResumableSourceManager(Generic[ResumableData]):@@ -172,3 +176,18 @@ class ResumableSourceManager(Generic[ResumableData]):self._logger.debug(f"Loading resumable source state. key={self._key}, data={data}")return self._load_json(data)+++def resolve_resume_manager(+ manager: ResumableSourceManager[ResumableData] | None,+ resource: SourceResponse,+) -> ResumableSourceManager[ResumableData] | None:+ """Combine the class-level capability (a manager exists) with the run-level one.++ A resumable-source class whose current run can't actually resume — a SQL full load with no+ orderable primary key, say — reports `supports_resume=False` and resolves to `None` here, so it+ is treated as non-resumable everywhere downstream instead of at each call site.+ """+ if manager is None or not resource.supports_resume:+ return None+ return managerdiff --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.pynew file mode 100644index 000000000000..1fbfd6591653--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/keyset.py@@ -0,0 +1,188 @@+"""Keyset (seek) pagination support for resumable full SQL loads.++A full (non-incremental) SQL load normally streams the whole table through a single server-side+cursor. That cursor is bound to one connection/transaction/snapshot, so it can't survive a pod+restart — if the worker drains mid-stream the load starts over from row 0.++Keyset pagination makes the load resumable without migrating a live cursor: order by a stable,+unique, orderable key (the primary key) and read in bounded batches with+``... WHERE pk > :last_key ORDER BY pk ASC LIMIT :n``. Once the consumer takes a page the source+checkpoints its last key (via `ResumableSourceManager`, like every other resumable source), so a+fresh pod resumes from that key instead of the start. Each batch is an independent short query — run+with autocommit so no read view or metadata lock is held across the whole load — so the read can also+yield to a draining worker between batches.++Eligibility is deliberately narrow (see `resolve_keyset_eligibility`): exactly one database-declared+primary-key column of an orderable type. Composite keys (per-dialect row-value comparison), keyless+tables and inferred keys stay on the single-cursor path, and report why via `KeysetEligibility.reason`+so the ineligible share is measurable before the approach is extended to other dialects.+"""++from __future__ import annotations++import dataclasses+from collections.abc import Callable, Iterator+from typing import Any++import pyarrow as pa++from posthog.dataclasses import frozen++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,+ SelectQueryBuilder,+)+++@frozen+class KeysetResumeState:+ """Checkpoint persisted between batches: the largest key value 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.+ """++ last_key: Any = None+++def is_orderable_keyset_type(arrow_type: pa.DataType) -> bool:+ """Whether a column type gives a stable, unambiguous total order for keyset pagination.++ Restricted to integer and temporal types. Strings/binary are excluded on purpose: their order+ depends on the database's collation, which can differ from the byte order the delta merge assumes+ and can even change mid-table, so ``WHERE k > :last`` could silently skip or duplicate rows across+ batches. Booleans and floats-with-NaN are too coarse/ill-ordered to seek on safely.++ Decimal is excluded for a different reason: the checkpoint cannot survive one. Neither encoder in+ `ResumableSourceManager._dump_json` handles `Decimal`, so it falls through to `str(data_dict)` and+ writes a Python repr into Redis that `_load_json` then refuses to parse, raising on every resume+ until the key expires. A decimal key keeps the streaming path: a slower load, never a wrong one.+ """+ 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.+ """++[email protected](frozen=True)+class KeysetEligibility:+ """Whether this run can keyset-resume, and if not, why.++ `column` is the primary-key column to seek on, or `None` when the run falls back to the+ single-cursor stream. `reason` is a stable token (never free text) so the ineligible share can be+ counted per dialect from logs — that rate is what decides whether extending keyset pagination to+ another SQL source is worth the work.+ """++ column: str | None = None+ reason: str | None = None+++def resolve_keyset_eligibility(+ *,+ primary_keys: list[str] | None,+ arrow_schema: pa.Schema,+ should_use_incremental_field: bool,+ primary_key_is_declared: bool,+) -> KeysetEligibility:+ """Decide whether a full load can keyset-resume, and on which primary-key column.++ Eligible only when all of:+ - the sync is a full load (incremental syncs already resume from their persisted watermark);+ - the table has exactly one detected primary-key column (composite keys need per-dialect+ row-value comparison — out of scope here);+ - that column is present in the projected Arrow schema with an orderable type; and+ - the database actually declared it a primary key (`primary_key_is_declared`).++ That last gate is what keeps the seek total. `WHERE pk > :last` can only advance on a key that+ is always present, and `primary_keys` is not always a key the database declared — a keyless+ table falls back to whatever `id` column it has, which may be nullable and full of NULLs. A page+ ending on a NULL would leave nothing to seek past and the next page would drop the predicate+ entirely. A declared primary key is `NOT NULL` by definition, which rules that out at the+ source; callers that infer a key some other way must report `primary_key_is_declared=False`.+ """+ if should_use_incremental_field:+ return KeysetEligibility(reason="incremental_sync")+ if not primary_keys:+ return KeysetEligibility(reason="no_primary_key")+ if not primary_key_is_declared:+ # An inferred key (e.g. the keyless-table `id` fallback) carries no NOT NULL guarantee.+ return KeysetEligibility(reason="undeclared_primary_key")+ if len(primary_keys) != 1:+ return KeysetEligibility(reason="composite_primary_key")++ key = primary_keys[0]+ field = arrow_schema.field(key) if key in arrow_schema.names else None+ if field is None:+ return KeysetEligibility(reason="primary_key_not_projected")+ if not is_orderable_keyset_type(field.type):+ return KeysetEligibility(reason=f"non_orderable_type:{field.type}")+ return KeysetEligibility(column=key)+++def iter_keyset_pages(+ *,+ builder: SelectQueryBuilder,+ schema: str,+ table_name: str,+ keyset_column: str,+ chunk_size: int,+ run_page: Callable[[SafeSQL], pa.Table | None],+ 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`.++ 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.++ `checkpoint` records the last key of a page 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.+ """+ 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,+ )+ table = run_page(page_sql)+ if table is None or table.num_rows == 0:+ break++ 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"+ )+ if checkpoint is not None:+ checkpoint(last_value)+ if table.num_rows < chunk_size:+ breakdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/query_builder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/query_builder.pyindex c4146f7eaa31..31d5aaac74b5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/query_builder.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/query_builder.py@@ -153,6 +153,65 @@ class SelectQueryBuilder:return SafeSQL(sql=" ".join(parts), params=params)+ def select_keyset(+ self,+ *,+ schema: str,+ table_name: str,+ keyset_column: str,+ keyset_last_value: Any | None,+ limit: int,+ enabled_columns: list[str] | None = None,+ primary_keys: list[str] | None = None,+ row_filters: list[ValidatedRowFilter] | None = None,+ ) -> SafeSQL:+ """Build one keyset (seek) page for a resumable full load.++ Emits ``SELECT … FROM schema.table [WHERE <keyset_column> > :keyset_value [AND …]]+ ORDER BY <keyset_column> ASC LIMIT <limit>``. The keyset predicate is omitted on the first+ page (`keyset_last_value is None`) so it reads from the start.++ `limit` is inlined as an integer literal (it is our own batch size, never user input) because+ several dialects reject a bound parameter in ``LIMIT``. `row_filters` compose with the keyset+ predicate exactly as in `select_all`. Callers must have validated `keyset_column` is a single+ orderable primary key (see `keyset.keyset_resume_column`).++ Note: `LIMIT n` is understood by MySQL/Postgres/Snowflake/BigQuery/Redshift/ClickHouse. MSSQL+ (which uses `TOP`/`OFFSET…FETCH`) needs its own builder when it opts in.+ """+ table_ref = self.quoter.quote_qualified(schema, table_name)+ quoted_keyset = self.quoter.quote(keyset_column)++ projected = compute_projected_columns(enabled_columns, primary_keys, None)+ select_clause = format_projected_select_clause(projected, self.quoter)++ params = self._empty_params()+ conditions: list[str] = []++ if keyset_last_value is not None:+ placeholder = self._append_param("keyset_value", keyset_last_value, params)+ conditions.append(f"{quoted_keyset} > {placeholder}")++ for index, row_filter in enumerate(row_filters or []):+ quoted_column = self.quoter.quote(row_filter.column)+ if is_multi_value_operator(row_filter.operator):+ placeholders = [+ self._append_param(f"row_filter_{index}_{position}", element, params)+ for position, element in enumerate(row_filter.value)+ ]+ conditions.append(f"{quoted_column} {row_filter.operator} ({', '.join(placeholders)})")+ else:+ placeholder = self._append_param(f"row_filter_{index}", row_filter.value, params)+ conditions.append(f"{quoted_column} {row_filter.operator} {placeholder}")++ parts = [f"SELECT {select_clause} FROM {table_ref}"]+ if conditions:+ parts.append("WHERE " + " AND ".join(conditions))+ parts.append(f"ORDER BY {quoted_keyset} ASC")+ parts.append(f"LIMIT {int(limit)}")++ return SafeSQL(sql=" ".join(parts), params=params)+def _empty_params(self) -> dict[str, Any] | list[Any]:if self.param_style in (ParamStyle.PYFORMAT_NAMED, ParamStyle.NAMED):return {}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.pynew file mode 100644index 000000000000..f692e31473d4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_keyset.py@@ -0,0 +1,293 @@+from __future__ import annotations++from datetime import UTC, date, datetime+from decimal import Decimal++import pytest+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.identifiers import (+ BacktickIdentifierQuoter,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import (+ KeysetNullKeyError,+ KeysetResumeState,+ is_orderable_keyset_type,+ iter_keyset_pages,+ resolve_keyset_eligibility,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.query_builder import SelectQueryBuilder++_FIELDS: list[pa.Field] = [+ pa.field("id", pa.int64()),+ pa.field("uuid", pa.string()),+ pa.field("created_at", pa.timestamp("us")),+ pa.field("amount", pa.decimal128(18, 2)),+ pa.field("active", pa.bool_()),+ pa.field("day", pa.date32()),+]+_SCHEMA = pa.schema(_FIELDS)+++ "arrow_type,expected",+ [+ (pa.int8(), True),+ (pa.int64(), True),+ (pa.uint32(), True),+ (pa.date32(), True),+ (pa.timestamp("us"), True),+ (pa.string(), False), # collation-dependent order+ (pa.large_binary(), False),+ (pa.bool_(), False),+ (pa.float64(), False), # NaN ordering / precision+ (pa.decimal128(18, 2), False), # no JSON encoding, so the checkpoint can't round-trip+ ],+)+def test_is_orderable_keyset_type(arrow_type, expected):+ assert is_orderable_keyset_type(arrow_type) is expected+++ "arrow_type,last_key",+ [+ (pa.int64(), 2**63 - 1),+ (pa.int32(), -1),+ (pa.date32(), date(2026, 1, 2)),+ (pa.timestamp("us"), datetime(2026, 1, 2, 3, 4, 5)),+ (pa.timestamp("us", tz="UTC"), datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)),+ (pa.decimal128(18, 2), Decimal("1.5")),+ (pa.string(), "abc"),+ ],+)+def test_an_eligible_key_type_can_always_be_checkpointed(arrow_type, last_key):+ # Eligibility and encodability have to stay the same set. A type that `is_orderable_keyset_type`+ # admits but the manager cannot encode leaves a Python repr in Redis that `_load_json` refuses to+ # parse, so every resume raises until the key expires instead of restarting cleanly — which is+ # what a decimal key did. Asserting the implication rather than a fixed list means admitting any+ # such type in future fails here rather than in production.+ if not is_orderable_keyset_type(arrow_type):+ pytest.skip(f"{arrow_type} is not an eligible keyset type, so it is never checkpointed")++ manager = ResumableSourceManager[KeysetResumeState](MagicMock(team_id=1, job_id="job-1"), KeysetResumeState)+ redis = MagicMock()++ with patch.object(ResumableSourceManager, "_get_redis") as get_redis:+ get_redis.return_value.__enter__.return_value = redis+ manager.save_state(KeysetResumeState(last_key=last_key))+ manager.commit()+ redis.get.return_value = redis.set.call_args.args[1]+ restored = manager.load_state()++ assert restored is not None+ assert restored.last_key is not None+++ "primary_keys,incremental,declared,expected_column,expected_reason",+ [+ (["id"], False, True, "id", None),+ (["created_at"], False, True, "created_at", None),+ (["day"], False, True, "day", None),+ # Incremental syncs already resume from their persisted watermark; keyset would double up.+ (["id"], True, True, None, "incremental_sync"),+ (None, False, True, None, "no_primary_key"),+ ([], False, True, None, "no_primary_key"),+ (["id", "created_at"], False, True, None, "composite_primary_key"),+ # If the PK was projected out of the Arrow schema there's nothing to seek on.+ (["missing"], False, True, None, "primary_key_not_projected"),+ # A string/uuid PK sorts by collation, which can skip or duplicate rows across keyset pages.+ (["uuid"], False, True, None, "non_orderable_type:string"),+ (["active"], False, True, None, "non_orderable_type:bool"),+ # A decimal PK orders fine but cannot be encoded into the checkpoint, so it would poison the+ # resume rather than restart it. See `is_orderable_keyset_type`.+ (["amount"], False, True, None, "non_orderable_type:decimal128(18, 2)"),+ # An inferred key (the keyless-table `id` fallback) has no NOT NULL guarantee, so a page+ # could end on a NULL and leave the seek with nothing to compare against.+ (["id"], False, False, None, "undeclared_primary_key"),+ ],+)+def test_resolve_keyset_eligibility(primary_keys, incremental, declared, expected_column, expected_reason):+ eligibility = resolve_keyset_eligibility(+ primary_keys=primary_keys,+ arrow_schema=_SCHEMA,+ should_use_incremental_field=incremental,+ primary_key_is_declared=declared,+ )++ assert eligibility.column == expected_column+ assert eligibility.reason == expected_reason+++_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]})+++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):+ self.all_ids = sorted(all_ids)+ self.chunk_size = chunk_size+ self.queries: list[str] = []++ 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+ remaining = [i for i in self.all_ids if after is None or i > after]+ page = remaining[: self.chunk_size]+ if not page:+ return None+ return _fake_table(page)+++def test_iter_keyset_pages_walks_whole_table_in_order():+ pages = _FakePages(all_ids=[1, 2, 3, 4, 5, 6, 7], chunk_size=3)+ tables = list(+ iter_keyset_pages(+ builder=_BUILDER,+ schema="db",+ table_name="t",+ keyset_column="id",+ chunk_size=3,+ run_page=pages.run_page,+ initial_last_value=None,+ )+ )+ seen = [v.as_py() for table in tables for v in table.column("id")]+ assert seen == [1, 2, 3, 4, 5, 6, 7]+ # 3 + 3 + 1: the final short page ends the walk without an extra empty query.+ assert [t.num_rows for t in tables] == [3, 3, 1]+ assert len(pages.queries) == 3+++def test_iter_keyset_pages_seeks_from_initial_value():+ pages = _FakePages(all_ids=[1, 2, 3, 4, 5], chunk_size=10)+ tables = list(+ iter_keyset_pages(+ builder=_BUILDER,+ schema="db",+ table_name="t",+ keyset_column="id",+ chunk_size=10,+ run_page=pages.run_page,+ initial_last_value=3,+ )+ )+ seen = [v.as_py() for table in tables for v in table.column("id")]+ assert seen == [4, 5] # rows <= the resume checkpoint are never re-read+++def test_iter_keyset_pages_stops_immediately_when_empty():+ pages = _FakePages(all_ids=[], chunk_size=5)+ tables = list(+ iter_keyset_pages(+ builder=_BUILDER,+ schema="db",+ table_name="t",+ keyset_column="id",+ chunk_size=5,+ run_page=pages.run_page,+ initial_last_value=None,+ )+ )+ assert tables == []+ assert len(pages.queries) == 1+++def test_iter_keyset_pages_full_page_then_empty_terminates():+ # An exact multiple of chunk_size needs one extra (empty) query to learn it's done.+ pages = _FakePages(all_ids=[1, 2, 3, 4], chunk_size=2)+ tables = list(+ iter_keyset_pages(+ builder=_BUILDER,+ schema="db",+ table_name="t",+ keyset_column="id",+ chunk_size=2,+ run_page=pages.run_page,+ initial_last_value=None,+ )+ )+ seen = [v.as_py() for table in tables for v in table.column("id")]+ assert seen == [1, 2, 3, 4]+ assert len(pages.queries) == 3 # [>none], [>2], [>4 -> empty]+++def test_checkpoint_records_each_page_only_once_the_consumer_takes_the_next():+ # Generator laziness is the contract: a page that has been read but not yet handed on must not+ # move the checkpoint, or an abandoned walk would resume past rows the consumer never saw.+ pages = _FakePages(all_ids=[1, 2, 3, 4, 5], chunk_size=2)+ saved: list[int] = []+ walk = iter_keyset_pages(+ builder=_BUILDER,+ schema="db",+ table_name="t",+ keyset_column="id",+ chunk_size=2,+ run_page=pages.run_page,+ initial_last_value=None,+ checkpoint=saved.append,+ )++ next(walk)+ assert saved == [] # first page read, consumer hasn't come back for more++ next(walk)+ assert saved == [2] # ...and now it has++ assert [v.as_py() for table in walk for v in table.column("id")] == [5]+ assert saved == [2, 4, 5]+++def test_checkpoint_is_optional():+ pages = _FakePages(all_ids=[1, 2], chunk_size=5)+ tables = list(+ iter_keyset_pages(+ builder=_BUILDER,+ schema="db",+ table_name="t",+ keyset_column="id",+ chunk_size=5,+ run_page=pages.run_page,+ initial_last_value=None,+ )+ )+ assert [t.num_rows for t in tables] == [2]+++def test_null_page_boundary_raises_instead_of_replaying_the_page():+ """A page ending on a NULL key must stop the walk, not re-issue an unbounded query.++ Without the guard `last_value` falls back to None, the next page is built with no seek+ predicate, and the same rows come back forever — an unbounded rewrite loop a source owner+ could trigger with a nullable key column.+ """+ queries: list[str] = []++ def run_page(page_sql):+ queries.append(page_sql.sql)+ return pa.table({"id": pa.array([1, None], type=pa.int64())})++ walk = iter_keyset_pages(+ builder=_BUILDER,+ schema="db",+ table_name="t",+ keyset_column="id",+ chunk_size=2,+ run_page=run_page,+ initial_last_value=None,+ )++ assert next(walk).num_rows == 2 # the page itself is still handed to the consumer++ with pytest.raises(KeysetNullKeyError):+ next(walk)++ assert len(queries) == 1 # crucially, no second query was ever issueddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_query_builder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_query_builder.pyindex 2b86c8f238bd..e3033c44a6b6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_query_builder.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_query_builder.py@@ -42,6 +42,78 @@ class TestSelectAllFullRefresh:self.builder.select_all(schema="mydb", table_name="messages; DROP TABLE x")+class TestSelectKeyset:+ builder = SelectQueryBuilder(quoter=BacktickIdentifierQuoter())++ def test_first_page_has_no_keyset_predicate(self) -> None:+ result = self.builder.select_keyset(+ schema="mydb", table_name="messages", keyset_column="id", keyset_last_value=None, limit=500+ )+ assert result.sql == "SELECT * FROM `mydb`.`messages` ORDER BY `id` ASC LIMIT 500"+ assert result.params == {}++ def test_resume_page_seeks_past_last_key(self) -> None:+ result = self.builder.select_keyset(+ schema="mydb", table_name="messages", keyset_column="id", keyset_last_value=4242, limit=500+ )+ assert result.sql == (+ "SELECT * FROM `mydb`.`messages` WHERE `id` > %(keyset_value)s ORDER BY `id` ASC LIMIT 500"+ )+ assert result.params == {"keyset_value": 4242}++ def test_limit_is_inlined_as_integer_literal(self) -> None:+ # A bound param in LIMIT is rejected by several dialects, and it's our own batch size, so it's+ # inlined — and coerced to int so nothing else can slip into the clause.+ result = self.builder.select_keyset(+ schema="mydb", table_name="t", keyset_column="id", keyset_last_value=None, limit=1000+ )+ assert result.sql.endswith("LIMIT 1000")+ assert "%(" not in result.sql.split("LIMIT")[1]++ def test_qmark_style_binds_keyset_value_positionally(self) -> None:+ builder = SelectQueryBuilder(quoter=AnsiIdentifierQuoter(), param_style=ParamStyle.QMARK)+ result = builder.select_keyset(+ schema="dbo", table_name="orders", keyset_column="id", keyset_last_value=7, limit=250+ )+ assert result.sql == 'SELECT * FROM "dbo"."orders" WHERE "id" > ? ORDER BY "id" ASC LIMIT 250'+ assert result.params == [7]++ def test_row_filters_compose_with_keyset_predicate(self) -> None:+ result = self.builder.select_keyset(+ schema="mydb",+ table_name="messages",+ keyset_column="id",+ keyset_last_value=10,+ limit=500,+ row_filters=[+ ValidatedRowFilter(column="status", operator=">", value=3, category=ColumnTypeCategory.INTEGER)+ ],+ )+ assert "WHERE `id` > %(keyset_value)s AND `status` > %(row_filter_0)s" in result.sql+ assert result.sql.endswith("ORDER BY `id` ASC LIMIT 500")+ assert result.params == {"keyset_value": 10, "row_filter_0": 3}++ def test_projection_still_orders_and_seeks_on_keyset_column(self) -> None:+ result = self.builder.select_keyset(+ schema="mydb",+ table_name="messages",+ keyset_column="id",+ keyset_last_value=1,+ limit=500,+ enabled_columns=["body"],+ primary_keys=["id"],+ )+ assert "`id`" in result.sql and "`body`" in result.sql+ assert "*" not in result.sql+ assert result.sql.endswith("ORDER BY `id` ASC LIMIT 500")++ def test_injection_in_keyset_column_raises(self) -> None:+ with pytest.raises(InvalidIdentifierError):+ self.builder.select_keyset(+ schema="mydb", table_name="messages", keyset_column="id; DROP TABLE x", keyset_last_value=None, limit=10+ )++class TestSelectAllIncremental:builder = SelectQueryBuilder(quoter=BacktickIdentifierQuoter())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.pyindex d03a23c3e5bc..63e097587dec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py@@ -5,7 +5,11 @@ import redis.exceptions as redis_exceptionsfrom posthog.dataclasses import frozen-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import (+ ResumableSourceManager,+ resolve_resume_manager,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@frozen@@ -17,6 +21,29 @@ def _manager() -> ResumableSourceManager[_SweepPosition]:return ResumableSourceManager[_SweepPosition](MagicMock(team_id=1, job_id="job-1"), _SweepPosition)+class TestResolveResumeManager:+ """The choke point every caller reads: a class that *can* resume, ANDed with a run that can."""++ def test_a_run_that_cannot_resume_resolves_to_no_manager(self):+ # The case that matters: a resumable source class whose current table isn't seekable. Callers+ # treat a manager as "this run commits a cursor", so leaving it set here would have the+ # pipeline suppress its table reset and stop coalescing for a run that checkpoints nothing.+ resource = SourceResponse(name="t", items=lambda: iter(()), primary_keys=None, supports_resume=False)++ assert resolve_resume_manager(_manager(), resource) is None++ def test_a_resumable_run_keeps_its_manager(self):+ manager = _manager()+ resource = SourceResponse(name="t", items=lambda: iter(()), primary_keys=None, supports_resume=True)++ assert resolve_resume_manager(manager, resource) is manager++ def test_a_source_without_a_manager_stays_without_one(self):+ resource = SourceResponse(name="t", items=lambda: iter(()), primary_keys=None, supports_resume=True)++ assert resolve_resume_manager(None, resource) is None++class TestResumableSourceManager:def test_state_written_by_a_newer_deploy_still_loads(self):manager = _manager()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.pyindex 1e36c89ada88..256a424fe2c0 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@@ -106,6 +106,11 @@ class SourceResponse:"""xmin syncs: full 64-bit `xid8` ceiling, the durable wraparound-safe cursor."""xmin_num_wraparound: Optional[int] = None"""xmin syncs: epoch (high 32 bits of `xmin_ceiling_xid8`) at this run's ceiling."""+ supports_resume: bool = True+ """Whether *this run* can cheaply resume after a bail (source checkpoints, or an ascending+ incremental watermark). Gated by the pipeline together with a non-None resumable-source manager,+ so a resumable-source class whose current table isn't actually resumable (e.g. a SQL full load+ with no orderable primary key) sets this False and is treated as non-resumable for shutdown."""lanes: Optional[list[OutputLane]] = None"""Tables this response's items feed, when it feeds more than the one `name` alone describes.None means the single lane built from `name` and `cdc_write_mode`."""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.pyindex cfa745f37ec8..3bb228c5a03f 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@@ -62,10 +62,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixhost_lookup_is_skipped,open_ssh_tunnel,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (BacktickIdentifierQuoter,Column,InvalidIdentifierError,+ SafeSQL,SelectQueryBuilder,Table,TableProjection,@@ -81,6 +83,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sqlfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.incremental import (IncrementalFieldFilter,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import (+ KeysetResumeState,+ iter_keyset_pages,+ resolve_keyset_eligibility,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.location import (normalize_namespace,resolve_source_location,@@ -937,6 +944,8 @@ class MySQLTableSetup:"""Everything `build_pipeline` learns about a table before it can stream rows."""primary_keys: list[str] | None+ primary_keys_are_declared: bool+ """Whether the database declared these, as opposed to `build_pipeline` guessing `id`."""projection: TableProjection[MySQLColumn]chunk_size: introws_to_sync: int@@ -1068,6 +1077,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conconfig: MySQLSourceConfig,*,read_timeout: int | None = None,+ autocommit: bool = False,team_id: int | None = None,) -> Iterator[pymysql.Connection]:"""Open a pymysql connection for the duration of the context.@@ -1075,10 +1085,11 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.ConOpens the SSH tunnel (if configured), then connects with theMySQL-wide conventions: safe date/datetime converters, and aPlanetScale workload hint injected automatically when the host- resolves to a `*.psdb.cloud` address. Callers only vary one- thing — the streaming path sets `read_timeout=STATEMENT_TIMEOUT_SECONDS`+ resolves to a `*.psdb.cloud` address. Callers vary two things —+ the streaming path sets `read_timeout=STATEMENT_TIMEOUT_SECONDS`so multi-GB filesorts don't drop on middlebox timeouts before the- first rows are ready.+ first rows are ready, and the keyset path sets `autocommit` so each+ page is its own transaction (see `_keyset_get_rows`)."""verify_certificate = config.verify_server_certificatessl_ca: str | None = None@@ -1108,6 +1119,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con"ssl_verify_cert": True if verify_certificate else None,"ssl_verify_identity": True if verify_hostname else None,"conv": _MYSQL_SAFE_CONVERSIONS,+ "autocommit": autocommit,"init_command": "SET workload = 'OLAP';" if host.endswith("psdb.cloud") else None,}if read_timeout is not None:@@ -1613,11 +1625,48 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con# `find_index_for_cursor`.logger.debug(f"EXPLAIN raised an exception: {e}", exc_info=e)+ def check_keyset_page_plan(self, cursor: Cursor, page_sql: SafeSQL, logger: FilteringBoundLogger) -> None:+ """Warn when a keyset page isn't reading the clustered index in key order.++ A seek page is only cheap if the optimizer answers it as a range scan on `PRIMARY`: one+ B-tree descent, then `LIMIT n` rows already in `ORDER BY` order. Row filters give it another+ choice — take the filter's secondary index, lose the index ordering, and sort the whole+ matched set — and that filesort runs *per page*, turning one table scan into thousands.++ Diagnostics only: log a stable token so the bad-plan rate is greppable, and let the page run.+ The streaming path's `FORCE INDEX` retry is the hammer if this turns out to be common.+ """+ try:+ cursor.execute(f"EXPLAIN {page_sql.sql}", page_sql.params)+ rows = cursor.fetchall()+ column_names = [column[0] for column in cursor.description or []]+ plans = [dict(zip(column_names, row)) for row in rows]+ except Exception as e:+ # Best-effort, exactly like `explain_query`: a failed EXPLAIN must never fail the page.+ logger.debug(f"Keyset EXPLAIN raised an exception: {e}", exc_info=e)+ return++ for plan in plans:+ index_used = plan.get("key")+ extra = str(plan.get("Extra") or "")+ sorts = "Using filesort" in extra or "Using temporary" in extra+ if index_used == "PRIMARY" and not sorts:+ continue+ logger.warning(+ f"Keyset page not served by the primary key: reason=bad_keyset_plan "+ f"key={index_used} type={plan.get('type')} rows={plan.get('rows')} extra='{extra}'"+ )+# ------------------------------------------------------------------# Pipeline build — the dlt `SourceResponse` for a single table# ------------------------------------------------------------------- def build_pipeline(self, config: MySQLSourceConfig, inputs: SourceInputs) -> SourceResponse:+ def build_pipeline(+ self,+ config: MySQLSourceConfig,+ inputs: SourceInputs,+ resumable_source_manager: ResumableSourceManager[KeysetResumeState] | None = None,+ ) -> SourceResponse:location = resolve_source_location(inputs,config_namespace=_configured_schema(config),@@ -1658,6 +1707,11 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conprimary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)full_table = self.get_table_metadata(cursor, schema, table_name)+ # Whether the database itself declared these as the primary key, as opposed to+ # the `id` guess below. Only a declared PK is guaranteed NOT NULL, which is what+ # keyset pagination needs to seek past every page (see `resolve_keyset_eligibility`).+ primary_keys_are_declared = primary_keys is not None+# Resolve PKs before the projection so probe/sample queries match the streaming SELECT.if primary_keys is None and "id" in full_table:primary_keys = ["id"]@@ -1686,6 +1740,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con)return MySQLTableSetup(primary_keys=primary_keys,+ primary_keys_are_declared=primary_keys_are_declared,projection=projection,chunk_size=chunk_size,rows_to_sync=rows_to_sync,@@ -1698,6 +1753,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con# first blip — see `_retry_on_transient_tablet_unavailable`.setup = _retry_on_transient_tablet_unavailable(_discover_metadata, logger)primary_keys = setup.primary_keys+ primary_keys_are_declared = setup.primary_keys_are_declaredsetup_projection = setup.projectionchunk_size = setup.chunk_sizerows_to_sync = setup.rows_to_sync@@ -1705,7 +1761,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conbinary_reporter = BinaryColumnReporter(logger)def _refreshed_projection(connection: pymysql.Connection) -> TableProjection[MySQLColumn]:- """Re-read the catalog on the streaming connection, right before the read query.+ """Re-read the catalog on the connection that runs the read, right before the query.A probe that fails keeps the setup projection, which is where this read would havestarted anyway. See `resolve_table_projection` for why the read resolves again.@@ -1718,6 +1774,90 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conreturn setup_projectionreturn _resolve_projection(fresh_table, primary_keys)+ # A full load over a single orderable primary key can page with keyset (seek) pagination+ # instead of one long streaming cursor, which makes it resumable across pods. Incremental syncs+ # already resume from their watermark, and keyless/composite/non-orderable tables fall through+ # to the streaming path below.+ eligibility = resolve_keyset_eligibility(+ primary_keys=primary_keys,+ arrow_schema=setup_projection.table.to_arrow_schema(),+ should_use_incremental_field=should_use_incremental_field,+ primary_key_is_declared=primary_keys_are_declared,+ )+ keyset_column = eligibility.column+ if keyset_column is None:+ # Logged for every ineligible table so the ineligible share (and its breakdown) is+ # measurable before keyset pagination is extended to the other SQL dialects.+ logger.info(f"MySQL keyset resume unavailable: reason={eligibility.reason}")++ if keyset_column is not None and resumable_source_manager is not None:+ 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+ 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+ # (and the metadata lock that blocks DDL) across the whole table the way the+ # streaming cursor does. A resume on a fresh pod starts a new snapshot regardless, so+ # there is no cross-page consistency here to give up — and the delta merge dedupes by+ # primary key if a row shifts between pages.+ with self.connect(+ config, read_timeout=STATEMENT_TIMEOUT_SECONDS, autocommit=True, team_id=inputs.team_id+ ) as connection:+ projection = _refreshed_projection(connection)+ arrow_schema = projection.table.to_arrow_schema()+ plan_checked = False++ def _run_page(page_sql: SafeSQL) -> pa.Table | None:+ nonlocal plan_checked+ with connection.cursor() as cursor:+ # Check the first page that actually seeks — page 1 has no `pk >`+ # predicate, so its plan says nothing about how the walk will behave.+ seeks = isinstance(page_sql.params, dict) and "keyset_value" in page_sql.params+ if not plan_checked and seeks:+ plan_checked = True+ self.check_keyset_page_plan(cursor, page_sql, logger)++ cursor.execute(page_sql.sql, page_sql.params)+ 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)++ def _checkpoint(last_key: Any) -> None:+ manager.save_state(KeysetResumeState(last_key=last_key))++ yield from iter_keyset_pages(+ builder=_QUERY_BUILDER,+ schema=schema,+ table_name=table_name,+ keyset_column=keyset_column,+ chunk_size=chunk_size,+ run_page=_run_page,+ initial_last_value=initial_last_value,+ checkpoint=_checkpoint,+ enabled_columns=projection.enabled_columns,+ primary_keys=primary_keys,+ row_filters=row_filters,+ )++ # Only reached when the walk exhausted the table. An abandoned generator (draining+ # worker) unwinds at the yield above, leaving the checkpoint in place to resume from.+ manager.clear_state()++ return SourceResponse(+ name=location.response_name,+ items=_keyset_get_rows,+ primary_keys=primary_keys,+ rows_to_sync=rows_to_sync,+ supports_resume=True,+ )+def _stream_with_optional_force_index(force_index_name: str | None) -> Iterator[Any]:"""Open a fresh connection and stream rows.@@ -1879,4 +2019,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conpartition_count=partition_settings.partition_count if partition_settings else None,partition_size=partition_settings.partition_size if partition_settings else None,rows_to_sync=rows_to_sync,+ # The streaming path can't be resumed across pods (its cursor is bound to one connection),+ # so this run is not cheaply resumable — treated as non-resumable for shutdown handling.+ supports_resume=False,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.pyindex a7b7dcac507c..69e78dde9a9e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py@@ -18,7 +18,7 @@ from products.warehouse_sources.backend.facade.source_config import (SourceFieldSelectConfigOption,SourceFieldSSHTunnelConfig,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (HostNotAllowedError,SSHTunnelMixin,@@ -26,8 +26,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixValidateDatabaseHostMixin,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import KeysetResumeState+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mysql import MySQLSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql import (_SSH_HANDSHAKE_EOF_ERROR,@@ -90,11 +93,30 @@ _HOST_IS_URL_ERROR = (@SourceRegistry.register-class MySQLSource(SQLSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):+class MySQLSource(+ SQLSource[MySQLSourceConfig],+ ResumableSource[MySQLSourceConfig, KeysetResumeState],+ SSHTunnelMixin,+ ValidateDatabaseHostMixin,+):@propertydef get_implementation(self) -> MySQLImplementation:return _MYSQL_IMPLEMENTATION+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KeysetResumeState]:+ return ResumableSourceManager[KeysetResumeState](inputs, KeysetResumeState)++ def source_for_pipeline( # type: ignore[override]+ self,+ config: MySQLSourceConfig,+ resumable_source_manager: ResumableSourceManager[KeysetResumeState],+ inputs: SourceInputs,+ ) -> SourceResponse:+ # A reset must not resume from a stale checkpoint — the full load restarts from the top.+ if inputs.reset_pipeline:+ resumable_source_manager.clear_state()+ return self.get_implementation.build_pipeline(config, inputs, resumable_source_manager=resumable_source_manager)+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MYSQLdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.pyindex 03c04ec71492..07ce510b7047 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py@@ -16,7 +16,8 @@ from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import HostNotAllowedError-from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import Table, TableStats+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import SafeSQL, Table, TableStats+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import KeysetResumeStatefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (ColumnTypeCategory,ValidatedRowFilter,@@ -746,6 +747,43 @@ class TestExplainQuery:capture.assert_not_called()+class TestCheckKeysetPagePlan:+ @staticmethod+ def _explain(cursor, **plan):+ row = {"key": None, "type": "ALL", "rows": 1, "Extra": "", **plan}+ cursor.description = [(name,) for name in row]+ cursor.fetchall.return_value = [tuple(row.values())]++ @pytest.mark.parametrize(+ "plan,warns",+ [+ ({"key": "PRIMARY", "type": "range", "Extra": "Using where"}, False),+ ({"key": "PRIMARY", "type": "range", "Extra": ""}, False),+ # A row filter pulled the optimizer onto a secondary index, so the page can't read in+ # key order and sorts the whole matched set — per page.+ ({"key": "idx_status", "type": "ref", "Extra": "Using where; Using filesort"}, True),+ # Right index, but still sorting: the ORDER BY isn't being served by the scan.+ ({"key": "PRIMARY", "type": "range", "Extra": "Using filesort"}, True),+ ({"key": "PRIMARY", "type": "range", "Extra": "Using temporary"}, True),+ ({"key": None, "type": "ALL", "Extra": ""}, True),+ ],+ )+ def test_warns_only_when_the_page_is_not_a_primary_key_scan(self, impl, cursor, logger, plan, warns):+ self._explain(cursor, **plan)++ impl.check_keyset_page_plan(cursor, SafeSQL(sql="SELECT 1", params={}), logger)++ assert logger.warning.called is warns++ def test_swallows_explain_failure(self, impl, cursor, logger):+ # Diagnostics must never fail the page that follows.+ cursor.execute.side_effect = pymysql.err.OperationalError(1345, "lacking privileges")++ impl.check_keyset_page_plan(cursor, SafeSQL(sql="SELECT 1", params={}), logger)++ assert logger.warning.called is False++class TestSafetyContract:"""Verifies that driver-specific metadata queries never splice untrusted identifiers into SQL."""@@ -826,6 +864,125 @@ def _drain_source():list(source.items()) # type: ignore[arg-type] # MySQL source is always sync+class TestKeysetReadPath:+ @pytest.fixture+ def keyset_mocks(self, mocker):+ """Drive the keyset branch of `build_pipeline` without a real MySQL server."""+ fake_table = Table(+ name="messages",+ parents=("mydb",),+ columns=[MySQLColumn(name="id", data_type="int", column_type="int", nullable=False)],+ )+ mocker.patch.object(MySQLImplementation, "get_table_metadata", return_value=fake_table)+ mocker.patch.object(MySQLImplementation, "get_primary_keys_for_table", return_value=["id"])+ mocker.patch.object(MySQLImplementation, "get_rows_to_sync", return_value=0)+ mocker.patch.object(MySQLImplementation, "get_chunk_size", return_value=2)+ mocker.patch.object(MySQLImplementation, "get_partition_settings", return_value=None)+ mocker.patch.object(MySQLImplementation, "explain_query")+ plan_check = mocker.patch.object(MySQLImplementation, "check_keyset_page_plan")++ cursor = MagicMock()+ cursor.__enter__.return_value = cursor+ cursor.description = [("id",)]+ # A full page, then a short one that ends the walk.+ cursor.fetchall.side_effect = [[(1,), (2,)], [(3,)]]++ connection = MagicMock()+ connection.__enter__.return_value = connection+ connection.cursor.return_value = cursor++ mock_connect = mocker.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.pymysql.connect",+ return_value=connection,+ )+ return mock_connect, cursor, plan_check++ @staticmethod+ def _keyset_source(manager):+ source = MySQLImplementation().build_pipeline(_make_config(), _make_inputs(), resumable_source_manager=manager)+ assert source.supports_resume is True+ return source++ @classmethod+ def _drain_keyset(cls, manager):+ # The keyset MySQL source always yields a sync generator of Arrow tables.+ return list(cast(Generator, cls._keyset_source(manager).items()))++ @staticmethod+ def _fake_manager():+ manager = MagicMock()+ manager.can_resume.return_value = False+ return manager++ def test_pages_read_with_autocommit(self, keyset_mocks):+ # Without autocommit every page shares one read view, so the load holds undo history and a+ # metadata lock on the source for its whole duration — the thing keyset paging exists to avoid.+ mock_connect, _, _ = keyset_mocks++ self._drain_keyset(self._fake_manager())++ read_connects = [call for call in mock_connect.call_args_list if call.kwargs.get("autocommit")]+ assert len(read_connects) == 1++ def test_plan_is_checked_on_the_first_seeking_page(self, keyset_mocks):+ # Page 1 has no `pk >` predicate, so its plan says nothing about how the walk behaves.+ _, _, plan_check = keyset_mocks++ self._drain_keyset(self._fake_manager())++ assert plan_check.call_count == 1+ checked_sql = plan_check.call_args.args[1]+ assert "keyset_value" in checked_sql.params++ def test_checkpoints_each_page_and_clears_once_the_table_is_walked(self, keyset_mocks):+ manager = self._fake_manager()++ self._drain_keyset(manager)++ assert [call.args[0].last_key for call in manager.save_state.call_args_list] == [2, 3]+ # The walk finished, so the next scheduled sync must start from the top, not mid-table.+ manager.clear_state.assert_called_once()++ def test_abandoned_walk_keeps_its_checkpoint(self, keyset_mocks):+ # A draining worker stops consuming mid-table: the checkpoint has to survive so the next pod+ # resumes from it instead of restarting the load from row 0.+ manager = self._fake_manager()+ items = cast(Generator, self._keyset_source(manager).items())++ next(items)+ next(items)+ items.close()++ assert manager.save_state.call_count == 1+ manager.clear_state.assert_not_called()++ def test_resumes_from_the_persisted_checkpoint(self, keyset_mocks):+ manager = self._fake_manager()+ manager.can_resume.return_value = True+ manager.load_state.return_value = KeysetResumeState(last_key=7)++ self._drain_keyset(manager)++ _, cursor, _ = keyset_mocks+ first_page_params = cursor.execute.call_args_list[0].args[1]+ assert first_page_params["keyset_value"] == 7++ def test_inferred_id_key_stays_on_the_streaming_path(self, keyset_mocks, mocker):+ """A keyless table falls back to whatever `id` column it has, which may be nullable.++ `WHERE id > :last` can't advance past a NULL — the next page would drop the predicate and+ re-read the same rows — so an undeclared key keeps the streaming cursor and reports itself+ non-resumable instead.+ """+ mocker.patch.object(MySQLImplementation, "get_primary_keys_for_table", return_value=None)++ source = MySQLImplementation().build_pipeline(+ _make_config(), _make_inputs(), resumable_source_manager=self._fake_manager()+ )++ assert source.supports_resume is False++class TestBuildPipelineSourceLocation:def test_uses_schema_metadata_when_schema_is_blank(self, build_pipeline_mocks):source = MySQLImplementation().build_pipeline(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.pyindex 5fddc3b212eb..94d7a79e62a6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.py@@ -32,6 +32,7 @@ class PlanetScaleMySQLImplementation(MySQLImplementation):config: MySQLSourceConfig,*,read_timeout: int | None = None,+ autocommit: bool = False,team_id: int | None = None,) -> Iterator[pymysql.Connection]:ssl_ca = "/etc/ssl/cert.pem" if settings.DEBUG else "/etc/ssl/certs/ca-certificates.crt"@@ -56,6 +57,11 @@ class PlanetScaleMySQLImplementation(MySQLImplementation):"ssl_verify_cert": True,"ssl_verify_identity": True,"conv": _MYSQL_SAFE_CONVERSIONS,+ # PlanetScale inherits the MySQL keyset read path, which pages with one+ # independent bounded query per page and relies on autocommit so no read view+ # (or metadata lock) is held across the whole load. Threaded through rather than+ # hardcoded so the streaming path keeps pymysql's default of autocommit off.+ "autocommit": autocommit,"init_command": _VITESS_OLAP_INIT_COMMAND,}if read_timeout is not None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/test_planetscale_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/test_planetscale_mysql.pyindex 304a88d0c586..765a3f23c7e3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/test_planetscale_mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/test_planetscale_mysql.py@@ -81,3 +81,13 @@ def test_read_timeout_is_only_sent_when_requested():with _connect(_config(), read_timeout=600) as kwargs:assert kwargs["read_timeout"] == 600+++def test_autocommit_is_off_by_default_and_threaded_through_when_requested():+ # PlanetScale inherits the MySQL keyset read path, which needs each page to be its own+ # transaction. The streaming path keeps pymysql's default (autocommit off).+ with _connect(_config()) as kwargs:+ assert kwargs["autocommit"] is False++ with _connect(_config(), autocommit=True) as kwargs:+ assert kwargs["autocommit"] is Truediff --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.pyindex b1af17245007..5e20c48248e2 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@@ -3,7 +3,7 @@ import jsonimport uuidimport functoolsimport contextlib-from collections.abc import AsyncIterator+from collections.abc import AsyncIterable, AsyncIteratorfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, timedeltafrom typing import Any, Optional, cast@@ -25,6 +25,7 @@ import psycopgimport pyarrow as paimport aioboto3import deltalake+import structlogimport pytest_asyncioimport pyarrow.parquet as pqimport posthoganalytics@@ -95,6 +96,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.regfrom 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.common.sql.keyset import KeysetResumeState+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql import MySQLImplementation+from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.source import MySQLSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import (XminBounds,_TableChunking,@@ -4675,6 +4680,107 @@ async def test_mysql_incremental_integer_cursor(team, mysql_config, mysql_connecassert [row[0] for row in res.results] == [1, 2, 3]+def _keyset_source_inputs(team_id: int, schema_name: str, job_id: str) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id=str(uuid.uuid4()),+ source_id=str(uuid.uuid4()),+ team_id=team_id,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id=job_id,+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )++[email protected]_db(transaction=True)+async def test_mysql_full_refresh_keyset_pages_whole_table(team, mysql_config, mysql_connection):+ """A full-refresh load over an integer primary key pages via keyset (seek) pagination and lands+ every row. A tiny chunk size forces several pages so the pagination itself is exercised end to+ end through the real pipeline, not just the first page."""+ await _mysql_setup(+ mysql_connection,+ [+ ("DROP TABLE IF EXISTS keyset_full", None),+ ("CREATE TABLE keyset_full (id INT PRIMARY KEY, payload VARCHAR(64))", None),+ *[(f"INSERT INTO keyset_full VALUES ({i}, 'row-{i}')", None) for i in range(1, 6)],+ ],+ )++ # chunk_size 2 over 5 rows -> keyset pages of [2, 2, 1].+ # `ignore_assertions` skips `_run`'s single-row expectation (the other MySQL tests load one row);+ # the multi-row assertion below is what proves keyset paging landed the whole table.+ with mock.patch.object(MySQLImplementation, "get_chunk_size", return_value=2):+ await _run(+ team=team,+ schema_name="keyset_full",+ table_name="mysql_keyset_full",+ source_type="MySQL",+ job_inputs=_mysql_job_inputs(mysql_config),+ mock_data_response=[],+ ignore_assertions=True,+ )++ res = await sync_to_async(execute_hogql_query)("SELECT id, payload FROM mysql_keyset_full ORDER BY id", team)+ assert [(row[0], row[1]) for row in res.results] == [(i, f"row-{i}") for i in range(1, 6)]++[email protected]_db(transaction=True)+async def test_mysql_keyset_resume_seeks_past_checkpoint(team, mysql_config, mysql_connection):+ """With a keyset checkpoint already persisted (as a prior pod would have left it), the source+ resumes the load from `WHERE id > checkpoint` and re-reads nothing at or below it. This is the+ property that makes a bailed-and-resumed full load safe: no skipped or duplicated rows."""+ await _mysql_setup(+ mysql_connection,+ [+ ("DROP TABLE IF EXISTS keyset_resume", None),+ ("CREATE TABLE keyset_resume (id INT PRIMARY KEY, payload VARCHAR(64))", None),+ *[(f"INSERT INTO keyset_resume VALUES ({i}, 'row-{i}')", None) for i in range(1, 8)],+ ],+ )++ with override_settings(DATA_WAREHOUSE_REDIS_HOST="localhost", DATA_WAREHOUSE_REDIS_PORT="6379"):+ source = MySQLSource()+ config = source.parse_config(_mysql_job_inputs(mysql_config))+ inputs = _keyset_source_inputs(team_id=team.pk, schema_name="keyset_resume", job_id=str(uuid.uuid4()))+ manager = source.get_resumable_source_manager(inputs)++ # Simulate the checkpoint a previous pod committed just before it drained. The commit is what+ # puts it in Redis — `save_state` only stages — and `can_resume()` reads Redis.+ await sync_to_async(manager.save_state)(KeysetResumeState(last_key=3))+ await sync_to_async(manager.commit)()++ # A small chunk keeps resumption paging rather than one-shotting the tail.+ with mock.patch.object(MySQLImplementation, "get_chunk_size", return_value=2):+ source_response = await sync_to_async(source.source_for_pipeline)(config, manager, inputs)++ def _collect_ids() -> list[int]:+ ids: list[int] = []+ items = source_response.items()+ assert not isinstance(items, AsyncIterable) # the keyset MySQL source yields a sync iterable+ for table in items:+ ids.extend(v.as_py() for v in table.column("id"))+ return ids++ ids = await sync_to_async(_collect_ids)()++ # The source walked the table to the end, so it drops its own checkpoint — the next+ # scheduled sync starts from the top rather than resuming past row 7.+ walked_to_completion = not await sync_to_async(manager.can_resume)()++ await sync_to_async(manager.clear_state)()++ assert ids == [4, 5, 6, 7] # rows 1..3 (<= checkpoint) are never re-read; 4..7 arrive once, in order+ assert source_response.supports_resume is True+ assert walked_to_completion++@pytest.mark.django_db(transaction=True)@pytest.mark.asyncioasync def test_mysql_full_refresh_with_zero_date(team, mysql_config, mysql_connection):