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(warehouse-sources): persist the resume cursor only after its rows are written (#98762)

Daniel RCf15f85a8e2d3
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index ec0df20ae302..da323f0eaefe 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -25,7 +25,7 @@ Before coding, read:
Every new source **must** inherit from one (or a combination) of these:
- **`SimpleSource[Config]`** — default for straightforward pull-based APIs where each run fully iterates the endpoint.
-- **`ResumableSource[Config, ResumableData]`** — **preferred for any new API-backed source whose underlying API supports resumption** (cursor/link-header pagination, time windows, offset tokens, or any other deterministic way to pick back up where we left off). If the API gives us a next-page token, a `Link` header, or a stable time filter, use `ResumableSource`. This lets Temporal resume after heartbeat timeouts without restarting from scratch. The manager persists state to Redis (24h TTL).
+- **`ResumableSource[Config, ResumableData]`** — **preferred for any new API-backed source whose underlying API supports resumption** (cursor/link-header pagination, time windows, offset tokens, or any other deterministic way to pick back up where we left off). If the API gives us a next-page token, a `Link` header, or a stable time filter, use `ResumableSource`. This lets Temporal resume after heartbeat timeouts without restarting from scratch. `save_state` stages the cursor in memory; the pipeline commits it to Redis (24h TTL) right after it writes the rows yielded so far.
- **`WebhookSource[Config]`** — only when the source can push events to us (e.g. Stripe webhook endpoints). Typically combined with `ResumableSource` so the initial backfill is resumable and subsequent deltas come via webhook.
Combine by multiple inheritance when both apply, e.g.:
@@ -405,15 +405,16 @@ url = resume.next_url if resume else initial_url
while True:
data = fetch_page(url)
- # yield batch
next_url = data.get("links", {}).get("next")
+ if next_url:
+ manager.save_state(MyResumeConfig(next_url=next_url)) # stage before the yield it covers
+ # yield batch
if not next_url:
break
- manager.save_state(MyResumeConfig(next_url=next_url))
url = next_url # advance before the next fetch, otherwise we loop on the same page
```
-Save state **after** yielding each batch, not before — so if we crash we re-yield the last batch (merge dedupes on primary key) rather than skipping it.
+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.
### Webhook source pattern
@@ -879,7 +880,7 @@ After changing source fields, re-run `pnpm run generate:source-configs` and `hog
- `sort_mode="asc"` declared on an API that returns newest-first: the watermark checkpoints to ≈now after the first batch and mid-sync shutdowns lose data ordering guarantees.
- 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` after yielding a batch; or saved before yield and a crash causes data loss.
+- 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.
- 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/core/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py
index 17efabeff4d3..dbb2a12916ec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py
@@ -114,10 +114,9 @@ class Batcher:
self._team_id = team_id
self._schema_name = schema_name
# Off by default because coalescing delays when a yielded table becomes a durable batch:
- # sources that checkpoint resume state or delete upstream staging right after yielding
- # (ResumableSource implementations, the webhook S3 path) rely on yield => persisted and
- # would lose data across a crash if their tables sat in this buffer. Only enable for
- # sources with no such dependency.
+ # the webhook S3 path deletes its staged files right after yielding, and the pipeline
+ # commits the resume cursor after a write on the assumption that the write drained every
+ # table yielded so far. Only enable for sources with no such dependency.
self._coalesce_tables = coalesce_tables
self._buffer = []
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 3f24a28e7e8f..255360514608 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,5 +1,6 @@
import sys
import time
+import asyncio
from typing import TYPE_CHECKING, Any, Generic, Literal
import pyarrow as pa
@@ -162,6 +163,10 @@ 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]] = {}
+ async def _commit_resume_state(self) -> None:
+ if self._resumable_source_manager is not None:
+ await asyncio.to_thread(self._resumable_source_manager.commit)
+
async def run(self) -> PipelineResult:
pa_memory_pool = pa.default_memory_pool()
@@ -221,26 +226,11 @@ class PipelineNonDLT(Generic[ResumableData]):
self._schema, partition_count_fallback=self._resource.partition_count
)
- async for item in async_iterate(self._resource.items()):
- py_table = None
-
- record_source_item_stats(
- item,
- source_type=self._source.source_type,
- logger=self._logger,
- team_id=self._job.team_id,
- schema_name=self._schema.name,
- )
-
- self._batcher.batch(item)
-
- # A single batched table may be split into several when a string/binary/list
- # column would otherwise overflow a 32-bit offset, so drain every ready chunk.
- while self._batcher.should_yield():
+ async def write_remaining_rows() -> None:
+ nonlocal chunk_index, row_count
+ while self._batcher.should_yield(include_incomplete_chunk=True):
py_table = self._batcher.get_table()
-
row_count += py_table.num_rows
-
await self._process_pa_table(
pa_table=py_table,
index=chunk_index,
@@ -248,26 +238,68 @@ class PipelineNonDLT(Generic[ResumableData]):
row_count=row_count,
is_first_ever_sync=is_first_ever_sync,
)
-
chunk_index += 1
+ # Every yielded row is written now, so whatever the source staged last is safe.
+ await self._commit_resume_state()
- cleanup_memory(pa_memory_pool, py_table)
+ awaiting_source = True
+ try:
+ async for item in async_iterate(self._resource.items()):
+ awaiting_source = False
py_table = None
- if should_check_shutdown(self._schema, self._resource, self._reset_pipeline, source_is_resumable):
- self._shutdown_monitor.raise_if_is_worker_shutdown()
-
- while self._batcher.should_yield(include_incomplete_chunk=True):
- py_table = self._batcher.get_table()
- row_count += py_table.num_rows
- await self._process_pa_table(
- pa_table=py_table,
- index=chunk_index,
- resuming_sync=should_resume,
- row_count=row_count,
- is_first_ever_sync=is_first_ever_sync,
- )
- chunk_index += 1
+ record_source_item_stats(
+ item,
+ source_type=self._source.source_type,
+ logger=self._logger,
+ team_id=self._job.team_id,
+ schema_name=self._schema.name,
+ )
+
+ self._batcher.batch(item)
+
+ # A single batched table may be split into several when a string/binary/list
+ # column would otherwise overflow a 32-bit offset, so drain every ready chunk.
+ wrote_chunk = False
+ while self._batcher.should_yield():
+ py_table = self._batcher.get_table()
+
+ row_count += py_table.num_rows
+
+ await self._process_pa_table(
+ pa_table=py_table,
+ index=chunk_index,
+ resuming_sync=should_resume,
+ row_count=row_count,
+ is_first_ever_sync=is_first_ever_sync,
+ )
+ wrote_chunk = True
+
+ chunk_index += 1
+
+ cleanup_memory(pa_memory_pool, py_table)
+ py_table = None
+
+ # A write is what makes the staged cursor safe to persist: after a buffered-only item
+ # it would skip rows that never landed, and after the shutdown check it would never land.
+ if wrote_chunk:
+ await self._commit_resume_state()
+
+ if should_check_shutdown(self._schema, self._resource, self._reset_pipeline, source_is_resumable):
+ 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. Writing them lets that cursor commit, so the
+ # next attempt continues from it instead of restarting the sweep.
+ if awaiting_source and source_is_resumable:
+ try:
+ await write_remaining_rows()
+ except Exception:
+ await self._logger.aexception("Failed to write the rows buffered before the source error")
+ raise
+
+ await write_remaining_rows()
await self._persist_observed_columns()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
index 01738c2744e3..f0af4b14427d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
@@ -1,13 +1,22 @@
+import json
import uuid
+from contextlib import ExitStack, nullcontext
+from dataclasses import dataclass
+from types import SimpleNamespace
from typing import cast
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+import pyarrow as pa
from parameterized import parameterized
+from posthog.temporal.common.shutdown import WorkerShuttingDownError
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline import PipelineNonDLT
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
ImportJobModels,
)
@@ -125,3 +134,156 @@ class TestDeltaTableRefFirstSyncWiring:
)
assert mock_delta_table_ref_cls.call_args.kwargs["is_first_sync"] is expected_is_first_sync
+
+
+@dataclass(frozen=True)
+class _Cursor:
+ id: str
+
+
+def _manager() -> ResumableSourceManager[_Cursor]:
+ inputs = cast(SourceInputs, SimpleNamespace(team_id=1, job_id="job-1", logger=MagicMock()))
+ return ResumableSourceManager[_Cursor](inputs, _Cursor)
+
+
+def _table_source(manager: ResumableSourceManager[_Cursor], ids: list[str], stage_before_yield: bool):
+ def items():
+ previous = None
+ for row_id in ids:
+ if stage_before_yield:
+ manager.save_state(_Cursor(row_id))
+ elif previous is not None:
+ manager.save_state(_Cursor(previous))
+ yield pa.table({"id": [row_id]})
+ previous = row_id
+
+ return items
+
+
+def _runnable_pipeline(manager: ResumableSourceManager[_Cursor], items) -> PipelineNonDLT:
+ pipeline = PipelineNonDLT.__new__(PipelineNonDLT)
+ logger = MagicMock()
+ logger.adebug = AsyncMock()
+ logger.ainfo = AsyncMock()
+ logger.awarning = AsyncMock()
+ logger.aexception = AsyncMock()
+ pipeline._logger = logger
+ pipeline._resumable_source_manager = manager
+ pipeline._resource = SourceResponse(name="orders", items=items, primary_keys=["id"])
+ pipeline._batcher = Batcher(MagicMock(), primary_keys=["id"])
+ pipeline._schema = MagicMock(should_use_incremental_field=False)
+ pipeline._source = MagicMock(source_type="Stripe")
+ pipeline._job = MagicMock(team_id=1, billable=False)
+ pipeline._table = None
+ pipeline._is_incremental = False
+ pipeline._reset_pipeline = False
+ delta_table_ref = AsyncMock()
+ delta_table_ref.get_delta_table.cache_pop.return_value = None
+ pipeline._delta_table_ref = delta_table_ref
+ pipeline._sinks = MagicMock(clear=AsyncMock())
+ pipeline._shutdown_monitor = MagicMock()
+ pipeline._process_pa_table = AsyncMock() # type: ignore[method-assign]
+ return pipeline
+
+
+def _raise_on_second_call(exc: Exception):
+ calls = {"n": 0}
+
+ def side_effect():
+ calls["n"] += 1
+ if calls["n"] == 2:
+ raise exc
+
+ return side_effect
+
+
+def _run_patches():
+ return (
+ patch(f"{_PIPELINE_MODULE}.reset_rows_synced_if_needed", new_callable=AsyncMock),
+ patch(f"{_PIPELINE_MODULE}.validate_incremental_sync"),
+ patch(f"{_PIPELINE_MODULE}.persist_primary_keys", new_callable=AsyncMock),
+ patch(f"{_PIPELINE_MODULE}.setup_row_tracking_with_billing_check", new_callable=AsyncMock),
+ patch(f"{_PIPELINE_MODULE}.handle_corrupted_delta_log", new_callable=AsyncMock),
+ patch(f"{_PIPELINE_MODULE}.handle_reset_or_full_refresh", new_callable=AsyncMock),
+ patch(f"{_PIPELINE_MODULE}.record_source_item_stats"),
+ )
+
+
+class TestResumeCursorCommit:
+ @parameterized.expand(
+ [
+ ("staged_before_yield", True, ["a", "b"]),
+ ("staged_after_yield", False, ["a"]),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_cursor_persisted_covers_exactly_the_written_chunks(
+ self, _name: str, stage_before_yield: bool, expected_committed: list[str]
+ ) -> None:
+ redis = MagicMock()
+ manager = _manager()
+ pipeline = _runnable_pipeline(manager, _table_source(manager, ["a", "b", "c"], stage_before_yield))
+ 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
+ )
+
+ with ExitStack() as stack:
+ stack.enter_context(patch.object(ResumableSourceManager, "_get_redis", lambda self: nullcontext(redis)))
+ for run_patch in _run_patches():
+ stack.enter_context(run_patch)
+ with pytest.raises(WorkerShuttingDownError):
+ await pipeline.run()
+
+ assert cast(AsyncMock, pipeline._process_pa_table).await_count == 2
+ assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == expected_committed
+
+ @pytest.mark.asyncio
+ async def test_cursor_not_persisted_for_rows_the_batcher_still_holds(self) -> None:
+ redis = MagicMock()
+ manager = _manager()
+
+ def items():
+ yield [{"id": "a"}]
+ manager.save_state(_Cursor("a"))
+ yield [{"id": "b"}]
+ manager.save_state(_Cursor("b"))
+ yield [{"id": "c"}]
+
+ 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
+ )
+
+ with ExitStack() as stack:
+ stack.enter_context(patch.object(ResumableSourceManager, "_get_redis", lambda self: nullcontext(redis)))
+ for run_patch in _run_patches():
+ stack.enter_context(run_patch)
+ with pytest.raises(WorkerShuttingDownError):
+ await pipeline.run()
+
+ cast(AsyncMock, pipeline._process_pa_table).assert_not_awaited()
+ redis.set.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_rows_buffered_when_the_source_raises_are_written_with_their_cursor(self) -> None:
+ redis = MagicMock()
+ manager = _manager()
+
+ def items():
+ manager.save_state(_Cursor("a"))
+ yield [{"id": "a"}]
+ raise RuntimeError("page budget")
+
+ pipeline = _runnable_pipeline(manager, items)
+
+ with ExitStack() as stack:
+ stack.enter_context(patch.object(ResumableSourceManager, "_get_redis", lambda self: nullcontext(redis)))
+ for run_patch in _run_patches():
+ stack.enter_context(run_patch)
+ with pytest.raises(RuntimeError):
+ await pipeline.run()
+
+ assert cast(AsyncMock, pipeline._process_pa_table).await_count == 1
+ assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == ["a"]
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 b17d6e716e8f..4b1eb65141de 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
@@ -215,9 +215,9 @@ class PipelineV3(Generic[ResumableData]):
# source->Arrow conversion doesn't materialise an oversized table; None falls back to defaults.
# Arrow coalescing keeps a driver's fetch size (e.g. a SQL cursor's 10k-row Arrow tables)
# from becoming the queue's batch granularity, but it delays when a yielded table is
- # persisted, so it must stay off for sources that treat yield as durable: resumable
- # sources checkpoint resume state right after yielding, and the webhook path deletes its
- # staged S3 files right after yielding.
+ # persisted, so it must stay off for sources that treat yield as durable: the webhook path
+ # deletes its staged S3 files right after yielding, and the resume cursor commit after a
+ # write assumes that write drained every table yielded so far.
self._batcher = Batcher(
self._logger,
chunk_size=source_response.chunk_size,
@@ -325,6 +325,10 @@ class PipelineV3(Generic[ResumableData]):
def _close_producers(self) -> None:
self._pg_producer.close()
+ async def _commit_resume_state(self) -> None:
+ if self._resumable_source_manager is not None:
+ await asyncio.to_thread(self._resumable_source_manager.commit)
+
async def run(self) -> PipelineResult:
pa_memory_pool = pa.default_memory_pool()
@@ -416,25 +420,11 @@ class PipelineV3(Generic[ResumableData]):
partition_count_fallback=self._resource.partition_count,
)
- async for item in async_iterate(self._resource.items()):
- py_table = None
-
- record_source_item_stats(
- item,
- source_type=source_type,
- logger=self._logger,
- team_id=self._job.team_id,
- schema_name=self._schema.name,
- )
-
- self._batcher.batch(item)
-
- # A single batched table may be split into several when a string/binary/list
- # column would otherwise overflow a 32-bit offset, so drain every ready chunk.
- while self._batcher.should_yield():
+ async def stage_remaining_rows() -> None:
+ nonlocal chunk_index, row_count
+ while self._batcher.should_yield(include_incomplete_chunk=True):
py_table = self._batcher.get_table()
row_count += py_table.num_rows
-
await self._process_batch(
pa_table=py_table,
batch_index=chunk_index,
@@ -446,27 +436,68 @@ 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.
+ await self._commit_resume_state()
- cleanup_memory(pa_memory_pool, py_table)
+ awaiting_source = True
+ try:
+ async for item in async_iterate(self._resource.items()):
+ awaiting_source = False
py_table = None
- if should_check_shutdown(self._schema, self._resource, self._reset_pipeline, source_is_resumable):
- self._shutdown_monitor.raise_if_is_worker_shutdown()
+ record_source_item_stats(
+ item,
+ source_type=source_type,
+ logger=self._logger,
+ team_id=self._job.team_id,
+ schema_name=self._schema.name,
+ )
- while self._batcher.should_yield(include_incomplete_chunk=True):
- py_table = self._batcher.get_table()
- row_count += py_table.num_rows
- await self._process_batch(
- pa_table=py_table,
- batch_index=chunk_index,
- row_count=row_count,
- )
+ self._batcher.batch(item)
+
+ # A single batched table may be split into several when a string/binary/list
+ # column would otherwise overflow a 32-bit offset, so drain every ready chunk.
+ wrote_chunk = False
+ while self._batcher.should_yield():
+ py_table = self._batcher.get_table()
+ row_count += py_table.num_rows
+
+ await self._process_batch(
+ pa_table=py_table,
+ batch_index=chunk_index,
+ row_count=row_count,
+ )
+ wrote_chunk = True
+
+ if activity.in_activity():
+ get_rows_extracted_metric(team_id_str, schema_id_str, source_type).add(py_table.num_rows)
+ get_batches_produced_metric(team_id_str, schema_id_str).add(1)
- if activity.in_activity():
- get_rows_extracted_metric(team_id_str, schema_id_str, source_type).add(py_table.num_rows)
- get_batches_produced_metric(team_id_str, schema_id_str).add(1)
+ chunk_index += 1
- chunk_index += 1
+ cleanup_memory(pa_memory_pool, py_table)
+ py_table = None
+
+ # A staged batch is what makes the cursor safe to persist: after a buffered-only item
+ # it would skip rows that never landed, and after the shutdown check it would never land.
+ if wrote_chunk:
+ await self._commit_resume_state()
+
+ if should_check_shutdown(self._schema, self._resource, self._reset_pipeline, source_is_resumable):
+ 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.
+ if awaiting_source and source_is_resumable:
+ try:
+ await stage_remaining_rows()
+ except Exception:
+ await self._logger.aexception("Failed to stage the rows buffered before the source error")
+ raise
+
+ 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 b5cf82412ff1..be2d2d0f4ec9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -1,3 +1,7 @@
+import json
+from contextlib import ExitStack, nullcontext
+from dataclasses import dataclass
+from types import SimpleNamespace
from typing import cast
import pytest
@@ -6,12 +10,20 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pyarrow as pa
from asgiref.sync import async_to_sync
+from posthog.temporal.common.shutdown import WorkerShuttingDownError
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.lanes import (
LanedPipelineV3,
_LaneWriter,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import OutputLane
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
+ OutputLane,
+ SourceInputs,
+ SourceResponse,
+)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
ImportJobModels,
)
@@ -783,3 +795,137 @@ class TestZeroBatchRunStampsTheFullRunMarker:
new=MagicMock(side_effect=RuntimeError("pooler is down")),
):
await pipeline._finalize(row_count=0)
+
+
+@dataclass(frozen=True)
+class _Cursor:
+ id: str
+
+
+def _manager() -> ResumableSourceManager[_Cursor]:
+ inputs = cast(SourceInputs, SimpleNamespace(team_id=1, job_id="job-1", logger=MagicMock()))
+ return ResumableSourceManager[_Cursor](inputs, _Cursor)
+
+
+def _table_source(manager: ResumableSourceManager[_Cursor], ids: list[str], stage_before_yield: bool):
+ def items():
+ previous = None
+ for row_id in ids:
+ if stage_before_yield:
+ manager.save_state(_Cursor(row_id))
+ elif previous is not None:
+ manager.save_state(_Cursor(previous))
+ yield pa.table({"id": [row_id]})
+ previous = row_id
+
+ return items
+
+
+def _runnable_pipeline(manager: ResumableSourceManager[_Cursor], items) -> PipelineV3:
+ pipeline = _make_pipeline()
+ pipeline._resumable_source_manager = manager
+ pipeline._resource = SourceResponse(name="test_table", items=items, primary_keys=["id"])
+ pipeline._batcher = Batcher(MagicMock(), primary_keys=["id"])
+ pipeline._schema = MagicMock(
+ id="schema-1",
+ source_id="source-1",
+ is_incremental=False,
+ is_webhook=False,
+ is_append=False,
+ should_use_incremental_field=False,
+ table=None,
+ )
+ pipeline._process_batch = AsyncMock() # type: ignore[method-assign]
+ return pipeline
+
+
+def _raise_on_second_call(exc: Exception):
+ calls = {"n": 0}
+
+ def side_effect():
+ calls["n"] += 1
+ if calls["n"] == 2:
+ raise exc
+
+ return side_effect
+
+
+async def _run_expecting(pipeline: PipelineV3, redis: MagicMock, exc: type[BaseException]) -> None:
+ 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
+ with pytest.raises(exc):
+ await pipeline.run()
+
+
+class TestResumeCursorCommit:
+ @pytest.mark.parametrize(
+ "stage_before_yield,expected_committed",
+ [(True, ["a", "b"]), (False, ["a"])],
+ ids=["staged_before_yield", "staged_after_yield"],
+ )
+ @pytest.mark.asyncio
+ async def test_cursor_persisted_covers_exactly_the_staged_batches(
+ self, stage_before_yield: bool, expected_committed: list[str]
+ ) -> None:
+ redis = MagicMock()
+ manager = _manager()
+ pipeline = _runnable_pipeline(manager, _table_source(manager, ["a", "b", "c"], stage_before_yield))
+ 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 == 2
+ assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == expected_committed
+
+ @pytest.mark.asyncio
+ async def test_cursor_not_persisted_for_rows_the_batcher_still_holds(self) -> None:
+ redis = MagicMock()
+ manager = _manager()
+
+ def items():
+ yield [{"id": "a"}]
+ manager.save_state(_Cursor("a"))
+ yield [{"id": "b"}]
+ manager.save_state(_Cursor("b"))
+ yield [{"id": "c"}]
+
+ 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)
+
+ cast(AsyncMock, pipeline._process_batch).assert_not_awaited()
+ redis.set.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_rows_buffered_when_the_source_raises_are_staged_with_their_cursor(self) -> None:
+ redis = MagicMock()
+ manager = _manager()
+
+ def items():
+ manager.save_state(_Cursor("a"))
+ yield [{"id": "a"}]
+ raise RuntimeError("page budget")
+
+ pipeline = _runnable_pipeline(manager, items)
+
+ await _run_expecting(pipeline, redis, RuntimeError)
+
+ 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"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py
index 028643a31493..f92f51360f1f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py
@@ -369,13 +369,14 @@ def _report_rows(
if resumable_source_manager is not None:
# Persist before the first poll — a retry that created a second report would
# be answered with a 425 until this one finished anyway.
- resumable_source_manager.save_state(
- AmazonAdsResumeConfig(
- profile_id=profile_id,
- window_start=window.start.isoformat(),
- report_id=report_id,
+ with resumable_source_manager.committing():
+ resumable_source_manager.save_state(
+ AmazonAdsResumeConfig(
+ profile_id=profile_id,
+ window_start=window.start.isoformat(),
+ report_id=report_id,
+ )
)
- )
url = client.await_report_url(report, profile_id, report_id)
if not url:
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 fb4c4b99f4cb..7f52437154c1 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
@@ -408,6 +408,7 @@ class TestBingAdsSource:
):
original = BingAdsResumeConfig(next_start_date="2025-02-01", end_date="2025-06-30")
manager.save_state(original)
+ manager.commit()
loaded = manager.load_state()
assert isinstance(loaded, BingAdsResumeConfig)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/clari.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/clari.py
index 573595b304f0..1ebb227df94c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/clari.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/clari.py
@@ -170,7 +170,8 @@ def _run_export_job(
raise ValueError(f"Clari export job creation returned no jobId: {created}")
# Persist immediately — exports are quota-limited, so a retried
# activity must re-poll this job rather than create another.
- resumable_source_manager.save_state(ClariResumeConfig(job_id=job_id))
+ with resumable_source_manager.committing():
+ resumable_source_manager.save_state(ClariResumeConfig(job_id=job_id))
status = None
for _attempt in range(EXPORT_POLL_MAX_ATTEMPTS):
@@ -182,7 +183,8 @@ def _run_export_job(
break
if status in ("FAILED", "CANCELLED", "ABORTED"):
# Don't re-poll a dead job on retry.
- resumable_source_manager.save_state(ClariResumeConfig(job_id=None))
+ with resumable_source_manager.committing():
+ resumable_source_manager.save_state(ClariResumeConfig(job_id=None))
raise ValueError(f"Clari export job {job_id} ended with status {status}")
time.sleep(EXPORT_POLL_INTERVAL_SECONDS)
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 32cd3d5472ee..364ce6995901 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
@@ -1,4 +1,5 @@
import json
+import functools
import dataclasses
import collections.abc
from contextlib import contextmanager
@@ -21,12 +22,22 @@ class ResumableSourceManager(Generic[ResumableData]):
_data_class: type[ResumableData]
_logger: FilteringBoundLogger
_namespace: str | None
-
- def __init__(self, inputs: SourceInputs, data_class: type[ResumableData], namespace: str | None = None):
+ _staged: dict[str, str]
+
+ def __init__(
+ self,
+ inputs: SourceInputs,
+ data_class: type[ResumableData],
+ namespace: str | None = None,
+ staged: dict[str, str] | None = None,
+ ):
self._inputs = inputs
self._data_class = data_class
self._logger = inputs.logger
self._namespace = namespace
+ # 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 {}
def with_namespace(self, namespace: str) -> "ResumableSourceManager[ResumableData]":
"""Return a sibling manager whose Redis state is isolated under `namespace`.
@@ -36,7 +47,7 @@ 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)
+ return ResumableSourceManager(self._inputs, self._data_class, namespace=namespace, staged=self._staged)
@contextmanager
def _get_redis(self):
@@ -100,14 +111,39 @@ 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.
+
+ 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.
+ """
+ json_data = self._dump_json(data)
+ self._logger.debug(f"Staging resumable source state. key={self._key}, data={json_data}")
+ self._staged[self._key] = json_data
+
+ def commit(self) -> None:
+ """Persist every staged cursor, across namespaces."""
+ if not self._staged:
+ return
with self._get_redis() as redis_client:
- json_data = self._dump_json(data)
- self._logger.debug(f"Saving resumable source state. key={self._key}, data={json_data}")
+ for key, json_data in list(self._staged.items()):
+ self._logger.debug(f"Saving resumable source state. key={key}, data={json_data}")
+ self._write_with_stale_replica_retry(
+ redis_client,
+ functools.partial(redis_client.set, key, json_data, ex=60 * 60 * 24), # 24 hours expiration
+ )
+ del self._staged[key]
- self._write_with_stale_replica_retry(
- redis_client,
- lambda: redis_client.set(self._key, json_data, ex=60 * 60 * 24), # 24 hours expiration
- )
+ @contextmanager
+ def committing(self) -> collections.abc.Iterator[None]:
+ """Commit whatever the block stages, even when the block raises.
+
+ For a bookmark that must persist before any row exists, such as an export or report id the
+ source polls before it yields. The pipeline has no write to commit on, so the source does.
+ """
+ try:
+ yield
+ finally:
+ self.commit()
def clear_state(self) -> None:
"""Drop any saved resume state so a subsequent attempt starts from scratch.
@@ -115,6 +151,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._staged.pop(self._key, None)
with self._get_redis() as redis_client:
self._logger.debug(f"Clearing resumable source state. key={self._key}")
self._write_with_stale_replica_retry(redis_client, lambda: redis_client.delete(self._key))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py
index 7c1e34913787..d03a23c3e5bc 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
@@ -13,9 +13,13 @@ class _SweepPosition:
cursor: str | None = None
+def _manager() -> ResumableSourceManager[_SweepPosition]:
+ return ResumableSourceManager[_SweepPosition](MagicMock(team_id=1, job_id="job-1"), _SweepPosition)
+
+
class TestResumableSourceManager:
def test_state_written_by_a_newer_deploy_still_loads(self):
- manager = ResumableSourceManager[_SweepPosition](MagicMock(team_id=1, job_id="job-1"), _SweepPosition)
+ manager = _manager()
redis = MagicMock()
redis.get.return_value = '{"cursor": "cus_1", "nested_starting_after": "txn_9"}'
@@ -25,8 +29,82 @@ class TestResumableSourceManager:
assert state == _SweepPosition(cursor="cus_1")
+ def test_state_reaches_redis_only_on_commit(self):
+ 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"))
+ manager.save_state(_SweepPosition(cursor="cus_2"))
+ redis.set.assert_not_called()
+
+ manager.commit()
+ manager.commit()
+
+ redis.set.assert_called_once_with(
+ "posthog:data_warehouse:resumable_source:1:job-1", '{"cursor":"cus_2"}', ex=60 * 60 * 24
+ )
+
+ def test_committing_persists_the_staged_state_even_when_the_block_raises(self):
+ manager = _manager()
+ redis = MagicMock()
+
+ with patch.object(ResumableSourceManager, "_get_redis") as get_redis:
+ get_redis.return_value.__enter__.return_value = redis
+ with pytest.raises(RuntimeError):
+ with manager.committing():
+ manager.save_state(_SweepPosition(cursor="job_1"))
+ raise RuntimeError("export failed")
+
+ redis.set.assert_called_once_with(
+ "posthog:data_warehouse:resumable_source:1:job-1", '{"cursor":"job_1"}', ex=60 * 60 * 24
+ )
+
+ def test_commit_persists_what_a_namespaced_sibling_staged(self):
+ manager = _manager()
+ redis = MagicMock()
+
+ 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.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):
+ 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"))
+ manager.clear_state()
+ manager.commit()
+
+ redis.delete.assert_called_once_with("posthog:data_warehouse:resumable_source:1:job-1")
+ redis.set.assert_not_called()
+
+ def test_commit_retries_once_after_a_stale_replica_write(self):
+ manager = _manager()
+ redis = MagicMock()
+ redis.set.side_effect = [
+ redis_exceptions.ReadOnlyError("You can't write against a read only replica."),
+ None,
+ ]
+
+ 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.commit()
+
+ redis.connection_pool.disconnect.assert_called_once()
+ assert redis.set.call_count == 2
+
def test_clear_state_retries_once_after_a_stale_replica_write(self):
- manager = ResumableSourceManager[_SweepPosition](MagicMock(team_id=1, job_id="job-1"), _SweepPosition)
+ manager = _manager()
redis = MagicMock()
redis.delete.side_effect = [
redis_exceptions.ReadOnlyError("You can't write against a read only replica."),
@@ -41,7 +119,7 @@ class TestResumableSourceManager:
assert redis.delete.call_count == 2
def test_clear_state_raises_when_the_retry_also_hits_a_stale_replica(self):
- manager = ResumableSourceManager[_SweepPosition](MagicMock(team_id=1, job_id="job-1"), _SweepPosition)
+ manager = _manager()
redis = MagicMock()
redis.delete.side_effect = redis_exceptions.ReadOnlyError("You can't write against a read only replica.")
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 9e76dc471be1..1fc80d02bf8c 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
@@ -585,6 +585,28 @@ class _WarehouseParentRows:
yield row
+def _fixed_state(position: StripeResumeConfig) -> Callable[[pa.Table], StripeResumeConfig]:
+ return lambda _table: position
+
+
+def _flush_staging_state(
+ batcher: Batcher,
+ resumable_source_manager: ResumableSourceManager[StripeResumeConfig],
+ state_for: Callable[[pa.Table], StripeResumeConfig],
+) -> Iterator[pa.Table]:
+ """Drain the batcher, staging a cursor only before the last table.
+
+ A drained table can be one slice of an oversized chunk, and a cursor read off an earlier slice
+ can end inside a parent whose rows continue in the next one. Only the last table's cursor
+ covers every drained row, so only that one is staged, for the commit after its write.
+ """
+ while batcher.should_yield(include_incomplete_chunk=True):
+ table = batcher.get_table()
+ if not batcher.should_yield(include_incomplete_chunk=True):
+ resumable_source_manager.save_state(state_for(table))
+ yield table
+
+
def _resume_state(position: Optional["ScanPosition"], parent_id: Optional[str]) -> StripeResumeConfig:
"""Resume state in whichever coordinate system this sweep is walking."""
if position is not None:
@@ -982,12 +1004,17 @@ def get_rows(
# (most customers have no payment methods) can take the entire customer base — so a
# sweep could walk hundreds of thousands of parents, one API call each, without ever
# recording progress, and a pod death restarted it from the first parent forever.
- # Flushing first is what makes the position safe to save: every row up to
- # `last_finished_parent` has been yielded by the time `starting_after` names it.
+ # Every buffered row belongs to a parent at or before `last_finished_parent`, so the
+ # 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:
- while batcher.should_yield(include_incomplete_chunk=True):
- yield batcher.get_table()
- resumable_source_manager.save_state(_resume_state(last_finished_position, last_finished_parent))
+ 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)
parents_since_checkpoint = 0
report_parent_rows_consumed()
@@ -1032,8 +1059,6 @@ def get_rows(
# "table already ready" guard.
while batcher.should_yield():
py_table = batcher.get_table()
- yield py_table
-
checkpoint = _nested_checkpoint(
py_table,
resource.nested_parent_param,
@@ -1043,6 +1068,7 @@ def get_rows(
)
if checkpoint is not None:
resumable_source_manager.save_state(checkpoint)
+ yield py_table
except stripe_lib.InvalidRequestError as e:
# The parent was deleted between listing it and fetching its nested resources,
# so Stripe 404s the nested call. Skip the now-gone parent and keep syncing the
@@ -1068,23 +1094,19 @@ def get_rows(
while batcher.should_yield():
py_table = batcher.get_table()
- yield py_table
-
+ # Staged before the yield, so the commit that follows this table's write covers it.
last_cur = py_table.column("id")[-1].as_py()
resumable_source_manager.save_state(StripeResumeConfig(starting_after=last_cur))
+ yield py_table
- while batcher.should_yield(include_incomplete_chunk=True):
- py_table = batcher.get_table()
- yield py_table
-
+ def trailing_state(py_table: pa.Table) -> StripeResumeConfig:
if isinstance(resource, StripeNestedResource):
last_cur = py_table.column(resource.nested_parent_param)[-1].as_py()
else:
last_cur = py_table.column("id")[-1].as_py()
+ return _resume_state(parent_pages.position_after_current if parent_pages else None, last_cur)
- resumable_source_manager.save_state(
- _resume_state(parent_pages.position_after_current if parent_pages else None, last_cur)
- )
+ yield from _flush_staging_state(batcher, resumable_source_manager, trailing_state)
return
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 a8db53c839bb..ff0cebfad417 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
@@ -691,6 +691,7 @@ 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
# 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]
@@ -2143,8 +2144,9 @@ class TestStripeNestedSweepResume:
def run(manager):
collected: list[dict] = []
- checkpoints: list[tuple[int, Any]] = []
- manager.save_state.side_effect = lambda state: checkpoints.append((len(collected), state))
+ staged: list[Any] = []
+ committed: list[tuple[int, Any]] = []
+ manager.save_state.side_effect = staged.append
with (
patch.object(stripe_module, "StripeClient"),
patch.object(stripe_module, "STRIPE_CHUNK_SIZE", 2),
@@ -2166,12 +2168,15 @@ class TestStripeNestedSweepResume:
warehouse_parent=warehouse_parent,
):
collected.extend(table.to_pylist())
- return collected, checkpoints
+ if staged:
+ committed.append((len(collected), staged[-1]))
+ staged.clear()
+ return collected, committed
killed = MagicMock()
killed.can_resume.return_value = False
- all_rows, checkpoints = run(killed)
- rows_written, crash_state = checkpoints[0]
+ all_rows, committed = run(killed)
+ rows_written, crash_state = committed[0]
restarted = MagicMock()
restarted.can_resume.return_value = True
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 e03f0d3d65df..aaed186be95e 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
@@ -258,7 +258,9 @@ def _get_export_rows(
if export_uuid is None:
export_uuid = _start_export(session, base_url, config, headers, logger, since)
- resumable_source_manager.save_state(TenableResumeConfig(export_uuid=export_uuid))
+ # Nothing is yielded before the export finishes, so the pipeline has no write to commit on.
+ with resumable_source_manager.committing():
+ resumable_source_manager.save_state(TenableResumeConfig(export_uuid=export_uuid))
deadline = time.monotonic() + EXPORT_MAX_WAIT_SECONDS
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tenable_vulnerability_management/tests/test_tenable_vulnerability_management.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tenable_vulnerability_management/tests/test_tenable_vulnerability_management.py
index 2f9e4ea43b81..0a0f5a152d70 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tenable_vulnerability_management/tests/test_tenable_vulnerability_management.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tenable_vulnerability_management/tests/test_tenable_vulnerability_management.py
@@ -1,4 +1,6 @@
import json
+from collections.abc import Iterator
+from contextlib import contextmanager
from datetime import UTC, date, datetime
from typing import Any
@@ -75,6 +77,7 @@ class _FakeResumableManager:
def __init__(self, state: TenableResumeConfig | None = None) -> None:
self._state = state
self.saved: list[TenableResumeConfig] = []
+ self.committed: list[TenableResumeConfig | None] = []
self.cleared = False
def can_resume(self) -> bool:
@@ -87,6 +90,11 @@ class _FakeResumableManager:
self.saved.append(data)
self._state = data
+ @contextmanager
+ def committing(self) -> Iterator[None]:
+ yield
+ self.committed.append(self._state)
+
def clear_state(self) -> None:
self.cleared = True
self._state = None
@@ -274,6 +282,8 @@ class TestExportFlow:
("u1", [1]),
("u1", [1, 2]),
]
+ # Only the job bookmark is committed by the source; chunk saves wait for the pipeline's write.
+ assert [(state.export_uuid, state.downloaded_chunks) for state in manager.committed if state] == [("u1", [])]
def test_chunk_state_is_saved_after_yield_not_before(self) -> None:
script = [
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_stripe_source.py
index e585151c9859..1380b6fb0588 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_stripe_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_stripe_source.py
@@ -17,6 +17,7 @@ from stripe._http_client import HTTPClient
from posthog.hogql.query import execute_hogql_query
from posthog.models.integration import Integration
+from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownError
from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -191,6 +192,42 @@ async def test_stripe_source_resuming_full_refresh(
assert mock_save_state.call_args[0][0].starting_after == BALANCE_TRANSACTIONS[-1]["id"]
[email protected]_db(transaction=True)
+async def test_stripe_source_full_refresh_resumes_after_worker_shutdown_without_duplicates(
+ team, mock_stripe_api, external_data_source, external_data_schema_full_refresh
+):
+ checks = {"n": 0}
+
+ def raise_on_second_check(self):
+ checks["n"] += 1
+ if checks["n"] == 2:
+ raise WorkerShuttingDownError(
+ "test_id", "test_type", "test_queue", 1, "test_workflow", "test_workflow_type"
+ )
+
+ with (
+ override_settings(DATA_WAREHOUSE_REDIS_HOST="localhost", DATA_WAREHOUSE_REDIS_PORT="6379"),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe.STRIPE_CHUNK_SIZE", 1
+ ),
+ mock.patch.object(ShutdownMonitor, "raise_if_is_worker_shutdown", raise_on_second_check),
+ ):
+ await run_external_data_job_workflow(
+ team=team,
+ external_data_source=external_data_source,
+ external_data_schema=external_data_schema_full_refresh,
+ table_name="stripe_balancetransaction",
+ expected_rows_synced=len(BALANCE_TRANSACTIONS),
+ expected_total_rows=len(BALANCE_TRANSACTIONS),
+ )
+
+ resumed_urls = [call.url for call in mock_stripe_api.get_all_api_calls() if "starting_after" in call.url]
+ assert resumed_urls == [
+ f"https://api.stripe.com/v1/balance_transactions?limit=100&starting_after={BALANCE_TRANSACTIONS[1]['id']}"
+ ]
+
+
# mock the chunk size to 1 so we can test how iterating over chunks of data works, particularly with updating the
# incremental field last value
@mock.patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher.DEFAULT_CHUNK_SIZE", 1)
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 bff5ce838747..882258464e8d 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.commit()
loaded = manager.load_state()
assert isinstance(loaded, GoogleAdsResumeConfig)