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): let a resumable source hand off from empty pages (#109061)

Tom Owers98e765b2684b
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index 96a771c5e51b..fb1478737d64 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -428,6 +428,13 @@ while True:
Save state **before** yielding the batch it covers. `save_state` only stages the cursor; the pipeline commits it to Redis once that batch is written, so a crash resumes exactly after the last written batch. A source that saves after yielding still works, but a crash re-yields its last batch (merge dedupes on primary key, append does not). A source with nothing yielded yet, such as one persisting an export job id before polling it, stages inside `with manager.committing():`, which commits when the block ends.
+Call `manager.safe_point()` wherever the source can make many requests that return no rows: an empty delta page, a fan-out parent with no children, a page with no comments.
+The pipeline checks for a worker shutdown only when an item arrives, so a run of empty responses otherwise holds the worker for the whole graceful shutdown timeout, and its cursor never commits.
+At a safe point the pipeline can hand the run to another worker, and it commits the staged cursor when nothing is waiting to be written.
+Call it only where resuming from the staged cursor loses no rows: every row the cursor covers is already yielded, and none sits in a local buffer.
+References: `document_deltas` in `convex/convex.py`, the sparse-sweep checkpoint in `stripe/stripe.py`, `_page_fan_out` in `notion/notion.py`.
+The `rest_source` framework reaches a safe point after each page on its own, but only when `SourceResponse.items` returns the framework's `Resource` directly. A source that wraps it gets no framework safe points, because the wrapper could buffer rows.
+
### Webhook source pattern
- Implement `webhook_template` returning a `HogFunctionTemplateDC` that transforms incoming webhook payloads.
@@ -893,6 +900,7 @@ After changing source fields, re-run `pnpm run generate:source-configs` and `hog
- Endless retries for bad credentials: missing `get_non_retryable_errors`.
- Source won't connect despite a valid token: `validate_credentials(schema_name=None)` probes every resource's scope instead of just the token, so one missing scope — often on a table the user won't sync — blocks the whole source. Probe only the token at create; report per-table scope via `get_endpoint_permissions`.
- Resumable state never saved: forgot to call `save_state`; or called `commit()` on a cursor that covers rows the pipeline has not written yet, which skips them on resume.
+- A deploy waits hours on a resumable source: it pages through responses with no rows and never calls `manager.safe_point()`, so it never sees the worker shutdown.
- Webhook rows not landing: schema `is_webhook=False`, or `initial_sync_complete=False`.
- Dependent resource path `KeyError`: pre-format static path placeholders (see Fan-out).
- Silent truncation risk: page caps hit without logs/metrics.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/safe_point.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/safe_point.py
new file mode 100644
index 000000000000..8084c6023d04
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/safe_point.py
@@ -0,0 +1,58 @@
+import time
+from collections.abc import Callable
+from typing import Any
+
+from posthog.temporal.common.shutdown import ShutdownMonitor
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+# A source can reach a safe point on every request, so the cursor commit it allows is rate-limited.
+# The value bounds how much empty-page progress an OOM or SIGKILL can lose.
+SAFE_POINT_COMMIT_INTERVAL_SECONDS = 30.0
+
+
+class PipelineSafePointHandler:
+ """The hook a pipeline installs for a resumable source's safe points (see `sources/common/safe_point.py`).
+
+ It runs in the source's thread while the pipeline waits for the next item, so the pipeline's own
+ state (the batcher, held queue rows) is not changing under it.
+ """
+
+ def __init__(
+ self,
+ *,
+ shutdown_monitor: ShutdownMonitor,
+ resumable_source_manager: ResumableSourceManager[Any],
+ has_unwritten_rows: Callable[[], bool],
+ commit_interval_seconds: float | None = None,
+ clock: Callable[[], float] = time.monotonic,
+ ):
+ self._shutdown_monitor = shutdown_monitor
+ self._resumable_source_manager = resumable_source_manager
+ self._has_unwritten_rows = has_unwritten_rows
+ self._commit_interval_seconds = (
+ SAFE_POINT_COMMIT_INTERVAL_SECONDS if commit_interval_seconds is None else commit_interval_seconds
+ )
+ self._clock = clock
+ self._last_commit = clock()
+
+ def __call__(self) -> None:
+ # The pipeline's `except` path writes the rows it holds and then commits the staged cursor,
+ # so a raise here hands the run to another worker without losing progress.
+ self._shutdown_monitor.raise_if_is_worker_shutdown()
+
+ now = self._clock()
+ if now - self._last_commit < self._commit_interval_seconds:
+ return
+ # A cursor may commit only once the rows it covers are written. With rows still buffered or a
+ # batch still held, the next write commits it instead.
+ if self._has_unwritten_rows() or not self._resumable_source_manager.has_staged_state():
+ return
+ self._resumable_source_manager.commit()
+ self._last_commit = now
+
+
+def source_items_are_framework_output(items: Any) -> bool:
+ """Whether the pipeline iterates the REST framework's own generator, with no source wrapper around it."""
+ return isinstance(items, Resource)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_safe_point.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_safe_point.py
new file mode 100644
index 000000000000..fe6cc6c4af09
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_safe_point.py
@@ -0,0 +1,109 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.safe_point import (
+ PipelineSafePointHandler,
+ source_items_are_framework_output,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import (
+ activate_safe_point,
+ reach_framework_safe_point,
+ reach_safe_point,
+)
+
+
+class _Clock:
+ def __init__(self) -> None:
+ self.now = 0.0
+
+ def __call__(self) -> float:
+ return self.now
+
+
+ "unwritten_rows,staged,elapsed,expect_commit",
+ [
+ (False, True, 30.0, True),
+ (True, True, 30.0, False),
+ (False, False, 30.0, False),
+ (False, True, 29.0, False),
+ ],
+ ids=["due", "rows_unwritten", "nothing_staged", "too_soon"],
+)
+def test_handler_commits_only_a_cursor_whose_rows_are_written(
+ unwritten_rows: bool, staged: bool, elapsed: float, expect_commit: bool
+) -> None:
+ clock = _Clock()
+ manager = MagicMock()
+ manager.has_staged_state.return_value = staged
+ handler = PipelineSafePointHandler(
+ shutdown_monitor=MagicMock(),
+ resumable_source_manager=manager,
+ has_unwritten_rows=lambda: unwritten_rows,
+ commit_interval_seconds=30.0,
+ clock=clock,
+ )
+
+ clock.now = elapsed
+ handler()
+
+ assert manager.commit.called is expect_commit
+
+
+def test_handler_raises_the_shutdown_before_it_commits() -> None:
+ monitor = MagicMock()
+ monitor.raise_if_is_worker_shutdown.side_effect = RuntimeError("worker shutting down")
+ manager = MagicMock()
+ handler = PipelineSafePointHandler(
+ shutdown_monitor=monitor,
+ resumable_source_manager=manager,
+ has_unwritten_rows=lambda: False,
+ commit_interval_seconds=0.0,
+ )
+
+ with pytest.raises(RuntimeError, match="worker shutting down"):
+ handler()
+
+ manager.commit.assert_not_called()
+
+
+ "covers_framework_checkpoints,expected_calls",
+ [(True, ["source", "framework"]), (False, ["source"])],
+ ids=["framework_output", "wrapped_output"],
+)
+def test_framework_safe_points_apply_only_to_unwrapped_framework_output(
+ covers_framework_checkpoints: bool, expected_calls: list[str]
+) -> None:
+ calls: list[str] = []
+ current: dict[str, str] = {}
+
+ def hook() -> None:
+ calls.append(current["caller"])
+
+ with activate_safe_point(hook, covers_framework_checkpoints=covers_framework_checkpoints):
+ current["caller"] = "source"
+ reach_safe_point()
+ current["caller"] = "framework"
+ reach_framework_safe_point()
+
+ reach_safe_point()
+ reach_framework_safe_point()
+
+ assert calls == expected_calls
+
+
+ "items,expected",
+ [
+ (Resource(lambda: iter([]), name="r", hints={}), True),
+ ((page for page in [[{"id": 1}]]), False),
+ ([[{"id": 1}]], False),
+ ],
+ ids=["resource", "wrapping_generator", "list"],
+)
+def test_only_a_bare_resource_counts_as_framework_output(items: Any, expected: bool) -> None:
+ assert source_items_are_framework_output(items) is expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
index 2e38d8fbccb0..b90f62ae1d61 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
@@ -1,6 +1,7 @@
import sys
import time
import asyncio
+import contextlib
from typing import TYPE_CHECKING, Any, Generic, Literal
import pyarrow as pa
@@ -37,6 +38,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.l
run_post_load_operations,
supports_partial_data_loading,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.safe_point import (
+ PipelineSafePointHandler,
+ source_items_are_framework_output,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
_append_debug_column_to_pyarrows_table,
_handle_null_columns_with_definitions,
@@ -67,6 +72,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
ResumableSourceManager,
resolve_resume_manager,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import activate_safe_point
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
ResumableData,
SourceResponse,
@@ -170,6 +176,19 @@ class PipelineNonDLT(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]] = {}
+ def _activate_safe_point(self, items: Any) -> contextlib.ExitStack:
+ scope = contextlib.ExitStack()
+ if self._resumable_source_manager is not None:
+ handler = PipelineSafePointHandler(
+ shutdown_monitor=self._shutdown_monitor,
+ resumable_source_manager=self._resumable_source_manager,
+ has_unwritten_rows=lambda: self._batcher.should_yield(include_incomplete_chunk=True),
+ )
+ scope.enter_context(
+ activate_safe_point(handler, covers_framework_checkpoints=source_items_are_framework_output(items))
+ )
+ return scope
+
async def _commit_resume_state(self) -> None:
if self._resumable_source_manager is not None:
await asyncio.to_thread(self._resumable_source_manager.commit)
@@ -249,9 +268,11 @@ class PipelineNonDLT(Generic[ResumableData]):
# Every yielded row is written now, so whatever the source staged last is safe.
await self._commit_resume_state()
+ items = self._resource.items()
+ safe_point_scope = self._activate_safe_point(items)
awaiting_source = True
try:
- async for item in async_iterate(self._resource.items()):
+ async for item in async_iterate(items):
awaiting_source = False
py_table = None
@@ -305,6 +326,8 @@ class PipelineNonDLT(Generic[ResumableData]):
except Exception:
await self._logger.aexception("Failed to write the rows buffered before the source error")
raise
+ finally:
+ safe_point_scope.close()
await write_remaining_rows()
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 f115812704d8..3f308cbff57b 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
@@ -1,6 +1,7 @@
import time
import asyncio
import datetime
+import contextlib
from typing import TYPE_CHECKING, Any, Generic
import pyarrow as pa
@@ -42,6 +43,10 @@ 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.safe_point import (
+ PipelineSafePointHandler,
+ source_items_are_framework_output,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
_append_debug_column_to_pyarrows_table,
_handle_null_columns_with_definitions,
@@ -84,6 +89,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
ResumableSourceManager,
resolve_resume_manager,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import activate_safe_point
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
ResumableData,
SourceResponse,
@@ -346,6 +352,21 @@ class PipelineV3(Generic[ResumableData]):
def _close_producers(self) -> None:
self._pg_producer.close()
+ def _activate_safe_point(self, items: Any) -> contextlib.ExitStack:
+ scope = contextlib.ExitStack()
+ if self._resumable_source_manager is not None:
+ handler = PipelineSafePointHandler(
+ shutdown_monitor=self._shutdown_monitor,
+ resumable_source_manager=self._resumable_source_manager,
+ has_unwritten_rows=lambda: (
+ self._batcher.should_yield(include_incomplete_chunk=True) or self._pg_producer.has_held_batch
+ ),
+ )
+ scope.enter_context(
+ activate_safe_point(handler, covers_framework_checkpoints=source_items_are_framework_output(items))
+ )
+ return scope
+
async def _commit_resume_state(self) -> None:
if self._resumable_source_manager is None:
return
@@ -472,9 +493,11 @@ class PipelineV3(Generic[ResumableData]):
# Every yielded row is staged now, so whatever the source staged last is safe.
await self._commit_resume_state()
+ items = self._resource.items()
+ safe_point_scope = self._activate_safe_point(items)
awaiting_source = True
try:
- async for item in async_iterate(self._resource.items()):
+ async for item in async_iterate(items):
awaiting_source = False
py_table = None
@@ -529,6 +552,8 @@ class PipelineV3(Generic[ResumableData]):
except Exception:
await self._logger.aexception("Failed to stage the rows buffered before the source error")
raise
+ finally:
+ safe_point_scope.close()
await stage_remaining_rows()
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 80c6391c1e03..5724a2d45d8b 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
@@ -36,6 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
)
_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"
_LANES = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.lanes"
_CONSUMER = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer"
_PRODUCER = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer"
@@ -1004,6 +1005,50 @@ class TestResumeCursorCommit:
assert cast(AsyncMock, pipeline._process_batch).await_count == 1
assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == ["a"]
+ @pytest.mark.asyncio
+ async def test_an_empty_page_safe_point_hands_off_at_shutdown_with_its_cursor(self) -> None:
+ redis = MagicMock()
+ manager = _manager()
+
+ def items():
+ manager.save_state(_Cursor("a"))
+ yield [{"id": "a"}]
+ for page in ("b", "c"):
+ manager.save_state(_Cursor(page))
+ manager.safe_point()
+
+ pipeline = _runnable_pipeline(manager, items)
+ shutdown = WorkerShuttingDownError("id", "type", "queue", 1, "workflow", "workflow_type")
+ cast(MagicMock, pipeline._shutdown_monitor).raise_if_is_worker_shutdown.side_effect = _raise_on_second_call(
+ shutdown
+ )
+
+ await _run_expecting(pipeline, redis, WorkerShuttingDownError)
+
+ assert cast(AsyncMock, pipeline._process_batch).await_count == 1
+ assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == ["b"]
+
+ @pytest.mark.asyncio
+ async def test_empty_page_safe_points_commit_the_cursor_when_nothing_is_unwritten(self) -> None:
+ redis = MagicMock()
+ manager = _manager()
+
+ def items():
+ for page in ("a", "b"):
+ manager.save_state(_Cursor(page))
+ manager.safe_point()
+ yield from ()
+ raise RuntimeError("page budget")
+
+ pipeline = _runnable_pipeline(manager, items)
+ pipeline._pg_producer = _recording_producer()
+
+ with patch(f"{_SAFE_POINT}.SAFE_POINT_COMMIT_INTERVAL_SECONDS", 0):
+ await _run_expecting(pipeline, redis, RuntimeError)
+
+ cast(AsyncMock, pipeline._process_batch).assert_not_awaited()
+ 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:
"""A real producer over a mocked queue connection, so the rows it inserts can be read back."""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
index 31e214f9dec9..4a94e376b958 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
@@ -21,6 +21,9 @@ from tenacity import RetryCallState, retry, retry_if_exception_type
from posthog.temporal.common.errors import NonReportableError
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import (
+ reach_framework_safe_point,
+)
from .auth import auth_secret_values
from .exceptions import IgnoreResponseException
@@ -476,6 +479,10 @@ class RESTClient:
if resume_hook is not None:
resume_hook(paginator.get_resume_state() if paginator is not None and paginator.has_next_page else None)
+ # Direct Resource traversal has consumed the page before execution resumes here, so this
+ # is safe even when a dependent resource routes its resume hook only to the child.
+ reach_framework_safe_point()
+
if paginator is None or not paginator.has_next_page:
break
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
index 10dcd541f7fd..6ffba7a6646a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTClientRetryableError,
_parse_retry_after,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import activate_safe_point
def _make_response(json_body: Any, status_code: int = 200) -> Response:
@@ -228,11 +229,41 @@ class TestRESTClient:
saved: list[Any] = []
client = RESTClient(base_url="https://api.example.com")
- list(client.paginate(path="/items", paginator=TwoPagePaginator(), resume_hook=saved.append))
+ with activate_safe_point(lambda: saved.append("safe_point"), covers_framework_checkpoints=True):
+ list(client.paginate(path="/items", paginator=TwoPagePaginator(), resume_hook=saved.append))
# Called once between page 1 and page 2 with the next-page state, and
- # once on the terminal page with None (no more pages to resume to).
- assert saved == [{"page": 1}, None]
+ # once on the terminal page with None (no more pages to resume to). Each checkpoint is
+ # followed by a safe point, never preceded by one, so the staged cursor covers the page.
+ assert saved == [{"page": 1}, "safe_point", None, "safe_point"]
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ )
+ def test_paginate_invokes_safe_point_without_resume_hook(self, MockSession) -> None:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.return_value = MagicMock()
+ mock_session.send.side_effect = [_make_response([]), _make_response([])]
+
+ class TwoPagePaginator(BasePaginator):
+ def __init__(self):
+ super().__init__()
+ self._page = 0
+
+ def update_state(self, response, data=None):
+ self._page += 1
+ self._has_next_page = self._page < 2
+
+ def update_request(self, request):
+ pass
+
+ safe_points: list[str] = []
+ client = RESTClient(base_url="https://api.example.com")
+ with activate_safe_point(lambda: safe_points.append("safe_point"), covers_framework_checkpoints=True):
+ list(client.paginate(path="/items", paginator=TwoPagePaginator()))
+
+ assert safe_points == ["safe_point", "safe_point"]
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
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 47a5aaa33883..191adbe5cd59 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
@@ -14,6 +14,7 @@ from structlog.types import FilteringBoundLogger
from posthog.redis import get_client
+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,
SourceInputs,
@@ -153,6 +154,17 @@ class ResumableSourceManager(Generic[ResumableData]):
finally:
self.commit()
+ def safe_point(self) -> None:
+ """Mark a point where resuming from the staged cursor loses no rows.
+
+ Call it only when every row the staged cursor covers has been yielded, and the source holds
+ none of them in a local buffer. The pipeline can then hand the run to another worker during a
+ shutdown, or commit the cursor when nothing is waiting to be written. A source that makes many
+ requests that return no rows needs this, because the pipeline otherwise acts only when an
+ item arrives. See `safe_point.py`.
+ """
+ reach_safe_point()
+
def clear_state(self) -> None:
"""Drop any saved resume state so a subsequent attempt starts from scratch.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/safe_point.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/safe_point.py
new file mode 100644
index 000000000000..8c6eb2a45678
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/safe_point.py
@@ -0,0 +1,62 @@
+"""Safe points: places in a resumable source where the run can stop and resume without losing rows.
+
+A resumable source stages its cursor with `ResumableSourceManager.save_state`, and the pipeline
+commits the cursor after it writes the rows that the cursor covers. The pipeline also checks for a
+worker shutdown, but only when the source yields an item. A source that makes many requests that
+return no rows (an empty delta page, a parent with no children) yields nothing for a long time. It
+then never sees the shutdown, and it never commits its cursor, so it holds the worker until the
+graceful shutdown timeout ends and restarts from its last commit.
+
+A safe point closes that gap. The pipeline installs a hook for the length of the extraction, and a
+source calls `reach_safe_point()` (or `ResumableSourceManager.safe_point()`) where resuming from the
+staged cursor loses no rows: every row the cursor covers has already been yielded to the pipeline,
+and the source holds none of those rows in a local buffer. The hook can raise
+`WorkerShuttingDownError`, which the pipeline handles the same way as a shutdown it detects itself,
+and it can commit the staged cursor when nothing is waiting to be written.
+"""
+
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from contextvars import ContextVar
+
+from posthog.dataclasses import frozen
+
+SafePointHook = Callable[[], None]
+
+
+@frozen
+class _ActiveSafePoint:
+ hook: SafePointHook
+ # The shared REST framework reaches a safe point after each page it hands on. That is only safe
+ # when the framework's own generator is what the pipeline iterates. A source that wraps it could
+ # buffer rows between the two, and the framework cannot see that buffer.
+ covers_framework_checkpoints: bool
+
+
+_active_safe_point: ContextVar[_ActiveSafePoint | None] = ContextVar("warehouse_source_safe_point", default=None)
+
+
+@contextmanager
+def activate_safe_point(hook: SafePointHook, *, covers_framework_checkpoints: bool) -> Iterator[None]:
+ """Install `hook` for code that runs in this context, including source threads started in it."""
+ token = _active_safe_point.set(
+ _ActiveSafePoint(hook=hook, covers_framework_checkpoints=covers_framework_checkpoints)
+ )
+ try:
+ yield
+ finally:
+ _active_safe_point.reset(token)
+
+
+def reach_safe_point() -> None:
+ """Tell the pipeline that the source is at a safe point. Does nothing outside an extraction."""
+ active = _active_safe_point.get()
+ if active is not None:
+ active.hook()
+
+
+def reach_framework_safe_point() -> None:
+ """The REST framework's safe point, which applies only when nothing wraps the framework's output."""
+ active = _active_safe_point.get()
+ if active is not None and active.covers_framework_checkpoints:
+ active.hook()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py
index d3cabf6ad1e2..68ac4a8495dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py
@@ -284,6 +284,7 @@ def list_snapshot(
if cursor is not None:
resumable_source_manager.save_state(ConvexResumeConfig(cursor=cursor, snapshot=snapshot))
+ resumable_source_manager.safe_point()
class InvalidWindowError(Exception):
@@ -355,6 +356,9 @@ def document_deltas(
return current_cursor
resumable_source_manager.save_state(ConvexResumeConfig(cursor=current_cursor))
+ # Most delta pages carry no change for this table, so a catch-up can walk for hours without
+ # yielding a row. The page's rows (if any) are yielded above, so the cursor loses nothing here.
+ resumable_source_manager.safe_point()
def validate_credentials(deploy_url: str, deploy_key: str) -> tuple[bool, str | None]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py
index 6391bd309ae3..51655f940f12 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py
@@ -256,6 +256,29 @@ class TestListSnapshotResumable:
manager.save_state.assert_not_called()
+class TestEmptyPagesReachSafePoints:
+ @parameterized.expand(
+ [
+ ("deltas", lambda manager: document_deltas("https://x.convex.cloud", "key", "t", 10, manager)),
+ ("snapshot", lambda manager: list_snapshot("https://x.convex.cloud", "key", "t", manager)),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.convex.convex.make_tracked_session")
+ def test_each_empty_page_stages_its_cursor_then_reaches_a_safe_point(self, _name, read, mock_get: Mock) -> None:
+ manager = _make_manager(can_resume=False)
+ mock_get.return_value.get.side_effect = [
+ _make_response({"values": [], "cursor": 20, "snapshot": 5, "hasMore": True}),
+ _make_response({"values": [], "cursor": 30, "snapshot": 5, "hasMore": True}),
+ _make_response({"values": [], "cursor": 40, "snapshot": 5, "hasMore": False}),
+ ]
+
+ batches = list(read(manager))
+
+ assert batches == []
+ calls = [name for name, *_ in manager.method_calls if name in ("save_state", "safe_point")]
+ assert calls == ["save_state", "safe_point", "save_state", "safe_point"]
+
+
class TestDocumentDeltasResumable:
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.convex.convex.make_tracked_session")
def test_fresh_run_saves_state_after_each_page(self, mock_get: Mock) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py
index 8d2dcb049a7e..dcc413d32f2b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py
@@ -1,6 +1,6 @@
import time
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from typing import Any, Literal, Optional
import requests
@@ -45,6 +45,12 @@ CHUNK_SIZE_BYTES = 100 * 1024 * 1024
# stream resumes across retries and paces itself under Notion's rate limit.
MAX_BLOCK_DEPTH = 30
MAX_CHILD_PAGES_PER_PARENT = 50
+# In the blocks and comments fan-out, a partly filled chunk is yielded at a page boundary once this
+# long has passed since the last yield, so sparse pages still reach the pipeline regularly.
+PARTIAL_FLUSH_INTERVAL_SECONDS = 60.0
+# A page with no buffered rows stages the shrinking page queue at most this often, because staging
+# serializes the whole queue.
+EMPTY_PAGE_STAGE_INTERVAL_SECONDS = 10.0
# Notion enforces an average of ~3 requests/second per integration. Pacing requests to this minimum
# interval keeps us under the cap proactively, avoiding the retry churn that reacting to 429s alone
@@ -448,89 +454,131 @@ def _iter_block_children(
cursor = data["next_cursor"]
-def _blocks_stream(
+def _page_fan_out(
session: requests.Session,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
+ rows_for_page: Callable[[str], Iterator[dict[str, Any]]],
throttle: Optional["_RateLimiter"] = None,
) -> Iterator[Any]:
+ """Fetch rows for every page, with the fan-out position saved as a shrinking queue of page ids."""
batcher = Batcher(logger=logger, chunk_size=CHUNK_SIZE, chunk_size_bytes=CHUNK_SIZE_BYTES)
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
if resume is not None and resume.remaining_page_ids is not None:
# Resume the fan-out from the persisted queue rather than re-enumerating every page.
page_ids = list(resume.remaining_page_ids)
- logger.debug(f"Notion: resuming blocks fan-out with {len(page_ids)} page(s) remaining")
+ logger.debug(f"Notion: resuming page fan-out with {len(page_ids)} page(s) remaining")
else:
# Materialize the full set of page IDs up front so the fan-out position can be persisted as a
# shrinking queue (a crash during this initial enumeration restarts it, like other sources).
page_ids = list(_iter_page_ids(session, logger, throttle))
+ last_flush_at = time.monotonic()
+ last_empty_stage_at = last_flush_at
while page_ids:
page_id = page_ids[0]
remaining = page_ids[1:]
- for block in _iter_block_children(session, page_id, page_id, logger, 0, throttle):
- batcher.batch(block)
+ for row in rows_for_page(page_id):
+ batcher.batch(row)
if batcher.should_yield():
yield batcher.get_table()
- # Keep the in-progress page at the head: yielding flushes every buffered block from
+ last_flush_at = time.monotonic()
+ # Keep the in-progress page at the head: yielding flushes every buffered row from
# already-finished pages, so only this page and the untouched rest can still be lost
- # on a crash. A retry re-fetches this page's blocks (deduped on merge), losing nothing.
+ # on a crash. A retry re-fetches this page's rows (deduped on merge), losing nothing.
resumable_source_manager.save_state(NotionResumeConfig(remaining_page_ids=[page_id, *remaining]))
page_ids = remaining
+ # Most pages have few or no rows (comments especially), so a chunk can take many pages to
+ # fill. Without the two branches below, a long run of sparse pages records no progress and
+ # gives the pipeline no point at which to hand the run off during a worker shutdown.
+ now = time.monotonic()
+ if batcher.should_yield(include_incomplete_chunk=True):
+ if now - last_flush_at >= PARTIAL_FLUSH_INTERVAL_SECONDS:
+ # Staged before the yield, so the commit that follows this table's write covers it.
+ resumable_source_manager.save_state(NotionResumeConfig(remaining_page_ids=remaining))
+ yield batcher.get_table()
+ last_flush_at = time.monotonic()
+ else:
+ # Every row of the finished pages is yielded, so the queue can move past them. Staging
+ # dumps the whole queue, so it runs at most every EMPTY_PAGE_STAGE_INTERVAL_SECONDS.
+ if now - last_empty_stage_at >= EMPTY_PAGE_STAGE_INTERVAL_SECONDS:
+ resumable_source_manager.save_state(NotionResumeConfig(remaining_page_ids=remaining))
+ last_empty_stage_at = now
+ resumable_source_manager.safe_point()
+
if batcher.should_yield(include_incomplete_chunk=True):
yield batcher.get_table()
-def _comments_stream(
- session: requests.Session, logger: FilteringBoundLogger, throttle: Optional["_RateLimiter"] = None
+def _blocks_stream(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
+ throttle: Optional["_RateLimiter"] = None,
) -> Iterator[Any]:
- batcher = Batcher(logger=logger, chunk_size=CHUNK_SIZE, chunk_size_bytes=CHUNK_SIZE_BYTES)
+ def blocks_for_page(page_id: str) -> Iterator[dict[str, Any]]:
+ return _iter_block_children(session, page_id, page_id, logger, 0, throttle)
- for page_id in _iter_page_ids(session, logger, throttle):
- cursor: str | None = None
- pages_fetched = 0
- while True:
- params: dict[str, Any] = {"block_id": page_id, "page_size": NOTION_PAGE_SIZE}
- if cursor:
- params["start_cursor"] = cursor
-
- try:
- data = _request(session, "GET", "/v1/comments", logger, params=params, throttle=throttle)
- except NotionNotFoundError:
- logger.warning(
- "Notion: skipping comments for missing or unshared page",
- page_id=page_id,
- )
- break
- except NotionBadRequestError as e:
- logger.warning(
- "Notion: skipping comments Notion rejected for page",
- page_id=page_id,
- error=str(e),
- )
- break
- for comment in data.get("results", []):
- comment["_page_id"] = page_id
- batcher.batch(comment)
- if batcher.should_yield():
- yield batcher.get_table()
-
- pages_fetched += 1
- if not data.get("has_more") or not data.get("next_cursor"):
- break
- if pages_fetched >= MAX_CHILD_PAGES_PER_PARENT:
- logger.warning(
- "Notion: reached comments page cap for parent",
- page_id=page_id,
- cap=MAX_CHILD_PAGES_PER_PARENT,
- )
- break
- cursor = data["next_cursor"]
+ yield from _page_fan_out(session, logger, resumable_source_manager, blocks_for_page, throttle)
- if batcher.should_yield(include_incomplete_chunk=True):
- yield batcher.get_table()
+
+def _iter_page_comments(
+ session: requests.Session,
+ page_id: str,
+ logger: FilteringBoundLogger,
+ throttle: Optional["_RateLimiter"] = None,
+) -> Iterator[dict[str, Any]]:
+ cursor: str | None = None
+ pages_fetched = 0
+ while True:
+ params: dict[str, Any] = {"block_id": page_id, "page_size": NOTION_PAGE_SIZE}
+ if cursor:
+ params["start_cursor"] = cursor
+
+ try:
+ data = _request(session, "GET", "/v1/comments", logger, params=params, throttle=throttle)
+ except NotionNotFoundError:
+ logger.warning(
+ "Notion: skipping comments for missing or unshared page",
+ page_id=page_id,
+ )
+ return
+ except NotionBadRequestError as e:
+ logger.warning(
+ "Notion: skipping comments Notion rejected for page",
+ page_id=page_id,
+ error=str(e),
+ )
+ return
+ for comment in data.get("results", []):
+ comment["_page_id"] = page_id
+ yield comment
+
+ pages_fetched += 1
+ if not data.get("has_more") or not data.get("next_cursor"):
+ return
+ if pages_fetched >= MAX_CHILD_PAGES_PER_PARENT:
+ logger.warning(
+ "Notion: reached comments page cap for parent",
+ page_id=page_id,
+ cap=MAX_CHILD_PAGES_PER_PARENT,
+ )
+ return
+ cursor = data["next_cursor"]
+
+
+def _comments_stream(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
+ throttle: Optional["_RateLimiter"] = None,
+) -> Iterator[Any]:
+ def comments_for_page(page_id: str) -> Iterator[dict[str, Any]]:
+ return _iter_page_comments(session, page_id, logger, throttle)
+
+ yield from _page_fan_out(session, logger, resumable_source_manager, comments_for_page, throttle)
def get_rows(
@@ -551,7 +599,7 @@ def get_rows(
elif config.stream_type == "blocks":
yield from _blocks_stream(session, logger, resumable_source_manager, throttle)
elif config.stream_type == "comments":
- yield from _comments_stream(session, logger, throttle)
+ yield from _comments_stream(session, logger, resumable_source_manager, throttle)
else:
raise ValueError(f"Unknown Notion stream type: {config.stream_type}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py
index bcd395959564..f756170c4449 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py
@@ -36,6 +36,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.notion.set
MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.notion.notion"
+def _fresh_manager() -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ return manager
+
+
class FakeResponse:
def __init__(
self,
@@ -269,20 +275,62 @@ class TestNotion:
assert len(blocks) == MAX_BLOCK_DEPTH + 1
assert any("exceeds max depth" in str(call.args[0]) for call in logger.warning.call_args_list)
- def test_blocks_stream_resumes_from_saved_queue(self) -> None:
- # On retry the blocks stream must consume the persisted page queue instead of re-running the
+ @parameterized.expand(
+ [
+ ("blocks", _blocks_stream, "/v1/blocks/p2/children"),
+ ("comments", _comments_stream, "/v1/comments"),
+ ]
+ )
+ def test_page_fan_out_resumes_from_saved_queue(self, _name, stream, expected_path) -> None:
+ # On retry the fan-out must consume the persisted page queue instead of re-running the
# full page search from scratch — restarting from zero was what burned API quota on retries.
session = FakeSession([_list_response([{"id": "b1", "has_children": False}], has_more=False, next_cursor=None)])
manager = mock.MagicMock()
manager.can_resume.return_value = True
manager.load_state.return_value = NotionResumeConfig(remaining_page_ids=["p2"])
- tables = list(_blocks_stream(cast(requests.Session, session), mock.MagicMock(), manager))
+ tables = list(stream(cast(requests.Session, session), mock.MagicMock(), manager))
assert sum(t.num_rows for t in tables) == 1
- # Only the resumed page's block-children fetch runs; no /v1/search re-enumeration.
+ # Only the resumed page's fetch runs; no /v1/search re-enumeration.
assert len(session.calls) == 1
- assert session.calls[0]["url"].endswith("/v1/blocks/p2/children")
+ assert session.calls[0]["url"].endswith(expected_path)
+
+ @parameterized.expand([("blocks", _blocks_stream), ("comments", _comments_stream)])
+ def test_pages_without_rows_move_the_queue_and_reach_safe_points(self, _name, stream) -> None:
+ def responses(index: int) -> FakeResponse:
+ if index == 0:
+ return _list_response([{"id": "p1"}, {"id": "p2"}, {"id": "p3"}], has_more=False, next_cursor=None)
+ return _list_response([], has_more=False, next_cursor=None)
+
+ session = FakeSession(responses)
+ manager = _fresh_manager()
+
+ with mock.patch(f"{MODULE}.EMPTY_PAGE_STAGE_INTERVAL_SECONDS", 0):
+ tables = list(stream(cast(requests.Session, session), mock.MagicMock(), manager))
+
+ assert tables == []
+ saved = [call.args[0].remaining_page_ids for call in manager.save_state.call_args_list]
+ assert saved == [["p2", "p3"], ["p3"], []]
+ assert manager.safe_point.call_count == 3
+
+ def test_a_sparse_page_run_yields_a_partial_chunk_with_its_queue_staged_first(self) -> None:
+ def responses(index: int) -> FakeResponse:
+ if index == 0:
+ return _list_response([{"id": "p1"}, {"id": "p2"}], has_more=False, next_cursor=None)
+ return _list_response([{"id": f"cm{index}"}], has_more=False, next_cursor=None)
+
+ session = FakeSession(responses)
+ manager = _fresh_manager()
+ events: list[Any] = []
+ manager.save_state.side_effect = lambda state: events.append(state.remaining_page_ids)
+
+ with mock.patch(f"{MODULE}.PARTIAL_FLUSH_INTERVAL_SECONDS", 0):
+ for table in _comments_stream(cast(requests.Session, session), mock.MagicMock(), manager):
+ events.append(table.num_rows)
+
+ assert events == [["p2"], 1, [], 1]
+ manager.safe_point.assert_not_called()
def test_blocks_stream_saves_progress_after_each_yield(self) -> None:
# After a batch is flushed the in-progress page must be persisted at the head of the queue, so a
@@ -474,7 +522,7 @@ class TestNotion:
session = FakeSession(responses)
logger = mock.MagicMock()
- tables = list(_comments_stream(cast(requests.Session, session), logger))
+ tables = list(_comments_stream(cast(requests.Session, session), logger, _fresh_manager()))
total_rows = sum(t.num_rows for t in tables)
assert total_rows == 1
@@ -493,7 +541,7 @@ class TestNotion:
session = FakeSession(responses)
logger = mock.MagicMock()
- tables = list(_comments_stream(cast(requests.Session, session), logger))
+ tables = list(_comments_stream(cast(requests.Session, session), logger, _fresh_manager()))
total_rows = sum(t.num_rows for t in tables)
assert total_rows == 1
@@ -539,7 +587,7 @@ class TestNotion:
session = FakeSession(responses)
logger = mock.MagicMock()
- list(_comments_stream(cast(requests.Session, session), logger))
+ list(_comments_stream(cast(requests.Session, session), logger, _fresh_manager()))
# One search call plus the capped number of comment-page fetches.
assert len(session.calls) == 1 + MAX_CHILD_PAGES_PER_PARENT
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py
index 809851cb5338..acc96ee44a5c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py
@@ -132,6 +132,9 @@ STRIPE_CHUNK_SIZE = 1000
# nothing, so thousands of parents can pass between chunks — and every pod death throws that walk
# away. Counting parents bounds the work a restart repeats no matter how sparse the data is.
NESTED_SWEEP_CHECKPOINT_PARENTS = 5000
+# The same checkpoint also fires after this much time, because 5000 parents at one API call each can
+# take long enough that a worker shutdown waits on the sweep instead of handing it off.
+NESTED_SWEEP_CHECKPOINT_SECONDS = 60.0
_JSON_WHITESPACE = frozenset(b" \t\n\r\f\v")
_OPEN_BRACE = ord("{")
@@ -975,6 +978,7 @@ def get_rows(
skipped_parents = 0
parents_consumed = 0
parents_since_checkpoint = 0
+ last_checkpoint_at = time.monotonic()
# Seeded from where this run started, so an interruption before any parent finishes
# checkpoints there rather than back at the first parent.
last_finished_parent: Optional[str] = resume_config.starting_after if resume_config else None
@@ -1008,14 +1012,21 @@ def get_rows(
# position is staged right before the last table of the flush and the pipeline commits
# it once that table is written. With nothing buffered there is nothing to wait for,
# and a sparse sweep that never writes a row would otherwise never record progress.
- if parents_since_checkpoint >= NESTED_SWEEP_CHECKPOINT_PARENTS and last_finished_parent is not None:
+ checkpoint_due = (
+ parents_since_checkpoint >= NESTED_SWEEP_CHECKPOINT_PARENTS
+ or time.monotonic() - last_checkpoint_at >= NESTED_SWEEP_CHECKPOINT_SECONDS
+ )
+ if checkpoint_due and last_finished_parent is not None:
position = _resume_state(last_finished_position, last_finished_parent)
if batcher.should_yield(include_incomplete_chunk=True):
yield from _flush_staging_state(batcher, resumable_source_manager, _fixed_state(position))
else:
- with resumable_source_manager.committing():
- resumable_source_manager.save_state(position)
+ resumable_source_manager.save_state(position)
+ # Nothing is buffered in the source, so this is where a sparse sweep can hand
+ # off. The pipeline still guards the commit until no queue row is held.
+ resumable_source_manager.safe_point()
parents_since_checkpoint = 0
+ last_checkpoint_at = time.monotonic()
report_parent_rows_consumed()
parent_obj_id = obj[resource.parent_id]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
index 053ce65e14af..d0d099f3a1fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
@@ -670,17 +670,31 @@ class TestStripeNestedResourceGetRows:
assert called_for == ["cus_credit", "cus_owed"]
assert {row["customer"] for row in rows} == {"cus_credit", "cus_owed"}
- def test_sparse_sweep_checkpoints_by_parent_count(self):
+ @pytest.mark.parametrize(
+ "checkpoint_parents,checkpoint_seconds,expected_positions,expected_rows_totals",
+ [
+ (3, 3600.0, ["cus_2", "cus_5"], [3, 6, 8]),
+ (1000, 0.0, [f"cus_{i}" for i in range(7)], [1, 2, 3, 4, 5, 6, 7, 8]),
+ ],
+ ids=["by_parent_count", "by_elapsed_time"],
+ )
+ def test_sparse_sweep_checkpoints_and_reaches_a_safe_point(
+ self, checkpoint_parents, checkpoint_seconds, expected_positions, expected_rows_totals
+ ):
# A nested resource where no parent has data (CustomerPaymentMethod over customers with no
# stored payment method) never fills a chunk, so the row-driven checkpoint never fires and
# a killed run restarted the whole customer walk. Position must be recorded by parents
- # walked, regardless of how few rows come back.
+ # walked or time spent, regardless of how few rows come back, and each such checkpoint is
+ # where the sweep can hand off during a worker shutdown.
def nested_method(customer=None, params=None):
return _list_object([])
manager = MagicMock()
logger = MagicMock()
- with patch.object(stripe_module, "NESTED_SWEEP_CHECKPOINT_PARENTS", 3):
+ with (
+ patch.object(stripe_module, "NESTED_SWEEP_CHECKPOINT_PARENTS", checkpoint_parents),
+ patch.object(stripe_module, "NESTED_SWEEP_CHECKPOINT_SECONDS", checkpoint_seconds),
+ ):
rows = _run_nested_get_rows(
nested_method,
parent_objects=[{"id": f"cus_{i}"} for i in range(8)],
@@ -689,12 +703,12 @@ class TestStripeNestedResourceGetRows:
)
assert rows == []
- # Checkpointed after the 3rd and 6th parent; the 7th and 8th are still in flight.
- assert [call.args[0].starting_after for call in manager.save_state.call_args_list] == ["cus_2", "cus_5"]
- assert manager.committing.call_count == 2
+ assert [call.args[0].starting_after for call in manager.save_state.call_args_list] == expected_positions
+ manager.committing.assert_not_called()
+ assert manager.safe_point.call_count == len(expected_positions)
# The pipeline kills this loop mid-sweep on a worker shutdown, so every checkpoint carries
# the running fan-out size instead of leaving the attempt's only line until after the loop.
- assert [call.kwargs["rows_total"] for call in logger.info.call_args_list] == [3, 6, 8]
+ assert [call.kwargs["rows_total"] for call in logger.info.call_args_list] == expected_rows_totals
def test_query_param_service_receives_parent_in_params(self):
# Flat Stripe services with a required filter (e.g. entitlements.active_entitlements.list)