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): make import hand-offs free and resume from the last queued batch (#112693)

Tom Owerse6fe0616ccc0
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index fdff492a7ab8..da578933692d 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -264,6 +264,17 @@ DATA_WAREHOUSE_CDP_PRODUCER_TASK_QUEUE = _set_temporal_task_queue("data-warehous
# Post-sync table metadata (semantic enrichment + column statistics) runs on its own worker so this
# best-effort work can't starve the import pipeline.
DATA_WAREHOUSE_METADATA_TASK_QUEUE = _set_temporal_task_queue("data-warehouse-metadata-task-queue")
+# A data import that leaves a worker which is shutting down runs again without using a retry
+# attempt. Turn this on only when every worker on the queue has the code that reads the hand-off
+# fields of the import activity: an older worker ignores them and reuses the first attempt's run id.
+DATA_WAREHOUSE_IMPORT_FREE_HANDOFFS_ENABLED: bool = get_from_env(
+ "DATA_WAREHOUSE_IMPORT_FREE_HANDOFFS_ENABLED", False, type_cast=str_to_bool
+)
+# An incremental import that was interrupted continues after the last batch it queued, instead of
+# after the watermark the job started with.
+DATA_WAREHOUSE_IMPORT_WATERMARK_CARRY_OVER_ENABLED: bool = get_from_env(
+ "DATA_WAREHOUSE_IMPORT_WATERMARK_CARRY_OVER_ENABLED", False, type_cast=str_to_bool
+)
MAX_AI_TASK_QUEUE = _set_temporal_task_queue("max-ai-task-queue")
BATCH_EXPORTS_TASK_QUEUE = _set_temporal_task_queue("batch-exports-task-queue")
DATA_MODELING_TASK_QUEUE = _set_temporal_task_queue("data-modeling-task-queue")
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.py
index ef116bcd11b4..5961f7a325a3 100644
--- a/posthog/temporal/common/worker.py
+++ b/posthog/temporal/common/worker.py
@@ -384,6 +384,13 @@ async def create_worker(
itertools.repeat(DATA_MODELING_LATENCY_HISTOGRAM_BUCKETS),
)
)
+ if task_queue == settings.DATA_WAREHOUSE_TASK_QUEUE:
+ # Both metrics hold small counts. The default buckets are for latencies in milliseconds,
+ # which puts every count into the first bucket.
+ histogram_bucket_overrides |= {
+ "warehouse_pipeline_run_attempt": [1.0, 2.0, 3.0, 5.0, 9.0, 20.0, 50.0, 100.0, 200.0],
+ "warehouse_import_handoffs_per_run": [0.0, 1.0, 2.0, 3.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0],
+ }
if task_queue == settings.TASKS_TASK_QUEUE:
histogram_bucket_overrides |= dict(
zip(
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 66d8fd683c36..2b3d18d2a350 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -183,6 +183,17 @@ def _schema_ids_with_running_jobs(schema_ids: list[uuid.UUID]) -> set[uuid.UUID]
# 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
+# The key, inside a staged cursor, for the incremental value a later attempt of the same workflow
+# run can resume after. It differs from the staged `last_value`, which the loader promotes only
+# when the whole run completes.
+STAGED_RESUME_VALUE_KEY = "resume_value"
+
+# The key, inside a staged cursor, for the run whose queue rows the resume value actually describes.
+# An attempt that only inherits the value from an earlier attempt, without queuing a batch of its
+# own yet, is not that run: finalizing a later zero-batch continuation must target the run that
+# holds the rows, not whichever attempt most recently restated the same value.
+STAGED_RESUME_OWNER_KEY = "resume_owner_run_uuid"
+
class ExternalDataSchemaQuerySet(models.QuerySet["ExternalDataSchema"]):
def update(self, **kwargs: Any) -> int:
@@ -1030,6 +1041,25 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan
}
self._stage_cursor_values(run_uuid, values)
+ def stage_handoff_resume_value(self, run_uuid: str, resume_value: Any, owner_run_uuid: str | None = None) -> None:
+ """Record the incremental value a later attempt of this workflow run can resume after.
+
+ Stage only a value whose rows already have their queue rows, because the next attempt reads
+ the source strictly above it. None records that this attempt has no such value, which stops
+ the next attempt from using the value of an older attempt.
+
+ `owner_run_uuid` is the run whose queue rows the value describes, for finalizing a later
+ zero-batch continuation. It defaults to `run_uuid`, the common case of an attempt that just
+ queued the batch the value describes.
+ """
+ self._stage_cursor_values(
+ run_uuid,
+ {
+ STAGED_RESUME_VALUE_KEY: self._serialize_incremental_value(resume_value),
+ STAGED_RESUME_OWNER_KEY: owner_run_uuid if owner_run_uuid is not None else run_uuid,
+ },
+ )
+
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})
@@ -1353,7 +1383,8 @@ 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", SOURCE_CURSOR_KEY} & staged.keys()):
+ cursor_keys = {"last_value", "earliest_value", SOURCE_CURSOR_KEY, STAGED_RESUME_VALUE_KEY}
+ if not staged.get("run_uuid") or not (cursor_keys & staged.keys()):
return
pending = [*config.get("incremental_staged_pending", []), staged]
config["incremental_staged_pending"] = pending[-STAGED_CURSOR_PENDING_LIMIT:]
@@ -1373,6 +1404,45 @@ def _drop_parked_staged_cursor(config: dict[str, Any], run_uuid: str) -> dict[st
return dropped
+def staged_handoff_resume_point(config: dict[str, Any], workflow_run_id: str | None) -> tuple[str, Any] | None:
+ """The run that owns the queued rows, and the value, recorded by the newest attempt of
+ `workflow_run_id`.
+
+ The returned run is `STAGED_RESUME_OWNER_KEY`, not necessarily the attempt that most recently
+ staged the entry: an attempt that only inherited the value, without queuing a batch of its own
+ yet, stages it under its own `run_uuid` for parking purposes but records the earlier run as the
+ owner. A caller that finalizes a zero-batch continuation needs the owner, since that is the run
+ whose queue rows still need the final marker.
+ """
+ if not workflow_run_id:
+ return None
+ prefix = f"{workflow_run_id}-a"
+ newest: dict[str, Any] | None = None
+ newest_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)
+ if newest is None:
+ return None
+ owner_run_uuid = newest.get(STAGED_RESUME_OWNER_KEY) or newest["run_uuid"]
+ return owner_run_uuid, newest.get(STAGED_RESUME_VALUE_KEY)
+
+
+def staged_handoff_resume_value(config: dict[str, Any], workflow_run_id: str | None) -> Any:
+ """The value the newest attempt of `workflow_run_id` recorded with `stage_handoff_resume_value`.
+
+ Only the newest attempt counts. An attempt that restarted from the stored watermark can replace
+ the queue rows of the attempts before it, so their values no longer describe what the loader
+ will load.
+ """
+ point = staged_handoff_resume_point(config, workflow_run_id)
+ return None if point is None else point[1]
+
+
def _advance_promoted_cursor(
config: dict[str, Any],
key: str,
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 9e453dfe85f5..54dd7e0b3f5a 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
@@ -59,6 +59,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_h
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
get_data_import_finished_metric,
get_fast_returned_run_metric,
+ get_import_handoffs_per_run_metric,
get_v3_lock_skipped_metric,
get_version_check_skipped_metric,
)
@@ -66,6 +67,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
DUPLICATE_PRIMARY_KEYS_ERROR,
MISSING_PRIMARY_KEYS_ERROR,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
release_v3_pipeline_lock,
)
@@ -144,6 +146,20 @@ MAX_INCREMENTAL_SOURCE_RETRIES = 3 if settings.DEBUG else 9
# deploys often therefore needs the same room as a resumable import.
MAX_REPARTITION_ACTIVITY_ATTEMPTS = MAX_RESUMABLE_SOURCE_RETRIES
+# The import activity returns a hand-off result when its worker shuts down, and the workflow runs
+# it again. The bound stops a run that no worker keeps long enough to finish. It is far above the
+# retry caps because a hand-off loses at most the batch in progress, where a failure can lose more.
+MAX_IMPORT_HANDOFFS = 200
+# A worker that got the shutdown signal takes no new activity, so each wait lets the rollout move
+# on and lowers the chance that the next worker also stops. The wait doubles while executions
+# keep ending early, and goes back to the first value after one that ran for a time.
+IMPORT_HANDOFF_FIRST_DELAY = dt.timedelta(seconds=5)
+IMPORT_HANDOFF_MAX_DELAY = dt.timedelta(seconds=60)
+IMPORT_HANDOFF_SETTLED_AFTER = dt.timedelta(minutes=5)
+FREE_IMPORT_HANDOFFS_PATCH_ID = "data-imports-free-handoffs-2026-10"
+
+IMPORT_NON_RETRYABLE_ERROR_TYPES = ["NonRetryableException", "BillingLimitsWillBeReachedException"]
+
MISSING_INTEGRATION_MESSAGE = (
"The connected account for this source is no longer available — it may have been disconnected. "
"Please reconnect the source's account."
@@ -786,6 +802,85 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
loaded = json.loads(inputs[0])
return ExternalDataWorkflowInputs(**loaded)
+ async def _run_import_across_handoffs(
+ self,
+ job_inputs: ImportDataActivityInputs,
+ *,
+ start_to_close_timeout: dt.timedelta,
+ max_attempts: int,
+ source_type: str | None,
+ ) -> PipelineResult | None:
+ """Run the import activity again after each worker hand-off. Returns None at the hand-off bound.
+
+ A hand-off completes the activity execution, so it uses none of `max_attempts`. Attempts
+ that failed before a hand-off still count: the next execution gets what is left, so the
+ budget for failures covers the workflow run and not each execution.
+ """
+ handoffs = 0
+ early_handoffs = 0
+ prior_attempts = 0
+ failed_attempts = 0
+ try:
+ while True:
+ started_at = workflow.now()
+ pipeline_result: PipelineResult = await workflow.execute_activity(
+ import_data_activity_sync,
+ dataclasses.replace(
+ job_inputs, handoffs_are_free=True, handoff_count=handoffs, prior_attempts=prior_attempts
+ ),
+ heartbeat_timeout=dt.timedelta(minutes=2),
+ start_to_close_timeout=start_to_close_timeout,
+ retry_policy=RetryPolicy(
+ maximum_attempts=max(1, max_attempts - failed_attempts),
+ non_retryable_error_types=IMPORT_NON_RETRYABLE_ERROR_TYPES,
+ ),
+ )
+ if not pipeline_result.get("handed_off", False):
+ return pipeline_result
+
+ handoffs += 1
+ attempts_used = max(1, pipeline_result.get("handoff_attempts_used", 1))
+ prior_attempts += attempts_used
+ failed_attempts += attempts_used - 1
+ if handoffs >= MAX_IMPORT_HANDOFFS:
+ return None
+
+ ended_early = workflow.now() - started_at < IMPORT_HANDOFF_SETTLED_AFTER
+ early_handoffs = early_handoffs + 1 if ended_early else 0
+ delay = min(IMPORT_HANDOFF_FIRST_DELAY * 2 ** min(early_handoffs, 10), IMPORT_HANDOFF_MAX_DELAY)
+ workflow.logger.info(
+ "Import handed off by a worker that is shutting down, running it again",
+ extra={"handoffs": handoffs, "delay_seconds": delay.total_seconds()},
+ )
+ await workflow.sleep(delay)
+ finally:
+ get_import_handoffs_per_run_metric(source_type).record(handoffs)
+
+ async def _fail_for_worker_restarts(
+ self,
+ inputs: ExternalDataWorkflowInputs,
+ update_inputs: UpdateExternalDataJobStatusInputs,
+ *,
+ is_v3: bool,
+ internal_error: str,
+ ) -> None:
+ if is_v3:
+ # No final batch reached the queue, so the loader can never complete this job.
+ # A COMPLETED write would release the pipeline lock and let the buffered run
+ # extract the same table again on top of this run's still-queued batches.
+ # Set before the buffer-one activity so a failure there cannot skip it.
+ update_inputs.status = ExternalDataJob.Status.FAILED
+ update_inputs.internal_error = internal_error
+ update_inputs.latest_error = WORKER_RESTART_ERROR_MESSAGE
+ # Ask the schedule for one more run of this schema, buffered behind the current one.
+ schedule_id = str(inputs.external_data_schema_id)
+ await workflow.execute_activity(
+ trigger_schedule_buffer_one_activity,
+ schedule_id,
+ start_to_close_timeout=dt.timedelta(minutes=10),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+
@workflow.run
async def run(self, inputs: ExternalDataWorkflowInputs):
assert inputs.external_data_schema_id is not None
@@ -908,6 +1003,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
billing_limit_checked = False
hit_billing_limit = False
source_templates_needed = True
+ import_handoffs_are_free = False
else:
job_id = create_job_result.job_id
incremental_or_append = create_job_result.incremental_or_append
@@ -924,6 +1020,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
billing_limit_checked = create_job_result.billing_limit_checked
hit_billing_limit = create_job_result.hit_billing_limit
source_templates_needed = create_job_result.source_templates_needed
+ import_handoffs_are_free = create_job_result.import_handoffs_are_free
update_inputs.job_id = str(job_id) if job_id is not None else None
# The job-creation activity answers the billing question in the same round trip. The
@@ -1007,36 +1104,47 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
max_incremental_attempts = MAX_INCREMENTAL_SOURCE_RETRIES
if is_resumable_source:
- timeout_params = {
- "start_to_close_timeout": dt.timedelta(weeks=1),
- "retry_policy": RetryPolicy(
- maximum_attempts=max_resumable_attempts,
- non_retryable_error_types=["NonRetryableException", "BillingLimitsWillBeReachedException"],
- ),
- }
+ import_start_to_close_timeout = dt.timedelta(weeks=1)
+ import_max_attempts = max_resumable_attempts
elif incremental_or_append:
- timeout_params = {
- "start_to_close_timeout": dt.timedelta(weeks=1),
- "retry_policy": RetryPolicy(
- maximum_attempts=max_incremental_attempts,
- non_retryable_error_types=["NonRetryableException", "BillingLimitsWillBeReachedException"],
- ),
- }
+ import_start_to_close_timeout = dt.timedelta(weeks=1)
+ import_max_attempts = max_incremental_attempts
else:
- timeout_params = {
- "start_to_close_timeout": dt.timedelta(hours=24),
- "retry_policy": RetryPolicy(
- maximum_attempts=3,
- non_retryable_error_types=["NonRetryableException", "BillingLimitsWillBeReachedException"],
+ import_start_to_close_timeout = dt.timedelta(hours=24)
+ import_max_attempts = 3
+
+ # A hand-off loop schedules the import activity more than once, which a history recorded
+ # without it cannot replay. Two things keep replay on the recorded branch. The flag is
+ # the output of the job-creation activity, so replay reads the value the first execution
+ # saw, and a payload that predates the flag reads False. patched() then marks the
+ # histories that took the loop.
+ if import_handoffs_are_free and workflow.patched(FREE_IMPORT_HANDOFFS_PATCH_ID):
+ handoff_result = await self._run_import_across_handoffs(
+ job_inputs,
+ start_to_close_timeout=import_start_to_close_timeout,
+ max_attempts=import_max_attempts,
+ source_type=source_type,
+ )
+ if handoff_result is None:
+ await self._fail_for_worker_restarts(
+ inputs,
+ update_inputs,
+ is_v3=is_v3,
+ internal_error=f"The import was handed off {MAX_IMPORT_HANDOFFS} times by workers that were shutting down",
+ )
+ return
+ pipeline_result = handoff_result
+ else:
+ pipeline_result = await workflow.execute_activity(
+ import_data_activity_sync,
+ job_inputs,
+ heartbeat_timeout=dt.timedelta(minutes=2),
+ start_to_close_timeout=import_start_to_close_timeout,
+ retry_policy=RetryPolicy(
+ maximum_attempts=import_max_attempts,
+ non_retryable_error_types=IMPORT_NON_RETRYABLE_ERROR_TYPES,
),
- }
-
- pipeline_result = await workflow.execute_activity(
- import_data_activity_sync,
- job_inputs,
- heartbeat_timeout=dt.timedelta(minutes=2),
- **timeout_params,
- ) # type: ignore
+ )
# Run-finalization ownership (terminal status write, v3 lock release, post-import
# start) — the full contract lives on the PipelineResult docstring. False on every
@@ -1270,22 +1378,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
except exceptions.ActivityError as e:
if isinstance(e.cause, exceptions.ApplicationError) and e.cause.type == "WorkerShuttingDownError":
- if is_v3:
- # No final batch reached the queue, so the loader can never complete this job.
- # A COMPLETED write would release the pipeline lock and let the buffered run
- # extract the same table again on top of this run's still-queued batches.
- # Set before the buffer-one activity so a failure there cannot skip it.
- update_inputs.status = ExternalDataJob.Status.FAILED
- update_inputs.internal_error = str(e.cause)
- update_inputs.latest_error = WORKER_RESTART_ERROR_MESSAGE
- # Check if this is a WorkerShuttingDownError - implement Buffer One retry
- schedule_id = str(inputs.external_data_schema_id)
- await workflow.execute_activity(
- trigger_schedule_buffer_one_activity,
- schedule_id,
- start_to_close_timeout=dt.timedelta(minutes=10),
- retry_policy=RetryPolicy(maximum_attempts=1),
- )
+ await self._fail_for_worker_restarts(inputs, update_inputs, is_v3=is_v3, internal_error=str(e.cause))
elif (
isinstance(e.cause, exceptions.ApplicationError)
and e.cause.type == "BillingLimitsWillBeReachedException"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/import_attempt.py b/products/warehouse_sources/backend/temporal/data_imports/import_attempt.py
new file mode 100644
index 000000000000..087b6c2bd9b1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/import_attempt.py
@@ -0,0 +1,35 @@
+"""The attempt number of a data import across every execution of its activity.
+
+A workflow that runs the import activity again after a worker hand-off starts a new activity
+execution, and Temporal numbers the attempts of that execution from 1 again. The import needs a
+number that stays unique in the workflow run: it names the folder and the queue rows of each
+attempt, and decides whether the attempt may reset the destination table.
+"""
+
+from contextvars import ContextVar
+from typing import Literal
+
+from posthog.temporal.common.activity_context import current_activity_attempt
+
+_ATTEMPTS_BEFORE_THIS_EXECUTION: ContextVar[int] = ContextVar("data_import_attempts_before_this_execution", default=0)
+
+ImportAttemptCause = Literal["first", "handoff", "retry"]
+
+
+def set_attempts_before_this_execution(attempts: int) -> None:
+ _ATTEMPTS_BEFORE_THIS_EXECUTION.set(max(attempts, 0))
+
+
+def current_import_attempt() -> int:
+ return _ATTEMPTS_BEFORE_THIS_EXECUTION.get() + current_activity_attempt()
+
+
+def current_import_attempt_cause() -> ImportAttemptCause:
+ """Why this attempt runs.
+
+ `retry` means Temporal started the attempt: the attempt before it failed, timed out, or left
+ a worker that does not return a hand-off result.
+ """
+ if current_activity_attempt() > 1:
+ return "retry"
+ return "handoff" if _ATTEMPTS_BEFORE_THIS_EXECUTION.get() > 0 else "first"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
index f4785d7171fe..bc6ed71a036b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
@@ -3,7 +3,7 @@ import datetime as dt
from typing import TYPE_CHECKING
from temporalio import activity, workflow
-from temporalio.common import MetricCounter
+from temporalio.common import MetricCounter, MetricHistogram
from posthog.kafka_client.routing import get_producer
from posthog.kafka_client.topics import KAFKA_APP_METRICS2
@@ -89,6 +89,19 @@ def get_worker_shutdown_handoff_metric(source_type: str | None) -> MetricCounter
)
+def get_import_handoffs_per_run_metric(source_type: str | None) -> MetricHistogram:
+ # One observation per workflow run that can hand off for free, zero included. Compare it with
+ # the attempt histogram to tell runs that worker restarts moved from runs that failed.
+ return (
+ workflow.metric_meter()
+ .with_additional_attributes({"source_type": source_type or "unknown"})
+ .create_histogram(
+ "warehouse_import_handoffs_per_run",
+ "Worker-shutdown hand-offs of the import activity in one workflow run.",
+ )
+ )
+
+
def emit_data_import_app_metrics(job: "ExternalDataJob") -> None:
"""Emit app_metrics2 rows for a data import job that just reached terminal state.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
index c67b0cc77a6f..d95fc7aa8bcd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
@@ -8,15 +8,15 @@ class PipelineResult(TypedDict):
writes the terminal job status, releases the v3 sync lock, and starts the post-import
workflow:
- - False / absent (a zero-batch run, and every failure path — an activity that raises returns
- no result): the workflow finalizes in its `finally` block.
+ - False / absent (a fresh zero-batch run, and every failure path — an activity that raises
+ returns no result): the workflow finalizes in its `finally` block.
- True: the v3 load consumer finalizes after loading the final batch, and the workflow must
keep its hands off all three.
It is a runtime value, not a pure property of `ExternalDataJob.pipeline_version`, for one
- reason: a v3 extraction that produced zero batches never notifies the load consumer, so the
- consumer cannot finalize a run it will never hear about — the workflow must. PipelineV3
- therefore reports True iff at least one batch reached the queue. The other producer of True,
+ reason: a fresh v3 extraction that produced zero batches never notifies the load consumer, so
+ the consumer cannot finalize a run it will never hear about — the workflow must. A zero-batch
+ continuation instead appends a final marker to the earlier attempt's queued batches. The other producer of True,
`import_data_sync`'s terminal-retry skip, is a run some other party already finalized, where
True likewise means "workflow: hands off".
Making this a pure version property requires an empty-final-batch queue message so the
@@ -25,6 +25,11 @@ class PipelineResult(TypedDict):
`fast_returned` marks a run completed on a negative source probe, before any extraction.
It always rides with `skip_post_import_activities=True` (which does the actual skipping);
the workflow reads it only to count these runs separately from other skipped ones.
+
+ `handed_off` marks an attempt that left a worker which is shutting down. The import is not
+ done: the workflow runs the activity again. Only an activity whose input says that hand-offs
+ are free returns it. `handoff_attempts_used` is the Temporal attempt number that handed off,
+ which the workflow adds up so the next execution continues the attempt numbers.
"""
should_trigger_cdp_producer: bool
@@ -32,3 +37,5 @@ class PipelineResult(TypedDict):
skip_post_import_activities: NotRequired[bool]
prepared_queryable_folder: NotRequired[str]
fast_returned: NotRequired[bool]
+ handed_off: NotRequired[bool]
+ handoff_attempts_used: NotRequired[int]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/handoff_checkpoint.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/handoff_checkpoint.py
new file mode 100644
index 000000000000..e8e1b3aabce0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/handoff_checkpoint.py
@@ -0,0 +1,122 @@
+from bisect import bisect_left
+from itertools import pairwise
+from typing import Any
+
+import pyarrow as pa
+import pyarrow.compute as pc
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, process_incremental_value
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import normalize_column_name
+
+
+@frozen
+class IncrementalBatchRange:
+ """The incremental values of one batch whose rows are in ascending order."""
+
+ first: Any
+ last: Any
+ # The largest value below `last`, or None when every row holds `last`.
+ below_last: Any
+
+
+class IncrementalBatchRangeReader:
+ """Reads the `IncrementalBatchRange` of a batch, or None when the batch gives no safe range.
+
+ A batch gives no range when its incremental column is missing, holds a null, or is not in
+ ascending order.
+ """
+
+ def __init__(self, schema: ExternalDataSchema) -> None:
+ self._field_type = schema.incremental_field_type
+ self._column_name = normalize_column_name(schema.incremental_field) if schema.incremental_field else None
+
+ def read(self, table: pa.Table) -> IncrementalBatchRange | None:
+ if self._column_name is None or self._column_name not in table.column_names:
+ return None
+ column = table[self._column_name]
+ if len(column) == 0 or column.null_count > 0:
+ return None
+ if self._orders_like_its_processed_values(column.type):
+ return self._read_native(column.combine_chunks())
+ return self._read_processed([self._process(value) for value in column.to_pylist()])
+
+ @staticmethod
+ def _orders_like_its_processed_values(arrow_type: pa.DataType) -> bool:
+ # `process_incremental_value` keeps the order of these types. A string can hold a date in
+ # any format, so its order is known only after the values are processed.
+ return (
+ pa.types.is_integer(arrow_type)
+ or pa.types.is_floating(arrow_type)
+ or pa.types.is_decimal(arrow_type)
+ or pa.types.is_timestamp(arrow_type)
+ or pa.types.is_date(arrow_type)
+ )
+
+ def _process(self, value: Any) -> Any:
+ return process_incremental_value(value, self._field_type)
+
+ def _read_native(self, column: pa.Array) -> IncrementalBatchRange | None:
+ size = len(column)
+ if not pc.all(pc.less_equal(column.slice(0, size - 1), column.slice(1))).as_py():
+ return None
+ last = column[size - 1]
+ rows_below_last = pc.less(column, last).true_count
+ return self._range(
+ first=self._process(column[0].as_py()),
+ last=self._process(last.as_py()),
+ below_last=self._process(column[rows_below_last - 1].as_py()) if rows_below_last else None,
+ )
+
+ def _read_processed(self, values: list[Any]) -> IncrementalBatchRange | None:
+ try:
+ if any(value is None for value in values) or not all(a <= b for a, b in pairwise(values)):
+ return None
+ rows_below_last = bisect_left(values, values[-1])
+ except TypeError:
+ return None
+ return self._range(
+ first=values[0], last=values[-1], below_last=values[rows_below_last - 1] if rows_below_last else None
+ )
+
+ @staticmethod
+ def _range(*, first: Any, last: Any, below_last: Any) -> IncrementalBatchRange | None:
+ if first is None or last is None:
+ return None
+ return IncrementalBatchRange(first=first, last=last, below_last=below_last)
+
+
+class IncrementalHandoffCheckpoint:
+ """Finds the incremental value a later attempt of the same workflow run can resume after.
+
+ Feed it every batch in the order the run stages them. The resume value stays below the newest
+ value seen, because rows that share the newest value can still arrive in a later batch and a
+ source reads strictly above the value it gets. Rows that arrive out of ascending order void
+ the checkpoint: a row that is still to come can then be below a value already given out.
+ """
+
+ def __init__(self, resume_value: Any = None) -> None:
+ self._resume_value = resume_value
+ self._newest: Any = None
+ self._void = False
+
+ @property
+ def resume_value(self) -> Any:
+ return None if self._void else self._resume_value
+
+ def observe(self, batch: IncrementalBatchRange | None) -> None:
+ if self._void:
+ return
+ try:
+ if batch is None or (self._newest is not None and batch.first < self._newest):
+ self._void = True
+ return
+ candidate = batch.below_last
+ if candidate is None and self._newest is not None and self._newest < batch.last:
+ candidate = self._newest
+ if candidate is not None and (self._resume_value is None or candidate > self._resume_value):
+ self._resume_value = candidate
+ self._newest = batch.last
+ except TypeError:
+ self._void = True
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 0b3b616b083c..4cbca6eb5958 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
@@ -89,6 +89,8 @@ class LanedPipelineV3(PipelineV3[ResumableData]):
*,
models: ImportJobModels,
source_cursor_manager: SourceCursorManager[Any] | None = None,
+ incremental_checkpoints_allowed: bool = False,
+ resumed_incremental_value: Any = None,
) -> None:
if not source_response.lanes:
raise ValueError(f"{source_response.name} declares no lanes; run it on PipelineV3")
@@ -103,6 +105,8 @@ class LanedPipelineV3(PipelineV3[ResumableData]):
resumable_source_manager,
models=models,
source_cursor_manager=source_cursor_manager,
+ incremental_checkpoints_allowed=incremental_checkpoints_allowed,
+ resumed_incremental_value=resumed_incremental_value,
)
# 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/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/metrics.py
index acc6bc4442ab..44077c4976d5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/metrics.py
@@ -1,6 +1,8 @@
from temporalio import activity
from temporalio.common import MetricCounter, MetricHistogram, MetricHistogramFloat
+from products.warehouse_sources.backend.temporal.data_imports.import_attempt import ImportAttemptCause
+
def get_rows_extracted_metric(team_id: str, schema_id: str, source_type: str) -> MetricCounter:
return (
@@ -44,8 +46,12 @@ def get_pipeline_run_duration_metric(
)
-def get_run_attempt_metric(source_type: str) -> MetricHistogram:
- """Temporal activity attempt number, recorded once as each attempt starts extracting.
+def get_run_attempt_metric(source_type: str, cause: ImportAttemptCause) -> MetricHistogram:
+ """Attempt number of the import in its workflow run, recorded once as each attempt starts extracting.
+
+ `cause` separates the reasons an attempt past the first one runs. `handoff` is an attempt the
+ workflow started after a worker shutdown, which uses none of the retry budget. `retry` is an
+ attempt Temporal started, so it used one retry.
Every attempt of a run stages a fresh set of batches under its own ``run_uuid`` (see
``pipeline.py``), and the idempotency key is keyed on that ``run_uuid`` — so a retried run
@@ -57,14 +63,14 @@ def get_run_attempt_metric(source_type: str) -> MetricHistogram:
retries, not workflow attempts. Read this as a distribution — a p99 above a handful means
runs are being restarted repeatedly and paying for the same extraction each time.
- Labelled by ``source_type`` only. Attempts are a per-run property, so team/schema labels would
- add cardinality without telling you anything the distribution does not.
+ Attempts are a per-run property, so team/schema labels would add cardinality without telling
+ you anything the distribution does not.
"""
return (
activity.metric_meter()
- .with_additional_attributes({"source_type": source_type})
+ .with_additional_attributes({"source_type": source_type, "cause": cause})
.create_histogram(
"warehouse_pipeline_run_attempt",
- "Temporal activity attempt number at the start of a pipeline run",
+ "Attempt number of the import in its workflow run at the start of a pipeline run",
)
)
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 402cf7454011..851cb8a352f0 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
@@ -11,11 +11,7 @@ from temporalio import activity
from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
from posthog.sync import database_sync_to_async_pool
-from posthog.temporal.common.activity_context import (
- current_activity_attempt,
- current_workflow_id,
- current_workflow_run_id,
-)
+from posthog.temporal.common.activity_context import current_workflow_id, current_workflow_run_id
from posthog.temporal.common.shutdown import ShutdownMonitor
from posthog.utils import get_machine_id
@@ -28,6 +24,10 @@ 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.import_attempt import (
+ current_import_attempt,
+ current_import_attempt_cause,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
cleanup_memory,
commit_source_cursor,
@@ -69,6 +69,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.sin
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import record_source_item_stats
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.handoff_checkpoint import (
+ IncrementalBatchRangeReader,
+ IncrementalHandoffCheckpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.metrics import (
get_batches_produced_metric,
get_pipeline_run_duration_metric,
@@ -140,6 +144,18 @@ class PipelineV3(Generic[ResumableData]):
_pg_producer: PostgresProducer
_accumulated_pa_schema: pa.Schema | None
_batch_results: list[BatchWriteResult]
+ # Set only for a run that can continue from its last queued batch after an interruption.
+ _handoff_checkpoint: IncrementalHandoffCheckpoint | None = None
+ _batch_range_reader: IncrementalBatchRangeReader
+ _staged_handoff_resume_value: Any = None
+ _staged_handoff_resume_owner: str | None = None
+ # True once this attempt has queued a batch of its own, rather than only inheriting the
+ # resume value an earlier attempt recorded. Decides who owns the queue rows the value describes.
+ _queued_own_batch: bool = False
+ # True when this attempt reads the source after a value an earlier attempt of the run recorded.
+ _continues_incremental_handoff: bool = False
+ _resumed_incremental_run_uuid: str | None = None
+ _sent_resumed_run_finalization: bool = False
def __init__(
self,
@@ -152,6 +168,9 @@ class PipelineV3(Generic[ResumableData]):
*,
models: "ImportJobModels",
source_cursor_manager: SourceCursorManager[Any] | None = None,
+ incremental_checkpoints_allowed: bool = False,
+ resumed_incremental_run_uuid: str | None = None,
+ resumed_incremental_value: Any = None,
) -> None:
self._resource = source_response
self._source_cursor_manager = source_cursor_manager
@@ -182,7 +201,7 @@ class PipelineV3(Generic[ResumableData]):
self._delta_table_ref = DeltaTableRef(self._resource_name, self._job, self._logger)
- attempt = current_activity_attempt()
+ 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._s3_batch_writer = self._build_s3_writer(self._run_uuid)
@@ -225,7 +244,18 @@ class PipelineV3(Generic[ResumableData]):
self._observed_columns: dict[str, dict[str, Any]] = {}
self._resumable_source_manager = resolve_resume_manager(resumable_source_manager, self._resource)
- is_resume = self._resumable_source_manager is not None and self._resumable_source_manager.can_resume()
+ # The earlier attempts of this run queued every row up to the value this attempt reads after,
+ # and this attempt does not extract those rows again. The queue must therefore treat it as a
+ # resume: a fresh run replaces the queue rows of earlier attempts and overwrites on batch 0.
+ self._continues_incremental_handoff = resumed_incremental_value is not None
+ self._resumed_incremental_run_uuid = resumed_incremental_run_uuid
+ self._sent_resumed_run_finalization = False
+ is_resume = self._continues_incremental_handoff or (
+ self._resumable_source_manager is not None and self._resumable_source_manager.can_resume()
+ )
+ if incremental_checkpoints_allowed and self._tracks_handoff_checkpoint(source_response, reset_pipeline):
+ self._handoff_checkpoint = IncrementalHandoffCheckpoint(resumed_incremental_value)
+ self._batch_range_reader = IncrementalBatchRangeReader(self._schema)
# Resolved in `_get_models`, not here: the pipeline is built inside an async activity,
# so the query that tells the warehouse from an external destination cannot run here.
@@ -275,6 +305,24 @@ class PipelineV3(Generic[ResumableData]):
models.schema.incremental_field_earliest_value, models.schema.incremental_field_type
)
+ def _tracks_handoff_checkpoint(self, source_response: SourceResponse, reset_pipeline: bool) -> bool:
+ """Whether a later attempt of this run can continue from the batches this attempt queues.
+
+ The source must promise ascending order, and nothing else may own the restart point: a
+ source that resumes from its own cursor reads that cursor, and a reset reloads the table.
+ A run that writes several tables keeps one queue per table, which one value cannot cover.
+ """
+ return (
+ self._schema.is_incremental
+ and bool(self._schema.incremental_field)
+ and source_response.sort_mode == "asc"
+ and not reset_pipeline
+ and self._resumable_source_manager is None
+ and not source_response.lanes
+ and source_response.cdc_write_mode is None
+ and self._run_uuid is not None
+ )
+
# The seams below are where a run that writes several tables from one read plugs in (see
# `lanes.py`). Each default is exactly what a single-table run has always done.
@@ -316,7 +364,20 @@ class PipelineV3(Generic[ResumableData]):
batch_result = await asyncio.to_thread(self._s3_batch_writer.write_batch, pa_table, batch_index)
self._batch_results.append(batch_result)
- self._pg_producer.hold_batch(batch_result, cumulative_row_count=row_count)
+ # `hold_batch` only inserts the batch this attempt is already holding, not the one it is
+ # about to hold. A row from this attempt exists in the queue only once this call flushes one.
+ flushes_a_held_batch = self._pg_producer.has_held_batch
+ try:
+ self._pg_producer.hold_batch(batch_result, cumulative_row_count=row_count)
+ except Exception:
+ # The insert that failed belongs to the batch before this one. The checkpoint already
+ # counts that batch, so no later value of it is safe. The value staged earlier stays valid.
+ self._handoff_checkpoint = None
+ raise
+ if flushes_a_held_batch:
+ # This attempt now owns an inserted queue row, so any resume value it stages from here
+ # describes rows it holds, not rows an earlier attempt queued.
+ self._queued_own_batch = True
return pa_table.num_rows
def _total_batches(self) -> int:
@@ -324,7 +385,7 @@ class PipelineV3(Generic[ResumableData]):
def _consumer_finalizes_this_run(self) -> bool:
"""Whether the load consumer will finalize THIS job, so the workflow must not."""
- return self._total_batches() > 0
+ return self._total_batches() > 0 or self._sent_resumed_run_finalization
async def _send_final_batches(self, total_batches: int, row_count: int) -> str | None:
schema_path = await asyncio.to_thread(self._s3_batch_writer.write_schema)
@@ -340,7 +401,9 @@ class PipelineV3(Generic[ResumableData]):
def _release_held_batches(self) -> None:
"""Put every held queue row into the queue now, as a non-final row."""
- self._pg_producer.release_held_batch()
+ if self._pg_producer.release_held_batch():
+ # The row this attempt was holding is inserted now, so it owns a queue row of its own.
+ self._queued_own_batch = True
def _mark_first_ever_sync(self) -> None:
self._pg_producer.is_first_ever_sync = True
@@ -382,14 +445,59 @@ class PipelineV3(Generic[ResumableData]):
self._release_held_batches()
await asyncio.to_thread(self._resumable_source_manager.commit)
+ async def _stage_handoff_resume_value(self, *, force: bool = False) -> None:
+ """Persist the checkpoint's value. Call it only when every observed batch has its queue row.
+
+ Until this attempt queues a batch of its own, the value is still inherited from an earlier
+ attempt and describes rows that attempt's queue holds. The owner recorded alongside it
+ stays that earlier attempt's run until this one actually queues a row, so a later zero-batch
+ continuation finalizes whichever run truly holds the queued rows.
+ """
+ if self._handoff_checkpoint is None:
+ return
+ resume_value = self._handoff_checkpoint.resume_value
+ # None (the common case) means "whichever run stages this", resolved against `run_uuid` on
+ # the model side. Only the inheritance window - before this attempt has queued a batch of
+ # its own - needs an explicit owner, so a zero-batch continuation still finalizes the run
+ # that holds the rows instead of this one, which holds none yet.
+ owner_run_uuid = None if self._queued_own_batch else self._resumed_incremental_run_uuid
+ if (
+ not force
+ and resume_value == self._staged_handoff_resume_value
+ and owner_run_uuid == self._staged_handoff_resume_owner
+ ):
+ return
+ await database_sync_to_async_pool(self._schema.stage_handoff_resume_value)(
+ self._s3_batch_writer.get_run_uuid(), resume_value, owner_run_uuid
+ )
+ self._staged_handoff_resume_value = resume_value
+ self._staged_handoff_resume_owner = owner_run_uuid
+
+ async def _advance_handoff_checkpoint(self, pa_table: pa.Table) -> None:
+ if self._handoff_checkpoint is None:
+ return
+ # Staging this batch inserted the queue row of the batch before it, so the value from before
+ # this batch is safe now. The row of this batch is still held back.
+ await self._stage_handoff_resume_value()
+ if pa_table.num_rows > 0:
+ self._handoff_checkpoint.observe(self._batch_range_reader.read(pa_table))
+ if self._handoff_checkpoint.resume_value is None:
+ # The checkpoint became void. The next attempt must not use the value staged earlier.
+ await self._stage_handoff_resume_value()
+
async def run(self) -> PipelineResult:
pa_memory_pool = pa.default_memory_pool()
- should_resume = self._resumable_source_manager is not None and self._resumable_source_manager.can_resume()
+ resumes_source_cursor = (
+ self._resumable_source_manager is not None and self._resumable_source_manager.can_resume()
+ )
+ should_resume = resumes_source_cursor or self._continues_incremental_handoff
source_is_resumable = self._resumable_source_manager is not None
- if should_resume:
+ if resumes_source_cursor:
await self._logger.ainfo("V3 Pipeline: Resumable source detected - attempting to resume previous import")
+ elif self._continues_incremental_handoff:
+ await self._logger.ainfo("V3 Pipeline: Continuing the incremental import after its last queued batch")
team_id_str = str(self._job.team_id)
schema_id_str = str(self._schema.id)
@@ -400,7 +508,7 @@ class PipelineV3(Generic[ResumableData]):
# work. A rising distribution means runs are restarting and re-extracting what earlier
# attempts already staged.
if activity.in_activity():
- get_run_attempt_metric(source_type).record(self._attempt)
+ get_run_attempt_metric(source_type, current_import_attempt_cause()).record(self._attempt)
start_time = time.perf_counter()
status = "success"
@@ -491,6 +599,11 @@ class PipelineV3(Generic[ResumableData]):
# Every yielded row is staged now, so whatever the source staged last is safe.
await self._commit_resume_state()
+ if self._attempt > 1:
+ # Written before this attempt can replace the queue rows of an earlier attempt, so the
+ # attempt after this one never reads a value that describes rows which are gone.
+ await self._stage_handoff_resume_value(force=True)
+
items = self._resource.items()
safe_point_scope = self._activate_safe_point(items)
awaiting_source = True
@@ -538,6 +651,12 @@ class PipelineV3(Generic[ResumableData]):
await self._commit_resume_state()
if should_check_shutdown(self._schema, self._resource, self._reset_pipeline, source_is_resumable):
+ if self._handoff_checkpoint is not None and self._shutdown_monitor.is_worker_shutdown():
+ # The next attempt continues after the last staged batch, so staging the
+ # buffered rows now keeps it from extracting them again. A source with its
+ # own cursor does not get this: its cursor can be behind the buffered rows,
+ # and staging them would load them a second time after the resume.
+ await stage_remaining_rows()
self._shutdown_monitor.raise_if_is_worker_shutdown()
awaiting_source = True
except Exception:
@@ -580,6 +699,12 @@ class PipelineV3(Generic[ResumableData]):
self._release_held_batches()
except Exception:
self._logger.exception("V3 Pipeline: Failed to enqueue the held batch after the extraction error")
+ else:
+ # Every staged batch has its queue row now, so the next attempt can continue after them.
+ try:
+ await self._stage_handoff_resume_value()
+ except Exception:
+ self._logger.exception("V3 Pipeline: Failed to record where the next attempt can continue")
raise
finally:
duration = time.perf_counter() - start_time
@@ -662,6 +787,7 @@ class PipelineV3(Generic[ResumableData]):
)
self._last_incremental_field_value = incremental_values.last_value
self._earliest_incremental_field_value = incremental_values.earliest_value
+ await self._advance_handoff_checkpoint(pa_table)
await update_row_tracking_after_batch(
str(self._job.id), self._job.team_id, self._schema.id, tracked_rows, self._logger
@@ -703,6 +829,15 @@ class PipelineV3(Generic[ResumableData]):
total_batches = self._total_batches()
if total_batches == 0:
+ if self._continues_incremental_handoff:
+ if self._resumed_incremental_run_uuid is None:
+ raise RuntimeError("A resumed incremental import has no queue run to finalize")
+ await asyncio.to_thread(
+ self._pg_producer.send_final_batch_for_resumed_run, self._resumed_incremental_run_uuid
+ )
+ self._sent_resumed_run_finalization = True
+ return
+
# A zero-batch run still ran the full extraction, which is what the fast-return
# valve counts. Post-load stamps this on every other path but never runs here: with
# no batches the load consumer is never notified. Without this a v3 schema whose
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
index 2a8bec7ec0f5..d7dd484ce532 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
@@ -199,6 +199,34 @@ class PostgresProducer:
cumulative_row_count=total_rows,
)
+ def send_final_batch_for_resumed_run(self, run_uuid: str) -> None:
+ """Append a final-only copy of the last queued batch from an earlier attempt."""
+ with _queue_db_errors():
+ cursor = self._conn.execute(
+ f"""
+ INSERT INTO {BATCH_TABLE} (
+ team_id, schema_id, source_id, job_id, run_uuid,
+ batch_index, s3_path, row_count, byte_size, is_final_batch,
+ total_batches, total_rows, sync_type, cumulative_row_count,
+ resource_name, is_resume, is_first_ever_sync, metadata, destination_ids, created_at
+ )
+ SELECT
+ team_id, schema_id, source_id, job_id, run_uuid,
+ batch_index, s3_path, row_count, byte_size, TRUE,
+ batch_index + 1, cumulative_row_count, sync_type, cumulative_row_count,
+ resource_name, is_resume, is_first_ever_sync, metadata, destination_ids, now()
+ FROM {BATCH_TABLE}
+ WHERE job_id = %(job_id)s AND run_uuid = %(run_uuid)s
+ ORDER BY batch_index DESC, created_at DESC
+ LIMIT 1
+ """,
+ {"job_id": self._job_id, "run_uuid": run_uuid},
+ )
+ if cursor.rowcount != 1:
+ raise RuntimeError(f"Could not finalize resumed queue run {run_uuid}")
+ self._batches_sent += 1
+ self._logger.info("resumed_run_final_batch_inserted", run_uuid=run_uuid)
+
def send_batch_notification(
self,
batch_result: BatchWriteResult,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
index c8c5fad14b02..a02d878aa13e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
@@ -327,6 +327,23 @@ class TestPostgresProducerHeldBatch:
assert _inserted_rows(producer) == [(0, False), (0, True)]
+ def test_a_zero_batch_continuation_finalizes_the_previous_queue_run(self) -> None:
+ producer = _make_producer()
+ _mock_conn(producer).execute.return_value.rowcount = 1
+
+ producer.send_final_batch_for_resumed_run("workflow-run-a1")
+
+ query, params = _mock_conn(producer).execute.call_args.args
+ assert "batch_index + 1, cumulative_row_count" in query
+ assert params == {"job_id": "job-1", "run_uuid": "workflow-run-a1"}
+
+ def test_a_zero_batch_continuation_fails_if_the_previous_queue_run_is_missing(self) -> None:
+ producer = _make_producer()
+ _mock_conn(producer).execute.return_value.rowcount = 0
+
+ with pytest.raises(RuntimeError, match="Could not finalize resumed queue run"):
+ producer.send_final_batch_for_resumed_run("workflow-run-a1")
+
def test_superseding_fires_when_batch_zero_is_staged_not_when_it_is_inserted(self) -> None:
# Holding the row back must not delay retiring the previous attempt's stalled batches, or
# they stay claimable for one extra batch of extraction time.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_handoff_checkpoint.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_handoff_checkpoint.py
new file mode 100644
index 000000000000..435d9e52b526
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_handoff_checkpoint.py
@@ -0,0 +1,173 @@
+from datetime import date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+import pyarrow as pa
+
+from products.warehouse_sources.backend.models.external_data_schema import staged_handoff_resume_value
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.handoff_checkpoint import (
+ IncrementalBatchRange,
+ IncrementalBatchRangeReader,
+ IncrementalHandoffCheckpoint,
+)
+from products.warehouse_sources.backend.types import IncrementalFieldType
+
+
+def _reader(field_type: IncrementalFieldType) -> IncrementalBatchRangeReader:
+ return IncrementalBatchRangeReader(MagicMock(incremental_field="Updated At", incremental_field_type=field_type))
+
+
+ "field_type,values,expected",
+ [
+ pytest.param(IncrementalFieldType.Integer, [1, 2, 2, 5], (1, 5, 2), id="native_ascending"),
+ pytest.param(IncrementalFieldType.Integer, [7, 7, 7], (7, 7, None), id="every_row_shares_one_value"),
+ pytest.param(IncrementalFieldType.Integer, [1, 3, 2], None, id="native_out_of_order"),
+ pytest.param(IncrementalFieldType.Integer, [1, None, 2], None, id="null_value"),
+ pytest.param(IncrementalFieldType.Integer, [], None, id="empty_batch"),
+ pytest.param(
+ IncrementalFieldType.DateTime,
+ [datetime(2026, 1, 1), datetime(2026, 1, 2), datetime(2026, 1, 2)],
+ (datetime(2026, 1, 1), datetime(2026, 1, 2), datetime(2026, 1, 1)),
+ id="native_timestamps",
+ ),
+ pytest.param(
+ IncrementalFieldType.Date,
+ [date(2026, 1, 1), date(2026, 1, 3)],
+ (date(2026, 1, 1), date(2026, 1, 3), date(2026, 1, 1)),
+ id="native_dates",
+ ),
+ # Text order and time order differ here: "9" sorts after "10" as text.
+ pytest.param(
+ IncrementalFieldType.DateTime,
+ ["2026-01-09T00:00:00", "2026-01-10T00:00:00"],
+ (datetime(2026, 1, 9), datetime(2026, 1, 10), datetime(2026, 1, 9)),
+ id="strings_ordered_by_their_parsed_value",
+ ),
+ pytest.param(
+ IncrementalFieldType.DateTime,
+ ["2026-01-10T00:00:00", "2026-01-09T00:00:00"],
+ None,
+ id="strings_out_of_order",
+ ),
+ ],
+)
+def test_batch_range_is_read_only_from_ascending_rows(
+ field_type: IncrementalFieldType, values: list[Any], expected: tuple[Any, Any, Any] | None
+) -> None:
+ batch = _reader(field_type).read(pa.table({"updated_at": values, "id": list(range(len(values)))}))
+
+ if expected is None:
+ assert batch is None
+ else:
+ assert batch == IncrementalBatchRange(first=expected[0], last=expected[1], below_last=expected[2])
+
+
+def test_a_batch_without_the_incremental_column_gives_no_range() -> None:
+ assert _reader(IncrementalFieldType.Integer).read(pa.table({"id": [1, 2]})) is None
+
+
+def _range(first: int, last: int, below_last: int | None) -> IncrementalBatchRange:
+ return IncrementalBatchRange(first=first, last=last, below_last=below_last)
+
+
+ "seed,batches,expected",
+ [
+ pytest.param(None, [_range(1, 5, 4)], 4, id="stays_below_the_newest_value"),
+ # Rows that share 5 can continue in the next batch, so 5 is not safe until a larger value shows up.
+ pytest.param(None, [_range(5, 5, None)], None, id="one_value_only_gives_nothing"),
+ pytest.param(None, [_range(1, 5, 4), _range(5, 5, None)], 4, id="a_tie_across_batches_does_not_advance"),
+ pytest.param(None, [_range(5, 5, None), _range(6, 6, None)], 5, id="previous_newest_is_safe_once_passed"),
+ pytest.param(None, [_range(1, 5, 4), _range(5, 9, 8)], 8, id="advances_batch_by_batch"),
+ pytest.param(None, [_range(1, 5, 4), _range(3, 9, 8)], None, id="a_batch_below_the_newest_value_voids"),
+ pytest.param(None, [_range(1, 5, 4), None], None, id="a_batch_with_no_range_voids"),
+ pytest.param(None, [_range(1, 5, 4), None, _range(6, 9, 8)], None, id="a_void_checkpoint_stays_void"),
+ pytest.param(7, [], 7, id="keeps_the_value_it_continued_from"),
+ pytest.param(7, [_range(2, 6, 5)], 7, id="never_moves_back_below_the_value_it_continued_from"),
+ pytest.param(7, [_range(8, 12, 11)], 11, id="advances_past_the_value_it_continued_from"),
+ ],
+)
+def test_resume_value_covers_only_rows_that_cannot_have_later_siblings(
+ seed: int | None, batches: list[IncrementalBatchRange | None], expected: int | None
+) -> None:
+ checkpoint = IncrementalHandoffCheckpoint(seed)
+ for batch in batches:
+ checkpoint.observe(batch)
+
+ assert checkpoint.resume_value == expected
+
+
+ "config,workflow_run_id,expected",
+ [
+ pytest.param({}, "run-1", None, id="nothing_staged"),
+ pytest.param(
+ {"incremental_staged": {"run_uuid": "run-1-a1", "last_value": 50, "resume_value": 40}},
+ "run-1",
+ 40,
+ id="live_slot_of_this_run",
+ ),
+ pytest.param(
+ {"incremental_staged": {"run_uuid": "run-1-a1", "last_value": 50, "resume_value": 40}},
+ "run-2",
+ None,
+ id="another_workflow_run_never_reads_it",
+ ),
+ pytest.param(
+ {"incremental_staged": {"run_uuid": "run-1-a1", "last_value": 50, "resume_value": 40}},
+ None,
+ None,
+ id="no_workflow_run",
+ ),
+ pytest.param(
+ {
+ "incremental_staged": {"run_uuid": "run-1-a2", "last_value": 90, "resume_value": 80},
+ "incremental_staged_pending": [{"run_uuid": "run-1-a1", "last_value": 50, "resume_value": 40}],
+ },
+ "run-1",
+ 80,
+ id="newest_attempt_wins_over_a_parked_one",
+ ),
+ pytest.param(
+ {
+ "incremental_staged": {"run_uuid": "run-1-a2", "last_value": 50, "resume_value": 40},
+ "incremental_staged_pending": [{"run_uuid": "run-1-a10", "last_value": 90, "resume_value": 80}],
+ },
+ "run-1",
+ 80,
+ id="attempts_compare_as_numbers",
+ ),
+ # Attempt 2 restarted from the stored watermark and can have replaced attempt 1's queue rows.
+ pytest.param(
+ {
+ "incremental_staged": {"run_uuid": "run-1-a2", "last_value": 20},
+ "incremental_staged_pending": [{"run_uuid": "run-1-a1", "last_value": 50, "resume_value": 40}],
+ },
+ "run-1",
+ None,
+ id="newest_attempt_without_a_value_hides_older_values",
+ ),
+ pytest.param(
+ {
+ "incremental_staged": {"run_uuid": "run-1-a2", "resume_value": None},
+ "incremental_staged_pending": [{"run_uuid": "run-1-a1", "last_value": 50, "resume_value": 40}],
+ },
+ "run-1",
+ None,
+ id="newest_attempt_recorded_that_it_has_no_value",
+ ),
+ pytest.param(
+ {"incremental_staged": {"run_uuid": "run-10-a1", "last_value": 50, "resume_value": 40}},
+ "run-1",
+ None,
+ id="run_id_prefix_of_another_run",
+ ),
+ ],
+)
+def test_staged_resume_value_comes_from_the_newest_attempt_of_the_same_workflow_run(
+ config: dict[str, Any], workflow_run_id: str | None, expected: int | None
+) -> None:
+ assert staged_handoff_resume_value(config, workflow_run_id) == expected
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 f7686b22126c..a6c4ba1f3db9 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
@@ -2,7 +2,7 @@ import json
from contextlib import ExitStack, nullcontext
from dataclasses import dataclass
from types import SimpleNamespace
-from typing import cast
+from typing import Any, cast
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -13,6 +13,10 @@ from asgiref.sync import async_to_sync
from posthog.temporal.common.shutdown import WorkerShuttingDownError
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.handoff_checkpoint import (
+ IncrementalBatchRangeReader,
+ IncrementalHandoffCheckpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.lanes import (
LanedPipelineV3,
_LaneWriter,
@@ -38,6 +42,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
ImportJobModels,
)
+from products.warehouse_sources.backend.types import IncrementalFieldType
_PIPELINE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline"
_SAFE_POINT = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.safe_point"
@@ -97,6 +102,9 @@ def _make_pipeline() -> PipelineV3:
pipeline._attempt = 1
pipeline._uses_delta_write_column_selection = False
pipeline._observed_columns = {}
+ pipeline._continues_incremental_handoff = False
+ pipeline._resumed_incremental_run_uuid = None
+ pipeline._sent_resumed_run_finalization = False
return pipeline
@@ -141,7 +149,7 @@ class TestAttemptScopedRunUuid:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.current_activity_attempt",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.current_import_attempt",
return_value=3,
),
patch(
@@ -271,7 +279,7 @@ class TestCDCSourceWiring:
base = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline"
with (
- patch(f"{base}.current_activity_attempt", return_value=1),
+ patch(f"{base}.current_import_attempt", return_value=1),
patch(f"{base}.current_workflow_id", return_value="wf-1"),
patch(f"{base}.current_workflow_run_id", return_value="wfrun-abc"),
patch(f"{base}.S3BatchWriter"),
@@ -386,7 +394,7 @@ def _build_laned(lanes) -> LanedPipelineV3:
lanes=lanes,
)
with (
- patch(f"{_PIPELINE}.current_activity_attempt", return_value=3),
+ patch(f"{_PIPELINE}.current_import_attempt", return_value=3),
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"),
@@ -1103,7 +1111,7 @@ class TestResumeCursorCommit:
assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == ["a", "b"]
-def _recording_producer(events: list[str] | None = None) -> PostgresProducer:
+def _recording_producer(events: list[str] | None = None, *, is_resume: bool = False) -> PostgresProducer:
"""A real producer over a mocked queue connection, so the rows it inserts can be read back."""
with patch(f"{_PRODUCER}.psycopg") as mock_psycopg:
conn = MagicMock()
@@ -1120,6 +1128,7 @@ def _recording_producer(events: list[str] | None = None) -> PostgresProducer:
sync_type="full_refresh",
run_uuid="run-1",
logger=MagicMock(),
+ is_resume=is_resume,
)
return producer
@@ -1200,6 +1209,19 @@ class TestFinalMarkerIsTheLastDataRow:
stack.enter_context(patch(f"{_PIPELINE}.activity")).in_activity.return_value = False
await pipeline.run()
+ @pytest.mark.asyncio
+ async def test_a_zero_batch_continuation_finalizes_the_earlier_queue_run(self) -> None:
+ pipeline = _make_pipeline()
+ pipeline._continues_incremental_handoff = True
+ pipeline._resumed_incremental_run_uuid = "workflow-run-a1"
+
+ await pipeline._finalize(row_count=0)
+
+ cast(MagicMock, pipeline._pg_producer.send_final_batch_for_resumed_run).assert_called_once_with(
+ "workflow-run-a1"
+ )
+ assert pipeline._consumer_finalizes_this_run() is True
+
@pytest.mark.parametrize(
"ids,expected_rows",
[
@@ -1277,3 +1299,288 @@ class TestFinalMarkerIsTheLastDataRow:
await self._run(pipeline)
assert _queue_rows(producer) == [(0, False)]
+
+
+def _passthrough_pool(fn):
+ async def call(*args, **kwargs):
+ return fn(*args, **kwargs)
+
+ return call
+
+
+class TestIncrementalHandoffCheckpoint:
+ def _pipeline(self, items, events: list[Any], *, resumed_from: int | None = None) -> PipelineV3:
+ pipeline = _make_pipeline()
+ pipeline._pg_producer = _recording_producer(events)
+ pipeline._batcher = Batcher(MagicMock(), primary_keys=["id"])
+ pipeline._schema = MagicMock(
+ id="schema-1",
+ source_id="source-1",
+ is_incremental=True,
+ is_webhook=False,
+ is_append=False,
+ should_use_incremental_field=True,
+ incremental_field="n",
+ incremental_field_type=IncrementalFieldType.Integer,
+ table=None,
+ )
+ pipeline._schema.stage_handoff_resume_value.side_effect = lambda run_uuid, value, owner_run_uuid=None: (
+ events.append(("resume_value", value))
+ )
+ pipeline._s3_batch_writer = MagicMock(
+ write_batch=MagicMock(
+ side_effect=lambda table, index: BatchWriteResult(
+ s3_path=f"s3://data/{index}.parquet",
+ row_count=table.num_rows,
+ byte_size=1,
+ batch_index=index,
+ timestamp_ns=0,
+ )
+ ),
+ get_run_uuid=MagicMock(return_value="run-1"),
+ )
+ pipeline._resource = SourceResponse(name="test_table", items=items, primary_keys=["id"])
+ pipeline._handoff_checkpoint = IncrementalHandoffCheckpoint(resumed_from)
+ pipeline._staged_handoff_resume_value = resumed_from
+ pipeline._batch_range_reader = IncrementalBatchRangeReader(pipeline._schema)
+
+ async def stage_and_checkpoint(pa_table: pa.Table, batch_index: int, row_count: int) -> None:
+ await pipeline._stage_batch(pa_table, batch_index, row_count)
+ events.append(("staged_rows", pa_table.column("n").to_pylist()))
+ await pipeline._advance_handoff_checkpoint(pa_table)
+
+ pipeline._process_batch = AsyncMock(side_effect=stage_and_checkpoint) # type: ignore[method-assign]
+ return pipeline
+
+ async def _run(self, pipeline: PipelineV3, exc: type[BaseException]) -> None:
+ with ExitStack() as stack:
+ for name in (
+ "reset_rows_synced_if_needed",
+ "setup_row_tracking_with_billing_check",
+ "handle_reset_or_full_refresh",
+ "handle_corrupted_delta_log",
+ ):
+ stack.enter_context(patch(f"{_PIPELINE}.{name}", new_callable=AsyncMock))
+ for name in ("validate_incremental_sync", "record_source_item_stats"):
+ stack.enter_context(patch(f"{_PIPELINE}.{name}"))
+ stack.enter_context(patch(f"{_PIPELINE}.should_check_shutdown", return_value=True))
+ stack.enter_context(patch(f"{_PIPELINE}.database_sync_to_async_pool", new=_passthrough_pool))
+ stack.enter_context(patch(f"{_PRODUCER}.BatchQueue.supersede_other_runs", return_value=0))
+ stack.enter_context(patch(f"{_PIPELINE}.activity")).in_activity.return_value = False
+ with pytest.raises(exc):
+ await pipeline.run()
+
+ def _shut_down_at_check(self, pipeline: PipelineV3, check: int) -> None:
+ monitor = cast(MagicMock, pipeline._shutdown_monitor)
+ calls = {"n": 0}
+ shutdown = WorkerShuttingDownError("id", "type", "queue", 1, "workflow", "workflow_type")
+
+ def is_shutdown() -> bool:
+ calls["n"] += 1
+ return calls["n"] >= check
+
+ def raise_if_shutdown() -> None:
+ if calls["n"] >= check:
+ raise shutdown
+
+ monitor.is_worker_shutdown.side_effect = is_shutdown
+ monitor.raise_if_is_worker_shutdown.side_effect = raise_if_shutdown
+
+ @pytest.mark.asyncio
+ async def test_an_inherited_value_keeps_the_earlier_owner_until_this_attempt_queues_a_batch(self) -> None:
+ # a2 inherits a1's value before extracting anything. If a2 hands off before queuing a batch
+ # of its own, a3 must still finalize a1 - the run whose queue rows the value describes.
+ events: list[Any] = []
+ pipeline = self._pipeline(lambda: iter(()), events, resumed_from=40)
+ pipeline._resumed_incremental_run_uuid = "run-0"
+
+ stage_mock = cast(MagicMock, pipeline._schema.stage_handoff_resume_value)
+
+ await pipeline._stage_handoff_resume_value(force=True)
+
+ assert stage_mock.call_args.args == ("run-1", 40, "run-0")
+
+ # Once a2 queues a batch of its own, it owns the queue rows: the owner is cleared so the
+ # model defaults it to this run, even though the resume value itself has not changed yet.
+ pipeline._queued_own_batch = True
+ await pipeline._stage_handoff_resume_value()
+
+ assert stage_mock.call_args.args == ("run-1", 40, None)
+
+ # A later write from this attempt's own progress keeps the owner cleared.
+ cast(IncrementalHandoffCheckpoint, pipeline._handoff_checkpoint)._resume_value = 55
+ await pipeline._stage_handoff_resume_value()
+
+ assert stage_mock.call_args.args == ("run-1", 55, None)
+
+ @pytest.mark.asyncio
+ async def test_ownership_follows_a_queue_row_only_once_it_is_actually_inserted(self) -> None:
+ # The first batch an attempt holds is not inserted yet, so a crash right there must not grant
+ # this attempt ownership of a queue row it does not yet have.
+ pipeline = self._pipeline(lambda: iter(()), [], resumed_from=40)
+ pipeline._resumed_incremental_run_uuid = "run-0"
+ pipeline._pg_producer = _recording_producer(is_resume=True)
+
+ await pipeline._stage_batch(pa.table({"id": ["a"], "n": [1]}), 0, 1)
+ assert pipeline._queued_own_batch is False
+
+ # Holding a second batch flushes the first one into the queue, so it is now this attempt's.
+ await pipeline._stage_batch(pa.table({"id": ["b"], "n": [2]}), 1, 2)
+ assert pipeline._queued_own_batch is True
+
+ @pytest.mark.asyncio
+ async def test_releasing_a_held_batch_also_grants_ownership(self) -> None:
+ pipeline = self._pipeline(lambda: iter(()), [], resumed_from=40)
+ pipeline._resumed_incremental_run_uuid = "run-0"
+ pipeline._pg_producer = _recording_producer(is_resume=True)
+
+ await pipeline._stage_batch(pa.table({"id": ["a"], "n": [1]}), 0, 1)
+ assert pipeline._queued_own_batch is False
+
+ pipeline._release_held_batches()
+
+ assert pipeline._queued_own_batch is True
+
+ @pytest.mark.asyncio
+ async def test_a_handoff_stages_the_buffered_rows_and_then_records_where_to_continue(self) -> None:
+ events: list[Any] = []
+
+ def items():
+ yield [{"id": 1, "n": 10}, {"id": 2, "n": 11}]
+ yield [{"id": 3, "n": 12}]
+ yield [{"id": 4, "n": 13}]
+
+ pipeline = self._pipeline(items, events)
+ self._shut_down_at_check(pipeline, check=2)
+
+ await self._run(pipeline, WorkerShuttingDownError)
+
+ # Neither item fills a chunk, so every row is still in the batcher at the shutdown check.
+ # The queue row must exist before the value that tells the next attempt to skip its rows.
+ assert events == [("staged_rows", [10, 11, 12]), "insert", ("resume_value", 11)]
+
+ @pytest.mark.parametrize(
+ "failure,expected_values",
+ [
+ # The source fails after three batches. The held row of the last batch is inserted on
+ # the way out, so the next attempt can continue after all three.
+ pytest.param("source_error", [10, 20, 29], id="every_batch_queued"),
+ # The row of the last batch never reaches the queue, so its rows stay ahead of the value.
+ pytest.param("held_row_not_inserted", [10, 20], id="held_batch_not_queued"),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_the_recorded_value_never_passes_a_batch_without_a_queue_row(
+ self, failure: str, expected_values: list[int]
+ ) -> None:
+ events: list[Any] = []
+
+ def items():
+ yield pa.table({"id": [1, 2], "n": [10, 11]})
+ yield pa.table({"id": [3, 4], "n": [20, 21]})
+ yield pa.table({"id": [5, 6], "n": [29, 30]})
+ raise RuntimeError("source went away")
+
+ pipeline = self._pipeline(items, events)
+ cast(MagicMock, pipeline._shutdown_monitor).is_worker_shutdown.return_value = False
+ if failure == "held_row_not_inserted":
+ pipeline._pg_producer.release_held_batch = MagicMock(side_effect=RuntimeError("queue down")) # type: ignore[method-assign]
+
+ await self._run(pipeline, RuntimeError)
+
+ assert [event[1] for event in events if event != "insert" and event[0] == "resume_value"] == expected_values
+
+ @pytest.mark.asyncio
+ async def test_a_queue_row_that_fails_to_insert_stops_the_value_from_advancing(self) -> None:
+ events: list[Any] = []
+
+ def items():
+ yield pa.table({"id": [1, 2], "n": [10, 11]})
+ yield pa.table({"id": [3, 4], "n": [20, 21]})
+ yield pa.table({"id": [5, 6], "n": [29, 30]})
+
+ pipeline = self._pipeline(items, events)
+ cast(MagicMock, pipeline._shutdown_monitor).is_worker_shutdown.return_value = False
+ inserts = {"n": 0}
+
+ def fail_second_insert(*_args, **_kwargs) -> None:
+ inserts["n"] += 1
+ if inserts["n"] == 2:
+ raise RuntimeError("queue down")
+
+ cast(MagicMock, pipeline._pg_producer._conn.execute).side_effect = fail_second_insert
+
+ await self._run(pipeline, RuntimeError)
+
+ # Batch 1's row is the insert that failed. The value 10 covers batch 0 only, whose row exists.
+ assert [event for event in events if event[0] == "resume_value"] == [("resume_value", 10)]
+
+ @pytest.mark.asyncio
+ async def test_rows_out_of_order_withdraw_the_recorded_value(self) -> None:
+ events: list[Any] = []
+
+ def items():
+ yield pa.table({"id": [1, 2], "n": [10, 11]})
+ yield pa.table({"id": [3, 4], "n": [20, 21]})
+ yield pa.table({"id": [5, 6], "n": [5, 6]})
+ raise RuntimeError("source went away")
+
+ pipeline = self._pipeline(items, events)
+ cast(MagicMock, pipeline._shutdown_monitor).is_worker_shutdown.return_value = False
+
+ await self._run(pipeline, RuntimeError)
+
+ assert [event[1] for event in events if event != "insert" and event[0] == "resume_value"] == [10, 20, None]
+
+ @pytest.mark.parametrize(
+ "resumed_incremental_value,expected_is_resume",
+ [pytest.param(None, False, id="fresh_attempt"), pytest.param(40, True, id="continues_after_a_queued_batch")],
+ )
+ def test_an_attempt_that_continues_keeps_the_queue_rows_of_earlier_attempts(
+ self, resumed_incremental_value: int | None, expected_is_resume: bool
+ ) -> None:
+ schema = MagicMock(
+ id="schema-1",
+ source_id="source-1",
+ is_incremental=True,
+ is_webhook=False,
+ is_xmin=False,
+ is_append=False,
+ table=None,
+ incremental_field="n",
+ incremental_field_type=IncrementalFieldType.Integer,
+ incremental_field_earliest_value=None,
+ )
+ resource = SourceResponse(name="orders", items=lambda: iter(()), primary_keys=["id"])
+
+ with (
+ patch(f"{_PIPELINE}.current_import_attempt", return_value=2),
+ 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") as producer_cls,
+ patch(f"{_PIPELINE}.DeltaTableRef"),
+ patch(f"{_PIPELINE}.resolve_primary_keys", return_value=["id"]),
+ ):
+ pipeline: PipelineV3 = PipelineV3(
+ source_response=resource,
+ logger=_make_logger(),
+ job_id="job-1",
+ reset_pipeline=False,
+ shutdown_monitor=MagicMock(),
+ resumable_source_manager=None,
+ models=ImportJobModels(
+ job=MagicMock(team_id=1, workflow_run_id="wfrun-abc", id="job-1", destination_ids=[]),
+ schema=schema,
+ source=MagicMock(source_type="Postgres"),
+ table=None,
+ ),
+ incremental_checkpoints_allowed=True,
+ resumed_incremental_value=resumed_incremental_value,
+ )
+
+ # A fresh run replaces the queue rows of earlier attempts and overwrites on batch 0. A run that
+ # reads after their rows must not, or the rows it skipped are never loaded.
+ assert producer_cls.call_args.kwargs["is_resume"] is expected_is_resume
+ assert pipeline._handoff_checkpoint is not None
+ assert pipeline._handoff_checkpoint.resume_value == resumed_incremental_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_import_handoff_loop.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_import_handoff_loop.py
new file mode 100644
index 000000000000..63a3f73f72c6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_import_handoff_loop.py
@@ -0,0 +1,283 @@
+import json
+import uuid
+import base64
+import logging
+import dataclasses
+from concurrent.futures import ThreadPoolExecutor
+
+import pytest
+from unittest import mock
+
+from temporalio import activity
+from temporalio.client import WorkflowFailureError, WorkflowHistory
+from temporalio.common import RetryPolicy
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
+
+from posthog.temporal.common.shutdown import WorkerShuttingDownError
+from posthog.temporal.utils import ExternalDataWorkflowInputs
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.temporal.data_imports import external_data_job as workflow_module
+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import (
+ WORKER_RESTART_ERROR_MESSAGE,
+ ExternalDataJobWorkflow,
+ UpdateExternalDataJobStatusInputs,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (
+ AcquireV3LockActivityInputs,
+ AcquireV3LockActivityOutputs,
+)
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
+ CreateExternalDataJobModelActivityInputs,
+ CreateExternalDataJobModelActivityOutputs,
+)
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
+ ImportDataActivityInputs,
+)
+
+_JOB_ID = "01960000-0000-0000-0000-000000000000"
+_TASK_QUEUE = "test-import-handoff-loop"
+
+# What one attempt of the import activity does.
+HANDOFF = "handoff"
+OLD_WORKER_HANDOFF = "old_worker_handoff"
+FAIL = "fail"
+SUCCEED = "succeed"
+
+
[email protected](autouse=True)
+def _workflow_logs_at_info(caplog):
+ # A bad logger call is inert below INFO and wedges the workflow task in production.
+ caplog.set_level(logging.INFO, logger="temporalio.workflow")
+ caplog.set_level(logging.INFO, logger="temporalio.activity")
+
+
[email protected](frozen=True, kw_only=True)
+class _WorkflowRun:
+ import_inputs: list[ImportDataActivityInputs]
+ import_attempts: list[int]
+ updates: list[UpdateExternalDataJobStatusInputs]
+ buffer_one_triggers: int
+ handoffs_recorded: list[int]
+ history: WorkflowHistory
+ failed: bool
+
+
+def _activities(
+ script: list[str],
+ *,
+ handoffs_are_free: bool,
+ import_inputs: list[ImportDataActivityInputs],
+ import_attempts: list[int],
+ updates: list[UpdateExternalDataJobStatusInputs],
+ buffer_one: list[str],
+) -> list:
+ @activity.defn(name="acquire_v3_pipeline_lock_activity")
+ async def acquire_lock(inputs: AcquireV3LockActivityInputs) -> AcquireV3LockActivityOutputs:
+ return AcquireV3LockActivityOutputs(acquired=True, token="token")
+
+ @activity.defn(name="create_external_data_job_model_activity")
+ async def create_job(inputs: CreateExternalDataJobModelActivityInputs) -> CreateExternalDataJobModelActivityOutputs:
+ return CreateExternalDataJobModelActivityOutputs(
+ job_id=_JOB_ID,
+ incremental_or_append=False,
+ source_type="Postgres",
+ schema_name="orders",
+ repartition_needed=False,
+ billing_limit_checked=True,
+ source_templates_needed=False,
+ import_handoffs_are_free=handoffs_are_free,
+ )
+
+ @activity.defn(name="import_data_activity_sync")
+ async def import_data(inputs: ImportDataActivityInputs) -> PipelineResult:
+ import_inputs.append(inputs)
+ attempt = activity.info().attempt
+ import_attempts.append(attempt)
+ step = script[len(import_inputs) - 1] if len(import_inputs) <= len(script) else script[-1]
+ if step == HANDOFF:
+ return PipelineResult(should_trigger_cdp_producer=False, handed_off=True, handoff_attempts_used=attempt)
+ if step == OLD_WORKER_HANDOFF:
+ raise WorkerShuttingDownError("1", "import_data_activity_sync", _TASK_QUEUE, attempt, "wf", "wt")
+ if step == FAIL:
+ raise RuntimeError("source went away")
+ return PipelineResult(should_trigger_cdp_producer=False, consumer_manages_job_status=True)
+
+ @activity.defn(name="update_external_data_job_model")
+ async def update_job(inputs: UpdateExternalDataJobStatusInputs) -> None:
+ updates.append(inputs)
+
+ @activity.defn(name="trigger_schedule_buffer_one_activity")
+ async def trigger_buffer_one(schedule_id: str) -> None:
+ buffer_one.append(schedule_id)
+
+ return [acquire_lock, create_job, import_data, update_job, trigger_buffer_one]
+
+
+def _patch_ids(history: WorkflowHistory) -> set[str]:
+ patch_ids = set()
+ for event in history.to_json_dict()["events"]:
+ marker = event.get("markerRecordedEventAttributes")
+ if marker and marker["markerName"] == "core_patch":
+ payload = marker["details"]["patch-data"]["payloads"][0]["data"]
+ patch_ids.add(json.loads(base64.b64decode(payload))["id"])
+ return patch_ids
+
+
+async def _run_workflow(script: list[str], *, handoffs_are_free: bool = True) -> _WorkflowRun:
+ import_inputs: list[ImportDataActivityInputs] = []
+ import_attempts: list[int] = []
+ updates: list[UpdateExternalDataJobStatusInputs] = []
+ buffer_one: list[str] = []
+ failed = False
+
+ with (
+ mock.patch.object(workflow_module.workflow, "start_child_workflow", new_callable=mock.AsyncMock),
+ mock.patch.object(workflow_module, "get_data_import_finished_metric"),
+ mock.patch.object(workflow_module, "get_import_handoffs_per_run_metric") as handoffs_metric,
+ ):
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=_TASK_QUEUE,
+ workflows=[ExternalDataJobWorkflow],
+ activities=_activities(
+ script,
+ handoffs_are_free=handoffs_are_free,
+ import_inputs=import_inputs,
+ import_attempts=import_attempts,
+ updates=updates,
+ buffer_one=buffer_one,
+ ),
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ activity_executor=ThreadPoolExecutor(max_workers=10),
+ ):
+ handle = await env.client.start_workflow(
+ ExternalDataJobWorkflow.run,
+ ExternalDataWorkflowInputs(
+ team_id=1,
+ external_data_source_id=uuid.uuid4(),
+ external_data_schema_id=uuid.uuid4(),
+ billable=False,
+ ),
+ id=str(uuid.uuid4()),
+ task_queue=_TASK_QUEUE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ execution_timeout=workflow_module.dt.timedelta(hours=1),
+ )
+ try:
+ await handle.result()
+ except WorkflowFailureError:
+ failed = True
+ history = await handle.fetch_history()
+
+ handoffs_recorded = [call.args[0] for call in handoffs_metric.return_value.record.call_args_list]
+ assert all(call.args == ("Postgres",) for call in handoffs_metric.call_args_list)
+
+ return _WorkflowRun(
+ import_inputs=import_inputs,
+ import_attempts=import_attempts,
+ updates=updates,
+ buffer_one_triggers=len(buffer_one),
+ handoffs_recorded=handoffs_recorded,
+ history=history,
+ failed=failed,
+ )
+
+
+async def test_handoffs_do_not_use_the_failure_budget():
+ # A full refresh gets 3 attempts. Five hand-offs would end the run if each one used an attempt.
+ run = await _run_workflow([HANDOFF] * 5 + [SUCCEED])
+
+ assert not run.failed
+ assert [inputs.handoffs_are_free for inputs in run.import_inputs] == [True] * 6
+ assert [inputs.handoff_count for inputs in run.import_inputs] == [0, 1, 2, 3, 4, 5]
+ # Each execution continues the attempt numbers, so no two attempts share a run id.
+ assert [inputs.prior_attempts for inputs in run.import_inputs] == [0, 1, 2, 3, 4, 5]
+ assert run.buffer_one_triggers == 0
+ assert run.handoffs_recorded == [5]
+ # The loader owns the status of a run with batches, so the workflow writes none.
+ assert run.updates == []
+
+
+async def test_failures_keep_one_budget_across_handoffs():
+ # Attempt 1 fails and attempt 2 hands off, which leaves 2 of the 3 attempts for failures.
+ run = await _run_workflow([FAIL, HANDOFF, FAIL, FAIL, SUCCEED])
+
+ assert run.failed
+ assert run.import_attempts == [1, 2, 1, 2]
+ assert [inputs.prior_attempts for inputs in run.import_inputs] == [0, 0, 2, 2]
+ assert [update.status for update in run.updates] == [ExternalDataJob.Status.FAILED]
+ assert run.updates[0].latest_error != WORKER_RESTART_ERROR_MESSAGE
+ assert run.buffer_one_triggers == 0
+
+
+async def test_the_handoff_loop_stops_at_its_bound():
+ with mock.patch.object(workflow_module, "MAX_IMPORT_HANDOFFS", 3):
+ run = await _run_workflow([HANDOFF])
+
+ assert not run.failed
+ assert len(run.import_inputs) == 3
+ # The same outcome a run had when worker restarts used up its retries: failed with the
+ # restart message, and the schedule is asked to run the schema once more.
+ assert [(update.status, update.latest_error) for update in run.updates] == [
+ (ExternalDataJob.Status.FAILED, WORKER_RESTART_ERROR_MESSAGE)
+ ]
+ assert run.buffer_one_triggers == 1
+ assert run.handoffs_recorded == [3]
+
+
+ "handoffs_are_free,script,expected_attempts,expected_buffer_one",
+ [
+ # The job-creation activity said hand-offs are not free: one execution, and Temporal's
+ # retries end the run as before.
+ pytest.param(False, [OLD_WORKER_HANDOFF], [1, 2, 3], 1, id="flag_off_keeps_the_retry_path"),
+ # A worker without the hand-off result raises instead. The retry still works inside the loop.
+ pytest.param(True, [OLD_WORKER_HANDOFF, HANDOFF, SUCCEED], [1, 2, 1], 0, id="old_worker_inside_the_loop"),
+ ],
+)
+async def test_a_raised_handoff_still_goes_through_temporal_retries(
+ handoffs_are_free: bool, script: list[str], expected_attempts: list[int], expected_buffer_one: int
+):
+ run = await _run_workflow(script, handoffs_are_free=handoffs_are_free)
+
+ assert run.import_attempts == expected_attempts
+ assert [inputs.handoffs_are_free for inputs in run.import_inputs] == [handoffs_are_free] * len(expected_attempts)
+ assert run.buffer_one_triggers == expected_buffer_one
+ assert run.handoffs_recorded == ([1] if handoffs_are_free else [])
+
+
+ "handoffs_are_free,script",
+ [
+ # Histories recorded before the loop have one import execution and no patch marker. The
+ # recorded histories next to this file cover a run that succeeds; these two cover the
+ # hand-off outcomes, which no recorded history has.
+ pytest.param(False, [OLD_WORKER_HANDOFF], id="pre_loop_history_with_retries_exhausted"),
+ pytest.param(False, [OLD_WORKER_HANDOFF, SUCCEED], id="pre_loop_history_with_a_retried_handoff"),
+ pytest.param(True, [HANDOFF, HANDOFF, SUCCEED], id="loop_history"),
+ pytest.param(True, [HANDOFF], id="loop_history_at_the_bound"),
+ ],
+)
+async def test_histories_replay_on_the_branch_they_recorded(handoffs_are_free: bool, script: list[str]):
+ with mock.patch.object(workflow_module, "MAX_IMPORT_HANDOFFS", 3):
+ run = await _run_workflow(script, handoffs_are_free=handoffs_are_free)
+
+ assert (workflow_module.FREE_IMPORT_HANDOFFS_PATCH_ID in _patch_ids(run.history)) is handoffs_are_free
+
+ with (
+ mock.patch.object(workflow_module, "get_data_import_finished_metric"),
+ mock.patch.object(workflow_module, "get_import_handoffs_per_run_metric"),
+ ):
+ await Replayer(
+ workflows=[ExternalDataJobWorkflow],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ).replay_workflow(run.history)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
index dd9dddf9c615..458264f148a1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
@@ -4,6 +4,7 @@ import datetime as dt
import dataclasses
from typing import Any
+from django.conf import settings
from django.db import IntegrityError, close_old_connections
from django.db.models import Max
from django.utils import timezone
@@ -319,6 +320,11 @@ class CreateExternalDataJobModelActivityOutputs:
# source's first completed sync does. Defaults True so a payload that predates the field still
# schedules the activity its history recorded.
source_templates_needed: bool = True
+ # True when the workflow runs the import again itself after a worker hand-off, so the hand-off
+ # uses no retry attempt. Read from settings here because a workflow must not: the value is
+ # recorded with this activity's result, so a replay takes the same branch. Defaults False so a
+ # payload that predates the field keeps the single import execution its history recorded.
+ import_handoffs_are_free: bool = False
@activity.defn
@@ -462,6 +468,7 @@ def create_external_data_job_model_activity(
billing_limit_checked=True,
hit_billing_limit=hit_billing_limit,
source_templates_needed=source_templates_needed,
+ import_handoffs_are_free=settings.DATA_WAREHOUSE_IMPORT_FREE_HANDOFFS_ENABLED,
)
except V3PipelineLockLostError:
# The takeover race the guard handles, not a defect — skip the generic handler's
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 f77116a27ea0..8777fee827a6 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
@@ -6,6 +6,7 @@ import functools
import dataclasses
from typing import TYPE_CHECKING, Any, NoReturn, Optional
+from django.conf import settings
from django.db import InterfaceError, InternalError, OperationalError
from django.db.models import Prefetch
@@ -35,12 +36,17 @@ from products.warehouse_sources.backend.models.external_data_schema import (
apply_incremental_lookback,
get_schema_if_exists,
process_incremental_value,
+ staged_handoff_resume_point,
)
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.destinations.enablement import (
external_destination_ids_for,
)
+from products.warehouse_sources.backend.temporal.data_imports.import_attempt import (
+ current_import_attempt,
+ set_attempts_before_this_execution,
+)
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
TERMINAL_JOB_STATUSES,
get_worker_shutdown_handoff_metric,
@@ -119,6 +125,13 @@ class ImportDataActivityInputs:
fast_return_eligible: bool = False
# Kept apart from `reset_pipeline`, which every retry would read again and wipe the table again.
scheduled_full_refresh: bool = False
+ # Set by a workflow that runs this activity again after a hand-off. The activity then returns
+ # a `handed_off` result when its worker shuts down, instead of raising for a Temporal retry.
+ # Defaults False so the payload of a workflow that predates the field keeps the retry.
+ handoffs_are_free: bool = False
+ handoff_count: int = 0
+ # Attempts that earlier executions of this activity used in the same workflow run.
+ prior_attempts: int = 0
@property
def properties_to_log(self) -> dict[str, Any]:
@@ -130,6 +143,9 @@ class ImportDataActivityInputs:
"reset_pipeline": self.reset_pipeline,
"fast_return_eligible": self.fast_return_eligible,
"scheduled_full_refresh": self.scheduled_full_refresh,
+ "handoffs_are_free": self.handoffs_are_free,
+ "handoff_count": self.handoff_count,
+ "prior_attempts": self.prior_attempts,
}
@@ -345,6 +361,7 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelin
bind_contextvars(team_id=inputs.team_id)
logger = LOGGER.bind()
tag_queries(team_id=inputs.team_id, product=Product.WAREHOUSE, feature=Feature.IMPORT_PIPELINE)
+ set_attempts_before_this_execution(inputs.prior_attempts)
await asyncio.to_thread(report_heartbeat_timeout, inputs, logger)
@@ -357,10 +374,20 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelin
host=socket.gethostname(),
# Retries share the run_id; the attempt lets the newest reporter own the run key while a
# zombie predecessor stands down (its heartbeat timed out, but it may still be running).
- attempt=current_activity_attempt(),
+ attempt=current_import_attempt(),
):
try:
return await _import_data_with_reporting(inputs, logger)
+ except WorkerShuttingDownError:
+ if not inputs.handoffs_are_free:
+ raise
+ # A result, not a failure, so the hand-off uses no retry attempt. The workflow reads it
+ # and runs the import again.
+ return PipelineResult(
+ should_trigger_cdp_producer=False,
+ handed_off=True,
+ handoff_attempts_used=current_activity_attempt(),
+ )
except (OperationalError, InterfaceError, InternalError, PostHogInternalDatabaseError) as e:
# The setup phase (resolving the job/schema/source rows for this run) reads PostHog's
# own app DB through the Django ORM before the source's error handling takes over. A
@@ -395,7 +422,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
f"Job {inputs.run_id} uses pipeline version {model.pipeline_version}. Only V3 jobs can run."
)
- attempt = current_activity_attempt()
+ attempt = current_import_attempt()
if attempt > 1 and model.status in TERMINAL_JOB_STATUSES:
await logger.ainfo(
"Skipping retry - job already terminal",
@@ -495,6 +522,32 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
schema.incremental_field_lookback_seconds,
)
+ # An earlier attempt of this workflow run queued every row up to this value, and the loader
+ # promotes the stored watermark only when the whole run completes. Reading after the value
+ # skips the rows that are already queued. A run that fails later leaves the stored watermark
+ # where it was, so the next run extracts those rows again.
+ incremental_checkpoints_allowed = use_stored_cursors and schema.is_incremental
+ resumed_incremental_run_uuid = None
+ resumed_incremental_value = None
+ if incremental_checkpoints_allowed and settings.DATA_WAREHOUSE_IMPORT_WATERMARK_CARRY_OVER_ENABLED:
+ resume_point = staged_handoff_resume_point(schema.sync_type_config, model.workflow_run_id)
+ if resume_point is not None:
+ resumed_incremental_run_uuid, resumed_incremental_value = resume_point
+ resumed_incremental_value = process_incremental_value(
+ resumed_incremental_value,
+ schema.incremental_field_type,
+ )
+ if resumed_incremental_value is None:
+ resumed_incremental_run_uuid = None
+ if resumed_incremental_value is not None:
+ # The earlier attempt already read the lookback window, so the value is used as it is.
+ processed_incremental_last_value = resumed_incremental_value
+ incremental_last_value_before_lookback = resumed_incremental_value
+ await logger.ainfo(
+ "Continuing the incremental import after the last batch an earlier attempt queued",
+ attempt=attempt,
+ )
+
if schema.should_use_incremental_field:
await logger.adebug(f"Incremental last value being used is: {processed_incremental_last_value}")
@@ -570,7 +623,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
# A schema-level override (user-managed) wins over the source pin.
api_version=new_source.resolve_api_version(schema.api_version or model.pipeline.api_version),
fanout_warehouse_reuse=fanout_warehouse_reuse,
- activity_attempt=activity.info().attempt if activity.in_activity() else 1,
+ activity_attempt=current_import_attempt(),
source_cursor=source_cursor_manager,
)
@@ -597,7 +650,10 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
# extraction below would, so watermark processing and row filters cannot drift.
# `reset_pipeline` is re-checked here because a reset asked for through the workflow
# input never reaches `sync_type_config`, which is all eligibility can see.
- if inputs.fast_return_eligible and not reset_pipeline:
+ # A continuing attempt probes after its resume value. A negative answer there says nothing
+ # about the rows the earlier attempts queued, and a fast return would leave their
+ # watermark without a final batch to promote it.
+ if inputs.fast_return_eligible and not reset_pipeline and resumed_incremental_value is None:
if not await _probe_found_new_data(new_source, config, source_inputs, logger):
# The run checked the source, so the schema must not read as stale. Mirrors
# `update_last_synced_at` on the extracting path (which also stamps
@@ -653,6 +709,9 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
shutdown_monitor=shutdown_monitor,
resumable_source_manager=resumable_source_manager,
source_cursor_manager=source_cursor_manager,
+ incremental_checkpoints_allowed=incremental_checkpoints_allowed,
+ resumed_incremental_run_uuid=resumed_incremental_run_uuid,
+ resumed_incremental_value=resumed_incremental_value,
)
else:
raise ValueError(f"Source type {model.pipeline.source_type} not supported")
@@ -732,7 +791,7 @@ def _log_worker_shutdown_during_import(logger: FilteringBoundLogger) -> None:
info = activity.info()
logger.info(
"Worker shutdown detected while import is running",
- attempt=info.attempt,
+ attempt=current_import_attempt(),
attempt_elapsed_seconds=round((dt.datetime.now(dt.UTC) - info.started_time).total_seconds()),
)
@@ -764,7 +823,8 @@ async def _handle_import_error(
Everything else is logged as an exception and re-raised so Temporal retries it as usual.
"""
if isinstance(error, WorkerShuttingDownError):
- # An expected hand-off, not a failure: Temporal retries the activity on another worker.
+ # An expected hand-off, not a failure. Another worker continues the import: the workflow runs
+ # the activity again when hand-offs are free, and Temporal retries it otherwise.
if activity.in_activity():
get_worker_shutdown_handoff_metric(str(job_inputs.job_type)).add(1)
await logger.ainfo("Handing the import off to another worker because this worker is shutting down")
@@ -985,6 +1045,9 @@ async def _run(
shutdown_monitor: ShutdownMonitor,
resumable_source_manager: ResumableSourceManager | None,
source_cursor_manager: SourceCursorManager[Any] | None = None,
+ incremental_checkpoints_allowed: bool = False,
+ resumed_incremental_run_uuid: str | None = None,
+ resumed_incremental_value: Any = None,
) -> PipelineResult:
try:
reset_pipeline = reset_pipeline or source_response.destination_reset_required
@@ -999,6 +1062,9 @@ async def _run(
resumable_source_manager,
models=models,
source_cursor_manager=source_cursor_manager,
+ incremental_checkpoints_allowed=incremental_checkpoints_allowed,
+ resumed_incremental_run_uuid=resumed_incremental_run_uuid,
+ resumed_incremental_value=resumed_incremental_value,
)
result = await pipeline.run()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
index fd6e33b5e8c5..3a6bb376da75 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
@@ -939,8 +939,9 @@ def _incremental_schema(*, is_incremental: bool, lookback_seconds: int | None) -
@contextlib.contextmanager
-def _patched_activity_reaching_run(source_mock, schema, api_version=None):
+def _patched_activity_reaching_run(source_mock, schema, api_version=None, workflow_run_id=None):
model = mock.MagicMock()
+ model.workflow_run_id = workflow_run_id
model.pipeline_version = ExternalDataJob.PipelineVersion.V3
model.pipeline.source_type = "MongoDB"
model.pipeline.job_inputs = {}
@@ -961,9 +962,9 @@ def _patched_activity_reaching_run(source_mock, schema, api_version=None):
mock.patch.object(module, "database_sync_to_async_pool", new=_passthrough),
mock.patch.object(module.SourceRegistry, "is_registered", return_value=True),
mock.patch.object(module.SourceRegistry, "get_source", return_value=source_mock),
- mock.patch.object(module, "_run", new=mock.AsyncMock(return_value=mock.sentinel.run_result)),
+ mock.patch.object(module, "_run", new=mock.AsyncMock(return_value=mock.sentinel.run_result)) as run_mock,
):
- yield
+ yield run_mock
def _inputs_no_reset() -> ImportDataActivityInputs:
@@ -1544,3 +1545,105 @@ def test_a_scheduled_full_refresh_resets_only_while_the_schema_is_due(
assert (
_resolve_reset_pipeline(inputs, schema, job_created_at=datetime(2026, 9, 22, 1, 30, tzinfo=UTC)) is expected
)
+
+
+_STORED_WATERMARK = datetime(2026, 6, 14, 15, 33, 31, 802833)
+_QUEUED_UP_TO = datetime(2026, 6, 20, 8, 0, 0)
+
+
+ "carry_over_enabled,staged,reset_pipeline,expected_last_value,expected_resumed",
+ [
+ pytest.param(
+ True,
+ {"run_uuid": "wfrun-1-a1", "last_value": "2026-06-21T00:00:00", "resume_value": "2026-06-20T08:00:00"},
+ False,
+ _QUEUED_UP_TO,
+ _QUEUED_UP_TO,
+ id="continues_after_the_last_queued_batch",
+ ),
+ # The lookback of one hour applies to a run that starts from the stored watermark.
+ pytest.param(
+ False,
+ {"run_uuid": "wfrun-1-a1", "last_value": "2026-06-21T00:00:00", "resume_value": "2026-06-20T08:00:00"},
+ False,
+ _STORED_WATERMARK - timedelta(hours=1),
+ None,
+ id="setting_off_restarts_from_the_stored_watermark",
+ ),
+ pytest.param(
+ True,
+ {"run_uuid": "wfrun-0-a1", "last_value": "2026-06-21T00:00:00", "resume_value": "2026-06-20T08:00:00"},
+ False,
+ _STORED_WATERMARK - timedelta(hours=1),
+ None,
+ id="value_of_an_earlier_workflow_run_is_not_used",
+ ),
+ pytest.param(
+ True,
+ {"run_uuid": "wfrun-1-a1", "last_value": "2026-06-21T00:00:00"},
+ False,
+ _STORED_WATERMARK - timedelta(hours=1),
+ None,
+ id="earlier_attempt_recorded_no_value",
+ ),
+ pytest.param(
+ True,
+ {"run_uuid": "wfrun-1-a1", "last_value": "2026-06-21T00:00:00", "resume_value": "2026-06-20T08:00:00"},
+ True,
+ None,
+ None,
+ id="reset_reads_everything",
+ ),
+ ],
+)
+async def test_an_interrupted_incremental_import_continues_after_its_last_queued_batch(
+ carry_over_enabled: bool,
+ staged: dict[str, Any],
+ reset_pipeline: bool,
+ expected_last_value: datetime | None,
+ expected_resumed: datetime | None,
+ settings,
+):
+ settings.DATA_WAREHOUSE_IMPORT_WATERMARK_CARRY_OVER_ENABLED = carry_over_enabled
+ source = mock.MagicMock(spec=SimpleSource)
+ source.parse_config.return_value = {}
+ source.source_for_pipeline.return_value = mock.MagicMock()
+ schema = _incremental_schema(is_incremental=True, lookback_seconds=3600)
+ schema.sync_type_config["incremental_staged"] = staged
+
+ with _patched_activity_reaching_run(source, schema, workflow_run_id="wfrun-1") as run_mock:
+ await import_data_activity_sync(dataclasses.replace(_inputs_no_reset(), reset_pipeline=reset_pipeline))
+
+ _, source_inputs = source.source_for_pipeline.call_args.args
+ assert source_inputs.db_incremental_field_last_value == expected_last_value
+ # The pipeline queues the attempt as a resume exactly when it reads after the earlier rows.
+ assert run_mock.await_args.kwargs["resumed_incremental_value"] == expected_resumed
+ assert run_mock.await_args.kwargs["resumed_incremental_run_uuid"] == (
+ "wfrun-1-a1" if expected_resumed is not None else None
+ )
+ # The stored watermark moves only when the loader completes the whole run.
+ assert schema.sync_type_config["incremental_field_last_value"] == "2026-06-14T15:33:31.802833"
+
+
[email protected]("handoffs_are_free", [True, False])
+async def test_a_free_handoff_is_a_result_and_any_other_handoff_is_a_retry(handoffs_are_free: bool):
+ error = WorkerShuttingDownError("5", "import_data_activity_sync", "data-warehouse-task-queue", 2, "wf", "wt")
+ inputs = dataclasses.replace(_inputs_no_reset(), handoffs_are_free=handoffs_are_free, prior_attempts=4)
+
+ with (
+ mock.patch.object(module, "tag_queries"),
+ mock.patch.object(module, "report_heartbeat_timeout"),
+ mock.patch.object(module, "aworkload_reporting", return_value=_FakeAsyncCM()),
+ mock.patch.object(module, "_import_data_with_reporting", new=mock.AsyncMock(side_effect=error)),
+ mock.patch.object(module, "current_activity_attempt", return_value=2),
+ ):
+ if handoffs_are_free:
+ result = await import_data_activity_sync(inputs)
+ # The workflow adds the attempts up, so it needs the attempt number of this execution only.
+ assert result == {"should_trigger_cdp_producer": False, "handed_off": True, "handoff_attempts_used": 2}
+ else:
+ with pytest.raises(WorkerShuttingDownError):
+ await import_data_activity_sync(inputs)
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 93e977da9b48..7139bdad1260 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -35,6 +35,8 @@ from products.warehouse_sources.backend.models.external_data_schema import (
mark_initial_sync_complete,
mark_schema_running_unless_halted,
process_incremental_value,
+ staged_handoff_resume_point,
+ staged_handoff_resume_value,
update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -249,6 +251,49 @@ class TestExternalDataSchemaActivityLogging(BaseTest):
schema.refresh_from_db()
assert schema.sync_type_config["incremental_staged"]["last_value"] == 42
+ def test_a_handoff_resume_value_never_moves_the_stored_watermark(self) -> None:
+ schema = self._create(
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ sync_type_config={
+ "incremental_field_type": IncrementalFieldType.Integer,
+ "incremental_field_last_value": 10,
+ },
+ )
+ schema.stage_incremental_field_value("wfrun-1-a1", 50)
+ schema.stage_handoff_resume_value("wfrun-1-a1", 40)
+ # The next attempt displaces the first one, which must keep its value in the parked list.
+ schema.stage_handoff_resume_value("wfrun-1-a2", 40)
+ schema.stage_incremental_field_value("wfrun-1-a2", 90)
+
+ schema.refresh_from_db()
+ # The run never completed, so nothing was promoted: the next workflow run starts from 10
+ # and extracts again the rows that this run queued but did not finish loading.
+ assert schema.sync_type_config["incremental_field_last_value"] == 10
+ assert staged_handoff_resume_value(schema.sync_type_config, "wfrun-1") == 40
+ assert staged_handoff_resume_value(schema.sync_type_config, "wfrun-2") is None
+
+ assert schema.promote_staged_incremental_values("wfrun-1-a2")
+ schema.refresh_from_db()
+ assert schema.sync_type_config["incremental_field_last_value"] == 90
+
+ def test_a_resume_value_inherited_without_a_new_batch_keeps_the_earlier_owner(self) -> None:
+ # Attempt a2 inherits a1's resume value before it has queued a batch of its own: the batches
+ # the value describes still belong to a1, so a3 must finalize a1, not a2, if a2 never queues one.
+ schema = self._create(
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ sync_type_config={"incremental_field_type": IncrementalFieldType.Integer},
+ )
+ schema.stage_handoff_resume_value("wfrun-1-a1", 40)
+ schema.stage_handoff_resume_value("wfrun-1-a2", 40, owner_run_uuid="wfrun-1-a1")
+
+ schema.refresh_from_db()
+ assert staged_handoff_resume_point(schema.sync_type_config, "wfrun-1") == ("wfrun-1-a1", 40)
+
+ # Once a2 queues a batch of its own, it becomes the owner for any later attempt.
+ schema.stage_handoff_resume_value("wfrun-1-a2", 55)
+ schema.refresh_from_db()
+ assert staged_handoff_resume_point(schema.sync_type_config, "wfrun-1") == ("wfrun-1-a2", 55)
+
def test_promote_staged_incremental_values_save_skips_activity_log(self) -> None:
schema = self._create(
sync_type=ExternalDataSchema.SyncType.INCREMENTAL,