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): add durable source cursors, move xmin onto them (#108390)

Tom Owerscbb1e9253027
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index 98ffe423d136..96a771c5e51b 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -44,9 +44,21 @@ Rule of thumb:
- Pull-only API, no cursor we can persist → `SimpleSource`.
- Pull-only API with any cursor/next-page/time-filter we can save between runs → `ResumableSource`.
- Source can call us back with change events → add `WebhookSource` on top of whichever pull base fits.
+- Source's next run starts from a position only the source can compute, not the max of a column → add `CursorSource`.
Databases and file-transfer sources (SFTP, S3) stay on `SimpleSource` unless there's a clear reason otherwise.
+### Durable source cursors (`CursorSource`)
+
+The incremental field covers the common case: the pipeline takes the max of a column and the next run filters above it.
+Some positions are not a column max: a Postgres xmin ceiling captured before the read, or a set of Kafka partition offsets.
+For those, add the `CursorSource[CursorT]` mixin from `sources/common/cursor.py` instead of new fields on `SourceResponse` or new keys in `sync_type_config`.
+
+- Define the cursor as a `@frozen` dataclass with a `cursor_kind: ClassVar[str]`. Keep the kind stable, because a changed kind discards every stored cursor. Give fields added later a default, because a stored cursor that lacks a required field is discarded.
+- Implement `cursor_class()`. Override `merge_cursors(current, candidate)` when a run that read less must not move the cursor back (Kafka keeps the per-partition max). Override `cursor_from_legacy()` only when migrating state that was stored under other keys.
+- In `source_for_pipeline`, call `self.get_cursor_manager(inputs)`. `load()` returns the stored cursor, or `None` on a reset or a table rebuild. `stage(cursor)` hands the next cursor to the pipeline.
+- The pipeline persists the staged cursor only after the run's rows are durable (on v3, the loader promotes it with the final batch), and a reset clears it. `postgres/xmin_cursor.py` is the reference.
+
## Prefer the shared REST framework
Most REST sources should be built on the shared `rest_source` framework
diff --git a/products/warehouse_sources/backend/management/commands/reset_wrapped_xmin_cursors.py b/products/warehouse_sources/backend/management/commands/reset_wrapped_xmin_cursors.py
index 97f2436147a7..8b8486d64990 100644
--- a/products/warehouse_sources/backend/management/commands/reset_wrapped_xmin_cursors.py
+++ b/products/warehouse_sources/backend/management/commands/reset_wrapped_xmin_cursors.py
@@ -6,10 +6,20 @@ import structlog
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.xmin_cursor import (
+ XMIN_LEGACY_KEYS,
+ XminCursor,
+)
logger = structlog.get_logger(__name__)
+def _stored_xmin_cursor(schema: ExternalDataSchema) -> XminCursor | None:
+ return SourceCursorManager.from_sync_type_config(PostgresSource(), schema.sync_type_config, logger).load()
+
+
class Command(BaseCommand):
help = (
"Clear the xmin cursor on schemas whose backfill may have run against a wrapped cluster. "
@@ -59,7 +69,11 @@ class Command(BaseCommand):
# Epoch 0 clusters never wrapped, so their [0, ceiling) window covered the whole xid
# space and the backfill read everything. Past a wraparound the window is a candidate
# rather than proof, since a large remainder can still have caught every tuple.
- candidates = [schema for schema in schemas if (schema.xmin_num_wraparound or 0) > 0]
+ candidates = [
+ schema
+ for schema in schemas
+ if (cursor := _stored_xmin_cursor(schema)) is not None and cursor.num_wraparound > 0
+ ]
if not candidates:
self.stdout.write(self.style.WARNING("No xmin schemas found with a cursor captured past a wraparound."))
@@ -79,10 +93,12 @@ class Command(BaseCommand):
for schema in candidates:
# Share of the 32-bit xid space the backfill window covered. The lower it is, the more
# of the table the backfill could have skipped.
- window_covered = (schema.xmin_last_value or 0) / 0x100000000
+ cursor = _stored_xmin_cursor(schema)
+ window_covered = (cursor.ceiling_xid if cursor else 0) / 0x100000000
self.stdout.write(
f" schema={schema.id} team={schema.team_id} source={schema.source_id} "
- f"name={schema.name} epoch={schema.xmin_num_wraparound} cursor={schema.xmin_ceiling} "
+ f"name={schema.name} epoch={cursor.num_wraparound if cursor else None} "
+ f"cursor={cursor.ceiling_xid8 if cursor else None} "
f"window_covered={window_covered:.1%}"
+ (" [sync running, will be skipped]" if schema.id in running else "")
)
@@ -107,7 +123,7 @@ class Command(BaseCommand):
)
continue
try:
- schema.clear_xmin_state()
+ schema.clear_source_cursor(legacy_keys=XMIN_LEGACY_KEYS)
succeeded += 1
logger.info(
"Cleared xmin cursor for re-backfill",
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 0dba61349bca..3b7ad01f04ff 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.naming_convention
from products.warehouse_sources.backend.temporal.data_imports.retry_limits import (
MAX_RESUMABLE_SOURCE_RETRIES_PRODUCTION,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SOURCE_CURSOR_KEY
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
PartitionFormat,
PartitionMode,
@@ -226,7 +227,9 @@ class ExternalDataSchemaQuerySet(models.QuerySet["ExternalDataSchema"]):
CDC_SNAPSHOT_LANE_KEY = "cdc_snapshot_lane"
-class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletedMetaFields):
+class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-django-pk -- grandfathered UUIDT primary key
+ ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletedMetaFields
+):
# Kept on the model so the nested names and the `choices=` below stay unchanged.
Status = ExternalDataSchemaStatus
SyncType = ExternalDataSchemaSyncType
@@ -263,7 +266,7 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
# See `sources/common/history_window.py`. A column rather than a `sync_type_config` key
# because it has to outlive a reset, and clearing that blob is what a reset is for.
history_start = models.DateTimeField(null=True, blank=True)
- # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "verified_primary_keys": list[str] | None, "xmin_last_value": int, "xmin_ceiling": int, "xmin_num_wraparound": int, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str }, "repartition_rewrite": { "temp_uri": str, "rows_written": int, "target": dict }, "query_folder_state": { "<table>__query": { "active": str, "active_since": iso8601 str, "active_job_id": str, "history_since": iso8601 str, "inactive_since": { str: iso8601 str } } }, "registered_schema_fingerprint": str }
+ # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "verified_primary_keys": list[str] | None, "source_cursor": { "kind": str, "data": dict }, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str }, "repartition_rewrite": { "temp_uri": str, "rows_written": int, "target": dict }, "query_folder_state": { "<table>__query": { "active": str, "active_since": iso8601 str, "active_job_id": str, "history_since": iso8601 str, "inactive_since": { str: iso8601 str } } }, "registered_schema_fingerprint": str }
sync_type_config = models.JSONField(
default=dict,
blank=True,
@@ -445,24 +448,6 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
"""True when syncing will not resume without user action."""
return not self.should_sync or self.cdc_halted
- @property
- def xmin_last_value(self) -> int | None:
- if self.sync_type_config:
- return self.sync_type_config.get("xmin_last_value", None)
- return None
-
- @property
- def xmin_ceiling(self) -> int | None:
- if self.sync_type_config:
- return self.sync_type_config.get("xmin_ceiling", None)
- return None
-
- @property
- def xmin_num_wraparound(self) -> int | None:
- if self.sync_type_config:
- return self.sync_type_config.get("xmin_num_wraparound", None)
- return None
-
@property
def cdc_mode(self) -> Literal["snapshot", "streaming"] | None:
if self.sync_type_config:
@@ -991,7 +976,13 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
for key, value in (("last_value", last_value), ("earliest_value", earliest_value))
if value is not None
}
+ self._stage_cursor_values(run_uuid, values)
+
+ def stage_source_cursor(self, run_uuid: str, payload: dict[str, Any]) -> None:
+ """Hold a run's source cursor in `incremental_staged`, which the load side promotes with the watermark."""
+ self._stage_cursor_values(run_uuid, {SOURCE_CURSOR_KEY: payload})
+ def _stage_cursor_values(self, run_uuid: str, values: dict[str, Any]) -> None:
def mutate(config: dict[str, Any]) -> None:
live = config.get("incremental_staged", {})
if live.get("run_uuid") == run_uuid:
@@ -1011,7 +1002,11 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
lambda: update_sync_type_config_keys(self.id, self.team_id, mutate=mutate)
)
- def promote_staged_incremental_values(self, run_uuid: str) -> bool:
+ def promote_staged_incremental_values(
+ self,
+ run_uuid: str,
+ merge_source_cursors: Callable[[Any, Any], dict[str, Any]] | None = None,
+ ) -> bool:
"""Move the staged cursor of `run_uuid` onto the live watermark keys.
Returns True when a staged cursor for the run existed, in the live slot or the parked list.
@@ -1037,6 +1032,14 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
_advance_promoted_cursor(
config, "incremental_field_earliest_value", staged["earliest_value"], "earliest", field_type
)
+ if SOURCE_CURSOR_KEY in staged:
+ candidate = staged[SOURCE_CURSOR_KEY]
+ current = config.get(SOURCE_CURSOR_KEY)
+ if current is not None:
+ if merge_source_cursors is None:
+ raise ValueError("Source cursor promotion requires a merger when a cursor is already stored")
+ candidate = merge_source_cursors(current, candidate)
+ config[SOURCE_CURSOR_KEY] = candidate
if live is not None:
config.pop("incremental_staged", None)
@@ -1110,6 +1113,9 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
"partitioning_keys",
"partition_mode",
"backfilled_partition_format",
+ SOURCE_CURSOR_KEY,
+ # Cursor keys from before `source_cursor`. A source still reads them when it has no
+ # `source_cursor`, so a reset has to drop them too.
"xmin_last_value",
"xmin_ceiling",
"xmin_num_wraparound",
@@ -1195,25 +1201,22 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
# put back settings the user changed during the run.
self.save(update_fields=["sync_type_config", "updated_at"], skip_activity_log=True)
- def update_xmin_state(self, ceiling_xid: int, ceiling_xid8: int, num_wraparound: int, save: bool = True) -> None:
- # Call at job completion, not per-batch: a mid-run crash then re-reads the window
+ def update_source_cursor(self, payload: dict[str, Any]) -> None:
+ # Call only once the run's rows are durable: a mid-run crash then re-reads the window
# instead of skipping it.
- self.sync_type_config["xmin_last_value"] = ceiling_xid
- self.sync_type_config["xmin_ceiling"] = ceiling_xid8
- self.sync_type_config["xmin_num_wraparound"] = num_wraparound
-
- if save:
- self.save(skip_activity_log=True)
+ self.sync_type_config = update_sync_type_config_keys(
+ self.id, self.team_id, updates={SOURCE_CURSOR_KEY: payload}
+ )
- def clear_xmin_state(self, save: bool = True) -> None:
- # Drops the cursor so the next run takes the backfill path and re-reads the whole table,
- # upserting by primary key. Use it to repair a schema whose backfill missed rows.
- self.sync_type_config.pop("xmin_last_value", None)
- self.sync_type_config.pop("xmin_ceiling", None)
- self.sync_type_config.pop("xmin_num_wraparound", None)
+ def clear_source_cursor(self, legacy_keys: Iterable[str] = ()) -> None:
+ """Drop the source cursor so the next run reads from the start of the source.
- if save:
- self.save(skip_activity_log=True)
+ `legacy_keys` names cursor keys from before `source_cursor`. Pass them for a source that
+ still reads them, or the next run reads its cursor from them instead.
+ """
+ self.sync_type_config = update_sync_type_config_keys(
+ self.id, self.team_id, removes=[SOURCE_CURSOR_KEY, *legacy_keys]
+ )
def soft_delete(self):
self.deleted = True
@@ -1277,7 +1280,7 @@ def _align_epoch_cursor(value: Any, partner: Any) -> Any:
def _park_displaced_staged_cursor(config: dict[str, Any], staged: dict[str, Any]) -> None:
"""A run is live or parked, never both: only another run's staging parks it, and its own
staging moves it back. Both happen under the row lock."""
- if not staged.get("run_uuid") or not ({"last_value", "earliest_value"} & staged.keys()):
+ if not staged.get("run_uuid") or not ({"last_value", "earliest_value", SOURCE_CURSOR_KEY} & staged.keys()):
return
pending = [*config.get("incremental_staged_pending", []), staged]
config["incremental_staged_pending"] = pending[-STAGED_CURSOR_PENDING_LIMIT:]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index d22781c8bf3b..15145613ffad 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -45,6 +45,7 @@ if TYPE_CHECKING:
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
ImportDataActivityInputs,
)
@@ -826,31 +827,28 @@ async def finalize_desc_sort_incremental_value(
await database_sync_to_async_pool(schema.update_incremental_field_value)(last_incremental_field_value)
-async def advance_xmin_state(
- resource: SourceResponse,
+async def commit_source_cursor(
+ source_cursor_manager: "SourceCursorManager[Any] | None",
schema: "ExternalDataSchema",
logger: FilteringBoundLogger,
+ *,
+ staging_run_uuid: str | None,
log_prefix: str = "",
) -> None:
- """Persist the xmin ceiling captured at sync start, once the run's data is durable.
+ """Persist the cursor the source staged, once this run's rows are durable or about to be.
- Persist-then-advance: the ceiling was captured before streaming and is stored only here, at
- completion, so a mid-run crash re-reads the window next time (the upsert on PK is idempotent).
- Deliberately not the per-batch MAX-of-observed advance, which would store the wrong value and is
- wraparound-unsafe for xmin.
+ With `staging_run_uuid`, the cursor waits in the staged slot until the loader promotes it with
+ the final batch, so a load that fails never leaves the cursor past rows it did not write.
+ Without it, the caller has already written every row and the cursor is stored directly.
"""
- if (
- not schema.is_xmin
- or resource.xmin_ceiling_xid is None
- or resource.xmin_ceiling_xid8 is None
- or resource.xmin_num_wraparound is None
- ):
+ if source_cursor_manager is None:
+ return
+ payload = source_cursor_manager.staged_payload()
+ if payload is None:
return
- await logger.adebug(f"{log_prefix}Advancing xmin cursor to ceiling {resource.xmin_ceiling_xid8}")
- await database_sync_to_async_pool(schema.refresh_from_db)()
- await database_sync_to_async_pool(schema.update_xmin_state)(
- ceiling_xid=resource.xmin_ceiling_xid,
- ceiling_xid8=resource.xmin_ceiling_xid8,
- num_wraparound=resource.xmin_num_wraparound,
- )
+ await logger.adebug(f"{log_prefix}Committing source cursor", kind=payload["kind"], staged=staging_run_uuid)
+ if staging_run_uuid is not None:
+ await database_sync_to_async_pool(schema.stage_source_cursor)(staging_run_uuid, payload)
+ else:
+ await database_sync_to_async_pool(schema.update_source_cursor)(payload)
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.py
index 24a4cb2804e9..2e38d8fbccb0 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
@@ -20,8 +20,8 @@ from products.warehouse_sources.backend.models.external_data_schema import (
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
- advance_xmin_state,
cleanup_memory,
+ commit_source_cursor,
handle_corrupted_delta_log,
handle_reset_or_full_refresh,
persist_primary_keys,
@@ -62,6 +62,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typ
from 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.cursor import SourceCursorManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import (
ResumableSourceManager,
resolve_resume_manager,
@@ -90,6 +91,7 @@ class PipelineNonDLT(Generic[ResumableData]):
_reset_pipeline: bool
_delta_table_ref: DeltaTableRef
_resumable_source_manager: ResumableSourceManager[ResumableData] | None
+ _source_cursor_manager: SourceCursorManager[Any] | None
_internal_schema = HogQLSchema()
_sinks: PipelineSinks
_batcher: Batcher
@@ -105,8 +107,10 @@ class PipelineNonDLT(Generic[ResumableData]):
resumable_source_manager: ResumableSourceManager[ResumableData] | None,
*,
models: "ImportJobModels",
+ source_cursor_manager: SourceCursorManager[Any] | None = None,
) -> None:
self._resource = source_response
+ self._source_cursor_manager = source_cursor_manager
self._resource_name = source_response.name
# Persisted PK (user override or earlier detection) > live-detected > `id` fallback. Keeps
@@ -308,7 +312,7 @@ class PipelineNonDLT(Generic[ResumableData]):
prepared_queryable_folder = await self._post_run_operations(row_count=row_count)
- await advance_xmin_state(self._resource, self._schema, self._logger)
+ await commit_source_cursor(self._source_cursor_manager, self._schema, self._logger, staging_run_uuid=None)
result = PipelineResult(should_trigger_cdp_producer=await self._sinks.cdp_producer.should_run())
if isinstance(prepared_queryable_folder, str):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py
index e0dc6ffbed0f..df98111a2a20 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py
@@ -14,7 +14,7 @@ single-table runs the loader already knows how to finish.
from __future__ import annotations
import asyncio
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
import pyarrow as pa
from structlog.types import FilteringBoundLogger
@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
BatchWriteResult,
S3BatchWriter,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager
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,
@@ -88,13 +89,21 @@ class LanedPipelineV3(PipelineV3[ResumableData]):
resumable_source_manager: ResumableSourceManager[ResumableData] | None,
*,
models: ImportJobModels,
+ source_cursor_manager: SourceCursorManager[Any] | None = None,
) -> None:
if not source_response.lanes:
raise ValueError(f"{source_response.name} declares no lanes; run it on PipelineV3")
self._output_lanes = list(source_response.lanes)
super().__init__(
- source_response, logger, job_id, reset_pipeline, shutdown_monitor, resumable_source_manager, models=models
+ source_response,
+ logger,
+ job_id,
+ reset_pipeline,
+ shutdown_monitor,
+ resumable_source_manager,
+ models=models,
+ source_cursor_manager=source_cursor_manager,
)
# The base built the first lane; it shares the base's batch list so the two never disagree.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index e4c5f28f901f..d197fb514ac8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -90,8 +90,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
release_v3_pipeline_lock,
)
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import finish_row_tracking
+from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import merge_cursor_payloads
from products.warehouse_sources.backend.temporal.data_imports.util import prepare_s3_files_for_querying
from products.warehouse_sources.backend.temporal.data_imports.workload_report import report_phase, workload_reporting
+from products.warehouse_sources.backend.types import ExternalDataSourceType
from products.warehouse_sources_queue.backend.core.batch_consumer import CoalescingDeclined, OwnershipLostError
logger = structlog.get_logger(__name__)
@@ -709,7 +712,14 @@ def _trigger_post_import_workflow(export_signal: ExportSignalMessage) -> None:
def _promote_staged_cursor(export_signal: ExportSignalMessage) -> None:
# Runs inside the completion transaction; failures roll it back so the batch retries.
schema = ExternalDataSchema.objects.get(id=export_signal.schema_id, team_id=export_signal.team_id)
- promoted = schema.promote_staged_incremental_values(export_signal.run_uuid)
+
+ def merge_source_cursors(current: Any, candidate: Any) -> dict[str, Any]:
+ source = SourceRegistry.get_source(ExternalDataSourceType(schema.source.source_type))
+ return merge_cursor_payloads(source, current, candidate, logger)
+
+ promoted = schema.promote_staged_incremental_values(
+ export_signal.run_uuid, merge_source_cursors=merge_source_cursors
+ )
if promoted:
logger.info(
"staged_cursor_promoted",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
index b3a463d91178..dd1e4c134368 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
@@ -5,7 +5,7 @@ from pathlib import Path
from typing import Any
import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import ANY, AsyncMock, MagicMock, patch
import pyarrow as pa
from deltalake import DeltaTable, write_deltalake
@@ -176,7 +176,7 @@ class TestPromoteStagedCursor:
_promote_staged_cursor(signal)
mock_objects.get.assert_called_once_with(id="schema-1", team_id=1)
- schema.promote_staged_incremental_values.assert_called_once_with("run-abc-a1")
+ schema.promote_staged_incremental_values.assert_called_once_with("run-abc-a1", merge_source_cursors=ANY)
@parameterized.expand(
[
@@ -448,7 +448,7 @@ class TestMarkJobCompleted:
_mark_job_completed(self._make_signal())
if expect_promotion:
- schema.promote_staged_incremental_values.assert_called_once_with("run-abc-a1")
+ schema.promote_staged_incremental_values.assert_called_once_with("run-abc-a1", merge_source_cursors=ANY)
else:
schema.promote_staged_incremental_values.assert_not_called()
mock_finish_row_tracking.assert_not_awaited()
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 8bd80014a043..f115812704d8 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
@@ -28,8 +28,8 @@ from products.warehouse_sources.backend.models.external_data_schema import (
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import SCD2_APPEND_MODE
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
- advance_xmin_state,
cleanup_memory,
+ commit_source_cursor,
finalize_desc_sort_incremental_value,
handle_corrupted_delta_log,
handle_reset_or_full_refresh,
@@ -79,6 +79,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
S3BatchWriter,
)
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.cursor import SourceCursorManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import (
ResumableSourceManager,
resolve_resume_manager,
@@ -124,6 +125,7 @@ class PipelineV3(Generic[ResumableData]):
_reset_pipeline: bool
_delta_table_ref: DeltaTableRef
_resumable_source_manager: ResumableSourceManager[ResumableData] | None
+ _source_cursor_manager: SourceCursorManager[Any] | None
_internal_schema: HogQLSchema
_sinks: PipelineSinks
_batcher: Batcher
@@ -143,8 +145,10 @@ class PipelineV3(Generic[ResumableData]):
resumable_source_manager: ResumableSourceManager[ResumableData] | None,
*,
models: "ImportJobModels",
+ source_cursor_manager: SourceCursorManager[Any] | None = None,
) -> None:
self._resource = source_response
+ self._source_cursor_manager = source_cursor_manager
self._resource_name = source_response.name
# Persisted PK (user override or earlier detection) > live-detected > `id` fallback. Keeps
@@ -676,6 +680,15 @@ class PipelineV3(Generic[ResumableData]):
# no batches the load consumer is never notified. Without this a v3 schema whose
# source stays quiet could never satisfy `_fast_return_eligible`.
await self._stamp_full_run()
+ # No batch reaches the loader, so nothing would promote a staged cursor. With no rows
+ # outstanding the cursor is already safe to store.
+ await commit_source_cursor(
+ self._source_cursor_manager,
+ self._schema,
+ self._logger,
+ staging_run_uuid=None,
+ log_prefix="V3 Pipeline: ",
+ )
self._logger.debug("V3 Pipeline: No batches extracted, skipping finalization")
return
@@ -695,11 +708,16 @@ class PipelineV3(Generic[ResumableData]):
log_prefix="V3 Pipeline: ",
staging_run_uuid=self._s3_batch_writer.get_run_uuid(),
)
+ await commit_source_cursor(
+ self._source_cursor_manager,
+ self._schema,
+ self._logger,
+ staging_run_uuid=self._s3_batch_writer.get_run_uuid(),
+ log_prefix="V3 Pipeline: ",
+ )
schema_path = await self._send_final_batches(total_batches, row_count)
- await advance_xmin_state(self._resource, self._schema, self._logger, log_prefix="V3 Pipeline: ")
-
# initial_sync_complete is set by the loader's post-load after data lands in Delta.
await self._logger.ainfo(
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 e125cb1c8770..80c6391c1e03 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
@@ -75,6 +75,7 @@ def _make_pipeline() -> PipelineV3:
pipeline._reset_pipeline = False
pipeline._delta_table_ref = MagicMock(is_first_sync=True)
pipeline._resumable_source_manager = None
+ pipeline._source_cursor_manager = None
pipeline._internal_schema = MagicMock()
pipeline._sinks = MagicMock(
clear=AsyncMock(),
@@ -518,10 +519,6 @@ class TestLaneFanOut:
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.finalize_desc_sort_incremental_value",
AsyncMock(),
),
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.advance_xmin_state",
- AsyncMock(),
- ),
):
await pipeline._finalize(row_count=1)
@@ -538,10 +535,6 @@ class TestLaneFanOut:
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.finalize_desc_sort_incremental_value",
AsyncMock(),
),
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.advance_xmin_state",
- AsyncMock(),
- ),
):
await pipeline._finalize(row_count=1)
@@ -789,12 +782,32 @@ class TestFinalizeStagesTheWatermarkFirst:
f"{_PIPELINE}.finalize_desc_sort_incremental_value",
AsyncMock(side_effect=lambda *_a, **_k: order.append("stage")),
),
- patch(f"{_PIPELINE}.advance_xmin_state", AsyncMock()),
):
await pipeline._finalize(row_count=1)
assert order == ["stage", "send"]
+ @pytest.mark.asyncio
+ async def test_the_source_cursor_is_staged_for_the_loader_before_the_final_batch_notification(self) -> None:
+ pipeline = _make_pipeline()
+ pipeline._batch_results = [MagicMock()]
+ pipeline._last_incremental_field_value = None
+ pipeline._s3_batch_writer = MagicMock(get_run_uuid=MagicMock(return_value="run-1"))
+ payload = {"kind": "postgres_xmin", "data": {}}
+ pipeline._source_cursor_manager = MagicMock(staged_payload=MagicMock(return_value=payload))
+ order: list[str] = []
+ schema = MagicMock()
+ schema.stage_source_cursor.side_effect = lambda *_a: order.append("stage")
+ pipeline._schema = schema
+ pipeline._send_final_batches = AsyncMock(side_effect=lambda *_a, **_k: order.append("send")) # type: ignore[method-assign]
+
+ with patch(f"{_PIPELINE}.finalize_desc_sort_incremental_value", AsyncMock()):
+ await pipeline._finalize(row_count=1)
+
+ assert order == ["stage", "send"]
+ schema.stage_source_cursor.assert_called_once_with("run-1", payload)
+ schema.update_source_cursor.assert_not_called()
+
class TestZeroBatchRunStampsTheFullRunMarker:
@pytest.mark.asyncio
@@ -812,6 +825,21 @@ class TestZeroBatchRunStampsTheFullRunMarker:
assert "last_full_run_at" in update.call_args.kwargs["updates"]
assert "extra_model_fields" not in update.call_args.kwargs
+ @pytest.mark.asyncio
+ async def test_a_run_that_extracted_nothing_stores_its_source_cursor_directly(self) -> None:
+ pipeline = _make_pipeline()
+ pipeline._batch_results = []
+ payload = {"kind": "postgres_xmin", "data": {}}
+ pipeline._source_cursor_manager = MagicMock(staged_payload=MagicMock(return_value=payload))
+ schema = MagicMock()
+ pipeline._schema = schema
+
+ with patch(f"{_PIPELINE}.update_sync_type_config_keys", new=MagicMock()):
+ await pipeline._finalize(row_count=0)
+
+ schema.update_source_cursor.assert_called_once_with(payload)
+ schema.stage_source_cursor.assert_not_called()
+
@pytest.mark.asyncio
async def test_a_bookkeeping_failure_does_not_fail_the_sync(self) -> None:
pipeline = _make_pipeline()
@@ -1066,7 +1094,6 @@ class TestFinalMarkerIsTheLastDataRow:
"handle_reset_or_full_refresh",
"handle_corrupted_delta_log",
"finalize_desc_sort_incremental_value",
- "advance_xmin_state",
):
stack.enter_context(patch(f"{_PIPELINE}.{name}", new_callable=AsyncMock))
for name in ("validate_incremental_sync", "record_source_item_stats", "update_sync_type_config_keys"):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/cursor.py
new file mode 100644
index 000000000000..00a7d8d9d3c2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/cursor.py
@@ -0,0 +1,154 @@
+"""Durable, source-defined sync cursors.
+
+A cursor is a position that only the source knows how to read from, such as a Postgres xmin ceiling
+or a set of Kafka partition offsets. The source defines its shape as a dataclass. The pipeline
+persists it on the schema after the rows of the run are durable, so a run that fails before its
+load finishes reads the same window again instead of skipping it.
+
+Unlike the incremental field, the pipeline does not derive a cursor from the rows. Unlike resumable
+state, a cursor outlives the job: it is the starting point of the next run.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+from abc import ABC, abstractmethod
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, ClassVar, Generic, Protocol, TypeVar, cast
+
+from structlog.types import FilteringBoundLogger
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+
+
+# The key in `ExternalDataSchema.sync_type_config` that holds the promoted cursor.
+SOURCE_CURSOR_KEY = "source_cursor"
+
+
+class SourceCursor(Protocol):
+ __dataclass_fields__: ClassVar[dict[str, Any]]
+ # Stored beside the cursor, so a stored cursor of another shape is never loaded into this class.
+ # It must stay stable: a changed kind discards every stored cursor of this class.
+ cursor_kind: ClassVar[str]
+
+
+CursorT = TypeVar("CursorT", bound=SourceCursor)
+
+
+class SourceCursorManager(Generic[CursorT]):
+ """The cursor one run reads from, and the cursor it stages for the pipeline to persist."""
+
+ def __init__(self, cursor_class: type[CursorT], stored: CursorT | None, source: CursorSource[CursorT]) -> None:
+ self._cursor_class = cursor_class
+ self._stored = stored
+ self._source = source
+ self._staged: CursorT | None = None
+
+ @classmethod
+ def from_sync_type_config(
+ cls,
+ source: CursorSource[CursorT],
+ sync_type_config: Mapping[str, Any] | None,
+ logger: FilteringBoundLogger,
+ ) -> SourceCursorManager[CursorT]:
+ """Build a manager from the stored schema config, or with no cursor when `sync_type_config` is None."""
+ cursor_class = source.cursor_class()
+ stored: CursorT | None = None
+ if sync_type_config is not None:
+ payload = sync_type_config.get(SOURCE_CURSOR_KEY)
+ if payload is None:
+ stored = source.cursor_from_legacy(sync_type_config)
+ else:
+ stored = _cursor_from_payload(cursor_class, payload, logger)
+ return cls(cursor_class, stored, source)
+
+ def load(self) -> CursorT | None:
+ return self._stored
+
+ def stage(self, cursor: CursorT) -> None:
+ """Hold `cursor` for the pipeline to persist after this run's rows are written.
+
+ Staging again replaces the earlier staged cursor. The source's `merge_cursors` runs against
+ the cursor this run loaded, so a run that read less never moves the stored cursor back.
+ """
+ self._staged = cursor if self._stored is None else self._source.merge_cursors(self._stored, cursor)
+
+ @property
+ def staged(self) -> CursorT | None:
+ return self._staged
+
+ def staged_payload(self) -> dict[str, Any] | None:
+ if self._staged is None:
+ return None
+ return cursor_to_payload(self._staged)
+
+
+class CursorSource(ABC, Generic[CursorT]):
+ """Capability for a source that keeps a durable cursor of its own between runs."""
+
+ @abstractmethod
+ def cursor_class(self) -> type[CursorT]: ...
+
+ def merge_cursors(self, current: CursorT, candidate: CursorT) -> CursorT:
+ """The cursor to store when a run stages `candidate` over the stored `current`."""
+ return candidate
+
+ def cursor_from_legacy(self, sync_type_config: Mapping[str, Any]) -> CursorT | None:
+ """Read a cursor that an earlier release stored under source-specific keys."""
+ return None
+
+ def get_cursor_manager(self, inputs: SourceInputs) -> SourceCursorManager[CursorT]:
+ if inputs.source_cursor is None:
+ raise ValueError(f"{type(self).__name__} ran without a source cursor manager")
+ return cast(SourceCursorManager[CursorT], inputs.source_cursor)
+
+
+def build_cursor_manager(
+ source: object, sync_type_config: Mapping[str, Any] | None, logger: FilteringBoundLogger
+) -> SourceCursorManager[Any] | None:
+ """The cursor manager for a `CursorSource`, or None for any other source."""
+ if not isinstance(source, CursorSource):
+ return None
+ return SourceCursorManager.from_sync_type_config(source, sync_type_config, logger)
+
+
+def cursor_to_payload(cursor: SourceCursor) -> dict[str, Any]:
+ return {"kind": cursor.cursor_kind, "data": dataclasses.asdict(cast(Any, cursor))}
+
+
+def merge_cursor_payloads(
+ source: object, current_payload: Any, candidate_payload: Any, logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ """Merge a staged cursor against the cursor stored at promotion time."""
+ if not isinstance(source, CursorSource):
+ raise ValueError(f"{type(source).__name__} does not support source cursors")
+ cursor_class = source.cursor_class()
+ candidate = _cursor_from_payload(cursor_class, candidate_payload, logger)
+ if candidate is None:
+ raise ValueError("The staged source cursor is invalid")
+ current = _cursor_from_payload(cursor_class, current_payload, logger)
+ return cursor_to_payload(candidate if current is None else source.merge_cursors(current, candidate))
+
+
+def _cursor_from_payload(cursor_class: type[CursorT], payload: Any, logger: FilteringBoundLogger) -> CursorT | None:
+ if not isinstance(payload, Mapping) or not isinstance(payload.get("data"), Mapping):
+ logger.warning("Discarding a stored source cursor that is not a mapping")
+ return None
+ if payload.get("kind") != cursor_class.cursor_kind:
+ logger.warning(
+ "Discarding a stored source cursor of another kind",
+ stored_kind=payload.get("kind"),
+ expected_kind=cursor_class.cursor_kind,
+ )
+ return None
+
+ # Fields the running code does not know come from a cursor that a newer deploy wrote. Dropping
+ # them lets a rollback keep running. Passing them through raises TypeError on every run.
+ data: Mapping[str, Any] = payload["data"]
+ known = {field.name for field in dataclasses.fields(cast(Any, cursor_class))}
+ try:
+ return cursor_class(**{name: value for name, value in data.items() if name in known})
+ except TypeError:
+ logger.warning("Discarding a stored source cursor that is missing fields", kind=cursor_class.cursor_kind)
+ return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_cursor.py
new file mode 100644
index 000000000000..d3974f705459
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_cursor.py
@@ -0,0 +1,98 @@
+from collections.abc import Mapping
+from typing import Any, ClassVar
+
+import pytest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import (
+ CursorSource,
+ SourceCursorManager,
+ merge_cursor_payloads,
+)
+
+
+@frozen
+class _OffsetsCursor:
+ cursor_kind: ClassVar[str] = "offsets"
+
+ offsets: dict[str, int]
+
+
+class _OffsetsSource(CursorSource[_OffsetsCursor]):
+ def cursor_class(self) -> type[_OffsetsCursor]:
+ return _OffsetsCursor
+
+ def merge_cursors(self, current: _OffsetsCursor, candidate: _OffsetsCursor) -> _OffsetsCursor:
+ merged = dict(current.offsets)
+ for partition, offset in candidate.offsets.items():
+ merged[partition] = max(offset, merged.get(partition, offset))
+ return _OffsetsCursor(offsets=merged)
+
+ def cursor_from_legacy(self, sync_type_config: Mapping[str, Any]) -> _OffsetsCursor | None:
+ legacy = sync_type_config.get("legacy_offsets")
+ return _OffsetsCursor(offsets=legacy) if legacy is not None else None
+
+
+def _manager(sync_type_config: dict[str, Any] | None) -> SourceCursorManager[_OffsetsCursor]:
+ return SourceCursorManager.from_sync_type_config(_OffsetsSource(), sync_type_config, MagicMock())
+
+
+class TestSourceCursorManager:
+ @parameterized.expand(
+ [
+ ("no_config_means_a_rebuild", None, None),
+ ("empty_config", {}, None),
+ ("stored_cursor", {"source_cursor": {"kind": "offsets", "data": {"offsets": {"0": 5}}}}, {"0": 5}),
+ (
+ "unknown_fields_from_a_newer_deploy_are_dropped",
+ {"source_cursor": {"kind": "offsets", "data": {"offsets": {"0": 5}, "added_later": 1}}},
+ {"0": 5},
+ ),
+ ("cursor_of_another_kind", {"source_cursor": {"kind": "postgres_xmin", "data": {"offsets": {}}}}, None),
+ ("cursor_missing_a_field", {"source_cursor": {"kind": "offsets", "data": {}}}, None),
+ ("malformed_payload", {"source_cursor": "not-a-mapping"}, None),
+ ("legacy_keys_when_no_cursor", {"legacy_offsets": {"0": 3}}, {"0": 3}),
+ (
+ "stored_cursor_wins_over_legacy_keys",
+ {"source_cursor": {"kind": "offsets", "data": {"offsets": {"0": 5}}}, "legacy_offsets": {"0": 3}},
+ {"0": 5},
+ ),
+ ]
+ )
+ def test_load(self, _name: str, sync_type_config: dict[str, Any] | None, expected: dict[str, int] | None) -> None:
+ loaded = _manager(sync_type_config).load()
+ assert (loaded.offsets if loaded is not None else None) == expected
+
+ @parameterized.expand(
+ [
+ ("no_stored_cursor_takes_the_candidate", None, {"0": 1, "1": 7}),
+ ("stage_merges_against_the_stored_cursor", {"0": 5, "1": 2}, {"0": 5, "1": 7}),
+ ]
+ )
+ def test_stage(self, _name: str, stored: dict[str, int] | None, expected: dict[str, int]) -> None:
+ config = None if stored is None else {"source_cursor": {"kind": "offsets", "data": {"offsets": stored}}}
+ manager = _manager(config)
+
+ manager.stage(_OffsetsCursor(offsets={"0": 1, "1": 7}))
+
+ assert manager.staged_payload() == {"kind": "offsets", "data": {"offsets": expected}}
+
+ def test_nothing_staged_has_no_payload(self) -> None:
+ assert _manager({}).staged_payload() is None
+
+ def test_promotion_merges_against_the_latest_stored_cursor(self) -> None:
+ current = {"kind": "offsets", "data": {"offsets": {"0": 20, "1": 5}}}
+ older_staged = {"kind": "offsets", "data": {"offsets": {"0": 10, "2": 7}}}
+
+ assert merge_cursor_payloads(_OffsetsSource(), current, older_staged, MagicMock()) == {
+ "kind": "offsets",
+ "data": {"offsets": {"0": 20, "1": 5, "2": 7}},
+ }
+
+ def test_get_cursor_manager_requires_a_manager_on_the_inputs(self) -> None:
+ with pytest.raises(ValueError):
+ _OffsetsSource().get_cursor_manager(MagicMock(source_cursor=None))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
index 9f611b8161f8..249c029104f7 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
@@ -15,6 +15,7 @@ if TYPE_CHECKING:
import pyarrow as pa
from dlt.common.data_types.typing import TDataType
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (
ValidatedRowFilter,
)
@@ -31,6 +32,13 @@ else:
def __repr__(self) -> str:
return "<ValidatedRowFilter: type-checking-only stub>"
+ class SourceCursorManager:
+ def __class_getitem__(cls, item: Any) -> type:
+ return cls
+
+ def __repr__(self) -> str:
+ return "<SourceCursorManager: type-checking-only stub>"
+
SortMode = Literal["asc", "desc"]
PartitionMode = Literal["md5", "numerical", "datetime"]
@@ -100,12 +108,6 @@ class SourceResponse:
"""Override the batcher's per-chunk byte cap (defaults to DEFAULT_CHUNK_SIZE_BYTES). Lower it for
sources whose rows are large (e.g. whole documents) so the source->Arrow conversion doesn't
materialise an oversized table and OOM the worker."""
- xmin_ceiling_xid: Optional[int] = None
- """xmin syncs: bare 32-bit ceiling captured this run, persisted as the next run's lower bound."""
- xmin_ceiling_xid8: Optional[int] = None
- """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,
@@ -169,3 +171,6 @@ class SourceInputs:
# Temporal's attempt number for this activity, starting at 1. A source can read a retry
# differently from a first run, because the first run has already shown what fails.
activity_attempt: int = 1
+ # Set for a source that implements `CursorSource`. It holds the cursor stored by the last
+ # successful run, or no cursor when this run rebuilds the table.
+ source_cursor: Optional[SourceCursorManager[Any]] = None
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 03b9613ad597..bdc4c30128fb 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
@@ -58,6 +58,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers
incremental_type_to_initial_value,
incremental_type_to_operator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
open_ssh_tunnel,
pinned_host_kwargs,
@@ -108,6 +109,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
iterate_partitions,
list_child_partitions,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.xmin_cursor import XminCursor
from products.warehouse_sources.backend.types import IncrementalFieldType, PartitionSettings
# Sources created after this date must use SSL/TLS connections
@@ -3496,8 +3498,7 @@ def postgres_source(
enabled_columns: Optional[list[str]] = None,
row_filters: Optional[list[ValidatedRowFilter]] = None,
is_xmin: bool = False,
- xmin_last_value: Optional[int] = None,
- xmin_num_wraparound: Optional[int] = None,
+ xmin_cursor: Optional[SourceCursorManager[XminCursor]] = None,
byte_bounded_extraction: bool = False,
activity_attempt: int = 1,
resumable_source_manager: Optional[ResumableSourceManager[KeysetResumeState]] = None,
@@ -3571,8 +3572,9 @@ def postgres_source(
setup_connection_dropped_errors = 0
# Captured once at sync start on the row-serving connection (see `_capture_xmin_ceiling`).
# Re-derived on each setup retry, which is harmless — a later ceiling just reads a slightly
- # wider window. Persisted only at job completion (see the pipeline's xmin advance).
+ # wider window. Staged on `xmin_cursor` below, and persisted only once the run's rows are durable.
xmin_bounds: XminBounds | None = None
+ stored_xmin = xmin_cursor.load() if xmin_cursor is not None else None
while True:
# Opening the setup connection can itself hit a transient drop ("server closed the
# connection unexpectedly", idle cull, failover) — the same class of error the read
@@ -3619,7 +3621,12 @@ def postgres_source(
# Capture the xmin ceiling on this row-serving connection before streaming.
if is_xmin:
- xmin_bounds = _capture_xmin_ceiling(cursor, xmin_last_value, xmin_num_wraparound, logger)
+ xmin_bounds = _capture_xmin_ceiling(
+ cursor,
+ stored_xmin.ceiling_xid if stored_xmin is not None else None,
+ stored_xmin.num_wraparound if stored_xmin is not None else None,
+ logger,
+ )
try:
logger.debug("Checking if source is a read replica...")
@@ -4565,6 +4572,15 @@ def postgres_source(
name = NamingConvention.normalize_identifier(table_name)
+ if xmin_cursor is not None and xmin_bounds is not None:
+ xmin_cursor.stage(
+ XminCursor(
+ ceiling_xid=xmin_bounds.upper,
+ ceiling_xid8=xmin_bounds.ceiling_xid8,
+ num_wraparound=xmin_bounds.num_wraparound,
+ )
+ )
+
return SourceResponse(
name=name,
items=lambda: get_rows(chunk_size),
@@ -4573,9 +4589,6 @@ def postgres_source(
partition_size=partition_settings.partition_size if partition_settings else None,
rows_to_sync=rows_to_sync,
has_duplicate_primary_keys=has_duplicate_primary_keys,
- xmin_ceiling_xid=xmin_bounds.upper if xmin_bounds is not None else None,
- xmin_ceiling_xid8=xmin_bounds.ceiling_xid8 if xmin_bounds is not None else None,
- xmin_num_wraparound=xmin_bounds.num_wraparound if xmin_bounds is not None else None,
# Both halves, because a run that seeks without a persistable key still cannot hand its
# position to another pod, and one that could checkpoint but reads through a server cursor
# has no position to hand over. `supports_resume` defaults to True, so this must be explicit.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
index 092fa4590e05..6c4d249a4d41 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
@@ -1,5 +1,6 @@
import logging
-from typing import TYPE_CHECKING, Optional, cast
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, Optional, cast
import structlog
from psycopg import OperationalError
@@ -27,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
FieldType,
ResumableSource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import CursorSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
HOST_RESOLUTION_EXHAUSTED_MESSAGE,
HostNotAllowedError,
@@ -73,6 +75,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
postgres_source,
source_requires_ssl,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.xmin_cursor import (
+ XminCursor,
+ xmin_cursor_from_legacy,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalField, IncrementalFieldType
log = logging.getLogger(__name__)
@@ -378,6 +384,7 @@ _RECOVERY_CONFLICT_EXHAUSTED_MESSAGE = (
class PostgresSource(
SQLSource[PostgresSourceConfig],
ResumableSource[PostgresSourceConfig, KeysetResumeState],
+ CursorSource[XminCursor],
SSHTunnelMixin,
ValidateDatabaseHostMixin,
):
@@ -385,6 +392,15 @@ class PostgresSource(
# `SourceSchema.supports_xmin` at discovery.
supports_xmin = True
+ def cursor_class(self) -> type[XminCursor]:
+ return XminCursor
+
+ def cursor_from_legacy(self, sync_type_config: Mapping[str, Any]) -> XminCursor | None:
+ return xmin_cursor_from_legacy(sync_type_config)
+
+ def merge_cursors(self, current: XminCursor, candidate: XminCursor) -> XminCursor:
+ return max(current, candidate, key=lambda cursor: cursor.ceiling_xid8)
+
def resume_covers_run(self, *, incremental_or_append: bool, keyset_full_load_enabled: bool = False) -> bool:
# Both halves. Keyset seeking is a full-load path, so an incremental or xmin run resumes from
# its watermark and keeps the incremental budget. And a full load only resumes once the flag
@@ -2009,16 +2025,11 @@ class PostgresSource(
is_initial_sync=not schema.initial_sync_complete,
enabled_columns=inputs.enabled_columns,
row_filters=inputs.row_filters,
- # xmin state is read straight off the schema here (the generic `SourceInputs` stays
- # Postgres-agnostic). xmin rides the normal full per-schema path — no CDC dispatch.
- # A reset, and a pending corrupt-delta revive, both delete the Delta table before
- # this read, so the cursor has to go with it: kept, the read covers only the window
- # since the last run, and the overwrite collapses the table to that slice. The
- # activity drops the incremental cursor for both cases for the same reason; the xmin
- # cursor is dropped here because it is read here.
+ # xmin rides the normal full per-schema path, with no CDC dispatch. On a reset or a
+ # pending corrupt-delta revive the activity loads no cursor, because both delete the
+ # Delta table before this read and a kept cursor would collapse it to one window.
is_xmin=schema.is_xmin,
- xmin_last_value=None if table_rebuild_pending else schema.xmin_last_value,
- xmin_num_wraparound=None if table_rebuild_pending else schema.xmin_num_wraparound,
+ xmin_cursor=self.get_cursor_manager(inputs) if schema.is_xmin else None,
byte_bounded_extraction=inputs.byte_bounded_extraction,
activity_attempt=inputs.activity_attempt,
resumable_source_manager=resumable_source_manager,
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 3ebe88cf8866..289d697e4cf7 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
@@ -4342,7 +4342,6 @@ class TestChunkedRereadAfterRecoveryConflict:
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,
activity_attempt=activity_attempt,
resumable_source_manager=resumable_source_manager,
keyset_full_load_enabled=keyset_full_load_enabled,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/xmin_cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/xmin_cursor.py
new file mode 100644
index 000000000000..91baf0dc7517
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/xmin_cursor.py
@@ -0,0 +1,28 @@
+from collections.abc import Mapping
+from typing import Any, ClassVar
+
+from posthog.dataclasses import frozen
+
+# Where xmin state was stored before `source_cursor`. Read only when a schema has no `source_cursor`.
+XMIN_LEGACY_KEYS = ("xmin_last_value", "xmin_ceiling", "xmin_num_wraparound")
+
+
+@frozen
+class XminCursor:
+ """The xmin ceiling of the last run that completed, and the lower bound of the next run."""
+
+ cursor_kind: ClassVar[str] = "postgres_xmin"
+
+ # Bare 32-bit xid, compared against tuple `xmin`.
+ ceiling_xid: int
+ # Full 64-bit `xid8`, the wraparound-safe form of the ceiling.
+ ceiling_xid8: int
+ # Epoch of the ceiling, which is the high 32 bits of `ceiling_xid8`.
+ num_wraparound: int
+
+
+def xmin_cursor_from_legacy(sync_type_config: Mapping[str, Any]) -> XminCursor | None:
+ ceiling_xid, ceiling_xid8, num_wraparound = (sync_type_config.get(key) for key in XMIN_LEGACY_KEYS)
+ if not isinstance(ceiling_xid, int) or not isinstance(ceiling_xid8, int) or not isinstance(num_wraparound, int):
+ return None
+ return XminCursor(ceiling_xid=ceiling_xid, ceiling_xid8=ceiling_xid8, num_wraparound=num_wraparound)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index f9fb6e25c98d..3c3617b1fc4a 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
@@ -100,6 +100,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
XminBounds,
_TableChunking,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.xmin_cursor import XminCursor
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (
BALANCE_TRANSACTION_RESOURCE_NAME as STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,
CHARGE_RESOURCE_NAME as STRIPE_CHARGE_RESOURCE_NAME,
@@ -4948,6 +4949,11 @@ def _postgres_job_inputs(postgres_config: dict) -> dict[str, str | dict[str, str
}
+def _stored_xmin_cursor(schema: ExternalDataSchema) -> XminCursor | None:
+ payload = schema.sync_type_config.get("source_cursor")
+ return XminCursor(**payload["data"]) if payload else None
+
+
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_postgres_xmin_sync(team, postgres_config, postgres_connection):
@@ -4979,10 +4985,8 @@ async def test_postgres_xmin_sync(team, postgres_config, postgres_connection):
# Ceiling state persisted at job completion (next run's lower bound + durable cursor + epoch).
schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)
- assert schema.xmin_last_value is not None
- assert schema.xmin_ceiling is not None
- assert schema.xmin_num_wraparound is not None
- first_ceiling = schema.xmin_last_value
+ first_cursor = _stored_xmin_cursor(schema)
+ assert first_cursor is not None
# Mutate: update the existing row and insert a new one. Both get a fresh xmin above the ceiling.
await postgres_connection.execute(
@@ -5002,8 +5006,9 @@ async def test_postgres_xmin_sync(team, postgres_config, postgres_connection):
# Ceiling advanced strictly past the first run's value — the delta committed new transactions.
schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)
- assert schema.xmin_last_value is not None
- assert schema.xmin_last_value > first_ceiling
+ second_cursor = _stored_xmin_cursor(schema)
+ assert second_cursor is not None
+ assert second_cursor.ceiling_xid8 > first_cursor.ceiling_xid8
# Hard deletes are invisible to xmin — a vacuumed tuple leaves nothing to read.
await postgres_connection.execute("DELETE FROM {schema}.xmin_table WHERE id = 2".format(schema=schema_name))
@@ -5115,7 +5120,7 @@ async def test_postgres_switch_to_xmin_rebuilds_table(team, postgres_config, pos
# Reset consumed: xmin state seeded fresh, reset_pipeline cleared.
schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)
assert schema.sync_type_config.get("reset_pipeline") is None
- assert schema.xmin_last_value is not None
+ assert _stored_xmin_cursor(schema) is not None
# --- Destinations ------------------------------------------------------------------------
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
index 22219e785fd6..02da25e53447 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
@@ -78,20 +78,26 @@ def _setup(
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "rebuild_trigger",
+ "rebuild_trigger,expected_ceiling",
[
- {"reset_pipeline": True},
- {
- "delta_revive_required": {
- "reason": "hollow",
- "missing_path": "p",
- "detected_at": "2026-01-01T00:00:00+00:00",
- }
- },
+ ({}, 100),
+ ({"reset_pipeline": True}, None),
+ (
+ {
+ "delta_revive_required": {
+ "reason": "hollow",
+ "missing_path": "p",
+ "detected_at": "2026-01-01T00:00:00+00:00",
+ }
+ },
+ None,
+ ),
],
- ids=["reset", "corrupt_delta_revive"],
+ ids=["no_rebuild", "reset", "corrupt_delta_revive"],
)
-async def test_table_rebuild_drops_the_xmin_cursor(activity_environment, team, rebuild_trigger, **kwargs):
+async def test_table_rebuild_drops_the_xmin_cursor(
+ activity_environment, team, rebuild_trigger, expected_ceiling, **kwargs
+):
# Both triggers delete the Delta table before the read. Keeping the cursor makes that read the
# window since the last run, and the overwrite collapses the table to that slice.
activity_inputs = await _setup(
@@ -117,8 +123,8 @@ async def test_table_rebuild_drops_the_xmin_cursor(activity_environment, team, r
called_with = mock_postgres_source.call_args.kwargs
assert called_with["is_xmin"] is True
- assert called_with["xmin_last_value"] is None
- assert called_with["xmin_num_wraparound"] is None
+ stored = called_with["xmin_cursor"].load()
+ assert (stored.ceiling_xid if stored is not None else None) == expected_ceiling
@pytest.mark.django_db(transaction=True)
@@ -169,8 +175,7 @@ async def test_job_inputs_with_whitespace(activity_environment, team, **kwargs):
enabled_columns=None,
row_filters=[],
is_xmin=False,
- xmin_last_value=None,
- xmin_num_wraparound=None,
+ xmin_cursor=None,
byte_bounded_extraction=False,
activity_attempt=1,
resumable_source_manager=mock.ANY,
@@ -226,8 +231,7 @@ async def test_postgres_source_without_ssh_tunnel(activity_environment, team, **
enabled_columns=None,
row_filters=[],
is_xmin=False,
- xmin_last_value=None,
- xmin_num_wraparound=None,
+ xmin_cursor=None,
byte_bounded_extraction=False,
activity_attempt=1,
resumable_source_manager=mock.ANY,
@@ -295,8 +299,7 @@ async def test_postgres_source_with_ssh_tunnel_disabled(activity_environment, te
enabled_columns=None,
row_filters=[],
is_xmin=False,
- xmin_last_value=None,
- xmin_num_wraparound=None,
+ xmin_cursor=None,
byte_bounded_extraction=False,
activity_attempt=1,
resumable_source_manager=mock.ANY,
@@ -379,8 +382,7 @@ async def test_postgres_source_with_ssh_tunnel_enabled(activity_environment, tea
enabled_columns=None,
row_filters=[],
is_xmin=False,
- xmin_last_value=None,
- xmin_num_wraparound=None,
+ xmin_cursor=None,
byte_bounded_extraction=False,
activity_attempt=1,
resumable_source_manager=mock.ANY,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index 992b43b11947..4a0da2dd1b3e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -69,6 +69,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.byte_bounded_extraction_flag import (
is_byte_bounded_extraction_enabled,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import (
+ SourceCursorManager,
+ build_cursor_manager,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.errors import (
is_transient_egress_proxy_error,
)
@@ -519,6 +523,11 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
source_type=source_type,
)
+ # A reset or a revive empties the table, so the run starts from no cursor, like the watermark above.
+ source_cursor_manager = build_cursor_manager(
+ new_source, schema.sync_type_config if use_stored_cursors else None, logger
+ )
+
source_inputs = SourceInputs(
schema_name=schema.name,
schema_id=str(schema.id),
@@ -553,6 +562,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
byte_bounded_extraction=byte_bounded_extraction,
keyset_full_load=inputs.keyset_full_load_enabled,
activity_attempt=activity.info().attempt if activity.in_activity() else 1,
+ source_cursor=source_cursor_manager,
)
try:
@@ -633,6 +643,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
reset_pipeline=reset_pipeline,
shutdown_monitor=shutdown_monitor,
resumable_source_manager=resumable_source_manager,
+ source_cursor_manager=source_cursor_manager,
)
else:
raise ValueError(f"Source type {model.pipeline.source_type} not supported")
@@ -924,6 +935,7 @@ async def _run(
reset_pipeline: bool,
shutdown_monitor: ShutdownMonitor,
resumable_source_manager: ResumableSourceManager | None,
+ source_cursor_manager: SourceCursorManager[Any] | None = None,
) -> PipelineResult:
try:
models = await _get_models(job_inputs.run_id)
@@ -942,6 +954,7 @@ async def _run(
shutdown_monitor,
resumable_source_manager,
models=models,
+ source_cursor_manager=source_cursor_manager,
)
else:
pipeline = PipelineNonDLT(
@@ -952,6 +965,7 @@ async def _run(
shutdown_monitor,
resumable_source_manager,
models=models,
+ source_cursor_manager=source_cursor_manager,
)
result = await pipeline.run()
diff --git a/products/warehouse_sources/backend/tests/management/test_reset_wrapped_xmin_cursors.py b/products/warehouse_sources/backend/tests/management/test_reset_wrapped_xmin_cursors.py
index 3884123464c3..65bb543b7080 100644
--- a/products/warehouse_sources/backend/tests/management/test_reset_wrapped_xmin_cursors.py
+++ b/products/warehouse_sources/backend/tests/management/test_reset_wrapped_xmin_cursors.py
@@ -5,9 +5,16 @@ from posthog.test.base import BaseTest
from django.core.management import call_command
+from parameterized import parameterized
+
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import cursor_to_payload
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.xmin_cursor import (
+ XminCursor,
+ xmin_cursor_from_legacy,
+)
class TestResetWrappedXminCursors(BaseTest):
@@ -27,16 +34,24 @@ class TestResetWrappedXminCursors(BaseTest):
sync_type_config=sync_type_config,
)
- def _xmin_schema(self, name: str, *, num_wraparound: int) -> ExternalDataSchema:
- return self._schema(
- name,
- sync_type=ExternalDataSchema.SyncType.XMIN,
- sync_type_config={
- "xmin_last_value": 500,
- "xmin_ceiling": (num_wraparound << 32) | 500,
- "xmin_num_wraparound": num_wraparound,
- },
+ def _xmin_schema(self, name: str, *, num_wraparound: int, legacy: bool = False) -> ExternalDataSchema:
+ cursor = XminCursor(ceiling_xid=500, ceiling_xid8=(num_wraparound << 32) | 500, num_wraparound=num_wraparound)
+ sync_type_config = (
+ {
+ "xmin_last_value": cursor.ceiling_xid,
+ "xmin_ceiling": cursor.ceiling_xid8,
+ "xmin_num_wraparound": cursor.num_wraparound,
+ }
+ if legacy
+ else {"source_cursor": cursor_to_payload(cursor)}
)
+ return self._schema(name, sync_type=ExternalDataSchema.SyncType.XMIN, sync_type_config=sync_type_config)
+
+ def _ceiling_xid(self, schema: ExternalDataSchema) -> int | None:
+ schema.refresh_from_db()
+ payload = schema.sync_type_config.get("source_cursor")
+ cursor = XminCursor(**payload["data"]) if payload else xmin_cursor_from_legacy(schema.sync_type_config)
+ return cursor.ceiling_xid if cursor else None
def _running_job(self, schema: ExternalDataSchema) -> ExternalDataJob:
return ExternalDataJob.objects.create(
@@ -58,12 +73,12 @@ class TestResetWrappedXminCursors(BaseTest):
output = self._run()
assert str(schema.id) in output
- schema.refresh_from_db()
- assert schema.xmin_last_value == 500
+ assert self._ceiling_xid(schema) == 500
- def test_live_run_clears_only_wrapped_xmin_cursors(self) -> None:
- wrapped = self._xmin_schema("orders", num_wraparound=12)
- never_wrapped = self._xmin_schema("customers", num_wraparound=0)
+ @parameterized.expand([("source_cursor", False), ("legacy_keys", True)])
+ def test_live_run_clears_only_wrapped_xmin_cursors(self, _name: str, legacy: bool) -> None:
+ wrapped = self._xmin_schema("orders", num_wraparound=12, legacy=legacy)
+ never_wrapped = self._xmin_schema("customers", num_wraparound=0, legacy=legacy)
incremental = self._schema(
"events",
sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
@@ -72,13 +87,8 @@ class TestResetWrappedXminCursors(BaseTest):
self._run(live_run=True)
- wrapped.refresh_from_db()
- assert wrapped.xmin_last_value is None
- assert wrapped.xmin_ceiling is None
- assert wrapped.xmin_num_wraparound is None
-
- never_wrapped.refresh_from_db()
- assert never_wrapped.xmin_last_value == 500
+ assert self._ceiling_xid(wrapped) is None
+ assert self._ceiling_xid(never_wrapped) == 500
incremental.refresh_from_db()
assert incremental.sync_type_config["incremental_field_last_value"] == "5"
@@ -89,8 +99,7 @@ class TestResetWrappedXminCursors(BaseTest):
output = self._run(live_run=True)
- wrapped.refresh_from_db()
- assert wrapped.xmin_last_value == 500
+ assert self._ceiling_xid(wrapped) == 500
assert "sync is running" in output
def test_named_schemas_skip_the_wraparound_filter(self) -> None:
@@ -98,5 +107,4 @@ class TestResetWrappedXminCursors(BaseTest):
self._run(live_run=True, schema_id=[str(never_wrapped.id)])
- never_wrapped.refresh_from_db()
- assert never_wrapped.xmin_last_value is None
+ assert self._ceiling_xid(never_wrapped) is None
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index cda8a6c60e8c..fa490e9f1efe 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -192,16 +192,17 @@ class TestExternalDataSchemaActivityLogging(BaseTest):
assert schema.initial_sync_complete is False
assert "xmin_last_value" not in schema.sync_type_config
- def test_update_xmin_state_save_skips_activity_log(self) -> None:
+ def test_update_source_cursor_save_skips_activity_log(self) -> None:
schema = self._create(sync_type=ExternalDataSchema.SyncType.XMIN, sync_type_config={})
+ payload = {"kind": "postgres_xmin", "data": {"ceiling_xid": 100}}
model_activity_signal.connect(self._signal_handler, sender=ExternalDataSchema)
try:
- schema.update_xmin_state(ceiling_xid=100, ceiling_xid8=4294967396, num_wraparound=1)
+ schema.update_source_cursor(payload)
assert not self.signal_received
finally:
model_activity_signal.disconnect(self._signal_handler, sender=ExternalDataSchema)
schema.refresh_from_db()
- assert schema.xmin_last_value == 100
+ assert schema.sync_type_config["source_cursor"] == payload
def test_update_incremental_field_value_save_skips_activity_log(self) -> None:
schema = self._create(
@@ -903,25 +904,6 @@ def test_table_row_count_is_cumulative(sync_type: str | None, expected: bool) ->
assert ExternalDataSchema(sync_type=sync_type).table_row_count_is_cumulative is expected
- "sync_type_config,expected",
- [
- ({"xmin_last_value": 42, "xmin_ceiling": (1 << 32) + 42, "xmin_num_wraparound": 1}, (42, (1 << 32) + 42, 1)),
- ({}, (None, None, None)),
- (None, (None, None, None)),
- ],
-)
-def test_xmin_accessors(sync_type_config: dict | None, expected: tuple) -> None:
- schema = ExternalDataSchema(sync_type_config=sync_type_config)
- assert (schema.xmin_last_value, schema.xmin_ceiling, schema.xmin_num_wraparound) == expected
-
-
-def test_update_xmin_state_writes_all_keys() -> None:
- schema = ExternalDataSchema(sync_type_config={})
- schema.update_xmin_state(ceiling_xid=100, ceiling_xid8=4294967396, num_wraparound=1, save=False)
- assert (schema.xmin_last_value, schema.xmin_ceiling, schema.xmin_num_wraparound) == (100, 4294967396, 1)
-
-
@contextmanager
def _merge_in_memory(schema: ExternalDataSchema) -> Iterator[None]:
def apply(
@@ -947,20 +929,38 @@ def _merge_in_memory(schema: ExternalDataSchema) -> Iterator[None]:
yield
-def test_reset_pipeline_clears_xmin_state() -> None:
+ "sync_type_config",
+ [
+ {"source_cursor": {"kind": "postgres_xmin", "data": {"ceiling_xid": 100}}},
+ {"xmin_last_value": 100, "xmin_ceiling": 4294967396, "xmin_num_wraparound": 1},
+ ],
+)
+def test_reset_pipeline_clears_the_source_cursor(sync_type_config: dict[str, Any]) -> None:
schema = ExternalDataSchema(
sync_type=ExternalDataSchema.SyncType.XMIN,
- sync_type_config={"xmin_last_value": 100, "xmin_ceiling": 4294967396, "xmin_num_wraparound": 1},
+ sync_type_config=dict(sync_type_config),
initial_sync_complete=True,
)
with _merge_in_memory(schema):
schema.update_sync_type_config_for_reset_pipeline()
- assert "xmin_last_value" not in schema.sync_type_config
- assert "xmin_ceiling" not in schema.sync_type_config
- assert "xmin_num_wraparound" not in schema.sync_type_config
+ assert not set(sync_type_config) & set(schema.sync_type_config)
assert schema.initial_sync_complete is False
+def test_clear_source_cursor_drops_the_legacy_keys_it_is_given() -> None:
+ schema = ExternalDataSchema(
+ sync_type_config={
+ "source_cursor": {"kind": "postgres_xmin", "data": {}},
+ "xmin_last_value": 100,
+ "primary_key_columns": ["id"],
+ }
+ )
+ with _merge_in_memory(schema):
+ schema.clear_source_cursor(legacy_keys=["xmin_last_value"])
+ assert schema.sync_type_config == {"primary_key_columns": ["id"]}
+
+
def test_reset_pipeline_preserves_partition_overrides_but_clears_auto_detected() -> None:
# The operator pins a count via the admin repartition action; it must survive the reset
# that repartition bundles, while the auto-detected partition_count is wiped so it gets
@@ -1199,6 +1199,15 @@ def test_apply_incremental_lookback(value, field_type, lookback_seconds, expecte
class TestStagedIncrementalCursor:
+ @staticmethod
+ def _merge_kafka_offsets(current: Any, candidate: Any) -> dict[str, Any]:
+ current_offsets = current["data"]["offsets"]
+ candidate_offsets = candidate["data"]["offsets"]
+ merged_offsets = dict(current_offsets)
+ for partition, offset in candidate_offsets.items():
+ merged_offsets[partition] = max(merged_offsets.get(partition, offset), offset)
+ return {"kind": "kafka", "data": {"offsets": merged_offsets}}
+
def _make_schema(self, **config: object) -> ExternalDataSchema:
schema = ExternalDataSchema(
sync_type_config={
@@ -1413,6 +1422,35 @@ class TestStagedIncrementalCursor:
assert result is False
assert "incremental_field_last_value" not in schema.sync_type_config
+ def test_promote_merges_the_source_cursor_with_the_current_value(self) -> None:
+ current_cursor = {"kind": "kafka", "data": {"offsets": {"0": 50}}}
+ schema = self._make_schema(source_cursor=current_cursor)
+ staged_cursor = {"kind": "kafka", "data": {"offsets": {"0": 10}}}
+ with self._staged_in_memory(schema):
+ schema.stage_incremental_field_value("run-1", 42)
+ schema.stage_source_cursor("run-1", staged_cursor)
+ assert (
+ schema.promote_staged_incremental_values("run-1", merge_source_cursors=self._merge_kafka_offsets)
+ is True
+ )
+ assert schema.sync_type_config["source_cursor"] == current_cursor
+ assert schema.sync_type_config["incremental_field_last_value"] == 42
+ assert "incremental_staged" not in schema.sync_type_config
+
+ def test_an_older_displaced_source_cursor_cannot_replace_a_newer_cursor(self) -> None:
+ older_cursor = {"kind": "kafka", "data": {"offsets": {"0": 10}}}
+ newer_cursor = {"kind": "kafka", "data": {"offsets": {"0": 20}}}
+ schema = self._make_schema(
+ source_cursor=newer_cursor,
+ incremental_staged_pending=[{"run_uuid": "run-1", "source_cursor": older_cursor}],
+ )
+ with self._staged_in_memory(schema):
+ assert (
+ schema.promote_staged_incremental_values("run-1", merge_source_cursors=self._merge_kafka_offsets)
+ is True
+ )
+ assert schema.sync_type_config["source_cursor"] == newer_cursor
+
def test_promote_returns_false_when_no_staged(self) -> None:
schema = self._make_schema()
with self._staged_in_memory(schema):