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): flush source buffers before saving a resume cursor (#113489)

Tom Owersb59ba909dd27
diff --git a/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt b/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
index 42395d02f6c3..254f1c2a1081 100644
--- a/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
+++ b/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
@@ -43,7 +43,6 @@ appsignal/appsignal.py::_walk_aggregate_windows
ashby/ashby.py::_fanned_out_pages
automox/automox.py::_iter_fan_out_rows
automox/automox.py::get_rows
-aviator/aviator.py::_get_fan_out_rows
awin/awin.py::get_rows
aws_budgets/aws_budgets.py::_budget_rows
aws_budgets/aws_budgets.py::_fanout_rows
@@ -73,7 +72,6 @@ chatwoot/chatwoot.py::_get_reporting_event_rows
chatwoot/chatwoot.py::get_rows
checkmarx/checkmarx.py::_get_fan_out_rows
checkmarx/checkmarx.py::get_rows
-checkout_com/payments.py::_get_rows
checkout_com/reports.py::_report_file_rows
circleci/circleci.py::get_rows
circleci_insights/circleci_insights.py::_project_workflow_fan_out_rows
@@ -213,7 +211,6 @@ honeybadger/honeybadger.py::_get_project_rows
honeycomb/honeycomb.py::_iter_board_views
honeycomb/honeycomb.py::_iter_fan_out
hubspot/hubspot.py::get_rows
-hubspot/hubspot.py::get_rows_via_search
hubspot/hubspot.py::get_rows_via_search._process_results
hyperspell/hyperspell.py::_get_list_rows
hyperspell/hyperspell.py::get_rows
@@ -238,7 +235,6 @@ intercom/intercom.py::_conversation_parts_generator
jamf_pro/jamf_pro.py::get_rows
jellyfish/jellyfish.py::_get_fan_out_rows
jellyfish/jellyfish.py::_get_month_windowed_rows
-jenkins/jenkins.py::_get_build_rows
jumpcloud/jumpcloud.py::_get_event_rows
jumpcloud/jumpcloud.py::_get_rest_rows
klaus/klaus.py::_iter_endpoint_pages
diff --git a/posthog/test/repo_invariants/test_resume_state_saved_by_the_source_generator.py b/posthog/test/repo_invariants/test_resume_state_saved_by_the_source_generator.py
new file mode 100644
index 000000000000..449cd0fbed8d
--- /dev/null
+++ b/posthog/test/repo_invariants/test_resume_state_saved_by_the_source_generator.py
@@ -0,0 +1,174 @@
+"""Warehouse sources must save resumable state from the generator that the pipeline iterates.
+
+The pipeline confirms a saved cursor when the source hands it an item, because the generator is
+then suspended and holds no rows that the cursor skips. A coroutine or a thread that reads ahead of
+the generator breaks that: it saves a cursor for rows that are still in a queue, the pipeline
+commits it, and a later attempt does not read those rows again. The failure message says how to fix
+a reported function.
+"""
+
+import ast
+import warnings
+from pathlib import Path
+
+from parameterized import parameterized
+
+REPO_ROOT = Path(__file__).parents[3]
+SOURCES_ROOT = REPO_ROOT / "products/warehouse_sources/backend/temporal/data_imports/sources"
+SKIPPED_DIRS = {"common", "tests", "test", "__pycache__"}
+
+FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
+# Calls that run their function argument on another thread or task.
+OFF_THREAD_CALLS = {
+ "Thread",
+ "submit",
+ "map",
+ "to_thread",
+ "run_in_executor",
+ "create_task",
+ "run_coroutine_threadsafe",
+}
+
+
+def _own_nodes(function: ast.AST) -> list[ast.AST]:
+ nodes: list[ast.AST] = []
+ stack: list[ast.AST] = [child for child in ast.iter_child_nodes(function) if not isinstance(child, FUNCTIONS)]
+ while stack:
+ node = stack.pop()
+ nodes.append(node)
+ stack.extend(child for child in ast.iter_child_nodes(node) if not isinstance(child, FUNCTIONS))
+ return nodes
+
+
+def _saves_state(function: ast.AST) -> bool:
+ return any(
+ isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "save_state"
+ for node in _own_nodes(function)
+ )
+
+
+def _called_name(call: ast.Call) -> str | None:
+ if isinstance(call.func, ast.Attribute):
+ return call.func.attr
+ # The builtin `map` runs its function in the calling thread. Only an executor's `map` does not.
+ if isinstance(call.func, ast.Name) and call.func.id != "map":
+ return call.func.id
+ return None
+
+
+def _off_thread_function_names(tree: ast.AST) -> set[str]:
+ names: set[str] = set()
+ for node in ast.walk(tree):
+ if not (isinstance(node, ast.Call) and _called_name(node) in OFF_THREAD_CALLS):
+ continue
+ for argument in [*node.args, *(keyword.value for keyword in node.keywords)]:
+ if isinstance(argument, ast.Name):
+ names.add(argument.id)
+ elif isinstance(argument, ast.Attribute):
+ names.add(argument.attr)
+ return names
+
+
+def _functions_in_source(source: str) -> list[str]:
+ tree = ast.parse(source)
+ off_thread = _off_thread_function_names(tree)
+ names: list[str] = []
+
+ def visit(node: ast.AST, prefix: str) -> None:
+ for child in ast.iter_child_nodes(node):
+ if isinstance(child, ast.FunctionDef | ast.AsyncFunctionDef):
+ qualified = f"{prefix}{child.name}"
+ runs_off_thread = isinstance(child, ast.AsyncFunctionDef) or child.name in off_thread
+ if runs_off_thread and _saves_state(child):
+ names.append(qualified)
+ visit(child, f"{qualified}.")
+ elif isinstance(child, ast.ClassDef):
+ visit(child, f"{prefix}{child.name}.")
+ else:
+ visit(child, prefix)
+
+ visit(tree, "")
+ return names
+
+
+def collect_functions() -> list[str]:
+ found: list[str] = []
+ for path in SOURCES_ROOT.rglob("*.py"):
+ relative = path.relative_to(SOURCES_ROOT)
+ if SKIPPED_DIRS.intersection(relative.parts) or path.name.startswith("test_"):
+ continue
+ source = path.read_text(encoding="utf-8", errors="ignore")
+ if "save_state" not in source:
+ continue
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", SyntaxWarning)
+ names = _functions_in_source(source)
+ except SyntaxError:
+ continue
+ found.extend(f"{relative.as_posix()}::{name}" for name in names)
+ return sorted(set(found))
+
+
+DETECTION_CASES = [
+ (
+ "save_in_a_coroutine_is_reported",
+ "async def rows(manager):\n"
+ " async for page in pages():\n"
+ " manager.save_state(page.cursor)\n"
+ " yield page\n",
+ ["rows"],
+ ),
+ (
+ "save_in_a_thread_target_is_reported",
+ "def source(manager):\n"
+ " def producer():\n"
+ " for page in pages():\n"
+ " manager.save_state(page.cursor)\n"
+ " queue.put(page)\n"
+ " threading.Thread(target=producer, daemon=True).start()\n",
+ ["source.producer"],
+ ),
+ (
+ "save_in_a_function_given_to_an_executor_is_reported",
+ "def fetch(manager, page):\n"
+ " manager.save_state(page.cursor)\n"
+ "def source(manager, executor):\n"
+ " return executor.submit(fetch, manager, first_page())\n",
+ ["fetch"],
+ ),
+ (
+ "save_in_the_generator_that_reads_the_queue_is_the_wanted_place",
+ "def rows(manager):\n"
+ " def producer():\n"
+ " for page in pages():\n"
+ " queue.put(page)\n"
+ " threading.Thread(target=producer, daemon=True).start()\n"
+ " while True:\n"
+ " page = queue.get()\n"
+ " manager.save_state(page.cursor)\n"
+ " yield page.rows\n",
+ [],
+ ),
+ (
+ "hook_defined_in_a_coroutine_is_not_a_save_in_the_coroutine",
+ "async def rows(manager):\n def hook(state):\n manager.save_state(state)\n return hook\n",
+ [],
+ ),
+]
+
+
[email protected](DETECTION_CASES)
+def test_detection(_name: str, source: str, expected: list[str]) -> None:
+ assert _functions_in_source(source) == expected
+
+
+def test_no_source_saves_resume_state_off_the_generator_thread() -> None:
+ found = collect_functions()
+ assert found == [], (
+ "These functions call `save_state` from a coroutine, or from a function that runs on another "
+ "thread or task. Such code reads ahead of the generator that the pipeline iterates, so the "
+ "cursor it saves can skip rows that are still in a queue. Pass the resume state through the "
+ "queue with the rows, and call `save_state` in the generator when it takes the state from the "
+ "queue (see `temporalio/temporalio.py::_async_iter_to_sync`).\n" + "\n".join(f" {line}" for line in found)
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_buffered_source_resume.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_buffered_source_resume.py
new file mode 100644
index 000000000000..98dc02b1749c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_buffered_source_resume.py
@@ -0,0 +1,211 @@
+import json
+import asyncio
+import threading
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.test_pipeline import (
+ _MemoryRedis,
+ run_attempts_until_done,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import boundary_checkpoint
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot import hubspot
+from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo import klaviyo
+from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.settings import KLAVIYO_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.temporalio import temporalio as temporalio_source
+
+_START_MS = 1_700_000_000_000
+
+
+class _Response:
+ def __init__(self, status_code: int, payload: Any) -> None:
+ self.status_code = status_code
+ self.ok = status_code < 400
+ self.text = json.dumps(payload)
+ self._payload = payload
+
+ def json(self) -> Any:
+ return self._payload
+
+
+class _HubspotSearchServer:
+ def __init__(self, rows_per_window: list[int], fail_from_request: int) -> None:
+ self.rows: list[dict[str, Any]] = [
+ {"id": f"{window}-{index}", "modified": _START_MS + 1 + window * (hubspot.WINDOW_SIZE_MS + 1) + index + 1}
+ for window, count in enumerate(rows_per_window)
+ for index in range(count)
+ ]
+ self.now_ms = _START_MS + len(rows_per_window) * (hubspot.WINDOW_SIZE_MS + 1)
+ self.requests = 0
+ self.fail_from_request: int | None = fail_from_request
+
+ def post(self, url: str, headers: Any = None, json: Any = None, timeout: Any = None) -> _Response:
+ self.requests += 1
+ if self.fail_from_request is not None and self.requests >= self.fail_from_request:
+ return _Response(500, {"message": "outage"})
+ bounds = {item["operator"]: int(item["value"]) for item in json["filterGroups"][0]["filters"]}
+ matched = [row for row in self.rows if bounds["GTE"] <= row["modified"] <= bounds["LTE"]]
+ start = int(json.get("after") or 0)
+ page = matched[start : start + json["limit"]]
+ payload: dict[str, Any] = {
+ "results": [
+ {
+ "id": row["id"],
+ "properties": {"hs_object_id": row["id"], "hs_lastmodifieddate": str(row["modified"])},
+ }
+ for row in page
+ ]
+ }
+ if start + json["limit"] < len(matched):
+ payload["paging"] = {"next": {"after": str(start + json["limit"])}}
+ return _Response(200, payload)
+
+
+ "fail_from_request,rows_written_two_times",
+ # 2,300 rows in window 1 are 12 search pages. Request 13 is the first request of window 2.
+ [(5, None), (13, 0), (17, None)],
+ ids=["fails_in_window_1", "fails_at_the_start_of_window_2", "fails_in_window_3"],
+)
+async def test_hubspot_search_resumes_at_a_window_end_only_after_the_rows_of_the_window(
+ fail_from_request: int, rows_written_two_times: int | None
+) -> None:
+ server = _HubspotSearchServer([2300, 700, 400], fail_from_request)
+ redis = _MemoryRedis()
+
+ def build_items(manager: Any):
+ def items():
+ try:
+ yield from hubspot.get_rows_via_search(
+ api_key="key",
+ refresh_token="refresh",
+ endpoint="deals",
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=_START_MS,
+ include_custom_props=False,
+ now_ms=server.now_ms,
+ api_version=hubspot.HUBSPOT_API_VERSION_V3,
+ )
+ finally:
+ server.fail_from_request = None
+
+ return items
+
+ with (
+ patch.object(hubspot, "make_tracked_session", lambda *args, **kwargs: server),
+ patch("tenacity.nap.time.sleep", lambda seconds: None),
+ patch.object(boundary_checkpoint, "PARTIAL_FLUSH_INTERVAL_SECONDS", 0),
+ ):
+ first, second = await run_attempts_until_done(redis, build_items, hubspot.HubspotResumeConfig)
+
+ assert set(first) | set(second) == {row["id"] for row in server.rows}
+ if rows_written_two_times is not None:
+ assert len(set(first) & set(second)) == rows_written_two_times
+
+
[email protected]("fail_on_request", [2, 3, 4])
+async def test_klaviyo_fan_out_bookmarks_the_next_parent_only_after_the_rows_of_the_parent(
+ fail_on_request: int,
+) -> None:
+ parents = ["L1", "L2", "L3", "L4"]
+ served = [f"{parent}-{index}" for parent in parents for index in range(3)]
+ requests = {"count": 0, "fail_on": fail_on_request}
+ redis = _MemoryRedis()
+
+ def fetch_page(session: Any, url: str, headers: Any, logger: Any, json_body: Any = None) -> dict[str, Any]:
+ requests["count"] += 1
+ if requests["count"] == requests["fail_on"]:
+ raise RuntimeError("request failed after its retries")
+ parent = next(parent for parent in parents if f"/lists/{parent}/" in url)
+ return {"data": [{"id": f"{parent}-{index}"} for index in range(3)], "links": {"next": None}}
+
+ def build_items(manager: Any):
+ def items():
+ # Four rows for each table, so a table ends in the middle of a parent.
+ batcher = Batcher(MagicMock(), chunk_size=4)
+ yield from klaviyo._get_fan_out_rows(
+ MagicMock(), {}, MagicMock(), batcher, manager, KLAVIYO_ENDPOINTS["list_profiles"], {}
+ )
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+ return items
+
+ with (
+ patch.object(klaviyo, "_iter_fan_out_parents", lambda *args: [({}, parent) for parent in parents]),
+ patch.object(klaviyo, "_fetch_page", fetch_page),
+ patch.object(boundary_checkpoint, "PARTIAL_FLUSH_INTERVAL_SECONDS", 0),
+ ):
+ attempts = await run_attempts_until_done(
+ redis, build_items, klaviyo.KlaviyoResumeConfig, id_column="profile_id"
+ )
+
+ assert sorted({row_id for attempt in attempts for row_id in attempt}) == served
+ assert len(attempts) == 2 and len(attempts[1]) < len(served)
+
+
+class _WorkflowPages:
+ def __init__(self, total: int, page_size: int, start: int, on_last_page: threading.Event) -> None:
+ self._total = total
+ self._page_size = page_size
+ self._position = start
+ self._on_last_page = on_last_page
+ self.next_page_token: bytes | None = str(start).encode() if start else None
+ self.current_page: list[Any] | None = None
+
+ async def fetch_next_page(self) -> None:
+ end = min(self._position + self._page_size, self._total)
+ self.current_page = [
+ SimpleNamespace(id=f"wf-{index}", run_id=f"run-{index}", close_time=None)
+ for index in range(self._position, end)
+ ]
+ self._position = end
+ self.next_page_token = str(end).encode() if end < self._total else None
+ if end >= self._total:
+ self._on_last_page.set()
+
+
[email protected]("shutdown_after_items", [250, 450])
+async def test_temporalio_commits_a_page_token_only_for_rows_the_pipeline_received(shutdown_after_items: int) -> None:
+ total = 1000
+ redis = _MemoryRedis()
+ producer_read_every_page = threading.Event()
+
+ class Client:
+ def list_workflows(self, query: Any = None, next_page_token: bytes | None = None, page_size: int = 100):
+ start = int(next_page_token.decode()) if next_page_token else 0
+ return _WorkflowPages(total, page_size, start, producer_read_every_page)
+
+ async def get_client(*args: Any, **kwargs: Any) -> Client:
+ return Client()
+
+ async def on_write(ids: list[str]) -> None:
+ # The producer thread reads ahead of the pipeline. Wait until it has read every page, so
+ # the first cursor commit comes when the producer is as far ahead as it can be.
+ await asyncio.to_thread(producer_read_every_page.wait, 30)
+
+ def build_items(manager: Any):
+ return lambda: temporalio_source._async_iter_to_sync(
+ temporalio_source._get_workflows(MagicMock(), None, False, manager, MagicMock(), 1),
+ save_resume_state=manager.save_state,
+ )
+
+ with patch.object(temporalio_source, "_get_temporal_client", get_client):
+ first, second = await run_attempts_until_done(
+ redis,
+ build_items,
+ temporalio_source.TemporalIOResumeConfig,
+ on_write=on_write,
+ chunk_size=200,
+ shutdown_after_items=shutdown_after_items,
+ )
+
+ assert set(first) | set(second) == {f"wf-{index}" for index in range(total)}
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 ef81ee720bdd..e3466b057431 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
@@ -977,6 +977,7 @@ async def _run_attempt(
chunk_size: int | None = None,
shutdown_after_items: int | None = None,
on_write: Any = None,
+ id_column: str = "id",
) -> tuple[list[Any], BaseException | None]:
pipeline = _runnable_pipeline(manager, items)
pipeline._batcher = Batcher(MagicMock(), chunk_size=chunk_size, primary_keys=["id"])
@@ -984,7 +985,7 @@ async def _run_attempt(
written: list[Any] = []
async def record(pa_table: pa.Table, batch_index: int, row_count: int) -> None:
- ids = pa_table["id"].to_pylist()
+ ids = pa_table[id_column].to_pylist()
written.extend(ids)
if on_write is not None:
await on_write(ids)
@@ -1019,7 +1020,14 @@ async def _run_attempt(
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
+ redis: Any,
+ build_items: Any,
+ data_class: type,
+ *,
+ max_attempts: int = 4,
+ on_write: Any = None,
+ id_column: str = "id",
+ **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]] = []
@@ -1027,7 +1035,12 @@ async def run_attempts_until_done(
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 {})
+ redis,
+ manager,
+ build_items(manager),
+ on_write=on_write,
+ id_column=id_column,
+ **(first_attempt if attempt == 0 else {}),
)
attempts.append(written)
if error is None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py
index 953b8d3d4c5a..346897d411a6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py
@@ -12,6 +12,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aviator.se
AVIATOR_ENDPOINTS,
AviatorEndpointConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.boundary_checkpoint import (
+ BoundaryCheckpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -395,6 +398,7 @@ def _get_fan_out_rows(
completed_repo_keys = list(resume.completed_repo_keys) if resume is not None else []
completed = set(completed_repo_keys)
+ repo_checkpoint = BoundaryCheckpoint(batcher, resumable_source_manager)
for repo in repos:
org, name = repo.get("org"), repo.get("name")
if not org or not name:
@@ -423,7 +427,8 @@ def _get_fan_out_rows(
# repo's batches so a crash mid-repo re-processes it (merge dedupes) rather than skipping it.
completed_repo_keys.append(repo_key)
completed.add(repo_key)
- resumable_source_manager.save_state(AviatorResumeConfig(completed_repo_keys=list(completed_repo_keys)))
+ # The batcher can hold rows of this repo, and a state that marks the repo done skips them.
+ yield from repo_checkpoint.save(AviatorResumeConfig(completed_repo_keys=list(completed_repo_keys)))
def get_rows(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/care_quality_commission/care_quality_commission.py b/products/warehouse_sources/backend/temporal/data_imports/sources/care_quality_commission/care_quality_commission.py
index 894ef0c2f026..2087cac5c899 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/care_quality_commission/care_quality_commission.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/care_quality_commission/care_quality_commission.py
@@ -43,6 +43,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.care_quali
CQC_ENDPOINTS,
CQCEndpointConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.boundary_checkpoint import (
+ BoundaryCheckpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -159,6 +162,7 @@ def _iter_endpoint_rows(
start_page: int,
) -> Iterator[Any]:
page = start_page
+ page_checkpoint = BoundaryCheckpoint(batcher, resumable_source_manager)
while True:
params: dict[str, Any] = {}
if config.paginated:
@@ -192,8 +196,9 @@ def _iter_endpoint_rows(
break
page += 1
- # Advance the bookmark so a crash between pages resumes on the next page.
- resumable_source_manager.save_state(CQCResumeConfig(page=page))
+ # Advance the bookmark so a crash between pages resumes on the next page. The batcher can
+ # hold rows of the page just read, and a bookmark at the next page skips them.
+ yield from page_checkpoint.save(CQCResumeConfig(page=page))
def get_rows(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/care_quality_commission/tests/test_care_quality_commission.py b/products/warehouse_sources/backend/temporal/data_imports/sources/care_quality_commission/tests/test_care_quality_commission.py
index 633b5d22687f..6c79913b5700 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/care_quality_commission/tests/test_care_quality_commission.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/care_quality_commission/tests/test_care_quality_commission.py
@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.care_quali
from products.warehouse_sources.backend.temporal.data_imports.sources.care_quality_commission.settings import (
CQC_ENDPOINTS,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import boundary_checkpoint
class _FakeResumableManager:
@@ -127,6 +128,7 @@ class TestGetRowsFanOut:
f"{CQC_BASE_URL}/providers/1-B?partnerCode=PC": {"providerId": "1-B"},
}
manager = _FakeResumableManager()
+ monkeypatch.setattr(boundary_checkpoint, "PARTIAL_FLUSH_INTERVAL_SECONDS", 0)
rows = _collect(manager, monkeypatch, pages)
assert rows == [{"providerId": "1-A"}, {"providerId": "1-B"}]
# The bookmark advances to page 2 after page 1 completes so a crash resumes mid-stream.
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 ec26f58c949d..7bc395c57120 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
@@ -831,6 +831,13 @@ def _get_rows(
# next scheduled sync re-covers it (merge dedupes overlapping rows).
break
resumable_source_manager.save_state(CheckoutComResumeConfig(search_window_to=_format_timestamp(window.end)))
+ # The cursor skips this window, so the rows of the window go to the pipeline with it.
+ if chunk:
+ latest_yielded = _latest_incremental_value(schema_name, chunk, latest_yielded)
+ yield chunk
+ chunk = []
+ else:
+ resumable_source_manager.safe_point()
covered_to = window.end
if chunk:
latest_yielded = _latest_incremental_value(schema_name, chunk, latest_yielded)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/boundary_checkpoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/boundary_checkpoint.py
new file mode 100644
index 000000000000..a9881e7499a8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/boundary_checkpoint.py
@@ -0,0 +1,60 @@
+"""Resume cursors at a boundary, for a source that batches rows in a local `Batcher`.
+
+Such a source reaches the end of a page, window or parent with rows still in its batcher. A cursor
+saved there says "continue after this boundary", so a resume from it does not read those rows again.
+The cursor is correct only when the batcher is empty, or when the rows go to the pipeline together
+with it.
+
+Each table that a resumable source yields is written as one batch, so a flush at every boundary
+makes many small batches. `BoundaryCheckpoint` therefore flushes a partly filled batcher at most
+once per interval, and saves no cursor for the boundaries between two flushes. The cursor is then
+late, which only makes a resume read more rows again.
+"""
+
+import time
+from collections.abc import Callable, Iterator
+from typing import Generic
+
+import pyarrow as pa
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+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 ResumableData
+
+PARTIAL_FLUSH_INTERVAL_SECONDS = 60.0
+
+
+class BoundaryCheckpoint(Generic[ResumableData]):
+ def __init__(
+ self,
+ batcher: Batcher,
+ manager: ResumableSourceManager[ResumableData],
+ *,
+ flush_interval_seconds: float | None = None,
+ clock: Callable[[], float] = time.monotonic,
+ ) -> None:
+ self._batcher = batcher
+ self._manager = manager
+ self._flush_interval_seconds = (
+ PARTIAL_FLUSH_INTERVAL_SECONDS if flush_interval_seconds is None else flush_interval_seconds
+ )
+ self._clock = clock
+ self._last_flush = clock()
+
+ def save(self, state: ResumableData) -> Iterator[pa.Table]:
+ """Save `state` at a boundary. Use it as `yield from checkpoint.save(state)`.
+
+ Call it only where `state` covers every row the source has read, and the batcher is the only
+ place that can still hold some of them.
+ """
+ if not self._batcher.should_yield(include_incomplete_chunk=True):
+ self._manager.save_state(state)
+ # Nothing is buffered, so a run of boundaries with no rows keeps its progress.
+ self._manager.safe_point()
+ return
+ if self._clock() - self._last_flush < self._flush_interval_seconds:
+ return
+ # Saved before the yield, so the pipeline receives the rows and their cursor together.
+ self._manager.save_state(state)
+ yield self._batcher.get_table()
+ self._last_flush = self._clock()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_boundary_checkpoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_boundary_checkpoint.py
new file mode 100644
index 000000000000..22252d484bd0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_boundary_checkpoint.py
@@ -0,0 +1,49 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.boundary_checkpoint import (
+ BoundaryCheckpoint,
+)
+
+
+ "steps,expected_events",
+ [
+ ([(0, 0.0)], ["save:1", "safe_point"]),
+ ([(2, 59.0)], []),
+ ([(2, 60.0)], ["save:1", "yield:2"]),
+ ([(2, 60.0), (1, 59.0)], ["save:1", "yield:2"]),
+ ([(2, 60.0), (1, 60.0)], ["save:1", "yield:2", "save:2", "yield:1"]),
+ ([(2, 10.0), (0, 0.0)], []),
+ ],
+ ids=[
+ "empty_batcher_saves_at_a_safe_point",
+ "buffered_rows_before_the_interval_save_nothing",
+ "buffered_rows_after_the_interval_go_out_with_the_cursor",
+ "the_interval_starts_again_after_a_flush",
+ "a_second_flush_follows_a_second_interval",
+ "rows_from_an_earlier_boundary_still_block_the_save",
+ ],
+)
+def test_a_cursor_is_saved_only_when_no_buffered_row_stays_behind_it(
+ steps: list[tuple[int, float]], expected_events: list[str]
+) -> None:
+ events: list[str] = []
+ now = [0.0]
+ manager = MagicMock()
+ manager.save_state.side_effect = lambda state: events.append(f"save:{state}")
+ manager.safe_point.side_effect = lambda: events.append("safe_point")
+ batcher = Batcher(MagicMock(), chunk_size=1000)
+ checkpoint: BoundaryCheckpoint[Any] = BoundaryCheckpoint(batcher, manager, clock=lambda: now[0])
+
+ for boundary, (new_rows, seconds_later) in enumerate(steps, start=1):
+ for row in range(new_rows):
+ batcher.batch({"id": f"{boundary}-{row}"})
+ now[0] += seconds_later
+ for table in checkpoint.save(boundary):
+ events.append(f"yield:{table.num_rows}")
+
+ assert events == expected_events
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py
index 72c580bda19d..79dc9d7e7da8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py
@@ -9,6 +9,9 @@ from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.boundary_checkpoint import (
+ BoundaryCheckpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -337,6 +340,7 @@ def _iter_events_windows(
# Rows of the first window already emitted in a prior run; skip them so a resume doesn't re-walk
# the whole (up to 7-day) window. Only the window we resume on carries a non-zero skip.
skip = start_row_offset
+ window_checkpoint = BoundaryCheckpoint(batcher, manager)
while window_start <= today:
window_end = min(window_start + timedelta(days=EVENTS_WINDOW_DAYS), today)
params = {"start": window_start.isoformat(), "end": window_end.isoformat()}
@@ -360,7 +364,8 @@ def _iter_events_windows(
# day. We don't know whether Concord's `end` is inclusive or exclusive, and the overlap is
# free: merge dedupes on the event id primary key, so no event can fall through the seam.
next_start = window_end
- manager.save_state(
+ # The batcher can hold rows of this window, and a cursor at the next window skips them.
+ yield from window_checkpoint.save(
ConcordResumeConfig(
window_start_ms=int(datetime.combine(next_start, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
index 954de8591f04..47a64611bf11 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
@@ -9,6 +9,7 @@ import requests
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import boundary_checkpoint
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.concord import concord
from products.warehouse_sources.backend.temporal.data_imports.sources.concord.concord import (
@@ -274,12 +275,13 @@ class TestEventsWindowPagination:
@time_machine.travel("2024-01-20", tick=False)
def test_walks_weekly_windows_with_bounded_range(self):
last_value = int(datetime(2024, 1, 1, tzinfo=UTC).timestamp() * 1000)
- _rows, urls, manager = _run(
- "events",
- [{"events": [{"id": 1}]}],
- should_use_incremental_field=True,
- db_incremental_field_last_value=last_value,
- )
+ with mock.patch.object(boundary_checkpoint, "PARTIAL_FLUSH_INTERVAL_SECONDS", 0):
+ _rows, urls, manager = _run(
+ "events",
+ [{"events": [{"id": 1}]}],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=last_value,
+ )
# 2024-01-01 .. 2024-01-20 chunked into <= 7-day windows
assert "start=2024-01-01" in urls[0]
assert "end=2024-01-08" in urls[0]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py
index 3b4558b669f9..7b9a7d6cbb95 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py
@@ -27,6 +27,9 @@ from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.boundary_checkpoint import (
+ BoundaryCheckpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -657,14 +660,13 @@ def get_rows_via_search(
except RequestsJSONDecodeError as e:
raise HubspotRetryableError(f"Hubspot search malformed JSON response (retryable): url={search_url}") from e
+ def progress() -> HubspotResumeConfig:
+ return HubspotResumeConfig(sync_start_ms=sync_start_ms, sync_end_ms=sync_end_ms, last_cursor_ms=last_cursor_ms)
+
def save_progress() -> None:
- resumable_source_manager.save_state(
- HubspotResumeConfig(
- sync_start_ms=sync_start_ms,
- sync_end_ms=sync_end_ms,
- last_cursor_ms=last_cursor_ms,
- )
- )
+ resumable_source_manager.save_state(progress())
+
+ window_checkpoint = BoundaryCheckpoint(batcher, resumable_source_manager)
def _process_results(results: list[dict[str, Any]]) -> Iterator[Any]:
"""Flatten, batch, and yield `results`, tracking cursor progress as a side effect."""
@@ -850,7 +852,8 @@ def get_rows_via_search(
current_lower = window_upper + 1
if last_cursor_ms < window_upper:
last_cursor_ms = window_upper
- save_progress()
+ # The batcher can hold rows of this window, and a cursor at the window end skips them.
+ yield from window_checkpoint.save(progress())
if batcher.should_yield(include_incomplete_chunk=True):
py_table = batcher.get_table()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/jenkins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/jenkins.py
index 41816c3bd1fe..58faae133d4e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/jenkins.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/jenkins.py
@@ -11,6 +11,9 @@ from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.boundary_checkpoint import (
+ BoundaryCheckpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -443,6 +446,7 @@ def _get_build_rows(
remaining = job_urls[job_urls.index(resume.next_job_url) :]
logger.debug(f"Jenkins: resuming builds fan-out from {resume.next_job_url}")
+ job_checkpoint = BoundaryCheckpoint(batcher, resumable_source_manager)
for index, job_url in enumerate(remaining):
for build in _iter_job_builds(session, job_url, auth, logger, watermark_ms):
batcher.batch(build)
@@ -452,8 +456,9 @@ def _get_build_rows(
# Bookmark the NEXT job only after the current one is fully yielded, so a crash resumes at an
# unprocessed job rather than re-emitting one whose rows already landed. The incremental
# watermark finalizes at job end (desc sort_mode), so a bounded re-pull on crash is safe.
+ # The batcher can hold builds of this job, and a bookmark at the next job skips them.
if index + 1 < len(remaining):
- resumable_source_manager.save_state(JenkinsResumeConfig(next_job_url=remaining[index + 1]))
+ yield from job_checkpoint.save(JenkinsResumeConfig(next_job_url=remaining[index + 1]))
def get_rows(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
index a49e352925a7..aed716e0ce83 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
@@ -12,6 +12,9 @@ from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_
from posthog.exceptions_capture import capture_exception
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.boundary_checkpoint import (
+ BoundaryCheckpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
@@ -479,6 +482,7 @@ def _get_fan_out_rows(
resume_url = resume.next_url
logger.debug(f"Klaviyo: resuming {config.name} from parent={resume.list_id}, url={resume_url}")
+ parent_checkpoint = BoundaryCheckpoint(batcher, resumable_source_manager)
for index, (ancestors, parent_id) in enumerate(remaining):
child_path = config.path.format(**{fan_out.parent_id_column: parent_id})
url = resume_url or _build_url(f"{KLAVIYO_BASE_URL}{child_path}", params)
@@ -514,9 +518,10 @@ def _get_fan_out_rows(
raise
# Advance the bookmark to the next parent so a crash between parents resumes correctly. Its
- # first page URL is built fresh when the loop reaches it.
+ # first page URL is built fresh when the loop reaches it. The batcher can hold rows of this
+ # parent, and a bookmark at the next parent skips them.
if index + 1 < len(remaining):
- resumable_source_manager.save_state(KlaviyoResumeConfig(next_url=None, list_id=remaining[index + 1][1]))
+ yield from parent_checkpoint.save(KlaviyoResumeConfig(next_url=None, list_id=remaining[index + 1][1]))
def _resolve_conversion_metric_id(
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 f16bac968a38..b2aff6fbdf6b 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
@@ -15,6 +15,9 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
from posthog.cloud_utils import is_cloud
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.boundary_checkpoint import (
+ BoundaryCheckpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -837,6 +840,7 @@ def _get_examples_rows(
start_index, resume_offset = _examples_start_position(resumable_source_manager, dataset_ids, logger)
pages = 0
+ dataset_checkpoint = BoundaryCheckpoint(batcher, resumable_source_manager)
for index in range(start_index, len(dataset_ids)):
dataset_id = dataset_ids[index]
is_last_dataset = index == len(dataset_ids) - 1
@@ -845,8 +849,9 @@ def _get_examples_rows(
else:
offset = 0
# Checkpoint the dataset boundary before reading it, so a crash resumes at this dataset
- # rather than re-reading the previous one.
- resumable_source_manager.save_state(LangSmithResumeConfig(dataset_id=dataset_id, offset=0))
+ # rather than re-reading the previous one. The batcher can hold examples of the previous
+ # dataset, and a checkpoint at this dataset skips them.
+ yield from dataset_checkpoint.save(LangSmithResumeConfig(dataset_id=dataset_id, offset=0))
while True:
page_offset = offset
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/linkrunner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/linkrunner.py
index 2d53f4fdd424..9d494b627799 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/linkrunner.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/linkrunner.py
@@ -8,6 +8,9 @@ from structlog.types import FilteringBoundLogger
from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.boundary_checkpoint import (
+ BoundaryCheckpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -250,6 +253,7 @@ def _get_attributed_user_rows(
f"Linkrunner: resuming attributed_users from campaign={resume.campaign_display_id}, page={resume_page}"
)
+ campaign_checkpoint = BoundaryCheckpoint(batcher, resumable_source_manager)
for index, display_id in enumerate(remaining):
page = resume_page
resume_page = 1 # only the resumed-into campaign uses the saved page; the rest start at 1
@@ -282,8 +286,9 @@ def _get_attributed_user_rows(
page += 1
# Advance the bookmark to the next campaign so a crash between campaigns resumes correctly.
+ # The batcher can hold rows of this campaign, and a bookmark at the next campaign skips them.
if index + 1 < len(remaining):
- resumable_source_manager.save_state(
+ yield from campaign_checkpoint.save(
LinkrunnerResumeConfig(page=1, campaign_display_id=remaining[index + 1])
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/tests/test_linkrunner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/tests/test_linkrunner.py
index b2b16cf78394..433d6c852372 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/tests/test_linkrunner.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/tests/test_linkrunner.py
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patch
import requests
from parameterized import parameterized
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import boundary_checkpoint
from products.warehouse_sources.backend.temporal.data_imports.sources.linkrunner import linkrunner
from products.warehouse_sources.backend.temporal.data_imports.sources.linkrunner.linkrunner import (
LinkrunnerRateLimitError,
@@ -146,6 +147,7 @@ class TestAttributedUsersFanOut:
def test_advances_bookmark_between_campaigns(self, monkeypatch: Any) -> None:
manager = _FakeResumableManager()
+ monkeypatch.setattr(boundary_checkpoint, "PARTIAL_FLUSH_INTERVAL_SECONDS", 0)
_collect(manager, "attributed_users", monkeypatch, self._responses_two_campaigns())
# After finishing C1 the bookmark must point at C2 so a crash resumes at the next campaign, not the first.
assert LinkrunnerResumeConfig(page=1, campaign_display_id="C2") in manager.saved
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py
index 132a4183d545..23a0ea15d1e1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py
@@ -192,7 +192,25 @@ class _ByteBudget:
return self._in_flight
-def _async_iter_to_sync(async_iter, max_items: int = _QUEUE_MAX_ITEMS, max_bytes: int = _QUEUE_MAX_BYTES):
+@frozen
+class _ResumePoint:
+ """The state that reads again the rows that follow it in the stream.
+
+ The producer thread reads ahead of the pipeline, so it must not save resume state itself: the
+ pipeline would commit a state for rows that are still in the queue. The producer puts the state
+ in the stream, and the consumer saves it when it reaches that position.
+ """
+
+ state: TemporalIOResumeConfig
+
+
+def _async_iter_to_sync(
+ async_iter,
+ max_items: int = _QUEUE_MAX_ITEMS,
+ max_bytes: int = _QUEUE_MAX_BYTES,
+ *,
+ save_resume_state: Callable[[TemporalIOResumeConfig], None] | None = None,
+):
q: Queue[tuple[Any, int]] = Queue(maxsize=max_items)
budget = _ByteBudget(max_bytes)
sentinel = object()
@@ -204,7 +222,7 @@ def _async_iter_to_sync(async_iter, max_items: int = _QUEUE_MAX_ITEMS, max_bytes
async def runner():
try:
async for item in async_iter:
- size = _estimate_size_bytes(item)
+ size = len(item.state.next_page_token) if isinstance(item, _ResumePoint) else _estimate_size_bytes(item)
budget.reserve(size)
q.put((item, size))
# The runner lives on a daemon thread, so an uncaught exception would
@@ -228,6 +246,12 @@ def _async_iter_to_sync(async_iter, max_items: int = _QUEUE_MAX_ITEMS, max_bytes
if isinstance(item, _Error):
q.task_done()
raise item.exc
+ if isinstance(item, _ResumePoint):
+ budget.release(size)
+ q.task_done()
+ if save_resume_state is not None:
+ save_resume_state(item.state)
+ continue
try:
yield item
@@ -327,8 +351,8 @@ async def _get_workflows(
page_count = 0
total_count = 0
while True:
- # Save the token that will be used to fetch this page *before* fetching.
- # On resume we re-fetch this same page — duplicates are safe thanks to primary keys.
+ # Keep the token that fetches this page. It goes into the stream before the rows of the page,
+ # so a resume fetches this same page again. Duplicates are safe thanks to primary keys.
pre_fetch_token = workflows.next_page_token
await _with_transient_rpc_retry(workflows.fetch_next_page, logger)
page = workflows.current_page
@@ -337,10 +361,8 @@ async def _get_workflows(
page_count += 1
if pre_fetch_token:
- resumable_source_manager.save_state(
- TemporalIOResumeConfig(next_page_token=_encode_page_token(pre_fetch_token))
- )
- logger.debug(f"TemporalIO: saved resume state at page {page_count} ({total_count} total workflows)")
+ yield _ResumePoint(state=TemporalIOResumeConfig(next_page_token=_encode_page_token(pre_fetch_token)))
+ logger.debug(f"TemporalIO: queued resume state at page {page_count} ({total_count} total workflows)")
for item in page:
yield _sanitize(item.__dict__)
@@ -379,8 +401,8 @@ async def _get_workflow_histories(
page_count = 0
workflow_count = 0
while True:
- # Save the token that will be used to fetch this page *before* fetching.
- # On resume we re-fetch this same page — duplicates are safe thanks to primary keys.
+ # Keep the token that fetches this page. It goes into the stream before the rows of the page,
+ # so a resume fetches this same page again. Duplicates are safe thanks to primary keys.
pre_fetch_token = workflows.next_page_token
await _with_transient_rpc_retry(workflows.fetch_next_page, logger)
page = workflows.current_page
@@ -389,11 +411,9 @@ async def _get_workflow_histories(
page_count += 1
if pre_fetch_token:
- resumable_source_manager.save_state(
- TemporalIOResumeConfig(next_page_token=_encode_page_token(pre_fetch_token))
- )
+ yield _ResumePoint(state=TemporalIOResumeConfig(next_page_token=_encode_page_token(pre_fetch_token)))
logger.debug(
- f"TemporalIO: saved resume state at page {page_count} ({workflow_count} total workflow histories)"
+ f"TemporalIO: queued resume state at page {page_count} ({workflow_count} total workflow histories)"
)
for item in page:
@@ -444,7 +464,9 @@ def temporalio_source(
team_id,
)
- workflows = _async_iter_to_sync(asyncio.run(get_workflows_iterator()))
+ workflows = _async_iter_to_sync(
+ asyncio.run(get_workflows_iterator()), save_resume_state=resumable_source_manager.save_state
+ )
return SourceResponse(
name=resource.value,
@@ -469,7 +491,9 @@ def temporalio_source(
team_id,
)
- workflows = _async_iter_to_sync(asyncio.run(get_histories_iterator()))
+ workflows = _async_iter_to_sync(
+ asyncio.run(get_histories_iterator()), save_resume_state=resumable_source_manager.save_state
+ )
return SourceResponse(
name=resource.value,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py
index 5b0bebfddbc5..ea80dbf31d77 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py
@@ -16,10 +16,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.temporalio.source import TemporalIOSource
from products.warehouse_sources.backend.temporal.data_imports.sources.temporalio.temporalio import (
FakeSettings,
+ TemporalIOResumeConfig,
_async_iter_to_sync,
_ByteBudget,
_estimate_size_bytes,
_get_temporal_client,
+ _ResumePoint,
_with_transient_rpc_retry,
)
@@ -235,3 +237,20 @@ class TestAsyncIterToSync:
assert list(_async_iter_to_sync(self._aiter(items), max_bytes=100_000)) == items
assert budgets[0].in_flight_bytes == 0
+
+ def test_resume_points_are_charged_by_their_page_token_size(self):
+ reserved: list[int] = []
+ original_reserve = _ByteBudget.reserve
+
+ def _spy(budget, size):
+ reserved.append(size)
+ original_reserve(budget, size)
+
+ token = "t" * 1000
+ saved: list[TemporalIOResumeConfig] = []
+ items = [_ResumePoint(state=TemporalIOResumeConfig(next_page_token=token)), {"id": 1}]
+ with patch.object(_ByteBudget, "reserve", _spy):
+ assert list(_async_iter_to_sync(self._aiter(items), save_resume_state=saved.append)) == [{"id": 1}]
+
+ assert reserved[0] == len(token)
+ assert [state.next_page_token for state in saved] == [token]