Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(warehouse-sources): keep a displaced staged cursor promotable (#97524)

jake sciottoe52104bfcfd1
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 00e47a77f084..6e7f6ab0b9a9 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -24,6 +24,9 @@ from posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMe
from posthog.sync import database_sync_to_async
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
+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.typings import (
PartitionFormat,
PartitionMode,
@@ -167,6 +170,11 @@ def _schema_ids_with_running_jobs(schema_ids: list[uuid.UUID]) -> set[uuid.UUID]
)
+# A run parks one cursor per displaced attempt, so the bound must cover the largest attempt cap an
+# import activity gets. The trim keeps the newest entries, and a live run's entries are the newest.
+STAGED_CURSOR_PENDING_LIMIT = MAX_RESUMABLE_SOURCE_RETRIES_PRODUCTION
+
+
class ExternalDataSchemaQuerySet(models.QuerySet["ExternalDataSchema"]):
def update(self, **kwargs: Any) -> int:
"""Chokepoint for bulk writes that stop a schema from syncing.
@@ -914,31 +922,68 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
self._save_sync_type_config()
def stage_incremental_field_value(self, run_uuid: str, last_value: Any, earliest_value: Any = None) -> None:
- existing = self.sync_type_config.get("incremental_staged", {})
- if existing.get("run_uuid") == run_uuid:
- staged = existing
- else:
- staged = {"run_uuid": run_uuid}
- if last_value is not None:
- staged["last_value"] = self._serialize_incremental_value(last_value)
- if earliest_value is not None:
- staged["earliest_value"] = self._serialize_incremental_value(earliest_value)
- self.sync_type_config["incremental_staged"] = staged
- # Pipeline-internal bookkeeping, not a user edit — skip_activity_log avoids the extra
- # `_get_before_update` SELECT (see save()).
- self.save(skip_activity_log=True)
+ """Hold a run's cursor in `incremental_staged` until the load side promotes it.
+
+ The outgoing attempt of a run and the incoming attempt stage concurrently, and each holds its
+ own in-memory copy of this row. The merge runs under the row lock so neither copy erases the
+ other's entry.
+ """
+ values = {
+ key: self._serialize_incremental_value(value)
+ for key, value in (("last_value", last_value), ("earliest_value", earliest_value))
+ if value is not None
+ }
+
+ def mutate(config: dict[str, Any]) -> None:
+ live = config.get("incremental_staged", {})
+ if live.get("run_uuid") == run_uuid:
+ staged = live
+ else:
+ # A run that stages after a newer attempt displaced it continues its parked cursor,
+ # so one run's values are never split between the live slot and the parked list.
+ staged = _drop_parked_staged_cursor(config, run_uuid) or {"run_uuid": run_uuid}
+ _park_displaced_staged_cursor(config, live)
+ staged.update(values)
+ config["incremental_staged"] = staged
+
+ # Deferred: this module loads during django.setup() and the util pulls in temporalio.
+ from posthog.temporal.common.utils import retry_on_db_connection_drop # noqa: PLC0415
+
+ self.sync_type_config = retry_on_db_connection_drop(
+ lambda: update_sync_type_config_keys(self.id, self.team_id, mutate=mutate)
+ )
def promote_staged_incremental_values(self, run_uuid: str) -> bool:
- staged = self.sync_type_config.get("incremental_staged")
- if not staged or staged.get("run_uuid") != run_uuid:
- return False
- if "last_value" in staged:
- self.sync_type_config["incremental_field_last_value"] = staged["last_value"]
- if "earliest_value" in staged:
- self.sync_type_config["incremental_field_earliest_value"] = staged["earliest_value"]
- self.sync_type_config.pop("incremental_staged", None)
- self.save(skip_activity_log=True)
- return True
+ """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.
+ The monotonic guard can still keep the current watermark, so True does not mean a key changed.
+ """
+ found = False
+
+ def mutate(config: dict[str, Any]) -> None:
+ nonlocal found
+ live: dict[str, Any] | None = config.get("incremental_staged")
+ if live is not None and live.get("run_uuid") != run_uuid:
+ live = None
+ staged = live if live is not None else _drop_parked_staged_cursor(config, run_uuid)
+ if staged is None:
+ return
+ found = True
+ field_type = config.get("incremental_field_type")
+ if "last_value" in staged:
+ _advance_promoted_cursor(
+ config, "incremental_field_last_value", staged["last_value"], "last", field_type
+ )
+ if "earliest_value" in staged:
+ _advance_promoted_cursor(
+ config, "incremental_field_earliest_value", staged["earliest_value"], "earliest", field_type
+ )
+ if live is not None:
+ config.pop("incremental_staged", None)
+
+ self.sync_type_config = update_sync_type_config_keys(self.id, self.team_id, mutate=mutate)
+ return found
def _serialize_incremental_value(self, value: Any) -> Any:
incremental_field_type = self.sync_type_config.get("incremental_field_type")
@@ -979,6 +1024,7 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
self.sync_type_config.pop("incremental_field_last_value", None)
self.sync_type_config.pop("incremental_field_earliest_value", None)
self.sync_type_config.pop("incremental_staged", None)
+ self.sync_type_config.pop("incremental_staged_pending", None)
self.sync_type_config.pop("partitioning_enabled", None)
self.sync_type_config.pop("partition_size", None)
self.sync_type_config.pop("partition_count", None)
@@ -1123,6 +1169,89 @@ def _parse_datetime_string(value: str) -> datetime:
return parser.parse(stripped)
+def _align_epoch_cursor(value: Any, partner: Any) -> Any:
+ # Two epoch numbers already order as numbers, so only a mixed pair needs the conversion.
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ return value
+ if not isinstance(partner, datetime | date):
+ return value
+ converted = datetime.fromtimestamp(value, tz=UTC)
+ if isinstance(partner, datetime):
+ return converted if partner.tzinfo else converted.replace(tzinfo=None)
+ return converted.date()
+
+
+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()):
+ return
+ pending = [*config.get("incremental_staged_pending", []), staged]
+ config["incremental_staged_pending"] = pending[-STAGED_CURSOR_PENDING_LIMIT:]
+
+
+def _drop_parked_staged_cursor(config: dict[str, Any], run_uuid: str) -> dict[str, Any] | None:
+ """Remove the parked cursor of `run_uuid` and return it, or None when the run has none."""
+ pending = config.get("incremental_staged_pending", [])
+ dropped = next((entry for entry in pending if entry.get("run_uuid") == run_uuid), None)
+ if dropped is None:
+ return None
+ remaining = [entry for entry in pending if entry.get("run_uuid") != run_uuid]
+ if remaining:
+ config["incremental_staged_pending"] = remaining
+ else:
+ config.pop("incremental_staged_pending", None)
+ return dropped
+
+
+def _advance_promoted_cursor(
+ config: dict[str, Any],
+ key: str,
+ value: Any,
+ kind: Literal["last", "earliest"],
+ field_type: IncrementalFieldType | None,
+) -> None:
+ current = config.get(key)
+ if current is None:
+ config[key] = value
+ return
+ comparison = _compare_incremental_values(current, value, field_type)
+ # For a pair the comparator cannot order (a null field type, a naive against an aware datetime,
+ # or a millisecond epoch) the newest promotion wins, so those sources still advance their
+ # watermark. Keeping the current value would freeze it for good.
+ if comparison is None or (kind == "last" and comparison < 0) or (kind == "earliest" and comparison > 0):
+ config[key] = value
+
+
+def _compare_incremental_values(current: Any, candidate: Any, field_type: IncrementalFieldType | None) -> int | None:
+ try:
+ left = process_incremental_value(current, field_type)
+ right = process_incremental_value(candidate, field_type)
+ left, right = _align_epoch_cursor(left, right), _align_epoch_cursor(right, left)
+ except Exception:
+ return None
+ if left is None or right is None:
+ return None
+ if field_type == IncrementalFieldType.ObjectID:
+ # An ObjectID is 24 hex digits that open with its creation time, so equal-length ids order
+ # as strings. Anything else is unordered.
+ if isinstance(left, str) and isinstance(right, str) and len(left) == len(right):
+ return (left > right) - (left < right)
+ return None
+ if isinstance(left, bool) or isinstance(right, bool):
+ return None
+ left_is_number = isinstance(left, int | float)
+ right_is_number = isinstance(right, int | float)
+ if left_is_number != right_is_number:
+ return None
+ if not left_is_number and not isinstance(left, datetime | date):
+ return None
+ try:
+ return (left > right) - (left < right)
+ except TypeError:
+ return None
+
+
def _coerce_incremental_datetime(value: str) -> datetime | int:
"""Parse a DateTime/Timestamp/Date cursor string, falling back to a raw integer.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index c769891df0f5..8ee5a0234cef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -69,6 +69,9 @@ from products.warehouse_sources.backend.temporal.data_imports.post_import_job im
PostImportWorkflowInputs,
build_post_import_workflow_id,
)
+from products.warehouse_sources.backend.temporal.data_imports.retry_limits import (
+ MAX_RESUMABLE_SOURCE_RETRIES_PRODUCTION,
+)
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import finish_row_tracking, get_rows
from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
@@ -127,7 +130,7 @@ LOGGER = get_logger(__name__)
# Cap retries at 3 in local dev so failing syncs don't loop for tens of minutes while developers
# iterate; prod cadence is unchanged. Defined at module level so tests can patch them to keep the
# expensive retry-exhaustion paths fast.
-MAX_RESUMABLE_SOURCE_RETRIES = 3 if settings.DEBUG else 20
+MAX_RESUMABLE_SOURCE_RETRIES = 3 if settings.DEBUG else MAX_RESUMABLE_SOURCE_RETRIES_PRODUCTION
MAX_INCREMENTAL_SOURCE_RETRIES = 3 if settings.DEBUG else 9
MISSING_INTEGRATION_MESSAGE = (
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 7d3426dbc1c2..f8470c86a33a 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
@@ -711,6 +711,18 @@ def _promote_staged_cursor(export_signal: ExportSignalMessage) -> None:
logger.info(
"staged_cursor_promoted",
run_uuid=export_signal.run_uuid,
+ team_id=export_signal.team_id,
+ external_data_job_id=export_signal.job_id,
+ external_data_schema_id=export_signal.schema_id,
+ )
+ elif schema.should_use_incremental_field:
+ # The watermark stays where it was, so the next run re-reads this run's window. A source with
+ # no watermark at all re-reads its full history.
+ logger.warning(
+ "staged_cursor_missing",
+ run_uuid=export_signal.run_uuid,
+ team_id=export_signal.team_id,
+ external_data_job_id=export_signal.job_id,
external_data_schema_id=export_signal.schema_id,
)
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 25071bd9987a..4d000bc3185a 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
@@ -169,6 +169,30 @@ class TestPromoteStagedCursor:
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")
+ @parameterized.expand(
+ [
+ ("incremental_run_warns", True, 1),
+ ("full_refresh_run_stays_quiet", False, 0),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.logger")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.ExternalDataSchema.objects"
+ )
+ def test_warns_when_a_completed_run_has_no_staged_cursor(
+ self, _name: str, uses_incremental_field: bool, warnings: int, mock_objects: MagicMock, mock_logger: MagicMock
+ ) -> None:
+ schema = MagicMock()
+ schema.promote_staged_incremental_values.return_value = False
+ schema.should_use_incremental_field = uses_incremental_field
+ mock_objects.get.return_value = schema
+
+ _promote_staged_cursor(self._make_signal())
+
+ assert mock_logger.warning.call_count == warnings
+ if warnings:
+ assert mock_logger.warning.call_args.args == ("staged_cursor_missing",)
+
@patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.ExternalDataSchema.objects"
)
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 4b1eb65141de..46e5d946c685 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
@@ -650,8 +650,8 @@ class PipelineV3(Generic[ResumableData]):
total_rows=row_count,
)
- schema_path = await self._send_final_batches(total_batches, row_count)
-
+ # Stage the watermark before the final-batch notification. The load consumer promotes the
+ # staged slot when that batch completes, and a slot staged after that is never promoted.
await finalize_desc_sort_incremental_value(
self._resource,
self._schema,
@@ -661,6 +661,8 @@ class PipelineV3(Generic[ResumableData]):
staging_run_uuid=self._s3_batch_writer.get_run_uuid(),
)
+ 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.
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 be2d2d0f4ec9..67bcc3a986fb 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
@@ -769,6 +769,27 @@ class TestSingleTableRunIsUntouched:
assert v3_pipeline_class(MagicMock(lanes=[OutputLane(name="users_cdc")])) is LanedPipelineV3
+class TestFinalizeStagesTheWatermarkFirst:
+ @pytest.mark.asyncio
+ async def test_desc_watermark_is_staged_before_the_final_batch_notification(self) -> None:
+ pipeline = _make_pipeline()
+ pipeline._batch_results = [MagicMock()]
+ pipeline._last_incremental_field_value = None
+ order: list[str] = []
+ 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(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"]
+
+
class TestZeroBatchRunStampsTheFullRunMarker:
@pytest.mark.asyncio
async def test_a_run_that_extracted_nothing_still_counts_as_a_full_run(self) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/retry_limits.py b/products/warehouse_sources/backend/temporal/data_imports/retry_limits.py
new file mode 100644
index 000000000000..97a0e25e214d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/retry_limits.py
@@ -0,0 +1,3 @@
+# The largest retry cap an import activity gets. It lives apart from `external_data_job` so the
+# schema model can read it: that module loads temporalio, and the model loads during django.setup().
+MAX_RESUMABLE_SOURCE_RETRIES_PRODUCTION = 20
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index f1ed37dd3e08..5fa5dfbbcf43 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -1,4 +1,6 @@
import uuid
+from collections.abc import Iterator
+from contextlib import contextmanager
from datetime import UTC, date, datetime, timedelta
from typing import Any
@@ -26,6 +28,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
MISSING_PRIMARY_KEY_DISABLED_MESSAGE,
MISSING_PRIMARY_KEYS_RAW_ERROR,
REPARTITION_HOLD_MAX_AGE,
+ STAGED_CURSOR_PENDING_LIMIT,
ExternalDataSchema,
apply_incremental_lookback,
complete_schema_run,
@@ -1126,9 +1129,21 @@ class TestStagedIncrementalCursor:
)
return schema
+ @contextmanager
+ def _staged_in_memory(self, schema: ExternalDataSchema) -> Iterator[None]:
+ def apply(schema_id: Any, team_id: Any, *, mutate: Any, **_: Any) -> dict[str, Any]:
+ mutate(schema.sync_type_config)
+ return schema.sync_type_config
+
+ with patch(
+ "products.warehouse_sources.backend.models.external_data_schema.update_sync_type_config_keys",
+ side_effect=apply,
+ ):
+ yield
+
def test_stage_writes_run_uuid_and_last_value(self) -> None:
schema = self._make_schema()
- with patch.object(schema, "save"):
+ with self._staged_in_memory(schema):
schema.stage_incremental_field_value("run-1", 42)
staged = schema.sync_type_config["incremental_staged"]
assert staged == {"run_uuid": "run-1", "last_value": 42}
@@ -1137,7 +1152,7 @@ class TestStagedIncrementalCursor:
# A datetime-typed epoch cursor must round-trip as a number, not "1718377611", so the next
# run's read-back doesn't feed a numeric string into dateutil and crash.
schema = self._make_schema(incremental_field_type=IncrementalFieldType.DateTime)
- with patch.object(schema, "save"):
+ with self._staged_in_memory(schema):
schema.stage_incremental_field_value("run-1", 1718377611)
assert schema.sync_type_config["incremental_staged"]["last_value"] == 1718377611
@@ -1148,23 +1163,150 @@ class TestStagedIncrementalCursor:
def test_stage_writes_earliest_value(self) -> None:
schema = self._make_schema()
- with patch.object(schema, "save"):
+ with self._staged_in_memory(schema):
schema.stage_incremental_field_value("run-1", None, earliest_value=10)
staged = schema.sync_type_config["incremental_staged"]
assert staged == {"run_uuid": "run-1", "earliest_value": 10}
def test_stage_overwrites_when_different_run_uuid(self) -> None:
schema = self._make_schema(incremental_staged={"run_uuid": "old", "last_value": 1, "earliest_value": 5})
- with patch.object(schema, "save"):
+ with self._staged_in_memory(schema):
schema.stage_incremental_field_value("run-2", 99)
staged = schema.sync_type_config["incremental_staged"]
assert staged["run_uuid"] == "run-2"
assert staged["last_value"] == 99
assert "earliest_value" not in staged
+ assert schema.sync_type_config["incremental_staged_pending"] == [
+ {"run_uuid": "old", "last_value": 1, "earliest_value": 5}
+ ]
+
+ def test_stage_does_not_park_a_cursor_that_holds_no_value(self) -> None:
+ schema = self._make_schema(incremental_staged={"run_uuid": "run-1"})
+ with self._staged_in_memory(schema):
+ schema.stage_incremental_field_value("run-2", 99)
+ assert "incremental_staged_pending" not in schema.sync_type_config
+
+ def test_stage_continues_a_parked_cursor_for_the_same_run(self) -> None:
+ schema = self._make_schema(
+ incremental_staged={"run_uuid": "run-2", "earliest_value": 3},
+ incremental_staged_pending=[{"run_uuid": "run-1", "earliest_value": 5}],
+ )
+ with self._staged_in_memory(schema):
+ schema.stage_incremental_field_value("run-1", 42)
+ assert schema.sync_type_config["incremental_staged"] == {
+ "run_uuid": "run-1",
+ "earliest_value": 5,
+ "last_value": 42,
+ }
+ assert schema.sync_type_config["incremental_staged_pending"] == [{"run_uuid": "run-2", "earliest_value": 3}]
+
+ def test_parked_cursors_stay_bounded(self) -> None:
+ schema = self._make_schema()
+ with self._staged_in_memory(schema):
+ for index in range(STAGED_CURSOR_PENDING_LIMIT + 5):
+ schema.stage_incremental_field_value(f"run-{index}", index)
+ pending = schema.sync_type_config["incremental_staged_pending"]
+ assert len(pending) == STAGED_CURSOR_PENDING_LIMIT
+ assert pending[0]["run_uuid"] == "run-4"
+ assert pending[-1]["run_uuid"] == f"run-{STAGED_CURSOR_PENDING_LIMIT + 3}"
+ assert schema.sync_type_config["incremental_staged"]["run_uuid"] == f"run-{STAGED_CURSOR_PENDING_LIMIT + 4}"
+
+ def test_promote_reads_a_parked_cursor(self) -> None:
+ schema = self._make_schema(
+ incremental_staged={"run_uuid": "run-2", "last_value": 10},
+ incremental_staged_pending=[{"run_uuid": "run-1", "last_value": 42}],
+ )
+ with self._staged_in_memory(schema):
+ assert schema.promote_staged_incremental_values("run-1") is True
+ assert schema.sync_type_config["incremental_field_last_value"] == 42
+ assert schema.sync_type_config["incremental_staged"] == {"run_uuid": "run-2", "last_value": 10}
+ assert "incremental_staged_pending" not in schema.sync_type_config
+
+ def test_promote_never_moves_last_value_backwards(self) -> None:
+ schema = self._make_schema(
+ incremental_field_last_value=99,
+ incremental_staged_pending=[{"run_uuid": "run-1", "last_value": 42}],
+ )
+ with self._staged_in_memory(schema):
+ assert schema.promote_staged_incremental_values("run-1") is True
+ assert schema.sync_type_config["incremental_field_last_value"] == 99
+
+ def test_promote_never_moves_earliest_value_forwards(self) -> None:
+ schema = self._make_schema(
+ incremental_field_earliest_value=5,
+ incremental_staged_pending=[{"run_uuid": "run-1", "earliest_value": 40}],
+ )
+ with self._staged_in_memory(schema):
+ assert schema.promote_staged_incremental_values("run-1") is True
+ assert schema.sync_type_config["incremental_field_earliest_value"] == 5
+
+ def test_promote_advances_earliest_value_backwards(self) -> None:
+ schema = self._make_schema(
+ incremental_field_earliest_value=40,
+ incremental_staged={"run_uuid": "run-1", "earliest_value": 5},
+ )
+ with self._staged_in_memory(schema):
+ assert schema.promote_staged_incremental_values("run-1") is True
+ assert schema.sync_type_config["incremental_field_earliest_value"] == 5
+
+ @parameterized.expand(
+ [
+ ("older_epoch_keeps_iso", IncrementalFieldType.DateTime, "2026-06-14T00:00:00+00:00", 1767225600),
+ ("older_iso_keeps_epoch", IncrementalFieldType.DateTime, 1781395200, "2026-01-01T00:00:00+00:00"),
+ ("older_epoch_keeps_naive_iso", IncrementalFieldType.DateTime, "2026-06-14T00:00:00", 1767225600),
+ ("older_epoch_keeps_date", IncrementalFieldType.Date, "2026-06-14", 1767225600),
+ (
+ "older_objectid_keeps_newer",
+ IncrementalFieldType.ObjectID,
+ "65f0c0c0a1b2c3d4e5f60002",
+ "65f0c0c0a1b2c3d4e5f60001",
+ ),
+ ]
+ )
+ def test_promote_never_moves_last_value_backwards_across_cursor_encodings(
+ self, _name: str, field_type: IncrementalFieldType, current: Any, older: Any
+ ) -> None:
+ schema = self._make_schema(
+ incremental_field_type=field_type,
+ incremental_field_last_value=current,
+ incremental_staged={"run_uuid": "run-1", "last_value": older},
+ )
+ with self._staged_in_memory(schema):
+ assert schema.promote_staged_incremental_values("run-1") is True
+ assert schema.sync_type_config["incremental_field_last_value"] == current
+
+ def test_promote_advances_an_epoch_cursor_to_a_newer_iso_cursor(self) -> None:
+ schema = self._make_schema(
+ incremental_field_type=IncrementalFieldType.DateTime,
+ incremental_field_last_value=1767225600,
+ incremental_staged={"run_uuid": "run-1", "last_value": "2026-06-14T00:00:00+00:00"},
+ )
+ with self._staged_in_memory(schema):
+ assert schema.promote_staged_incremental_values("run-1") is True
+ assert schema.sync_type_config["incremental_field_last_value"] == "2026-06-14T00:00:00+00:00"
+
+ def test_promote_keeps_newest_when_cursors_cannot_be_ordered(self) -> None:
+ schema = self._make_schema(
+ incremental_field_type=None,
+ incremental_field_last_value="aaa",
+ incremental_staged={"run_uuid": "run-1", "last_value": "bbb"},
+ )
+ with self._staged_in_memory(schema):
+ assert schema.promote_staged_incremental_values("run-1") is True
+ assert schema.sync_type_config["incremental_field_last_value"] == "bbb"
+
+ def test_promote_rejects_a_run_uuid_with_no_slot_anywhere(self) -> None:
+ schema = self._make_schema(
+ incremental_staged={"run_uuid": "run-2", "last_value": 10},
+ incremental_staged_pending=[{"run_uuid": "run-1", "last_value": 42}],
+ )
+ with self._staged_in_memory(schema):
+ assert schema.promote_staged_incremental_values("run-WRONG") is False
+ assert "incremental_field_last_value" not in schema.sync_type_config
def test_stage_merges_when_same_run_uuid(self) -> None:
schema = self._make_schema()
- with patch.object(schema, "save"):
+ with self._staged_in_memory(schema):
schema.stage_incremental_field_value("run-1", None, earliest_value=10)
schema.stage_incremental_field_value("run-1", 42)
staged = schema.sync_type_config["incremental_staged"]
@@ -1172,7 +1314,7 @@ class TestStagedIncrementalCursor:
def test_promote_moves_last_value_to_live(self) -> None:
schema = self._make_schema(incremental_staged={"run_uuid": "run-1", "last_value": 42})
- with patch.object(schema, "save"):
+ with self._staged_in_memory(schema):
result = schema.promote_staged_incremental_values("run-1")
assert result is True
assert schema.sync_type_config["incremental_field_last_value"] == 42
@@ -1180,29 +1322,72 @@ class TestStagedIncrementalCursor:
def test_promote_moves_earliest_value_to_live(self) -> None:
schema = self._make_schema(incremental_staged={"run_uuid": "run-1", "earliest_value": 5})
- with patch.object(schema, "save"):
+ with self._staged_in_memory(schema):
result = schema.promote_staged_incremental_values("run-1")
assert result is True
assert schema.sync_type_config["incremental_field_earliest_value"] == 5
def test_promote_rejects_wrong_run_uuid(self) -> None:
schema = self._make_schema(incremental_staged={"run_uuid": "run-1", "last_value": 42})
- with patch.object(schema, "save"):
+ with self._staged_in_memory(schema):
result = schema.promote_staged_incremental_values("run-WRONG")
assert result is False
assert "incremental_field_last_value" not in schema.sync_type_config
def test_promote_returns_false_when_no_staged(self) -> None:
schema = self._make_schema()
- with patch.object(schema, "save"):
+ with self._staged_in_memory(schema):
result = schema.promote_staged_incremental_values("run-1")
assert result is False
def test_reset_pipeline_clears_staged(self) -> None:
- schema = self._make_schema(incremental_staged={"run_uuid": "run-1", "last_value": 42})
+ schema = self._make_schema(
+ incremental_staged={"run_uuid": "run-1", "last_value": 42},
+ incremental_staged_pending=[{"run_uuid": "run-0", "last_value": 1}],
+ )
with patch.object(schema, "save"):
schema.update_sync_type_config_for_reset_pipeline()
assert "incremental_staged" not in schema.sync_type_config
+ assert "incremental_staged_pending" not in schema.sync_type_config
+
+
+class TestStagedIncrementalCursorStaleWriters(BaseTest):
+ def test_two_stale_instances_of_one_run_keep_each_others_entries(self) -> None:
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+ schema = ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source=source,
+ name="events",
+ sync_type_config={"incremental_field_type": IncrementalFieldType.Integer},
+ )
+ outgoing = ExternalDataSchema.objects.get(id=schema.id)
+ incoming = ExternalDataSchema.objects.get(id=schema.id)
+
+ outgoing.stage_incremental_field_value("run-a1", None, earliest_value=5)
+ incoming.stage_incremental_field_value("run-a2", None, earliest_value=7)
+ outgoing.stage_incremental_field_value("run-a1", 42)
+
+ schema.refresh_from_db()
+ assert schema.sync_type_config["incremental_staged"] == {
+ "run_uuid": "run-a1",
+ "earliest_value": 5,
+ "last_value": 42,
+ }
+ assert schema.sync_type_config["incremental_staged_pending"] == [{"run_uuid": "run-a2", "earliest_value": 7}]
+
+ assert schema.promote_staged_incremental_values("run-a1") is True
+ assert schema.promote_staged_incremental_values("run-a2") is True
+ schema.refresh_from_db()
+ assert schema.sync_type_config["incremental_field_last_value"] == 42
+ assert schema.sync_type_config["incremental_field_earliest_value"] == 5
+ assert "incremental_staged" not in schema.sync_type_config
+ assert "incremental_staged_pending" not in schema.sync_type_config
class TestSSHTunnelPortValidation(SimpleTestCase):