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): preempt imports that do not hand off at worker shutdown (#112721)

Tom Owers05f97915aa06
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 420afd57fb33..9e223e27875d 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -275,6 +275,19 @@ DATA_WAREHOUSE_IMPORT_FREE_HANDOFFS_ENABLED: bool = get_from_env(
DATA_WAREHOUSE_IMPORT_WATERMARK_CARRY_OVER_ENABLED: bool = get_from_env(
"DATA_WAREHOUSE_IMPORT_WATERMARK_CARRY_OVER_ENABLED", False, type_cast=str_to_bool
)
+# At a worker shutdown the import pipeline stops waiting for a source that neither yields an item
+# nor reaches a safe point, and hands the run to another worker. It applies only to runs whose
+# hand-offs are free (DATA_WAREHOUSE_IMPORT_FREE_HANDOFFS_ENABLED), because preemption makes
+# hand-offs frequent and they must not use the retry attempts.
+DATA_WAREHOUSE_IMPORT_PREEMPTION_ENABLED: bool = get_from_env(
+ "DATA_WAREHOUSE_IMPORT_PREEMPTION_ENABLED", False, type_cast=str_to_bool
+)
+# How long a source has, after the shutdown starts, to hand off by itself before the pipeline preempts it.
+# Keep it above the read timeout of a source request, so a healthy source hands off first and
+# preemption is only the backstop.
+DATA_WAREHOUSE_IMPORT_PREEMPTION_QUIET_PERIOD_SECONDS: float = get_from_env(
+ "DATA_WAREHOUSE_IMPORT_PREEMPTION_QUIET_PERIOD_SECONDS", 300.0, type_cast=float
+)
# Restore unfinished append runs only after all extract and load workers have this implementation.
DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED: bool = get_from_env(
"DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED", False, type_cast=str_to_bool
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.py
index 5961f7a325a3..e422cb1fa404 100644
--- a/posthog/temporal/common/worker.py
+++ b/posthog/temporal/common/worker.py
@@ -391,6 +391,22 @@ async def create_worker(
"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],
}
+ # Recorded in seconds, from a hand-off at once to a run that holds the worker for hours.
+ histogram_bucket_overrides["warehouse_import_shutdown_handoff_delay_seconds"] = [
+ 1.0,
+ 5.0,
+ 15.0,
+ 30.0,
+ 60.0,
+ 90.0,
+ 120.0,
+ 300.0,
+ 900.0,
+ 1800.0,
+ 3600.0,
+ 7200.0,
+ 21600.0,
+ ]
if task_queue == settings.TASKS_TASK_QUEUE:
histogram_bucket_overrides |= dict(
zip(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
index 12691fce974e..b3ab9e416f72 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, MetricHistogram
+from temporalio.common import MetricCounter, MetricHistogram, MetricHistogramFloat
from posthog.kafka_client.routing import get_producer
from posthog.kafka_client.topics import KAFKA_APP_METRICS2
@@ -136,6 +136,44 @@ def get_import_handoffs_per_run_metric(source_type: str | None) -> MetricHistogr
)
+def get_import_preempted_metric(source_type: str | None, reason: str) -> MetricCounter:
+ # `reason` is why the run could continue on another worker (see `PreemptionDecision`).
+ return (
+ activity.metric_meter()
+ .with_additional_attributes({"source_type": source_type or "unknown", "reason": reason})
+ .create_counter(
+ "warehouse_import_preempted_total",
+ "Imports the pipeline handed off at a worker shutdown without waiting for the source.",
+ )
+ )
+
+
+def get_import_not_preempted_metric(source_type: str | None, reason: str) -> MetricCounter:
+ # Counted once per attempt that waits for its source at a worker shutdown and must keep the worker.
+ return (
+ activity.metric_meter()
+ .with_additional_attributes({"source_type": source_type or "unknown", "reason": reason})
+ .create_counter(
+ "warehouse_import_not_preempted_total",
+ "Imports that could not be preempted at a worker shutdown.",
+ )
+ )
+
+
+def get_shutdown_handoff_delay_metric(source_type: str | None, mode: str) -> MetricHistogramFloat:
+ # `mode` is `preempted` when the pipeline stopped waiting for the source, and `cooperative`
+ # when the source yielded an item or reached a safe point.
+ return (
+ activity.metric_meter()
+ .with_additional_attributes({"source_type": source_type or "unknown", "mode": mode})
+ .create_histogram_float(
+ "warehouse_import_shutdown_handoff_delay_seconds",
+ "Seconds from the worker shutdown to the hand-off of an import.",
+ "s",
+ )
+ )
+
+
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/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index 66053c11de9a..413dbf0945b3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -850,7 +850,7 @@ async def update_row_tracking_after_batch(
await decrement_rows(team_id, schema_id, row_count)
-def _is_young_first_attempt() -> bool:
+def is_young_first_attempt() -> bool:
if not activity.in_activity():
return False
@@ -873,7 +873,7 @@ def should_check_shutdown(
incremental_sync_raise_during_shutdown = (
schema.should_use_incremental_field and resource.sort_mode != "desc" and not reset_pipeline
)
- return incremental_sync_raise_during_shutdown or source_is_resumable or _is_young_first_attempt()
+ return incremental_sync_raise_during_shutdown or source_is_resumable or is_young_first_attempt()
async def finalize_desc_sort_incremental_value(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/preemption.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/preemption.py
new file mode 100644
index 000000000000..c8c3db8df523
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/preemption.py
@@ -0,0 +1,182 @@
+"""Preemption: the pipeline stops waiting for a source that does not hand off at a worker shutdown.
+
+The pipeline sees a shutdown only when the source yields an item or reaches a safe point. A source
+that is inside one long call does neither, so the run holds its worker until the call returns.
+`SourcePreemptor` waits for the next item and for the shutdown at the same time. After a shutdown
+it gives the source a quiet period to hand off in the usual way, and then it raises
+`SourcePreemptedError` from the event loop and leaves the source behind.
+"""
+
+import time
+import asyncio
+from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Iterable
+from typing import Any, TypeVar
+
+from structlog.types import FilteringBoundLogger
+from temporalio import activity
+
+from posthog.dataclasses import frozen
+from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownError
+
+from products.warehouse_sources.backend.temporal.data_imports.metrics import (
+ get_import_not_preempted_metric,
+ get_import_preempted_metric,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.abandonable_iterate import (
+ AbandonableSourcePuller,
+ PulledItem,
+)
+
+T = TypeVar("T")
+
+
+@frozen
+class PreemptionConfig:
+ quiet_period_seconds: float
+ # Whether the next attempt of an incremental run reads the value this attempt records.
+ watermark_carry_over_enabled: bool
+
+
+@frozen
+class PreemptionDecision:
+ eligible: bool
+ # A metric label: why the run can continue on another worker, or why it cannot.
+ reason: str
+
+
+class SourcePreemptedError(WorkerShuttingDownError):
+ """The pipeline stopped waiting for the source because the worker is shutting down."""
+
+ @classmethod
+ def build(cls) -> "SourcePreemptedError":
+ if activity.in_activity():
+ return cls.from_activity_context()
+ return cls("unknown", "unknown", "unknown", 1, None, None)
+
+
+class ShutdownStopwatch:
+ """Measures the time since the worker started to shut down."""
+
+ def __init__(self, shutdown_monitor: ShutdownMonitor, clock: Callable[[], float] = time.monotonic) -> None:
+ self._clock = clock
+ self._started_at: float | None = None
+ shutdown_monitor.run_on_shutdown(self.start)
+
+ def start(self) -> None:
+ if self._started_at is None:
+ self._started_at = self._clock()
+
+ def elapsed_seconds(self) -> float | None:
+ return None if self._started_at is None else self._clock() - self._started_at
+
+
+class SourcePreemptor:
+ def __init__(
+ self,
+ *,
+ config: PreemptionConfig,
+ shutdown_monitor: ShutdownMonitor,
+ stopwatch: ShutdownStopwatch,
+ decide: Callable[[], PreemptionDecision],
+ fence_source: Callable[[], Awaitable[bool]],
+ source_type: str,
+ logger: FilteringBoundLogger,
+ ) -> None:
+ self._config = config
+ self._shutdown_monitor = shutdown_monitor
+ self._stopwatch = stopwatch
+ self._decide = decide
+ self._fence_source = fence_source
+ self._source_type = source_type
+ self._logger = logger
+ self._decision: PreemptionDecision | None = None
+ self._quiet_period_extension = 0.0
+
+ async def iterate(self, items: Iterable[T] | AsyncIterable[T]) -> AsyncIterator[T]:
+ """Yield the items of the source. Raises `SourcePreemptedError` when it preempts the source.
+
+ Close this generator when the loop over it ends for any reason. The close is what stops
+ the thread of the source.
+ """
+ puller: AbandonableSourcePuller[T] = AbandonableSourcePuller(items)
+ shutdown_wait = asyncio.ensure_future(self._shutdown_monitor.wait_for_worker_shutdown())
+ abandon = False
+ try:
+ while True:
+ pull = puller.pull()
+ await self._wait_for_item_or_preempt(pull, shutdown_wait)
+ has_value, item = pull.result()
+ if not has_value:
+ return
+ assert item is not None
+ yield item
+ except SourcePreemptedError:
+ abandon = True
+ raise
+ finally:
+ shutdown_wait.cancel()
+ await puller.stop(abandon=abandon)
+
+ async def _wait_for_item_or_preempt(
+ self, pull: "asyncio.Future[PulledItem[T]]", shutdown_wait: "asyncio.Future[None]"
+ ) -> None:
+ while not pull.done():
+ if not (shutdown_wait.done() or self._shutdown_monitor.is_worker_shutdown()):
+ either: set[asyncio.Future[Any]] = {pull, shutdown_wait}
+ await asyncio.wait(either, return_when=asyncio.FIRST_COMPLETED)
+ continue
+
+ self._stopwatch.start()
+ decision = await self._decision_at_shutdown()
+ if not decision.eligible:
+ await asyncio.wait({pull})
+ return
+
+ elapsed = self._stopwatch.elapsed_seconds() or 0.0
+ remaining = self._config.quiet_period_seconds + self._quiet_period_extension - elapsed
+ if remaining > 0:
+ # An item or a safe point in this time hands the run off in the usual way.
+ await asyncio.wait({pull}, timeout=remaining)
+ continue
+
+ if not await self._fence_source():
+ # The source is in the middle of a write of its resume state. A hand-off now could
+ # let that write land after the next attempt starts.
+ self._quiet_period_extension += self._config.quiet_period_seconds
+ await self._logger.awarning(
+ "Could not stop the writes of the source, waiting another quiet period before preemption",
+ quiet_period_seconds=self._config.quiet_period_seconds,
+ )
+ continue
+
+ # The source can no longer store resume state, so the run must leave this worker now,
+ # also when an item arrived during the fence. The next attempt reads that item again.
+ if activity.in_activity():
+ get_import_preempted_metric(self._source_type, decision.reason).add(1)
+ await self._logger.ainfo(
+ "Preempting the import because the source did not hand off in the quiet period",
+ preemption_reason=decision.reason,
+ quiet_period_seconds=self._config.quiet_period_seconds,
+ seconds_since_shutdown=round(self._stopwatch.elapsed_seconds() or 0.0, 1),
+ )
+ raise SourcePreemptedError.build()
+
+ async def _decision_at_shutdown(self) -> PreemptionDecision:
+ # Decided once, at the shutdown. A run that was young then stays eligible for the whole
+ # quiet period.
+ if self._decision is None:
+ self._decision = self._decide()
+ if self._decision.eligible:
+ await self._logger.ainfo(
+ "Worker is shutting down, the source has a quiet period to hand off before preemption",
+ preemption_reason=self._decision.reason,
+ quiet_period_seconds=self._config.quiet_period_seconds,
+ )
+ else:
+ if activity.in_activity():
+ get_import_not_preempted_metric(self._source_type, self._decision.reason).add(1)
+ await self._logger.ainfo(
+ "Not preempting the import at worker shutdown",
+ not_preempted_reason=self._decision.reason,
+ )
+ return self._decision
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/abandonable_iterate.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/abandonable_iterate.py
new file mode 100644
index 000000000000..b996e38fed8a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/abandonable_iterate.py
@@ -0,0 +1,183 @@
+"""Pull items from a source in a way the caller can stop waiting for.
+
+`async_iterate` runs each `next()` on a shared thread pool and waits for it. A source that blocks
+in one call (a request with no deadline, a slow query, a long retry sleep) then holds the caller
+and a pool thread for as long as the call takes. `AbandonableSourcePuller` gives each source its
+own daemon thread, so the caller can stop waiting and the thread cannot keep the process alive.
+"""
+
+import queue
+import asyncio
+import threading
+import contextvars
+from collections.abc import AsyncIterable, AsyncIterator, Iterable, Iterator
+from typing import Any, Generic, TypeVar, cast
+
+from structlog import get_logger
+
+T = TypeVar("T")
+
+LOGGER = get_logger(__name__)
+
+# (has_value, item). `has_value` is False when the source has no more items.
+PulledItem = tuple[bool, T | None]
+
+
+class SourceAbandonedError(BaseException):
+ """Raised inside the code of a source that the pipeline no longer reads.
+
+ It derives from `BaseException` so that the `except Exception` of a retry wrapper in the source
+ does not catch it and continue the work.
+ """
+
+
+class _ThreadedSource(Generic[T]):
+ """Runs a sync iterator on one daemon thread, one `next()` for each pull."""
+
+ def __init__(self, iterator: Iterator[T]) -> None:
+ self._iterator = iterator
+ self._loop = asyncio.get_running_loop()
+ self._requests: queue.SimpleQueue[asyncio.Future[PulledItem[T]] | None] = queue.SimpleQueue()
+ self._stopped = threading.Event()
+ self._thread: threading.Thread | None = None
+ self._thread_stopped: asyncio.Future[None] = self._loop.create_future()
+
+ def pull(self) -> "asyncio.Future[PulledItem[T]]":
+ future: asyncio.Future[PulledItem[T]] = self._loop.create_future()
+ if self._thread is None:
+ # `threading.Thread` does not carry contextvars into the thread. The source needs them
+ # for its log context and for the safe point hook. One copy serves every pull, so a
+ # value the source sets in one pull is still set in the next one.
+ context = contextvars.copy_context()
+ self._thread = threading.Thread(
+ target=context.run, args=(self._serve,), name="source-iter-abandonable", daemon=True
+ )
+ self._thread.start()
+ self._requests.put(future)
+ return future
+
+ def stop(self) -> None:
+ self._stopped.set()
+ self._requests.put(None)
+
+ async def wait_until_stopped(self) -> None:
+ if self._thread is not None:
+ await asyncio.shield(self._thread_stopped)
+
+ def _serve(self) -> None:
+ try:
+ while True:
+ future = self._requests.get()
+ if future is None or self._stopped.is_set():
+ return
+ try:
+ result: PulledItem[T] = (True, next(self._iterator))
+ except StopIteration:
+ result = (False, None)
+ except BaseException as error:
+ self._deliver(future, error=error)
+ return
+ self._deliver(future, result=result)
+ finally:
+ self._close_iterator()
+ try:
+ self._loop.call_soon_threadsafe(self._mark_thread_stopped)
+ except RuntimeError:
+ pass
+
+ def _mark_thread_stopped(self) -> None:
+ if not self._thread_stopped.done():
+ self._thread_stopped.set_result(None)
+
+ def _deliver(
+ self,
+ future: "asyncio.Future[PulledItem[T]]",
+ *,
+ result: PulledItem[T] | None = None,
+ error: BaseException | None = None,
+ ) -> None:
+ if self._stopped.is_set():
+ return
+
+ def resolve() -> None:
+ if future.done():
+ return
+ if error is not None:
+ future.set_exception(error)
+ else:
+ future.set_result(cast(PulledItem[T], result))
+
+ try:
+ self._loop.call_soon_threadsafe(resolve)
+ except RuntimeError:
+ # The event loop is closed, so nothing waits for this item.
+ pass
+
+ def _close_iterator(self) -> None:
+ close = getattr(self._iterator, "close", None)
+ if not callable(close):
+ return
+ try:
+ close()
+ except BaseException:
+ LOGGER.debug("Closing the source iterator failed", exc_info=True)
+
+
+class _AsyncSource(Generic[T]):
+ """Runs an async iterator on the event loop, one task for each pull."""
+
+ def __init__(self, iterator: AsyncIterator[T]) -> None:
+ self._iterator = iterator
+ self._pending: asyncio.Future[PulledItem[T]] | None = None
+
+ def pull(self) -> "asyncio.Future[PulledItem[T]]":
+ self._pending = asyncio.ensure_future(self._next())
+ return self._pending
+
+ async def _next(self) -> PulledItem[T]:
+ try:
+ return (True, await anext(self._iterator))
+ except StopAsyncIteration:
+ return (False, None)
+
+ def stop(self) -> None:
+ pending = self._pending
+ if pending is None or pending.done():
+ return
+ pending.add_done_callback(_ignore_outcome)
+ pending.cancel()
+
+
+def _ignore_outcome(future: "asyncio.Future[Any]") -> None:
+ if not future.cancelled():
+ future.exception()
+
+
+class AbandonableSourcePuller(Generic[T]):
+ """Pulls the items of a sync or async source one at a time.
+
+ The source advances only inside a pull, the same as with `async_iterate`. So while the caller
+ works on an item, the source is idle and does not change any state it shares with the caller.
+ """
+
+ def __init__(self, iterable: Iterable[T] | AsyncIterable[T]) -> None:
+ self._source: _ThreadedSource[T] | _AsyncSource[T]
+ if isinstance(iterable, AsyncIterable):
+ self._source = _AsyncSource(aiter(iterable))
+ else:
+ self._source = _ThreadedSource(iter(iterable))
+
+ def pull(self) -> "asyncio.Future[PulledItem[T]]":
+ """Ask for the next item. Call it again only after the future of the last call is done."""
+ return self._source.pull()
+
+ async def stop(self, *, abandon: bool = False) -> None:
+ """Stop reading the source.
+
+ A sync source normally finishes its current pull before returning, preserving the worker's
+ bound on live source calls. Worker-shutdown preemption can instead abandon that pull. An
+ async source gets a cancellation.
+ """
+ self._source.stop()
+ if not abandon and isinstance(self._source, _ThreadedSource):
+ await self._source.wait_until_stopped()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_abandonable_iterate.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_abandonable_iterate.py
new file mode 100644
index 000000000000..103efe9f3d70
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_abandonable_iterate.py
@@ -0,0 +1,91 @@
+import asyncio
+import threading
+import contextvars
+
+import pytest
+from unittest.mock import patch
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.abandonable_iterate import (
+ AbandonableSourcePuller,
+)
+
+_probe: contextvars.ContextVar[str] = contextvars.ContextVar("probe", default="unset")
+
+
+async def test_the_source_thread_keeps_one_copy_of_the_callers_context():
+ _probe.set("outer")
+
+ def source():
+ yield _probe.get()
+ _probe.set("inner")
+ yield _probe.get()
+ yield _probe.get()
+
+ puller = AbandonableSourcePuller(source())
+ seen = [(await puller.pull())[1] for _ in range(3)]
+ has_more, _ = await puller.pull()
+ await puller.stop()
+
+ assert seen == ["outer", "inner", "inner"]
+ assert has_more is False
+ assert _probe.get() == "outer"
+
+
+async def test_stopping_a_sync_source_waits_for_its_pull_and_closes_on_the_daemon_thread():
+ release = threading.Event()
+ blocked = threading.Event()
+ closed = threading.Event()
+ thread: list[threading.Thread] = []
+
+ def source():
+ try:
+ thread.append(threading.current_thread())
+ blocked.set()
+ release.wait()
+ yield "late"
+ finally:
+ closed.set()
+
+ puller = AbandonableSourcePuller(source())
+ pull = puller.pull()
+ await asyncio.to_thread(blocked.wait, 5)
+
+ with patch.object(asyncio, "to_thread", side_effect=AssertionError("stop used the shared executor")):
+ stopping = asyncio.create_task(puller.stop())
+ await asyncio.sleep(0)
+ assert not stopping.done()
+
+ release.set()
+ await stopping
+
+ assert await asyncio.to_thread(closed.wait, 5)
+ await asyncio.to_thread(thread[0].join, 5)
+ assert thread[0].daemon
+ assert not thread[0].is_alive()
+ assert not pull.done()
+
+
+async def test_a_stopped_async_source_gets_a_cancellation():
+ started = asyncio.Event()
+ outcome: list[str] = []
+
+ async def source():
+ try:
+ started.set()
+ await asyncio.Event().wait()
+ yield "never"
+ except asyncio.CancelledError:
+ outcome.append("cancelled")
+ raise
+
+ puller = AbandonableSourcePuller(source())
+ pull = puller.pull()
+ await started.wait()
+
+ await puller.stop()
+ await asyncio.wait({pull})
+
+ assert outcome == ["cancelled"]
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
index e8e1b3aabce0..65ce7f2c3ca1 100644
--- 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
@@ -105,6 +105,10 @@ class IncrementalHandoffCheckpoint:
def resume_value(self) -> Any:
return None if self._void else self._resume_value
+ @property
+ def is_void(self) -> bool:
+ return self._void
+
def observe(self, batch: IncrementalBatchRange | None) -> None:
if self._void:
return
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 83446b1f024e..21179889f12d 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
@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs
record_companion_job,
retire_companion_job,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.preemption import PreemptionConfig
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer import (
@@ -92,6 +93,7 @@ class LanedPipelineV3(PipelineV3[ResumableData]):
incremental_checkpoints_allowed: bool = False,
resumed_incremental_run_uuid: str | None = None,
resumed_incremental_value: Any = None,
+ preemption: PreemptionConfig | None = None,
) -> None:
if not source_response.lanes:
raise ValueError(f"{source_response.name} declares no lanes; run it on PipelineV3")
@@ -109,6 +111,7 @@ class LanedPipelineV3(PipelineV3[ResumableData]):
incremental_checkpoints_allowed=incremental_checkpoints_allowed,
resumed_incremental_run_uuid=resumed_incremental_run_uuid,
resumed_incremental_value=resumed_incremental_value,
+ preemption=preemption,
)
# 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/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index ffadcce4ad0b..ea3613be38ea 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
@@ -2,6 +2,7 @@ import time
import asyncio
import datetime
import contextlib
+from collections.abc import AsyncGenerator, AsyncIterator
from typing import TYPE_CHECKING, Any, Generic
import pyarrow as pa
@@ -12,7 +13,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_workflow_id, current_workflow_run_id
-from posthog.temporal.common.shutdown import ShutdownMonitor
+from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownError
from posthog.utils import get_machine_id
from products.warehouse_sources.backend.models import DataWarehouseTable
@@ -28,12 +29,14 @@ from products.warehouse_sources.backend.temporal.data_imports.import_attempt imp
current_import_attempt,
current_import_attempt_cause,
)
+from products.warehouse_sources.backend.temporal.data_imports.metrics import get_shutdown_handoff_delay_metric
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
cleanup_memory,
commit_source_cursor,
finalize_desc_sort_incremental_value,
handle_corrupted_delta_log,
handle_reset_or_full_refresh,
+ is_young_first_attempt,
persist_primary_keys,
reset_rows_synced_if_needed,
resets_table_before_extraction,
@@ -44,6 +47,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.e
update_row_tracking_after_batch,
validate_incremental_sync,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.preemption import (
+ PreemptionConfig,
+ PreemptionDecision,
+ ShutdownStopwatch,
+ SourcePreemptedError,
+ SourcePreemptor,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.safe_point import (
PipelineSafePointHandler,
source_items_are_framework_output,
@@ -108,6 +118,9 @@ if TYPE_CHECKING:
PARQUET_COMPRESSION: ParquetCompression = "zstd"
+# How long a preemption waits for a write of the source's resume state that is in progress.
+SOURCE_FENCE_TIMEOUT_SECONDS = 5.0
+
def should_coalesce_tables(*, resume_manager: ResumableSourceManager[Any] | None, is_webhook: bool) -> bool:
"""Whether the batcher may merge small Arrow tables before staging a batch.
@@ -160,6 +173,11 @@ class PipelineV3(Generic[ResumableData]):
_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
+ # The manager the source holds, also when this run cannot resume from it.
+ _source_resume_manager: ResumableSourceManager[ResumableData] | None = None
+ # None when the pipeline waits for the source for as long as the source takes.
+ _preemption: PreemptionConfig | None = None
+ _shutdown_stopwatch: ShutdownStopwatch | None = None
_resumed_incremental_run_uuid: str | None = None
_sent_resumed_run_finalization: bool = False
_writes_staged_repartition_scheme: bool = False
@@ -178,6 +196,7 @@ class PipelineV3(Generic[ResumableData]):
incremental_checkpoints_allowed: bool = False,
resumed_incremental_run_uuid: str | None = None,
resumed_incremental_value: Any = None,
+ preemption: PreemptionConfig | None = None,
) -> None:
self._resource = source_response
self._source_cursor_manager = source_cursor_manager
@@ -232,7 +251,9 @@ class PipelineV3(Generic[ResumableData]):
self._uses_delta_write_column_selection = source_uses_delta_write_column_selection(models.source.source_type)
self._observed_columns: dict[str, dict[str, Any]] = {}
+ self._source_resume_manager = resumable_source_manager
self._resumable_source_manager = resolve_resume_manager(resumable_source_manager, self._resource)
+ self._preemption = preemption
# 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.
@@ -330,6 +351,7 @@ class PipelineV3(Generic[ResumableData]):
self._accumulated_pa_schema = None
self._batch_results = []
self._shutdown_monitor = shutdown_monitor
+ self._shutdown_stopwatch = ShutdownStopwatch(shutdown_monitor)
self._last_incremental_field_value: Any = None
self._earliest_incremental_field_value: Any = process_incremental_value(
models.schema.incremental_field_earliest_value, models.schema.incremental_field_type
@@ -475,6 +497,54 @@ class PipelineV3(Generic[ResumableData]):
)
return scope
+ def _preemption_decision(self) -> PreemptionDecision:
+ """Whether another worker can continue this run from now without losing or duplicating rows."""
+ if self._schema.is_webhook:
+ # The webhook path deletes its staged files after it yields them, so a row that is only
+ # in the batcher exists nowhere else.
+ return PreemptionDecision(eligible=False, reason="webhook")
+ if self._resource.lanes:
+ return PreemptionDecision(eligible=False, reason="multiple_tables")
+ if self._resumable_source_manager is not None:
+ return PreemptionDecision(eligible=True, reason="resumable")
+ checkpoint = self._handoff_checkpoint
+ carry_over_enabled = self._preemption is not None and self._preemption.watermark_carry_over_enabled
+ if checkpoint is not None and not checkpoint.is_void and carry_over_enabled:
+ return PreemptionDecision(eligible=True, reason="watermark_carry_over")
+ if is_young_first_attempt():
+ return PreemptionDecision(eligible=True, reason="young_first_attempt")
+ if checkpoint is not None and not checkpoint.is_void:
+ return PreemptionDecision(eligible=False, reason="watermark_carry_over_disabled")
+ if self._schema.should_use_incremental_field:
+ return PreemptionDecision(eligible=False, reason="no_watermark_carry_over")
+ return PreemptionDecision(eligible=False, reason="non_resumable_full_refresh")
+
+ async def _fence_abandoned_source(self) -> bool:
+ if self._source_resume_manager is None:
+ return True
+ return await asyncio.to_thread(self._source_resume_manager.revoke_writes, SOURCE_FENCE_TIMEOUT_SECONDS)
+
+ def _source_items(self, items: Any, source_type: str) -> AsyncIterator[Any]:
+ if self._preemption is None or self._shutdown_stopwatch is None:
+ return async_iterate(items)
+ return SourcePreemptor(
+ config=self._preemption,
+ shutdown_monitor=self._shutdown_monitor,
+ stopwatch=self._shutdown_stopwatch,
+ decide=self._preemption_decision,
+ fence_source=self._fence_abandoned_source,
+ source_type=source_type,
+ logger=self._logger,
+ ).iterate(items)
+
+ def _record_handoff_delay(self, error: WorkerShuttingDownError, source_type: str) -> None:
+ if self._shutdown_stopwatch is None or not activity.in_activity():
+ return
+ delay = self._shutdown_stopwatch.elapsed_seconds()
+ if delay is not None:
+ mode = "preempted" if isinstance(error, SourcePreemptedError) else "cooperative"
+ get_shutdown_handoff_delay_metric(source_type, mode).record(delay)
+
async def _commit_resume_state(self) -> None:
if self._resumable_source_manager is None:
return
@@ -692,9 +762,10 @@ class PipelineV3(Generic[ResumableData]):
items = self._resource.items()
safe_point_scope = self._activate_safe_point(items)
+ source_items = self._source_items(items, source_type)
awaiting_source = True
try:
- async for item in async_iterate(items):
+ async for item in source_items:
awaiting_source = False
py_table = None
@@ -746,6 +817,15 @@ class PipelineV3(Generic[ResumableData]):
await stage_remaining_rows()
self._shutdown_monitor.raise_if_is_worker_shutdown()
awaiting_source = True
+ except SourcePreemptedError:
+ # The source is still inside a call, so the cursor it staged can cover rows it did
+ # not yield yet. That cursor must not commit, and the buffered rows of a source with
+ # its own cursor stay unwritten: the committed cursor is behind them, so the next
+ # attempt reads them again. A run that continues after its last staged batch has no
+ # such cursor, so its buffered rows are staged.
+ if self._handoff_checkpoint is not None:
+ await stage_remaining_rows()
+ raise
except Exception:
# The source raised, so a cursor it saved after its last yield is not confirmed: it can
# skip rows that the source fetched and did not hand on. The cursor confirmed at that
@@ -761,6 +841,9 @@ class PipelineV3(Generic[ResumableData]):
raise
finally:
safe_point_scope.close()
+ if isinstance(source_items, AsyncGenerator) and self._preemption is not None:
+ # Stops the thread of the source now. A loop that ended early left it waiting.
+ await source_items.aclose()
# The source ended, so it holds no rows and its last cursor is safe.
self._confirm_resume_state()
@@ -782,7 +865,7 @@ class PipelineV3(Generic[ResumableData]):
except Exception:
await self._logger.aexception("Failed to clean up completed source state")
return result
- except Exception:
+ except Exception as error:
status = "error"
self._logger.exception("V3 Pipeline: Extraction failed")
# Same queue state a failed run has always left: every staged batch has a row, so an
@@ -797,6 +880,8 @@ class PipelineV3(Generic[ResumableData]):
await self._stage_handoff_resume_value()
except Exception:
self._logger.exception("V3 Pipeline: Failed to record where the next attempt can continue")
+ if isinstance(error, WorkerShuttingDownError):
+ self._record_handoff_delay(error, source_type)
raise
finally:
duration = time.perf_counter() - start_time
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 c867f981a26e..2b28dd34a868 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
@@ -1,5 +1,7 @@
import json
+import asyncio
import inspect
+import threading
from contextlib import ExitStack, nullcontext
from dataclasses import dataclass
from types import SimpleNamespace
@@ -19,6 +21,14 @@ from products.warehouse_sources.backend.models.external_data_schema import Exter
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
handle_reset_or_full_refresh,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.preemption import (
+ PreemptionConfig,
+ ShutdownStopwatch,
+ SourcePreemptedError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.abandonable_iterate import (
+ SourceAbandonedError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (
@@ -2173,3 +2183,316 @@ class TestIncrementalHandoffCheckpoint:
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
+
+
+class _ShutdownSwitch:
+ """Stands in for `ShutdownMonitor`. A source thread can start the shutdown at an exact point."""
+
+ def __init__(self) -> None:
+ self._loop = asyncio.get_running_loop()
+ self._flag = threading.Event()
+ self.seen_by_event_loop = asyncio.Event()
+ self._callbacks: list[Any] = []
+
+ def shut_down(self) -> None:
+ self._flag.set()
+ self._loop.call_soon_threadsafe(self._notify)
+
+ def _notify(self) -> None:
+ for callback in self._callbacks:
+ callback()
+ self.seen_by_event_loop.set()
+
+ def run_on_shutdown(self, callback: Any) -> None:
+ self._callbacks.append(callback)
+
+ def is_worker_shutdown(self) -> bool:
+ return self._flag.is_set()
+
+ async def wait_for_worker_shutdown(self) -> None:
+ await self.seen_by_event_loop.wait()
+
+ def raise_if_is_worker_shutdown(self) -> None:
+ if self._flag.is_set():
+ raise WorkerShuttingDownError("id", "type", "queue", 1, "workflow", "workflow_type")
+
+
+def _dict_redis() -> MagicMock:
+ store: dict[str, str] = {}
+ redis = MagicMock()
+ redis.set.side_effect = lambda key, value, ex=None: store.__setitem__(key, value)
+ redis.get.side_effect = store.get
+ redis.exists.side_effect = lambda key: int(key in store)
+ return redis
+
+
+def _with_preemption(
+ pipeline: PipelineV3, *, quiet_period_seconds: float = 0.0, carry_over: bool = True
+) -> _ShutdownSwitch:
+ switch = _ShutdownSwitch()
+ pipeline._shutdown_monitor = cast(Any, switch)
+ pipeline._shutdown_stopwatch = ShutdownStopwatch(cast(Any, switch))
+ pipeline._preemption = PreemptionConfig(
+ quiet_period_seconds=quiet_period_seconds, watermark_carry_over_enabled=carry_over
+ )
+ pipeline._source_resume_manager = pipeline._resumable_source_manager
+ return switch
+
+
+def _staged_ids(pipeline: PipelineV3) -> list[str]:
+ return [
+ row_id
+ for call in cast(AsyncMock, pipeline._process_batch).await_args_list
+ for row_id in call.kwargs["pa_table"].column("id").to_pylist()
+ ]
+
+
+class TestSourcePreemption:
+ @pytest.mark.parametrize("late_write", ["commit", "clear_state"])
+ @pytest.mark.asyncio
+ async def test_a_source_blocked_in_a_call_is_handed_off_and_cannot_store_state_afterwards(
+ self, late_write: str
+ ) -> None:
+ redis = MagicMock()
+ manager = _manager()
+ release = threading.Event()
+ source_ended = threading.Event()
+ seen: dict[str, Any] = {}
+
+ def items():
+ try:
+ manager.save_state(_Cursor("a"))
+ yield pa.table({"id": ["a"]})
+ # Saved for a row that the blocked call has not returned yet.
+ manager.save_state(_Cursor("b"))
+ seen["daemon"] = threading.current_thread().daemon
+ switch.shut_down()
+ release.wait()
+ try:
+ # The late thread confirms the cursor first, as `committing()` and a safe point do.
+ manager.confirm()
+ getattr(manager, late_write)()
+ except BaseException as error:
+ seen["late_write_error"] = error
+ raise
+ finally:
+ source_ended.set()
+
+ pipeline = _runnable_pipeline(manager, items)
+ switch = _with_preemption(pipeline)
+
+ try:
+ await _run_expecting(pipeline, redis, SourcePreemptedError)
+ committed_at_handoff = [json.loads(call.args[1])["id"] for call in redis.set.call_args_list]
+ finally:
+ release.set()
+ with patch.object(ResumableSourceManager, "_get_redis", lambda self: nullcontext(redis)):
+ assert await asyncio.to_thread(source_ended.wait, 5)
+
+ assert committed_at_handoff == ["a"]
+ assert isinstance(seen["late_write_error"], SourceAbandonedError)
+ assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == ["a"]
+ redis.delete.assert_not_called()
+ # A thread that never returns must not keep the worker process alive.
+ assert seen["daemon"] is True
+
+ @pytest.mark.asyncio
+ async def test_a_source_that_reaches_a_safe_point_in_the_quiet_period_hands_off_with_its_cursor(self) -> None:
+ redis = MagicMock()
+ manager = _manager()
+
+ def items():
+ manager.save_state(_Cursor("a"))
+ yield pa.table({"id": ["a"]})
+ manager.save_state(_Cursor("b"))
+ switch.shut_down()
+ manager.safe_point()
+
+ pipeline = _runnable_pipeline(manager, items)
+ switch = _with_preemption(pipeline, quiet_period_seconds=3600.0)
+
+ await _run_expecting(pipeline, redis, WorkerShuttingDownError)
+
+ # A preemption leaves the staged cursor out, so the commit of `b` shows the usual hand-off.
+ assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == ["a", "b"]
+
+ @pytest.mark.parametrize(
+ "preemption_on,resumable,expected_error",
+ [
+ # The source is the kind a preemption covers, so only the setting keeps the run waiting.
+ pytest.param(False, True, WorkerShuttingDownError, id="setting_off"),
+ pytest.param(True, False, RuntimeError, id="full_refresh_that_cannot_resume"),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_the_pipeline_waits_for_the_source_when_it_must_not_preempt(
+ self, preemption_on: bool, resumable: bool, expected_error: type[Exception]
+ ) -> None:
+ redis = MagicMock()
+ manager = _manager()
+ release = threading.Event()
+
+ def items():
+ yield pa.table({"id": ["a"]})
+ switch.shut_down()
+ release.wait()
+ yield pa.table({"id": ["b"]})
+ raise RuntimeError("end of the source")
+
+ pipeline = _runnable_pipeline(manager, items)
+ if not resumable:
+ pipeline._resumable_source_manager = None
+ switch = _with_preemption(pipeline)
+ if not preemption_on:
+ pipeline._preemption = None
+
+ run = asyncio.ensure_future(_run_expecting(pipeline, redis, expected_error))
+ try:
+ await switch.seen_by_event_loop.wait()
+ # A preemption needs no more than a few turns of the event loop from here.
+ for _ in range(20):
+ await asyncio.sleep(0)
+ assert not run.done()
+ finally:
+ release.set()
+ await run
+
+ assert _staged_ids(pipeline) == ["a", "b"]
+ if preemption_on:
+ not_preempted = [
+ call.kwargs["not_preempted_reason"]
+ for call in cast(AsyncMock, pipeline._logger.ainfo).await_args_list
+ if "not_preempted_reason" in call.kwargs
+ ]
+ assert not_preempted == ["non_resumable_full_refresh"]
+
+ @pytest.mark.parametrize(
+ "is_webhook,lanes,resumable,checkpoint,carry_over,young,expected",
+ [
+ pytest.param(False, False, True, None, False, False, (True, "resumable"), id="resumable"),
+ pytest.param(False, False, False, "live", True, False, (True, "watermark_carry_over"), id="carry_over"),
+ pytest.param(
+ False, False, False, None, False, True, (True, "young_first_attempt"), id="young_first_attempt"
+ ),
+ pytest.param(
+ False, False, False, "live", False, True, (True, "young_first_attempt"), id="young_without_carry_over"
+ ),
+ pytest.param(
+ False,
+ False,
+ False,
+ "live",
+ False,
+ False,
+ (False, "watermark_carry_over_disabled"),
+ id="carry_over_setting_off",
+ ),
+ # Rows arrived out of order, so the next attempt has no value to continue after.
+ pytest.param(
+ False, False, False, "void", True, False, (False, "no_watermark_carry_over"), id="void_checkpoint"
+ ),
+ pytest.param(
+ False, False, False, None, True, False, (False, "non_resumable_full_refresh"), id="old_full_refresh"
+ ),
+ pytest.param(True, False, True, None, True, True, (False, "webhook"), id="webhook"),
+ pytest.param(False, True, True, None, True, True, (False, "multiple_tables"), id="multiple_tables"),
+ ],
+ )
+ def test_only_a_run_that_another_worker_can_continue_is_preempted(
+ self,
+ is_webhook: bool,
+ lanes: bool,
+ resumable: bool,
+ checkpoint: str | None,
+ carry_over: bool,
+ young: bool,
+ expected: tuple[bool, str],
+ ) -> None:
+ pipeline = _make_pipeline()
+ pipeline._schema = MagicMock(is_webhook=is_webhook, should_use_incremental_field=checkpoint is not None)
+ pipeline._resource = MagicMock(lanes=[MagicMock()] if lanes else None)
+ pipeline._resumable_source_manager = MagicMock() if resumable else None
+ pipeline._preemption = PreemptionConfig(quiet_period_seconds=60.0, watermark_carry_over_enabled=carry_over)
+ if checkpoint is not None:
+ pipeline._handoff_checkpoint = IncrementalHandoffCheckpoint()
+ if checkpoint == "void":
+ pipeline._handoff_checkpoint.observe(None)
+
+ with patch(f"{_PIPELINE}.is_young_first_attempt", return_value=young):
+ decision = pipeline._preemption_decision()
+
+ assert (decision.eligible, decision.reason) == expected
+
+ @pytest.mark.parametrize("rows_reach_a_batch", [True, False], ids=["rows_staged", "rows_still_buffered"])
+ @pytest.mark.asyncio
+ async def test_a_preempted_resumable_run_and_its_next_attempt_stage_every_row_once(
+ self, rows_reach_a_batch: bool
+ ) -> None:
+ ids = ["a", "b", "c", "d", "e"]
+ redis = _dict_redis()
+ release = threading.Event()
+
+ def source(manager: ResumableSourceManager[_Cursor], block_before: str | None, shut_down: Any):
+ def items():
+ state = manager.load_state()
+ for row_id in ids[ids.index(state.id) + 1 if state else 0 :]:
+ # The cursor is staged before the read of its row, so it is ahead of the yielded
+ # rows for as long as that read takes.
+ manager.save_state(_Cursor(row_id))
+ if row_id == block_before:
+ shut_down()
+ release.wait()
+ yield pa.table({"id": [row_id]}) if rows_reach_a_batch else [{"id": row_id}]
+ raise RuntimeError("end of the source")
+
+ return items
+
+ async def attempt(block_before: str | None, expected_error: type[Exception]) -> list[str]:
+ manager = _manager()
+ pipeline = _runnable_pipeline(manager, lambda: iter(()))
+ switch = _with_preemption(pipeline)
+ pipeline._resource = SourceResponse(
+ name="test_table", items=source(manager, block_before, switch.shut_down), primary_keys=["id"]
+ )
+ await _run_expecting(pipeline, redis, expected_error)
+ return _staged_ids(pipeline)
+
+ try:
+ interrupted = await attempt("c", SourcePreemptedError)
+ continued = await attempt(None, RuntimeError)
+ uninterrupted = ids
+ finally:
+ release.set()
+
+ assert interrupted + continued == uninterrupted
+
+ @pytest.mark.asyncio
+ async def test_a_preempted_incremental_run_stages_its_buffered_rows_and_loses_none(self) -> None:
+ events: list[Any] = []
+ release = threading.Event()
+ rows = [{"id": 1, "n": 10}, {"id": 2, "n": 11}, {"id": 3, "n": 12}, {"id": 4, "n": 13}]
+
+ def items():
+ yield rows[:2]
+ yield rows[2:3]
+ switch.shut_down()
+ release.wait()
+ yield rows[3:]
+
+ checkpoint_tests = TestIncrementalHandoffCheckpoint()
+ pipeline = checkpoint_tests._pipeline(items, events)
+ switch = _with_preemption(pipeline)
+
+ try:
+ await checkpoint_tests._run(pipeline, SourcePreemptedError)
+ finally:
+ release.set()
+
+ # The same order as a hand-off at an item: the queue row exists before the value that tells
+ # the next attempt to skip its rows.
+ assert events == [("staged_rows", [10, 11, 12]), "insert", ("resume_value", 11)]
+ # The next attempt reads the source above the recorded value. Its rows and the staged rows
+ # together are the rows of an uninterrupted run, and the loader merges the overlap by key.
+ staged, resume_value = events[0][1], events[-1][1]
+ next_attempt = [row["n"] for row in rows if row["n"] > resume_value]
+ assert sorted(set(staged) | set(next_attempt)) == [row["n"] for row in rows]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
index dbea2ebc34cb..49ad58a89a64 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
@@ -1,5 +1,6 @@
import json
import functools
+import threading
import dataclasses
import collections.abc
from contextlib import contextmanager
@@ -14,6 +15,9 @@ from structlog.types import FilteringBoundLogger
from posthog.redis import get_client
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.abandonable_iterate import (
+ SourceAbandonedError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import reach_safe_point
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
ResumableData,
@@ -22,6 +26,34 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
)
+class _WriteFence:
+ """Stops the writes of a source that the pipeline abandoned.
+
+ The lock covers each write to Redis, so `revoke` returns True only when no write is in
+ progress and no later write can start.
+ """
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._revoked = False
+
+ @contextmanager
+ def writing(self) -> collections.abc.Iterator[None]:
+ with self._lock:
+ if self._revoked:
+ raise SourceAbandonedError("The pipeline no longer reads this source, so it cannot store resume state")
+ yield
+
+ def revoke(self, timeout_seconds: float) -> bool:
+ if not self._lock.acquire(timeout=timeout_seconds):
+ return False
+ try:
+ self._revoked = True
+ finally:
+ self._lock.release()
+ return True
+
+
class ResumableSourceManager(Generic[ResumableData]):
_inputs: SourceInputs
_data_class: type[ResumableData]
@@ -37,6 +69,7 @@ class ResumableSourceManager(Generic[ResumableData]):
namespace: str | None = None,
pending: dict[str, str] | None = None,
staged: dict[str, str] | None = None,
+ write_fence: _WriteFence | None = None,
):
self._inputs = inputs
self._data_class = data_class
@@ -48,6 +81,8 @@ class ResumableSourceManager(Generic[ResumableData]):
# Cursors wait here until commit(). Siblings from with_namespace() share the dict, so the
# one commit the pipeline issues after a write covers every namespace a source touched.
self._staged = staged if staged is not None else {}
+ # Shared with the siblings for the same reason: one revoke stops every namespace.
+ self._write_fence = write_fence if write_fence is not None else _WriteFence()
def with_namespace(self, namespace: str) -> "ResumableSourceManager[ResumableData]":
"""Return a sibling manager whose Redis state is isolated under `namespace`.
@@ -58,9 +93,24 @@ class ResumableSourceManager(Generic[ResumableData]):
cursor the other endpoint wrote and replay it against an API that can't parse it.
"""
return ResumableSourceManager(
- self._inputs, self._data_class, namespace=namespace, pending=self._pending, staged=self._staged
+ self._inputs,
+ self._data_class,
+ namespace=namespace,
+ pending=self._pending,
+ staged=self._staged,
+ write_fence=self._write_fence,
)
+ def revoke_writes(self, timeout_seconds: float) -> bool:
+ """Make every later `commit` and `clear_state` raise `SourceAbandonedError`.
+
+ The pipeline calls this before it hands a run to another worker while the source is still
+ inside a call. The thread of that source can run for a long time after the hand-off, and a
+ cursor it stored then would move the resume point of the attempt that continues the run.
+ Returns False, and revokes nothing, when a write is still in progress after `timeout_seconds`.
+ """
+ return self._write_fence.revoke(timeout_seconds)
+
@contextmanager
def _get_redis(self):
if not settings.DATA_WAREHOUSE_REDIS_HOST or not settings.DATA_WAREHOUSE_REDIS_PORT:
@@ -156,7 +206,7 @@ class ResumableSourceManager(Generic[ResumableData]):
"""Persist every confirmed cursor, across namespaces."""
if not self._staged:
return
- with self._get_redis() as redis_client:
+ with self._write_fence.writing(), self._get_redis() as redis_client:
for key, json_data in list(self._staged.items()):
self._logger.debug(f"Saving resumable source state. key={key}")
self._write_with_stale_replica_retry(
@@ -197,7 +247,7 @@ class ResumableSourceManager(Generic[ResumableData]):
"""
self._pending.pop(self._key, None)
self._staged.pop(self._key, None)
- with self._get_redis() as redis_client:
+ with self._write_fence.writing(), self._get_redis() as redis_client:
self._logger.debug(f"Clearing resumable source state. key={self._key}")
self._write_with_stale_replica_retry(redis_client, lambda: redis_client.delete(self._key))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py
index 59812f392f29..f733640b0fea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py
@@ -1,4 +1,5 @@
import typing
+import threading
import pytest
from unittest.mock import MagicMock, patch
@@ -7,6 +8,9 @@ import redis.exceptions as redis_exceptions
from posthog.dataclasses import frozen
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.abandonable_iterate import (
+ SourceAbandonedError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import ResumableSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import (
@@ -241,3 +245,56 @@ class TestResumeCoversRun:
# on its incremental field, so narrowing the default would cut their retry budgets.
for incremental in (True, False):
assert ResumableSource.resume_covers_run(MagicMock(), incremental_or_append=incremental) is True
+
+
+class TestRevokedWrites:
+ @pytest.mark.parametrize("write", ["commit", "clear_state", "sibling_commit"])
+ def test_a_revoked_manager_writes_nothing_to_redis(self, write: str):
+ manager = _manager()
+ sibling = manager.with_namespace("other")
+ redis = MagicMock()
+
+ with patch.object(ResumableSourceManager, "_get_redis") as get_redis:
+ get_redis.return_value.__enter__.return_value = redis
+ manager.save_state(_SweepPosition(cursor="cus_1"))
+ sibling.save_state(_SweepPosition(cursor="cus_2"))
+
+ assert manager.revoke_writes(timeout_seconds=1) is True
+ # A source thread that still runs after the hand-off can confirm its cursors.
+ manager.confirm()
+ with pytest.raises(SourceAbandonedError):
+ {"commit": manager.commit, "clear_state": manager.clear_state, "sibling_commit": sibling.commit}[
+ write
+ ]()
+
+ redis.set.assert_not_called()
+ redis.delete.assert_not_called()
+
+ def test_a_write_in_progress_blocks_the_revoke_and_still_lands(self):
+ manager = _manager()
+ redis = MagicMock()
+ in_redis = threading.Event()
+ release = threading.Event()
+
+ def blocked_write(*args: typing.Any, **kwargs: typing.Any) -> None:
+ in_redis.set()
+ release.wait()
+
+ redis.set.side_effect = blocked_write
+
+ with patch.object(ResumableSourceManager, "_get_redis") as get_redis:
+ get_redis.return_value.__enter__.return_value = redis
+ manager.save_state(_SweepPosition(cursor="cus_1"))
+ manager.confirm()
+ writer = threading.Thread(target=manager.commit, daemon=True)
+ writer.start()
+ assert in_redis.wait(5)
+
+ # A hand-off now would let this write land after the next attempt starts.
+ assert manager.revoke_writes(timeout_seconds=0.01) is False
+
+ release.set()
+ writer.join(5)
+ assert manager.revoke_writes(timeout_seconds=1) is True
+
+ assert redis.set.call_count == 1
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 2f3ab5bfbfea..f62b58eb44e8 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
@@ -61,6 +61,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.e
reset_pipeline_requested,
trim_source_job_inputs,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.preemption import PreemptionConfig
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
SchemaColumnTypeChangedException,
)
@@ -555,6 +556,15 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
attempt=attempt,
)
+ # Preemption makes hand-offs frequent, so it applies only to a run whose hand-offs use no
+ # retry attempt.
+ preemption: PreemptionConfig | None = None
+ if settings.DATA_WAREHOUSE_IMPORT_PREEMPTION_ENABLED and inputs.handoffs_are_free:
+ preemption = PreemptionConfig(
+ quiet_period_seconds=settings.DATA_WAREHOUSE_IMPORT_PREEMPTION_QUIET_PERIOD_SECONDS,
+ watermark_carry_over_enabled=settings.DATA_WAREHOUSE_IMPORT_WATERMARK_CARRY_OVER_ENABLED,
+ )
+
if schema.should_use_incremental_field:
await logger.adebug(f"Incremental last value being used is: {processed_incremental_last_value}")
@@ -739,6 +749,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
on_resumable_retry_budget=inputs.on_resumable_retry_budget,
resumed_incremental_run_uuid=resumed_incremental_run_uuid,
resumed_incremental_value=resumed_incremental_value,
+ preemption=preemption,
)
else:
raise ValueError(f"Source type {model.pipeline.source_type} not supported")
@@ -1112,6 +1123,7 @@ async def _run(
incremental_checkpoints_allowed: bool = False,
resumed_incremental_run_uuid: str | None = None,
resumed_incremental_value: Any = None,
+ preemption: PreemptionConfig | None = None,
on_resumable_retry_budget: bool = False,
) -> PipelineResult:
try:
@@ -1130,6 +1142,7 @@ async def _run(
incremental_checkpoints_allowed=incremental_checkpoints_allowed,
resumed_incremental_run_uuid=resumed_incremental_run_uuid,
resumed_incremental_value=resumed_incremental_value,
+ preemption=preemption,
)
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 2cbf6b75868e..42705ba003a9 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
@@ -36,6 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_job
NEW_TABLE_NOT_READY_MESSAGE,
_transient_error_message,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.preemption import PreemptionConfig
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import repartition_controller
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
SchemaColumnTypeChangedException,
@@ -1670,6 +1671,50 @@ async def test_a_free_handoff_is_a_result_and_any_other_handoff_is_a_retry(hando
await import_data_activity_sync(inputs)
+ "preemption_enabled,handoffs_are_free,carry_over_enabled,expected",
+ [
+ pytest.param(
+ True,
+ True,
+ True,
+ PreemptionConfig(quiet_period_seconds=45.0, watermark_carry_over_enabled=True),
+ id="on_for_a_run_with_free_handoffs",
+ ),
+ pytest.param(
+ True,
+ True,
+ False,
+ PreemptionConfig(quiet_period_seconds=45.0, watermark_carry_over_enabled=False),
+ id="carry_over_setting_reaches_the_pipeline",
+ ),
+ # A preempted run that uses a retry attempt for each hand-off fails after a few deploys.
+ pytest.param(True, False, True, None, id="off_when_a_handoff_uses_a_retry_attempt"),
+ pytest.param(False, True, True, None, id="off_by_default"),
+ ],
+)
+async def test_the_pipeline_preempts_only_with_the_setting_on_and_free_handoffs(
+ preemption_enabled: bool,
+ handoffs_are_free: bool,
+ carry_over_enabled: bool,
+ expected: PreemptionConfig | None,
+ settings,
+):
+ settings.DATA_WAREHOUSE_IMPORT_PREEMPTION_ENABLED = preemption_enabled
+ settings.DATA_WAREHOUSE_IMPORT_PREEMPTION_QUIET_PERIOD_SECONDS = 45.0
+ 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=None)
+
+ 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(), handoffs_are_free=handoffs_are_free))
+
+ assert run_mock.await_args.kwargs["preemption"] == expected
+
+
@parameterized.expand(
[
("no_checkpoint_past_the_allowance", True, PROGRESSLESS_RESUMABLE_ATTEMPTS + 1, False, True),