:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): keep a desc run's newest row as its watermark (#101811)
jake sciottoce48c95418d8
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex bbe675d8e3e5..b0820ac2a388 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -50,6 +50,9 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)type IncrementalFieldValue = str | int | float | None+# A stored cursor after process_incremental_value: the serialized form above, widened by the+# datetime or date a DateTime, Timestamp or Date field parses to.+type ProcessedIncrementalValue = datetime | date | str | int | float# Sync type strings that early clients wrote to the column. They name a real mode, so they map to it.LEGACY_SYNC_TYPE_ALIASES: dict[str, ExternalDataSchemaSyncType] = {@@ -1501,6 +1504,30 @@ def _park_displaced_staged_cursor(config: dict[str, Any], staged: dict[str, Any]config["incremental_staged_pending"] = pending[-STAGED_CURSOR_PENDING_LIMIT:]+def attempt_run_uuid(workflow_run_id: str, attempt: int) -> str:+ """The run id that one import attempt stages its cursor and queues its batches under."""+ return f"{workflow_run_id}-a{attempt}"+++def attempt_of(run_uuid: str) -> tuple[str, int] | None:+ """Split a run id from `attempt_run_uuid` into its workflow run id and attempt, or None."""+ workflow_run_id, separator, attempt = run_uuid.rpartition("-a")+ if not separator or not workflow_run_id or not attempt.isdigit():+ return None+ return workflow_run_id, int(attempt)+++def _staged_attempts_of_run(config: dict[str, Any], workflow_run_id: str) -> list[tuple[dict[str, Any], int]]:+ """Each staged cursor, live or parked, that an attempt of `workflow_run_id` wrote, with its attempt."""+ attempts: list[tuple[dict[str, Any], int]] = []+ for staged in (config.get("incremental_staged") or {}, *config.get("incremental_staged_pending", [])):+ run_uuid = staged.get("run_uuid")+ parsed = attempt_of(run_uuid) if isinstance(run_uuid, str) else None+ if parsed is not None and parsed[0] == workflow_run_id:+ attempts.append((staged, parsed[1]))+ return attempts++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", [])@@ -1527,16 +1554,11 @@ def staged_handoff_resume_point(config: dict[str, Any], workflow_run_id: str | N"""if not workflow_run_id:return None- prefix = f"{workflow_run_id}-a"newest: dict[str, Any] | None = Nonenewest_attempt = 0- for staged in (config.get("incremental_staged") or {}, *config.get("incremental_staged_pending", [])):- run_uuid = staged.get("run_uuid")- if not isinstance(run_uuid, str) or not run_uuid.startswith(prefix):- continue- attempt = run_uuid.removeprefix(prefix)- if attempt.isdigit() and int(attempt) > newest_attempt:- newest, newest_attempt = staged, int(attempt)+ for staged, attempt in _staged_attempts_of_run(config, workflow_run_id):+ if attempt > newest_attempt:+ newest, newest_attempt = staged, attemptif newest is None:return Noneowner_run_uuid = newest.get(STAGED_RESUME_OWNER_KEY) or newest["run_uuid"]@@ -1554,6 +1576,54 @@ def staged_handoff_resume_value(config: dict[str, Any], workflow_run_id: str | Nreturn None if point is None else point[1]+def staged_run_last_value(config: dict[str, Any], workflow_run_id: str | None) -> ProcessedIncrementalValue | None:+ """The newest `last_value` that any attempt of `workflow_run_id` staged, or None.++ A resumed attempt of a descending source reads only rows older than the rows that the earlier+ attempts read, so it must start from their newest value. Each attempt stages the newest value+ of the whole run so far, so the value survives when the parked list drops the attempt that read+ the newest row.+ """+ if not workflow_run_id:+ return None+ field_type = config.get("incremental_field_type")+ newest: ProcessedIncrementalValue | None = None+ # Newest attempt first: for a pair the comparator cannot order, the newest attempt wins, the same+ # rule that `_advance_promoted_cursor` applies.+ for staged, attempt in sorted(_staged_attempts_of_run(config, workflow_run_id), key=lambda item: -item[1]):+ if staged.get("last_value") is None:+ continue+ try:+ candidate = process_incremental_value(staged["last_value"], field_type)+ except Exception:+ # A value that does not parse must not fail the attempt at startup. The attempt then+ # starts from an older value, which can only make the next run read rows again.+ logger.warning(+ "staged_run_last_value_unparseable",+ run_uuid=staged.get("run_uuid"),+ attempt=attempt,+ incremental_field_type=field_type,+ exc_info=True,+ )+ continue+ if candidate is None:+ continue+ if newest is None:+ newest = candidate+ continue+ comparison = _compare_incremental_values(newest, candidate, field_type)+ if comparison is None:+ logger.warning(+ "staged_run_last_value_unordered",+ run_uuid=staged.get("run_uuid"),+ attempt=attempt,+ incremental_field_type=field_type,+ )+ elif comparison < 0:+ newest = candidate+ return newest++def _advance_promoted_cursor(config: dict[str, Any],key: str,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.pyindex 413dbf0945b3..2e70b9259196 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@@ -803,7 +803,8 @@ async def update_incremental_field_values(last_value = get_incremental_field_value(schema, pa_table)if last_value is not None:- if (last_incremental_field_value is None) or (last_value > last_incremental_field_value):+ last_advanced = (last_incremental_field_value is None) or (last_value > last_incremental_field_value)+ if last_advanced:last_incremental_field_value = last_valueif resource.sort_mode == "asc":@@ -819,18 +820,27 @@ async def update_incremental_field_values(if resource.sort_mode == "desc":earliest_value = get_incremental_field_value(schema, pa_table, aggregate="min")-- if earliest_incremental_field_value is None or earliest_value < earliest_incremental_field_value:+ earliest_advanced = (+ earliest_incremental_field_value is None or earliest_value < earliest_incremental_field_value+ )+ if earliest_advanced:earliest_incremental_field_value = earliest_valueawait logger.adebug(f"{log_prefix}Updating incremental_field_earliest_value with {earliest_value}")- if staging_run_uuid is not None:++ if staging_run_uuid is not None:+ # The high-water mark is staged with every checkpoint so a resumed attempt can inherit it+ # (see `staged_run_last_value`). Staging is not promotion: the loader promotes the+ # watermark only when the final batch of the run completes the job.+ if last_advanced or earliest_advanced:await database_sync_to_async_pool(schema.stage_incremental_field_value)(- staging_run_uuid, None, earliest_value- )- else:- await database_sync_to_async_pool(schema.update_incremental_field_value)(- earliest_value, type="earliest"+ staging_run_uuid,+ last_incremental_field_value,+ earliest_value if earliest_advanced else None,)+ elif earliest_advanced:+ await database_sync_to_async_pool(schema.update_incremental_field_value)(+ earliest_value, type="earliest"+ )return IncrementalFieldValues(last_value=last_incremental_field_value, earliest_value=earliest_incremental_field_valuediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.pyindex bb9a2026010d..681c0a2acb0e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py@@ -6,6 +6,7 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patch+import pyarrow as pafrom asgiref.sync import async_to_syncfrom parameterized import parameterizedfrom redis import exceptions as redis_exceptions@@ -13,7 +14,11 @@ from redis import exceptions as redis_exceptionsfrom posthog.temporal.common.errors import NonReportableErrorfrom 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_schema import (+ ExternalDataSchema,+ attempt_run_uuid,+ staged_run_last_value,+)from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEventfrom products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors@@ -21,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.eNON_RETRYABLE_ERROR_RETRY_LIMIT,UNREADABLE_JOB_INPUTS_MESSAGE,_get_redis,+ finalize_desc_sort_incremental_value,handle_corrupted_delta_log,handle_non_retryable_error,handle_reset_or_full_refresh,@@ -31,12 +37,15 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.eresolve_primary_keys,should_check_shutdown,trim_source_job_inputs,+ update_incremental_field_values,validate_incremental_sync,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (MissingPrimaryKeysException,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException+from products.warehouse_sources.backend.types import IncrementalFieldType_EXTRACT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract"@@ -377,6 +386,74 @@ class TestReportHeartbeatTimeoutRecording(BaseTest):assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == 0+# transaction=True: the staging writes run on the async thread pool (database_sync_to_async_pool),+# which can't see an atomic TestCase's uncommitted rows.[email protected]_db(transaction=True)+class TestDescSortIncrementalHandoff:+ def _schema(self, team) -> ExternalDataSchema:+ source = ExternalDataSource.objects.create(+ source_id=str(uuid.uuid4()), connection_id=str(uuid.uuid4()), team=team, source_type="Persona"+ )+ return ExternalDataSchema.objects.create(+ name="inquiries",+ team=team,+ source=source,+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={+ "incremental_field": "created_at",+ "incremental_field_type": IncrementalFieldType.DateTime,+ },+ )++ def _batch(self, *created_at: datetime) -> pa.Table:+ return pa.table({"id": list(range(len(created_at))), "created_at": list(created_at)})++ def test_a_resumed_attempt_promotes_the_high_water_mark_of_the_whole_run(self, team):+ # Newest-first: attempt 1 yields the newest rows and dies. Attempt 2 resumes below them and+ # only ever sees older rows. The promoted watermark must be attempt 1's newest row, otherwise+ # the next run re-reads everything newer than the resume point.+ schema = self._schema(team)+ resource = SourceResponse(name="inquiries", items=lambda: iter([]), primary_keys=["id"], sort_mode="desc")+ logger = MagicMock(adebug=AsyncMock())+ newest = datetime(2026, 3, 1, tzinfo=UTC)+ resume_point = datetime(2026, 1, 1, tzinfo=UTC)++ values = async_to_sync(update_incremental_field_values)(+ schema,+ self._batch(newest, resume_point),+ resource,+ None,+ None,+ logger,+ staging_run_uuid=attempt_run_uuid("wf-1", 1),+ )+ assert values.last_value == newest+ schema.refresh_from_db()+ assert schema.sync_type_config["incremental_staged"]["last_value"] == newest.isoformat()+ assert "incremental_field_last_value" not in schema.sync_type_config++ seed = staged_run_last_value(schema.sync_type_config, "wf-1")+ assert seed == newest++ values = async_to_sync(update_incremental_field_values)(+ schema,+ self._batch(datetime(2025, 12, 1, tzinfo=UTC)),+ resource,+ seed,+ None,+ logger,+ staging_run_uuid=attempt_run_uuid("wf-1", 2),+ )+ async_to_sync(finalize_desc_sort_incremental_value)(+ resource, schema, values.last_value, logger, staging_run_uuid=attempt_run_uuid("wf-1", 2)+ )+ schema.refresh_from_db()+ assert "incremental_field_last_value" not in schema.sync_type_config++ assert schema.promote_staged_incremental_values(attempt_run_uuid("wf-1", 2)) is True+ assert schema.sync_type_config["incremental_field_last_value"] == newest.isoformat()++# transaction=True: handle_corrupted_delta_log writes to the DB from the async thread pool# (database_sync_to_async_pool), which can't see an atomic TestCase's uncommitted rows.@pytest.mark.django_db(transaction=True)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/append_rollback.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/append_rollback.pyindex 92c170481540..6d8f47130105 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/append_rollback.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/append_rollback.py@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.models.external_data_job import Externalfrom products.warehouse_sources.backend.models.external_data_schema import (APPEND_RUN_MARKER_KEY,ExternalDataSchema,+ attempt_of,update_sync_type_config_keys,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (@@ -37,7 +38,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineAPPEND_ROLLBACK_TOTAL,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.table_rebuild import attempt_oflogger = structlog.get_logger(__name__)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.pyindex d25b0473f957..f410e10c8bad 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@@ -760,6 +760,10 @@ def _trigger_post_import_workflow(export_signal: ExportSignalMessage, table_sizedef _promote_staged_cursor(export_signal: ExportSignalMessage) -> None:# Runs inside the completion transaction; failures roll it back so the batch retries.+ # A descending source stages the newest value of its run from the first batch, so a resumed+ # attempt can start from it. That staged `last_value` sits above rows that are not loaded yet,+ # so it must be promoted only here, when the final batch completes the job. A run that completes+ # outside the loader (a run with zero batches) must not promote it.schema = ExternalDataSchema.objects.get(id=export_signal.schema_id, team_id=export_signal.team_id)def merge_source_cursors(current: Any, candidate: Any) -> dict[str, Any]: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.pyindex 20cc64ac5d22..6f60600361ed 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@@ -704,6 +704,50 @@ class TestFinalDataBatch:mock_mark_completed.assert_not_called()+class TestStagedCursorWaitsForTheFinalBatch:+ # A descending source stages the newest value of its run from the first batch. Promoting it on a+ # batch before the final one moves the watermark above rows that are not loaded yet.++ @parameterized.expand([("mid_run_batch", False, 0), ("final_batch", True, 1)])+ def test_a_staged_cursor_is_promoted_only_by_the_final_batch(+ self, _name: str, is_final_batch: bool, promotions: int+ ) -> None:+ delta_table = MagicMock()+ delta_table.schema.return_value = pa.schema([pa.field("id", pa.int64())])+ delta_table.file_uris.return_value = []+ with ExitStack() as stack:+ for target in (+ "posthoganalytics",+ "mark_batch_as_processed",+ "_trigger_post_import_workflow",+ "_trigger_ducklake_register_data_imports",+ "transaction",+ "release_v3_pipeline_lock",+ ):+ stack.enter_context(patch(f"{_PROCESSOR}.{target}"))+ stack.enter_context(patch(f"{_PROCESSOR}.finish_row_tracking", new_callable=AsyncMock))+ stack.enter_context(+ patch(f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, return_value=_POST_LOAD_RESULT)+ )+ stack.enter_context(patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]})))+ stack.enter_context(patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False))+ mock_writer_cls = stack.enter_context(patch(f"{_PROCESSOR}.DeltaWriter"))+ mock_writer_cls.return_value.write = AsyncMock(return_value=delta_table)+ mock_helper_cls = stack.enter_context(patch(f"{_PROCESSOR}.DeltaTableRef"))+ mock_helper_cls.return_value.get_delta_table = AsyncMock(return_value=None)+ mock_job_cls = stack.enter_context(patch(f"{_PROCESSOR}.ExternalDataJob"))+ mock_update = stack.enter_context(patch(f"{_PROCESSOR}.update_external_job_status"))+ mock_update.return_value.status = mock_job_cls.Status.COMPLETED+ mock_schema_objects = stack.enter_context(patch(f"{_PROCESSOR}.ExternalDataSchema.objects"))++ process_message(_message(is_final_batch=is_final_batch, run_uuid="wfrun-1-a2"))++ promote = mock_schema_objects.get.return_value.promote_staged_incremental_values+ assert promote.call_count == promotions+ if promotions:+ promote.assert_called_with("wfrun-1-a2", merge_source_cursors=ANY)++def _set_messages(count: int, *, sync_type: str = "full_refresh", final: bool = True) -> list[dict[str, Any]]:return [_message(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.pyindex 363dc7bd6ddf..ded0450173a0 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@@ -20,7 +20,9 @@ from products.warehouse_sources.backend.models import DataWarehouseTablefrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import (ExternalDataSchema,+ attempt_run_uuid,process_incremental_value,+ staged_run_last_value,update_sync_type_config_keys,)from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -231,7 +233,7 @@ class PipelineV3(Generic[ResumableData]):attempt = current_import_attempt()self._attempt = attempt- self._run_uuid = f"{self._job.workflow_run_id}-a{attempt}" if self._job.workflow_run_id else None+ self._run_uuid = attempt_run_uuid(self._job.workflow_run_id, attempt) if self._job.workflow_run_id else Noneself._s3_batch_writer = self._build_s3_writer(self._run_uuid)sync_type: SyncTypeLiteral = "full_refresh"@@ -356,6 +358,19 @@ class PipelineV3(Generic[ResumableData]):self._shutdown_monitor = shutdown_monitorself._shutdown_stopwatch = ShutdownStopwatch(shutdown_monitor)self._last_incremental_field_value: Any = None+ if is_resume and source_response.sort_mode == "desc":+ # A resumed descending attempt reads only rows older than the rows that the earlier attempts+ # of this run read. Without their newest value, the run promotes the resume point as its+ # watermark, and the next run reads every newer row again. `models.schema` is loaded when+ # this attempt starts, so it holds what the earlier attempts staged.+ self._last_incremental_field_value = staged_run_last_value(+ models.schema.sync_type_config or {}, self._job.workflow_run_id+ )+ if self._last_incremental_field_value is None:+ self._logger.warning(+ "V3 Pipeline: Resumed desc extract found no staged last value of this run",+ workflow_run_id=self._job.workflow_run_id,+ )self._earliest_incremental_field_value: Any = process_incremental_value(models.schema.incremental_field_earliest_value, models.schema.incremental_field_type)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/table_rebuild.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/table_rebuild.pyindex d1276b5e7fa2..7ae9d681c68e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/table_rebuild.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/table_rebuild.py@@ -2,20 +2,13 @@ from typing import Anyfrom products.warehouse_sources.backend.models.external_data_schema import (ExternalDataSchema,+ attempt_of,update_sync_type_config_keys,)TABLE_REBUILD_RUN_KEY = "table_rebuild_run_uuid"-def attempt_of(run_uuid: str) -> tuple[str, int] | None:- """Split `<workflow run id>-a<attempt>`, the run id format of the extract pipeline."""- workflow_run_id, separator, attempt = run_uuid.rpartition("-a")- if not separator or not workflow_run_id or not attempt.isdigit():- return None- return workflow_run_id, int(attempt)--class TableRebuildRun:"""The newest attempt that loads an incremental table from empty.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.pyindex 2b28dd34a868..2af5f24dd030 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@@ -4,6 +4,7 @@ import inspectimport threadingfrom contextlib import ExitStack, nullcontextfrom dataclasses import dataclass+from datetime import UTC, datetime, timedeltafrom types import SimpleNamespacefrom typing import Any, cast@@ -19,7 +20,9 @@ from posthog.temporal.common.shutdown import WorkerShuttingDownErrorfrom products.warehouse_sources.backend.models import external_data_schema as schema_modelsfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (+ finalize_desc_sort_incremental_value,handle_reset_or_full_refresh,+ update_incremental_field_values,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.preemption import (PreemptionConfig,@@ -1169,6 +1172,112 @@ class TestFinalizeStagesTheWatermarkFirst:schema.update_source_cursor.assert_not_called()+class TestDescWatermarkAcrossResumedAttempts:+ _NEWEST = datetime(2026, 1, 31, tzinfo=UTC)++ def _schema(self) -> ExternalDataSchema:+ return ExternalDataSchema(+ name="events",+ team_id=1,+ sync_type="incremental",+ sync_type_config={+ "incremental_field": "created_at",+ "incremental_field_type": IncrementalFieldType.DateTime,+ },+ )++ def _attempt(self, schema: ExternalDataSchema, attempt: int) -> PipelineV3:+ resource = MagicMock(+ name="events",+ primary_keys=["id"],+ partition_count=None,+ partition_size=None,+ partition_keys=["id"],+ partition_format=None,+ partition_mode="md5",+ cdc_write_mode=None,+ lanes=None,+ webhook_only=False,+ sort_mode="desc",+ )+ manager = MagicMock(can_resume=MagicMock(return_value=attempt > 1))+ with (+ patch(f"{_PIPELINE}.current_import_attempt", return_value=attempt),+ patch(f"{_PIPELINE}.current_workflow_id", return_value="wf-1"),+ patch(f"{_PIPELINE}.current_workflow_run_id", return_value="wfrun-abc"),+ patch(f"{_PIPELINE}.S3BatchWriter"),+ patch(f"{_PIPELINE}.PostgresProducer"),+ patch(f"{_PIPELINE}.DeltaTableRef"),+ patch(f"{_PIPELINE}.resolve_resume_manager", return_value=manager),+ ):+ return PipelineV3(+ source_response=resource,+ logger=_make_logger(),+ job_id="job-1",+ reset_pipeline=False,+ shutdown_monitor=MagicMock(),+ resumable_source_manager=manager,+ models=ImportJobModels(+ job=MagicMock(team_id=1, workflow_run_id="wfrun-abc", billable=False, id="job-1"),+ schema=schema,+ source=MagicMock(source_type="Langfuse"),+ table=MagicMock(),+ ),+ )++ async def _extract(self, schema: ExternalDataSchema, attempt: int, *, final: bool) -> str:+ pipeline = self._attempt(schema, attempt)+ run_uuid = cast(str, pipeline._run_uuid)+ # Each attempt resumes on an older page than the attempt before it read.+ newest_row = self._NEWEST - timedelta(hours=10 * (attempt - 1))+ table = pa.table(+ {"created_at": pa.array([newest_row, newest_row - timedelta(hours=5)], pa.timestamp("us", tz="UTC"))}+ )+ values = await update_incremental_field_values(+ schema,+ table,+ pipeline._resource,+ pipeline._last_incremental_field_value,+ pipeline._earliest_incremental_field_value,+ _make_logger(),+ staging_run_uuid=run_uuid,+ )+ if final:+ await finalize_desc_sort_incremental_value(+ pipeline._resource, schema, values.last_value, _make_logger(), staging_run_uuid=run_uuid+ )+ return run_uuid++ @pytest.mark.parametrize(+ "attempts",+ [+ pytest.param(2, id="one_resume"),+ pytest.param(schema_models.STAGED_CURSOR_PENDING_LIMIT + 5, id="the_first_attempt_left_the_parked_list"),+ ],+ )+ @pytest.mark.asyncio+ async def test_the_completed_run_promotes_the_newest_value_of_every_attempt(self, attempts: int) -> None:+ schema = self._schema()++ with (+ patch.object(schema_models, "update_sync_type_config_keys", side_effect=_in_memory_config_update(schema)),+ patch.object(ExternalDataSchema, "refresh_from_db"),+ ):+ for attempt in range(1, attempts + 1):+ run_uuid = await self._extract(schema, attempt, final=attempt == attempts)+ assert schema.sync_type_config.get("incremental_field_last_value") is None+ assert schema.promote_staged_incremental_values(run_uuid)++ parked_run_uuids = {+ entry["run_uuid"] for entry in schema.sync_type_config.get("incremental_staged_pending", [])+ }+ first_attempt_is_parked = schema_models.attempt_run_uuid("wfrun-abc", 1) in parked_run_uuids+ assert first_attempt_is_parked == (attempts <= schema_models.STAGED_CURSOR_PENDING_LIMIT)+ oldest_row = self._NEWEST - timedelta(hours=10 * (attempts - 1) + 5)+ assert schema.sync_type_config["incremental_field_last_value"] == self._NEWEST.isoformat()+ assert schema.sync_type_config["incremental_field_earliest_value"] == oldest_row.isoformat()++class TestZeroBatchRunStampsTheFullRunMarker:@pytest.mark.asyncioasync def test_a_run_that_extracted_nothing_still_counts_as_a_full_run(self) -> None:diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex 3c057e4a1c45..ec731c9947bc 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (process_incremental_value,staged_handoff_resume_point,staged_handoff_resume_value,+ staged_run_last_value,update_sync_type_config_keys,)from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -1527,6 +1528,106 @@ class TestStagedIncrementalCursor:assert result is Trueassert schema.sync_type_config["incremental_field_earliest_value"] == 5+ @parameterized.expand(+ [+ (+ "live_slot_of_a_later_attempt",+ IncrementalFieldType.Integer,+ {"run_uuid": "wf-1-a2", "last_value": 7},+ [],+ 7,+ [],+ ),+ (+ "highest_across_live_and_parked_attempts",+ IncrementalFieldType.Integer,+ {"run_uuid": "wf-1-a3", "earliest_value": 1},+ [{"run_uuid": "wf-1-a1", "last_value": 42}, {"run_uuid": "wf-1-a2", "last_value": 9}],+ 42,+ [],+ ),+ (+ "another_run_is_ignored",+ IncrementalFieldType.Integer,+ {"run_uuid": "wf-2-a1", "last_value": 42},+ [],+ None,+ [],+ ),+ (+ "a_run_id_that_merely_shares_a_prefix_is_ignored",+ IncrementalFieldType.Integer,+ {"run_uuid": "wf-10-a1", "last_value": 42},+ [{"run_uuid": "wf-1-a1", "last_value": 3}],+ 3,+ [],+ ),+ (+ "malformed_attempt_suffixes_are_ignored",+ IncrementalFieldType.Integer,+ {"run_uuid": "wf-1-ax", "last_value": 90},+ [+ {"run_uuid": "wf-1", "last_value": 91},+ {"run_uuid": "wf-1-a", "last_value": 92},+ {"run_uuid": "wf-1-a2-retry", "last_value": 93},+ {"run_uuid": 1, "last_value": 94},+ {"run_uuid": "wf-1-a1", "last_value": 5},+ ],+ 5,+ [],+ ),+ (+ "earliest_only_is_not_a_high_water_mark",+ IncrementalFieldType.Integer,+ {"run_uuid": "wf-1-a1", "earliest_value": 5},+ [],+ None,+ [],+ ),+ (+ "unparseable_value_is_skipped",+ IncrementalFieldType.DateTime,+ {"run_uuid": "wf-1-a2", "last_value": "not-a-date"},+ [{"run_uuid": "wf-1-a1", "last_value": "2026-01-09T00:00:00+00:00"}],+ datetime(2026, 1, 9, tzinfo=UTC),+ ["staged_run_last_value_unparseable"],+ ),+ (+ "epoch_and_iso_values_order_by_time",+ IncrementalFieldType.DateTime,+ {"run_uuid": "wf-1-a2", "last_value": "2026-01-01T00:00:00+00:00"},+ [{"run_uuid": "wf-1-a1", "last_value": 1768000000}],+ 1768000000,+ [],+ ),+ (+ "unordered_pair_keeps_the_newest_attempt",+ IncrementalFieldType.DateTime,+ {"run_uuid": "wf-1-a2", "last_value": "2026-01-01T00:00:00"},+ [{"run_uuid": "wf-1-a1", "last_value": "2026-01-09T00:00:00+00:00"}],+ datetime(2026, 1, 1),+ ["staged_run_last_value_unordered"],+ ),+ ]+ )+ def test_staged_run_last_value(+ self,+ _name: str,+ field_type: IncrementalFieldType,+ live: dict[str, Any],+ parked: list[dict[str, Any]],+ expected: Any,+ warnings: list[str],+ ) -> None:+ config = {+ "incremental_field_type": field_type,+ "incremental_staged": live,+ "incremental_staged_pending": parked,+ }+ with patch("products.warehouse_sources.backend.models.external_data_schema.logger") as mock_logger:+ assert staged_run_last_value(config, "wf-1") == expected+ assert [call.args[0] for call in mock_logger.warning.call_args_list] == warnings+def test_promote_rejects_wrong_run_uuid(self) -> None:schema = self._make_schema(incremental_staged={"run_uuid": "run-1", "last_value": 42})with self._staged_in_memory(schema):