Skip to content

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

fix(data-warehouse): commit a resume cursor only after its rows reach the pipeline (#113488)

Tom Owers5bd434b11b35
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index 63395489a725..909e8b714266 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -428,6 +428,10 @@ 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. Do not save after the yield. On a worker shutdown the pipeline ends the attempt before control returns to the source, so state saved after the `yield` is lost for the last batch: the next attempt reads that batch again (merge dedupes on primary key, a resumed full refresh appends it twice), and an attempt that writes one batch or fewer keeps no progress. 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.
+A saved cursor can commit only after the pipeline confirms it. The pipeline confirms when the source hands it the next item, ends, or reaches a safe point.
+A cursor saved after the last `yield` therefore does not persist when the source raises, because the source can still hold rows that the cursor skips. The next attempt continues from the cursor of the last `yield`.
+A source that ends its own attempt on a page or time budget calls `manager.safe_point()` directly before the raise, with its local buffer empty, to keep its last cursor.
+
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.
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
index 8084c6023d04..bb80a140d73e 100644
--- 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
@@ -38,7 +38,9 @@ class PipelineSafePointHandler:
self._last_commit = clock()
def __call__(self) -> None:
- # The pipeline's `except` path writes the rows it holds and then commits the staged cursor,
+ # A safe point is the source's statement that it holds no row that its cursor skips.
+ self._resumable_source_manager.confirm()
+ # The pipeline's `except` path writes the rows it holds and then commits the confirmed cursor,
# so a raise here hands the run to another worker without losing progress.
self._shutdown_monitor.raise_if_is_worker_shutdown()
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
index fe6cc6c4af09..afd96a6e6c1a 100644
--- 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
@@ -53,7 +53,7 @@ def test_handler_commits_only_a_cursor_whose_rows_are_written(
assert manager.commit.called is expect_commit
-def test_handler_raises_the_shutdown_before_it_commits() -> None:
+def test_handler_confirms_the_cursor_and_raises_the_shutdown_before_it_commits() -> None:
monitor = MagicMock()
monitor.raise_if_is_worker_shutdown.side_effect = RuntimeError("worker shutting down")
manager = MagicMock()
@@ -67,6 +67,7 @@ def test_handler_raises_the_shutdown_before_it_commits() -> None:
with pytest.raises(RuntimeError, match="worker shutting down"):
handler()
+ manager.confirm.assert_called_once()
manager.commit.assert_not_called()
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 de2207f1a692..864ed3b4b095 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
@@ -448,6 +448,15 @@ class PipelineV3(Generic[ResumableData]):
self._release_held_batches()
await asyncio.to_thread(self._resumable_source_manager.commit)
+ def _confirm_resume_state(self) -> None:
+ """Make the cursors the source saved so far ready to commit.
+
+ Call it only while the source cannot hold a row that those cursors skip: it is suspended at
+ the `yield` of an item, or it has ended.
+ """
+ if self._resumable_source_manager is not None:
+ self._resumable_source_manager.confirm()
+
async def _stage_handoff_resume_value(self, *, force: bool = False) -> None:
"""Persist the checkpoint's value. Call it only when every observed batch has its queue row.
@@ -610,7 +619,7 @@ class PipelineV3(Generic[ResumableData]):
get_batches_produced_metric(team_id_str, schema_id_str).add(1)
chunk_index += 1
- # Every yielded row is staged now, so whatever the source staged last is safe.
+ # Every yielded row is staged now, so the cursor confirmed last is safe.
await self._commit_resume_state()
if self._attempt > 1:
@@ -634,6 +643,7 @@ class PipelineV3(Generic[ResumableData]):
schema_name=self._schema.name,
)
+ self._confirm_resume_state()
self._batcher.batch(item)
# A single batched table may be split into several when a string/binary/list
@@ -674,9 +684,12 @@ class PipelineV3(Generic[ResumableData]):
self._shutdown_monitor.raise_if_is_worker_shutdown()
awaiting_source = True
except Exception:
- # A resumable source that ends its own attempt (a page or time budget) has staged a
- # cursor for rows the batcher still holds. Staging them lets that cursor commit, so the
- # next attempt continues from it instead of restarting the sweep.
+ # 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
+ # yield covers rows the batcher still holds. Staging them lets that cursor commit, so
+ # the next attempt continues from it instead of restarting the sweep. A source that
+ # ends its own attempt (a page or time budget) reaches a safe point first to keep its
+ # last cursor.
if awaiting_source and source_is_resumable:
try:
await stage_remaining_rows()
@@ -686,6 +699,8 @@ class PipelineV3(Generic[ResumableData]):
finally:
safe_point_scope.close()
+ # The source ended, so it holds no rows and its last cursor is safe.
+ self._confirm_resume_state()
await stage_remaining_rows()
await self._finalize(row_count=row_count)
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 146ef2b2a106..ef81ee720bdd 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
@@ -949,6 +949,162 @@ async def _run_expecting(pipeline: PipelineV3, redis: MagicMock, exc: type[BaseE
await pipeline.run()
+class _MemoryRedis:
+ def __init__(self) -> None:
+ self.store: dict[str, str] = {}
+ self.on_set: Any = None
+
+ def set(self, key: str, value: str, ex: int | None = None) -> None:
+ self.store[key] = value
+ if self.on_set is not None:
+ self.on_set(value)
+
+ def get(self, key: str) -> str | None:
+ return self.store.get(key)
+
+ def exists(self, key: str) -> int:
+ return int(key in self.store)
+
+ def delete(self, key: str) -> None:
+ self.store.pop(key, None)
+
+
+async def _run_attempt(
+ redis: Any,
+ manager: ResumableSourceManager[Any],
+ items: Any,
+ *,
+ chunk_size: int | None = None,
+ shutdown_after_items: int | None = None,
+ on_write: Any = None,
+) -> tuple[list[Any], BaseException | None]:
+ pipeline = _runnable_pipeline(manager, items)
+ pipeline._batcher = Batcher(MagicMock(), chunk_size=chunk_size, primary_keys=["id"])
+ pipeline._finalize = AsyncMock() # type: ignore[method-assign]
+ written: list[Any] = []
+
+ async def record(pa_table: pa.Table, batch_index: int, row_count: int) -> None:
+ ids = pa_table["id"].to_pylist()
+ written.extend(ids)
+ if on_write is not None:
+ await on_write(ids)
+
+ pipeline._process_batch = AsyncMock(side_effect=record) # type: ignore[method-assign]
+ if shutdown_after_items is not None:
+ checks = iter(range(1, shutdown_after_items + 1))
+
+ def raise_at_the_last_check() -> None:
+ if next(checks) == shutdown_after_items:
+ raise WorkerShuttingDownError("id", "type", "queue", 1, "workflow", "workflow_type")
+
+ cast(MagicMock, pipeline._shutdown_monitor).raise_if_is_worker_shutdown.side_effect = raise_at_the_last_check
+
+ with ExitStack() as stack:
+ stack.enter_context(patch.object(ResumableSourceManager, "_get_redis", lambda self: nullcontext(redis)))
+ for name in (
+ "reset_rows_synced_if_needed",
+ "setup_row_tracking_with_billing_check",
+ "handle_reset_or_full_refresh",
+ "handle_corrupted_delta_log",
+ ):
+ stack.enter_context(patch(f"{_PIPELINE}.{name}", new_callable=AsyncMock))
+ for name in ("validate_incremental_sync", "record_source_item_stats"):
+ stack.enter_context(patch(f"{_PIPELINE}.{name}"))
+ stack.enter_context(patch(f"{_PIPELINE}.activity")).in_activity.return_value = False
+ try:
+ await pipeline.run()
+ except Exception as error:
+ return written, error
+ return written, None
+
+
+async def run_attempts_until_done(
+ redis: Any, build_items: Any, data_class: type, *, max_attempts: int = 4, on_write: Any = None, **first_attempt: Any
+) -> list[list[Any]]:
+ """Run import attempts of one job, each with a new manager, until one ends without an error."""
+ attempts: list[list[Any]] = []
+ for attempt in range(max_attempts):
+ inputs = cast(SourceInputs, SimpleNamespace(team_id=1, job_id="job-1", logger=MagicMock()))
+ manager: ResumableSourceManager[Any] = ResumableSourceManager(inputs, data_class)
+ written, error = await _run_attempt(
+ redis, manager, build_items(manager), on_write=on_write, **(first_attempt if attempt == 0 else {})
+ )
+ attempts.append(written)
+ if error is None:
+ return attempts
+ raise AssertionError(f"The import did not end in {max_attempts} attempts")
+
+
+_ROWS_PER_PAGE = 3
+_SOURCE_BUFFER_ROWS = 4
+
+
+class _PagedServer:
+ def __init__(self, pages: int, fail_on_request: int | None = None) -> None:
+ self.pages = pages
+ self.requests = 0
+ self._fail_on_request = fail_on_request
+
+ @property
+ def row_ids(self) -> list[int]:
+ return list(range(self.pages * _ROWS_PER_PAGE))
+
+ def fetch(self, page: int) -> list[dict[str, int]]:
+ self.requests += 1
+ if self.requests == self._fail_on_request:
+ raise RuntimeError("request failed after its retries")
+ return [{"id": page * _ROWS_PER_PAGE + offset} for offset in range(_ROWS_PER_PAGE)]
+
+
+def _paged_source(manager: ResumableSourceManager[_PageCursor], server: _PagedServer, shape: str):
+ """A source that saves "the next page to read", in the shapes that real sources use."""
+
+ def items():
+ state = manager.load_state()
+ page = state.page if state else 0
+ buffer: list[dict[str, int]] = []
+ while page < server.pages:
+ rows = server.fetch(page)
+ following = _PageCursor(page + 1)
+ if shape == "save_before_yield":
+ manager.save_state(following)
+ yield rows
+ elif shape == "save_after_yield":
+ yield rows
+ manager.save_state(following)
+ elif shape == "save_at_page_end_with_rows_in_buffer":
+ buffer.extend(rows)
+ if len(buffer) >= _SOURCE_BUFFER_ROWS:
+ yield buffer
+ buffer = []
+ manager.save_state(following)
+ elif shape == "yield_in_page_then_save_next_page":
+ for row in rows:
+ buffer.append(row)
+ if len(buffer) >= _SOURCE_BUFFER_ROWS:
+ yield buffer
+ buffer = []
+ manager.save_state(following)
+ elif shape == "safe_point_after_each_page":
+ yield rows
+ manager.save_state(following)
+ manager.safe_point()
+ page += 1
+ if buffer:
+ yield buffer
+
+ return items
+
+
+_SOURCE_SHAPES = [
+ "save_before_yield",
+ "save_after_yield",
+ "save_at_page_end_with_rows_in_buffer",
+ "yield_in_page_then_save_next_page",
+ "safe_point_after_each_page",
+]
+
+
class TestShouldCoalesceTables:
@pytest.mark.parametrize(
"resume_manager,is_webhook,expected",
@@ -1075,6 +1231,88 @@ 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.parametrize("chunk_size", [2, None], ids=["writes_during_the_read", "writes_at_the_error"])
+ @pytest.mark.parametrize(
+ "interruption",
+ [
+ *[{"fail_on_request": request} for request in range(1, 6)],
+ {"shutdown_after_items": 1},
+ {"shutdown_after_items": 2},
+ {},
+ ],
+ ids=lambda interruption: "_".join(f"{key}_{value}" for key, value in interruption.items()) or "none",
+ )
+ @pytest.mark.parametrize("shape", _SOURCE_SHAPES)
+ @pytest.mark.asyncio
+ async def test_an_interrupted_import_writes_every_row_and_never_commits_a_cursor_ahead_of_them(
+ self, shape: str, interruption: dict[str, int], chunk_size: int | None
+ ) -> None:
+ server = _PagedServer(pages=5, fail_on_request=interruption.get("fail_on_request"))
+ redis = _MemoryRedis()
+ written_at_commit: list[tuple[int, set[int]]] = []
+ written: list[int] = []
+
+ async def on_write(ids: list[int]) -> None:
+ written.extend(ids)
+
+ redis.on_set = lambda value: written_at_commit.append((json.loads(value)["page"], set(written)))
+
+ attempts = await run_attempts_until_done(
+ redis,
+ lambda manager: _paged_source(manager, server, shape),
+ _PageCursor,
+ chunk_size=chunk_size,
+ shutdown_after_items=interruption.get("shutdown_after_items"),
+ on_write=on_write,
+ )
+ all_written = [row_id for attempt in attempts for row_id in attempt]
+
+ assert sorted(set(all_written)) == server.row_ids
+ for page, rows_written in written_at_commit:
+ assert set(range(page * _ROWS_PER_PAGE)) <= rows_written
+ if not interruption:
+ assert all_written == server.row_ids
+
+ @pytest.mark.parametrize(
+ "reaches_safe_point,expected_cursor,expected_second_attempt",
+ [(True, 2, [6, 7, 8]), (False, 1, [3, 4, 5, 6, 7, 8])],
+ ids=["safe_point_before_the_raise", "no_safe_point"],
+ )
+ @pytest.mark.asyncio
+ async def test_a_source_that_ends_its_own_attempt_keeps_its_last_cursor_only_from_a_safe_point(
+ self, reaches_safe_point: bool, expected_cursor: int, expected_second_attempt: list[int]
+ ) -> None:
+ server = _PagedServer(pages=3)
+ redis = _MemoryRedis()
+ committed: list[int] = []
+ redis.on_set = lambda value: committed.append(json.loads(value)["page"])
+ budgets = iter([2, 5])
+
+ def build_items(manager: ResumableSourceManager[_PageCursor]):
+ page_budget = next(budgets)
+
+ def items():
+ state = manager.load_state()
+ page = state.page if state else 0
+ for pages_read in range(1, page_budget + 1):
+ if page >= server.pages:
+ return
+ yield server.fetch(page)
+ page += 1
+ manager.save_state(_PageCursor(page))
+ if pages_read == page_budget:
+ if reaches_safe_point:
+ manager.safe_point()
+ raise RuntimeError("page budget")
+
+ return items
+
+ first, second = await run_attempts_until_done(redis, build_items, _PageCursor)
+
+ assert first == [0, 1, 2, 3, 4, 5]
+ assert committed[0] == expected_cursor
+ assert second == expected_second_attempt
+
@pytest.mark.asyncio
async def test_an_empty_page_safe_point_hands_off_at_shutdown_with_its_cursor(self) -> None:
redis = MagicMock()
@@ -1276,6 +1514,7 @@ class TestFinalMarkerIsTheLastDataRow:
manager = _manager()
if staged:
manager.save_state(_Cursor("a"))
+ manager.confirm()
redis = MagicMock()
redis.set.side_effect = lambda *_a, **_k: events.append("commit")
pipeline = _make_pipeline()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/tests/test_acculynx.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/tests/test_acculynx.py
index ef9fc1262848..0e334a49e72c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/tests/test_acculynx.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/tests/test_acculynx.py
@@ -91,13 +91,16 @@ def test_resume_stages_after_yield_and_replays_only_uncommitted_pages(
http_send.side_effect = send
pages = iter(pipeline("contacts").items())
assert next(pages) == [{"id": "0"}]
+ manager.confirm()
assert not manager.has_staged_state()
assert next(pages) == [{"id": "1"}]
+ manager.confirm()
manager.commit()
saved = manager.load_state()
assert saved is not None and saved.paginator_state == {"offset": 1}
pages.close()
assert list(pipeline("contacts").items()) == [[{"id": "1"}], [{"id": "2"}]]
+ manager.confirm()
manager.commit()
assert list(pipeline("contacts").items()) == []
@@ -109,6 +112,7 @@ def test_jobs_split_before_offset_cap_without_duplicate_boundary_rows(
response: Callable[..., Response],
) -> None:
manager.save_state(AcculynxResumeConfig(windows=[["2025-01-01", "2025-01-02"]]))
+ manager.confirm()
manager.commit()
attempts = 0
@@ -141,6 +145,7 @@ def test_unsplittable_job_day_fails_instead_of_truncating(
response: Callable[..., Response],
) -> None:
manager.save_state(AcculynxResumeConfig(windows=[["2025-01-01", "2025-01-01"]]))
+ manager.confirm()
manager.commit()
http_send.side_effect = lambda request, **_: response(
request,
@@ -267,6 +272,7 @@ def test_fanout_resume_skips_completed_parents_and_keeps_the_current_parent(
pages = iter(pipeline("estimates").items())
assert next(pages)[0]["id"] == "estimate-0"
assert next(pages)[0]["id"] == "estimate-1"
+ manager.confirm()
manager.commit()
pages.close()
child_paths.clear()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alegra/tests/test_alegra.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alegra/tests/test_alegra.py
index 218cd7694c04..6d7440a81115 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alegra/tests/test_alegra.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alegra/tests/test_alegra.py
@@ -80,9 +80,11 @@ def test_offset_pagination_and_checkpoint_resume(
response = source.source_for_pipeline(config, manager, inputs)
pages = iter(cast(Iterable[list[dict[str, Any]]], response.items()))
assert next(pages) == first_page
+ manager.confirm()
assert not manager.has_staged_state()
assert list(pages) == ([terminal_rows] if terminal_rows else [])
assert [parse_qs(urlsplit(request.url or "").query)["start"] for request in sent] == [["0"], ["30"]]
+ manager.confirm()
manager.commit()
assert [json.loads(value) for value in redis_boundary.values()] == [{"offset": 30}]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py
index 10a61f629903..5644a28809a5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py
@@ -412,6 +412,7 @@ class TestBingAdsSource:
):
original = BingAdsResumeConfig(next_start_date="2025-02-01", end_date="2025-06-30")
manager.save_state(original)
+ manager.confirm()
manager.commit()
loaded = manager.load_state()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buy_me_a_coffee/tests/test_buy_me_a_coffee.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buy_me_a_coffee/tests/test_buy_me_a_coffee.py
index 713785901ae0..fae033e3a5c9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buy_me_a_coffee/tests/test_buy_me_a_coffee.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buy_me_a_coffee/tests/test_buy_me_a_coffee.py
@@ -209,6 +209,7 @@ class TestBuyMeACoffee(SimpleTestCase):
self.inputs.schema_name = "subscriptions"
manager = self.source.get_resumable_source_manager(self.inputs)
manager.save_state(BuyMeACoffeeResumeConfig(page=3))
+ manager.confirm()
manager.commit()
self.respond([{"data": [{"subscription_id": 100}], "current_page": 3, "last_page": 3}])
response = self.source.source_for_pipeline(self.config, manager, self.inputs)
@@ -226,10 +227,13 @@ class TestBuyMeACoffee(SimpleTestCase):
response = self.source.source_for_pipeline(self.config, manager, self.inputs)
pages = iter(cast(Iterable[Any], response.items()))
assert next(pages) == [{"support_id": 2}]
+ manager.confirm()
assert not manager.has_staged_state()
assert next(pages) == [{"support_id": 1}]
+ manager.confirm()
assert manager.has_staged_state()
assert not manager.can_resume()
+ manager.confirm()
manager.commit()
assert manager.load_state() == BuyMeACoffeeResumeConfig(page=2)
assert list(pages) == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
index 0614ea232e1e..ec26f58c949d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
@@ -858,6 +858,8 @@ def _get_rows(
"commits what it covered and the next scheduled sync continues from there"
)
return
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
raise CheckoutComSyncBudgetExceeded(
f"{SYNC_BUDGET_EXCEEDED_MARKER}: {schema_name} is {_describe_lag(now - covered_to)} behind and "
"this run stopped before closing the gap. The sync retries and continues automatically. If the "
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 f06f55eb9aa7..dbea2ebc34cb 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
@@ -27,6 +27,7 @@ class ResumableSourceManager(Generic[ResumableData]):
_data_class: type[ResumableData]
_logger: FilteringBoundLogger
_namespace: str | None
+ _pending: dict[str, str]
_staged: dict[str, str]
def __init__(
@@ -34,12 +35,16 @@ class ResumableSourceManager(Generic[ResumableData]):
inputs: SourceInputs,
data_class: type[ResumableData],
namespace: str | None = None,
+ pending: dict[str, str] | None = None,
staged: dict[str, str] | None = None,
):
self._inputs = inputs
self._data_class = data_class
self._logger = inputs.logger
self._namespace = namespace
+ # A cursor from save_state() waits here until confirm(). A source can save a cursor and still
+ # hold rows that the cursor covers, so the source alone cannot make a cursor ready to commit.
+ self._pending = pending if pending is not None else {}
# 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 {}
@@ -52,7 +57,9 @@ class ResumableSourceManager(Generic[ResumableData]):
state in separate slots. Without it a retry that switches endpoints could load a
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, staged=self._staged)
+ return ResumableSourceManager(
+ self._inputs, self._data_class, namespace=namespace, pending=self._pending, staged=self._staged
+ )
@contextmanager
def _get_redis(self):
@@ -116,20 +123,37 @@ class ResumableSourceManager(Generic[ResumableData]):
write()
def save_state(self, data: ResumableData) -> None:
- """Stage `data` as the cursor to resume from once every row yielded so far is written.
+ """Save `data` as the cursor to resume from once every row it covers is written.
- Nothing reaches Redis until commit(), which the pipeline calls right after a write lands.
- A source with nothing outstanding stages inside committing(), which commits at block end.
+ The cursor is only pending here. It becomes ready to commit at confirm(), which the pipeline
+ calls when the source hands it an item or reaches a safe point. A cursor saved after the last
+ yield therefore does not persist when the source raises. Nothing reaches Redis until commit(),
+ which the pipeline calls right after a write lands. A source with nothing outstanding saves
+ inside committing(), which commits at block end.
"""
- # No log here: a source can stage on every row, and commit() logs each cursor that persists.
- self._staged[self._key] = self._dump_json(data)
+ # No log here: a source can save on every row, and commit() logs each cursor that persists.
+ self._pending[self._key] = self._dump_json(data)
def has_staged_state(self) -> bool:
"""Whether the next `commit` will write anything."""
return bool(self._staged)
+ def confirm(self) -> None:
+ """Make every pending cursor ready for the next commit(), across namespaces.
+
+ Call it only when the source holds no fetched row that a pending cursor skips: the source is
+ suspended at a `yield`, has ended, or has reached a safe point.
+ """
+ # One item at a time, so a cursor that another thread saves during the loop is not dropped.
+ while self._pending:
+ try:
+ key, json_data = self._pending.popitem()
+ except KeyError:
+ break
+ self._staged[key] = json_data
+
def commit(self) -> None:
- """Persist every staged cursor, across namespaces."""
+ """Persist every confirmed cursor, across namespaces."""
if not self._staged:
return
with self._get_redis() as redis_client:
@@ -151,6 +175,7 @@ class ResumableSourceManager(Generic[ResumableData]):
try:
yield
finally:
+ self.confirm()
self.commit()
def safe_point(self) -> None:
@@ -170,6 +195,7 @@ class ResumableSourceManager(Generic[ResumableData]):
Called once a source has walked its data to completion: leaving the final checkpoint in
place would let a later attempt resume mid-stream instead of restarting cleanly.
"""
+ self._pending.pop(self._key, None)
self._staged.pop(self._key, None)
with self._get_redis() as redis_client:
self._logger.debug(f"Clearing resumable source state. key={self._key}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_keyset.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_keyset.py
index eb47d32bf012..e778326c7ab9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_keyset.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_keyset.py
@@ -83,6 +83,7 @@ def test_an_eligible_key_type_can_always_be_checkpointed(arrow_type, last_key):
with patch.object(ResumableSourceManager, "_get_redis") as get_redis:
get_redis.return_value.__enter__.return_value = redis
manager.save_state(KeysetResumeState(last_key=last_key))
+ manager.confirm()
manager.commit()
redis.get.return_value = redis.set.call_args.args[1]
restored = manager.load_state()
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 63e4a2dc9044..59812f392f29 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
@@ -61,7 +61,7 @@ class TestResumableSourceManager:
assert state == _SweepPosition(cursor="cus_1")
- def test_state_reaches_redis_only_on_commit(self):
+ def test_only_a_confirmed_cursor_reaches_redis_and_only_on_commit(self):
manager = _manager()
redis = MagicMock()
@@ -69,6 +69,11 @@ class TestResumableSourceManager:
get_redis.return_value.__enter__.return_value = redis
manager.save_state(_SweepPosition(cursor="cus_1"))
manager.save_state(_SweepPosition(cursor="cus_2"))
+ manager.commit()
+ redis.set.assert_not_called()
+
+ manager.confirm()
+ manager.save_state(_SweepPosition(cursor="cus_3"))
redis.set.assert_not_called()
manager.commit()
@@ -86,6 +91,7 @@ class TestResumableSourceManager:
with patch.object(ResumableSourceManager, "_get_redis") as get_redis:
get_redis.return_value.__enter__.return_value = redis
manager.save_state(_SweepPosition(cursor="sensitive-customer-id"))
+ manager.confirm()
manager.commit()
manager.load_state()
@@ -115,20 +121,25 @@ class TestResumableSourceManager:
with patch.object(ResumableSourceManager, "_get_redis") as get_redis:
get_redis.return_value.__enter__.return_value = redis
manager.with_namespace("deltas").save_state(_SweepPosition(cursor="cus_3"))
+ manager.confirm()
manager.commit()
redis.set.assert_called_once_with(
"posthog:data_warehouse:resumable_source:1:job-1:deltas", '{"cursor":"cus_3"}', ex=60 * 60 * 24
)
- def test_clear_state_drops_the_staged_cursor(self):
+ @pytest.mark.parametrize("confirmed", [True, False], ids=["confirmed", "pending"])
+ def test_clear_state_drops_the_staged_cursor(self, confirmed: bool):
manager = _manager()
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"))
+ if confirmed:
+ manager.confirm()
manager.clear_state()
+ manager.confirm()
manager.commit()
redis.delete.assert_called_once_with("posthog:data_warehouse:resumable_source:1:job-1")
@@ -145,6 +156,7 @@ class TestResumableSourceManager:
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()
manager.commit()
redis.connection_pool.disconnect.assert_called_once()
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 db17e61a2d50..e8bb469fc905 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
@@ -552,6 +552,7 @@ def test_catches_up_and_stages_the_cursor(
assert [body["cursor"] for body in requests[1:]] == ["snapshot", "stale"]
assert inputs.source_cursor is not None
assert inputs.source_cursor.staged == ConvexDataSyncCursor(cursor="end")
+ manager.confirm()
manager.commit()
assert manager.with_namespace("data_sync").load_state() == ConvexResumeConfig(
cursor="end", started_from_cursor=stored is not None
@@ -720,6 +721,14 @@ def test_truncates_and_expiry_reset_only_when_required(
reset.assert_not_called()
+def _pipeline_safe_point(manager: Any) -> Any:
+ def hook() -> None:
+ manager.confirm()
+ manager.commit()
+
+ return hook
+
+
@pytest.mark.parametrize("rows", [[], [{"value": {"_id": "a"}, "ts": 100, "deleted": False}]])
def test_each_page_saves_resume_state_after_rows_and_continues_on_retry(
rows: list[dict[str, Any]], redis_boundary: Mock, http_boundary: Mock
@@ -728,7 +737,7 @@ def test_each_page_saves_resume_state_after_rows_and_continues_on_retry(
manager = ConvexSource().get_resumable_source_manager(inputs)
scoped = manager.with_namespace("data_sync")
http_boundary.post.side_effect = [_page("checkpoint", status="stale", values=rows), RuntimeError("interrupted")]
- with activate_safe_point(manager.commit, covers_framework_checkpoints=False):
+ with activate_safe_point(_pipeline_safe_point(manager), covers_framework_checkpoints=False):
iterator = iter(_items(_resource(inputs, manager)))
if rows:
assert next(iterator) == [{"_id": "a", "_ts": 100, "_deleted": False}]
@@ -739,7 +748,7 @@ def test_each_page_saves_resume_state_after_rows_and_continues_on_retry(
http_boundary.post.side_effect = None
http_boundary.post.return_value = _page("end")
retry_manager = ConvexSource().get_resumable_source_manager(inputs)
- with activate_safe_point(retry_manager.commit, covers_framework_checkpoints=False):
+ with activate_safe_point(_pipeline_safe_point(retry_manager), covers_framework_checkpoints=False):
list(_items(_resource(inputs, retry_manager)))
assert http_boundary.post.call_args.kwargs["json"]["cursor"] == "checkpoint"
assert scoped.load_state() == ConvexResumeConfig(cursor="end", started_from_cursor=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/fullstory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/fullstory.py
index 3264755385a5..9cbdfc635dc9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/fullstory.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/fullstory.py
@@ -328,6 +328,9 @@ def _start_event_export(
else:
# Staged only: committing now would move the cursor past rows not yet written.
resumable_source_manager.save_state(checkpoint)
+ # The source holds no rows here. Without the safe point, an export that fails after this
+ # loses the operation id, and each retry starts a new export.
+ resumable_source_manager.safe_point()
return operation_id
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_cs/gainsight_cs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_cs/gainsight_cs.py
index 4ab3218e290e..648b92b6cc7f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_cs/gainsight_cs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_cs/gainsight_cs.py
@@ -343,6 +343,8 @@ def gainsight_cs_source(
# dedupes on the primary key — instead of stepping over it.
resumable_source_manager.save_state(GainsightCsResumeConfig(offset=offset))
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
raise GainsightCsPageBudgetExhaustedError(
f"Stopped after {MAX_PAGES_PER_ATTEMPT} pages of '{object_name}'; the next attempt resumes at offset {offset}."
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/givebutter/tests/test_givebutter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/givebutter/tests/test_givebutter.py
index ada8bedde230..860f704cfd7e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/givebutter/tests/test_givebutter.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/givebutter/tests/test_givebutter.py
@@ -71,8 +71,10 @@ def test_pagination_and_resume_after_yield(
iterator = pages(givebutter_source("test-api-key", inputs, manager))
assert next(iterator) == [first]
+ manager.confirm()
assert not manager.has_staged_state()
assert next(iterator) == last
+ manager.confirm()
manager.commit()
saved = manager.load_state()
assert saved is not None
@@ -80,6 +82,7 @@ def test_pagination_and_resume_after_yield(
iterator.close()
assert list(pages(givebutter_source("test-api-key", inputs, manager))) == [last]
+ manager.confirm()
manager.commit()
assert list(pages(givebutter_source("test-api-key", inputs, manager))) == []
assert len(requests_mock.request_history) == 3
@@ -119,6 +122,7 @@ def test_household_array_pagination_resumes_by_page_number(
iterator = pages(givebutter_source("test-api-key", inputs, manager))
assert next(iterator) == [{"id": 101}]
assert next(iterator) == [{"id": 102}]
+ manager.confirm()
manager.commit()
iterator.close()
requests_mock.reset_mock()
@@ -169,6 +173,7 @@ def test_child_rows_have_unique_parent_keys_and_resume_within_parent(
assert response.primary_keys is not None
assert len({tuple(row[key] for key in response.primary_keys) for row in rows}) == 2
assert next(iterator) == [{"id": "last-id", parent_column: "parent-two"}]
+ manager.confirm()
manager.commit()
iterator.close()
requests_mock.reset_mock()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py
index 7ab9104179b4..6e858982413b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py
@@ -398,6 +398,8 @@ def google_analytics_source(
offset = resume_offset if chunk_start_iso == resume_chunk_start else 0
while True:
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
payload = _run_report(
session=session,
property_id=config.property_id,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py
index 278a0c2fa1a7..0e360e05133f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py
@@ -730,6 +730,8 @@ def google_search_console_source(
start_row = resume_start_row if (resume_date is not None and iso == resume_date) else 0
while True:
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
rows = _query_search_analytics(
session=session,
site_url=site_url,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heygen/tests/test_heygen.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heygen/tests/test_heygen.py
index 660568f3a6d1..a6808d404792 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/heygen/tests/test_heygen.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heygen/tests/test_heygen.py
@@ -70,8 +70,10 @@ def test_cursor_pages_checkpoint_after_yield(
]
pages = iter(sync_items(heygen_source("fake-key", "videos", "v3", 1, "job-test", manager)))
assert next(pages) == [{"id": "video-first"}]
+ manager.confirm()
assert not manager.has_staged_state()
assert next(pages) == [{"id": "video-last"}]
+ manager.confirm()
manager.commit()
saved = redis.set.call_args.args[1]
assert saved == '{"cursor":"opaque+/=token"}'
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/infisical.py b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/infisical.py
index 3d6cb81e5e2b..21da5015d66c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/infisical.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/infisical/infisical.py
@@ -532,6 +532,8 @@ def _get_audit_log_rows(
pagination_deadline = time.monotonic() + MAX_PAGINATION_SECONDS
for page in range(MAX_PAGES):
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
_check_pagination_budget(pagination_deadline, config.name)
params: dict[str, Any] = {"limit": config.page_limit, "offset": offset, "endDate": window_end}
@@ -581,6 +583,8 @@ def _get_offset_paginated_rows(
pagination_deadline = time.monotonic() + MAX_PAGINATION_SECONDS
for page in range(MAX_PAGES):
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
_check_pagination_budget(pagination_deadline, config.name)
params: dict[str, Any] = {"limit": config.page_limit, "offset": offset, **config.extra_params}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py
index 78a031f81763..7d45c34f2097 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py
@@ -444,6 +444,8 @@ def get_rows(
# host's pagination metadata can extract from a single run.
if pages_fetched >= MAX_PAGES_PER_RUN:
logger.warning(f"Langfuse: page limit reached for {endpoint} after {pages_fetched} pages")
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
raise LangfusePaginationError(f"{PAGE_LIMIT_ERROR}: {pages_fetched} pages fetched from {endpoint}")
if config.pagination == "page":
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/langsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/langsmith.py
index 1776b8ea605c..f16bac968a38 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/langsmith.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/langsmith.py
@@ -616,6 +616,8 @@ def _stop_at_page_limit(
if batcher.should_yield(include_incomplete_chunk=True):
yield batcher.get_table()
resumable_source_manager.save_state(resume_state)
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
raise LangSmithPageLimitError(message)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/tests/test_langsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/tests/test_langsmith.py
index 6dafc7a4c0b7..e31268012772 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/tests/test_langsmith.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/tests/test_langsmith.py
@@ -52,6 +52,7 @@ class FakeManager:
def __init__(self, resume: LangSmithResumeConfig | None = None):
self._resume = resume
self.saved: list[LangSmithResumeConfig] = []
+ self.safe_points_after_save: list[int] = []
def can_resume(self) -> bool:
return self._resume is not None
@@ -62,6 +63,9 @@ class FakeManager:
def save_state(self, data: LangSmithResumeConfig) -> None:
self.saved.append(data)
+ def safe_point(self) -> None:
+ self.safe_points_after_save.append(len(self.saved))
+
def _collect(tables) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
@@ -537,6 +541,7 @@ class TestPaginationAbuseGuards:
rows.extend(table.to_pylist())
assert manager.saved[-1].cursor is not None
+ assert manager.safe_points_after_save == [len(manager.saved)]
assert [r["id"] for r in rows] == ["r1", "r2", "r3"]
def test_offset_page_limit_checkpoints_and_raises(self):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py
index ec572b193874..901cc86efebd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py
@@ -416,6 +416,8 @@ def _bulk_rows(
# Checkpoint on the window boundary only once the whole window has been yielded, so a
# resumed attempt re-exports the window it died in rather than skipping its tail.
resumable_source_manager.save_state(MarketoResumeConfig(window_start=format_datetime(window_end)))
+ # The window is yielded in full. The safe point keeps this cursor if the next export fails.
+ resumable_source_manager.safe_point()
def _rest_token_rows(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql_resume.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql_resume.py
index fb694e09609b..1bc973c8f93b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql_resume.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql_resume.py
@@ -281,6 +281,7 @@ def _read(
if index == stop_after and not write_last:
break
written.extend(table.to_pylist())
+ manager.confirm()
manager.commit()
if index == stop_after:
break
@@ -337,6 +338,7 @@ class TestKeysetFullRefresh:
store: dict[str, str] = {}
manager = _MemoryResumeManager(store)
manager.save_state(MSSQLResumeState(key_columns=["legacy_id"], last_key=[10**12]))
+ manager.confirm()
manager.commit()
source, manager = _build(store)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/octopus_deploy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/octopus_deploy.py
index c24a10272192..de0753759da1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/octopus_deploy.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octopus_deploy/octopus_deploy.py
@@ -311,6 +311,8 @@ def _paginate(
# dedupes on the primary key.
resumable_source_manager.save_state(OctopusDeployResumeConfig(skip=skip, space_id=space_id))
else:
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
raise OctopusDeployPaginationLimitError(
f"{PAGINATION_LIMIT_ERROR}: {url} exceeded {MAX_PAGES_PER_LISTING} pages"
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinecone/tests/test_pinecone.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinecone/tests/test_pinecone.py
index 2b21ff68759b..2f47b3749c0d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinecone/tests/test_pinecone.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinecone/tests/test_pinecone.py
@@ -160,14 +160,18 @@ class TestPineconeTransport(SimpleTestCase):
response = source.source_for_pipeline(PineconeSourceConfig(api_key="fake-pinecone-key"), manager, inputs)
pages = iter(sync_items(response))
assert next(pages) == [{key: "first"}]
+ manager.confirm()
assert not manager.has_staged_state()
assert next(pages) == [{key: "second"}]
+ manager.confirm()
manager.commit()
assert json.loads(redis.set.call_args.args[1]) == {"cursor": "next+/="}
assert next(pages) == [{key: "third"}]
+ manager.confirm()
manager.commit()
assert json.loads(redis.set.call_args.args[1]) == {"cursor": "last-token"}
assert list(pages) == []
+ manager.confirm()
assert not manager.has_staged_state()
assert redis.set.call_count == 2
assert [parse_qs(urlsplit(call.request.url or "").query).get("paginationToken") for call in http.calls] == [
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_keyset_key_types.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_keyset_key_types.py
index af9b5e1abeea..a4c085bddd72 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_keyset_key_types.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_keyset_key_types.py
@@ -69,6 +69,7 @@ def test_uuid_key_returns_from_the_checkpoint_as_text():
key = (7, uuid.UUID(int=0xABCDEF << 64))
manager.save_state(keyset_state(key))
+ manager.confirm()
manager.commit()
assert keyset_last_key(manager.load_state(), key_length=2) == (7, str(key[1]))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/qualtrics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/qualtrics.py
index 32f35a241b0f..e51ffcd9d06c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/qualtrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/qualtrics.py
@@ -418,6 +418,9 @@ def _iter_collection(
while True:
if pages >= MAX_PAGES:
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ if resumable_source_manager is not None:
+ resumable_source_manager.safe_point()
raise QualtricsPaginationLimitError(
f"Qualtrics pagination exceeded {MAX_PAGES} pages without terminating: {first_url}"
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/retell_ai/tests/test_retell_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/retell_ai/tests/test_retell_ai.py
index 7a89da5ee1e1..6b3bfa3b44dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/retell_ai/tests/test_retell_ai.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/retell_ai/tests/test_retell_ai.py
@@ -48,13 +48,17 @@ def test_cursor_pages_and_terminal_page(
result = source.source_for_pipeline(RetellAISourceConfig(api_key="fake-key"), manager, inputs)
iterator = iter(cast(Iterable[Any], result.items()))
assert next(iterator) == [{key: "record-one"}]
+ manager.confirm()
assert not manager.has_staged_state()
assert next(iterator) == [{key: "record-two"}]
+ manager.confirm()
assert manager.has_staged_state()
+ manager.confirm()
manager.commit()
assert manager.load_state() == RetellAIResumeConfig(cursor="next-page")
with pytest.raises(StopIteration):
next(iterator)
+ manager.confirm()
manager.commit()
assert manager.load_state() == RetellAIResumeConfig(completed=True)
assert result.primary_keys == [key]
@@ -131,6 +135,7 @@ def test_resume_skips_written_pages(
inputs = replace(inputs, schema_name=name)
manager = source.get_resumable_source_manager(inputs)
manager.save_state(RetellAIResumeConfig(cursor="saved-cursor", completed=completed))
+ manager.confirm()
manager.commit()
http.return_value = response({"items": [{"record": "remaining"}], "has_more": False})
result = source.source_for_pipeline(RetellAISourceConfig(api_key="fake-key"), manager, inputs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sevdesk/tests/test_sevdesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sevdesk/tests/test_sevdesk.py
index b0ef6c536873..c0b712a13b72 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sevdesk/tests/test_sevdesk.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sevdesk/tests/test_sevdesk.py
@@ -79,9 +79,11 @@ def test_pagination_checkpoints_after_yield_and_resumes_at_next_page(
http.side_effect = [response({"objects": rows}), RuntimeError("interrupted")]
iterator = iter(sync_items(source.source_for_pipeline(source_config, manager, inputs)))
assert next(iterator) == rows
+ manager.confirm()
assert not manager.has_staged_state()
with pytest.raises(RuntimeError, match="interrupted"):
next(iterator)
+ manager.confirm()
manager.commit()
assert manager.load_state() == SevdeskResumeConfig(offset=PAGE_SIZE)
@@ -94,6 +96,7 @@ def test_pagination_checkpoints_after_yield_and_resumes_at_next_page(
request = http.call_args.args[0]
assert parse_qs(urlsplit(request.url).query)["offset"] == [str(PAGE_SIZE)]
http.assert_called_once()
+ resumed_manager.confirm()
resumed_manager.commit()
assert resumed_manager.load_state() == SevdeskResumeConfig(completed=True)
http.reset_mock()
@@ -118,6 +121,7 @@ def test_malformed_success_does_not_replace_table_with_empty_data(
manager = source.get_resumable_source_manager(inputs)
with patch("time.sleep"), pytest.raises(RESTClientRetryableError):
list(sync_items(source.source_for_pipeline(source_config, manager, inputs)))
+ manager.confirm()
assert not manager.has_staged_state()
@@ -136,6 +140,7 @@ def test_sync_auth_errors_are_terminal(
with pytest.raises(HTTPError) as error:
list(sync_items(source.source_for_pipeline(source_config, manager, inputs)))
assert any(pattern in str(error.value) for pattern in source.get_non_retryable_errors())
+ manager.confirm()
assert not manager.has_staged_state()
http.assert_called_once()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim.py
index 76a48f12b7ab..09b115fa9eaa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sim/tests/test_sim.py
@@ -52,9 +52,12 @@ def test_paginated_full_refresh(
response = sim_source(config, inputs, manager, "v2")
pages = iter(cast(Iterable[Any], response.items()))
assert next(pages) == [first]
+ manager.confirm()
assert not manager.has_staged_state()
assert next(pages) == [last]
+ manager.confirm()
assert manager.has_staged_state()
+ manager.confirm()
manager.commit()
assert json.loads(redis_client.set.call_args.args[1]) == {"cursor": "next-page"}
assert list(pages) == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/sonatype_nexus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/sonatype_nexus.py
index 5d994c9edbd5..7a4c62f91c4c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/sonatype_nexus.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonatype_nexus/sonatype_nexus.py
@@ -270,6 +270,8 @@ def _get_repository_fanout_rows(
# slow-drips each one's single terminal page to just under the per-response budget
# would bypass the check and hold the worker for repositories × MAX_RESPONSE_SECONDS.
if time.monotonic() > pagination_deadline:
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
raise SonatypeNexusPaginationError(
f"Nexus pagination exceeded the {MAX_PAGINATION_SECONDS:g}s time budget for repository={repository}"
)
@@ -294,6 +296,8 @@ def _get_repository_fanout_rows(
f"Nexus returned a non-advancing continuation token for repository={repository}"
)
if page_count >= MAX_PAGES_PER_ENDPOINT:
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
raise SonatypeNexusPaginationError(
f"Nexus pagination exceeded {MAX_PAGES_PER_ENDPOINT} pages for repository={repository}"
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/sourcegraph.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/sourcegraph.py
index cca819d770c0..9fb389a10b47 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/sourcegraph.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/sourcegraph.py
@@ -400,6 +400,8 @@ def get_rows(
# fail the run once it crosses either per-run bound so it can't occupy a worker until the
# activity's week-long timeout. The cursor is already checkpointed, so an activity retry
# within this job resumes from here rather than re-walking from the start.
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
if pages_fetched >= MAX_PAGES_PER_RUN:
raise SourcegraphPaginationLimitError(
f"Sourcegraph {endpoint} exceeded the per-run page limit ({MAX_PAGES_PER_RUN})"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/sumo_logic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/sumo_logic.py
index 463b70cf44f6..2f60f9a885fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/sumo_logic.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/sumo_logic.py
@@ -413,6 +413,8 @@ def _get_log_rows(
# Save AFTER the window's rows are yielded so a crash re-runs this window instead of
# skipping it; merge dedupes the re-yielded rows on the primary key.
resumable_source_manager.save_state(SumoLogicResumeConfig(log_window_start_ms=window_end))
+ # The window is yielded in full. The safe point keeps this cursor if the next job fails.
+ resumable_source_manager.safe_point()
def get_rows(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tenable_vulnerability_management/tenable_vulnerability_management.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tenable_vulnerability_management/tenable_vulnerability_management.py
index aaed186be95e..d74048e83dba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tenable_vulnerability_management/tenable_vulnerability_management.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tenable_vulnerability_management/tenable_vulnerability_management.py
@@ -297,6 +297,8 @@ def _get_export_rows(
break
if time.monotonic() > deadline:
+ # A safe point keeps the cursor saved after the last yield. The source holds no rows here.
+ resumable_source_manager.safe_point()
raise Exception(f"Tenable export {export_uuid} did not finish within {EXPORT_MAX_WAIT_SECONDS}s")
time.sleep(EXPORT_POLL_INTERVAL_SECONDS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index 5ce958e26c51..40f446d655a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -4426,8 +4426,9 @@ async def test_mysql_keyset_resume_seeks_past_checkpoint(team, mysql_config, mys
manager = source.get_resumable_source_manager(inputs)
# Simulate the checkpoint a previous pod committed just before it drained. The commit is what
- # puts it in Redis — `save_state` only stages — and `can_resume()` reads Redis.
+ # puts it in Redis — `save_state` only stages, `confirm` readies it — and `can_resume()` reads Redis.
await sync_to_async(manager.save_state)(KeysetResumeState(last_key=3))
+ await sync_to_async(manager.confirm)()
await sync_to_async(manager.commit)()
# A small chunk keeps resumption paging rather than one-shotting the tail.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_google_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_google_ads_source.py
index 882258464e8d..198a4a78ac31 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_google_ads_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_google_ads_source.py
@@ -381,6 +381,7 @@ class TestGoogleAdsSourceResumableBinding:
):
original = GoogleAdsResumeConfig(page_token="TEST_TOKEN")
manager.save_state(original)
+ manager.confirm()
manager.commit()
loaded = manager.load_state()