: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(square): tolerate repeated cursor expiry on full-refresh streams (#64753)
Tom Owers2e8ef813aad2
diff --git a/posthog/temporal/data_imports/sources/square/square.py b/posthog/temporal/data_imports/sources/square/square.pyindex 731118c3e68c..7ddde97c34f7 100644--- a/posthog/temporal/data_imports/sources/square/square.py+++ b/posthog/temporal/data_imports/sources/square/square.py@@ -25,6 +25,11 @@ SQUARE_HOSTS = {PAGE_SIZE = 100REQUEST_TIMEOUT_SECONDS = 60+# A Square cursor that outlives its ~5 minute TTL mid-stream forces a full restart.+# Allow a few restarts so a transient stall during the re-scan doesn't fail the sync,+# while still bounding the work for a stream that paginates slower than its cursor lives.+MAX_CURSOR_RESTARTS = 3+class SquareRetryableError(Exception):pass@@ -165,7 +170,7 @@ def get_rows(return response.json()- restarted_after_invalid_cursor = False+ restarts_remaining = MAX_CURSOR_RESTARTSwhile True:# Square encodes the original query in the cursor, so subsequent pages are# requested with the cursor alone — re-sending filters/sort can error.@@ -174,10 +179,13 @@ def get_rows(data = fetch_page(params)except SquareInvalidCursorError:# An expired cursor can't be recovered by retrying it, so restart the- # stream from the beginning (merge dedupes on the primary key). Bounded- # to a single restart so a genuinely malformed query can't loop forever.- if cursor is None or restarted_after_invalid_cursor:+ # stream from the beginning (merge dedupes on the primary key). A cursor-less+ # initial request can't trigger this error, so a rejection there signals a+ # malformed query rather than expiry — surface it instead of looping. The+ # restart budget bounds the work when a stream keeps outliving its cursor.+ if cursor is None or restarts_remaining <= 0:raise+ restarts_remaining -= 1logger.warning(f"Square: cursor for {endpoint} was rejected, restarting stream from the beginning")# Overwrite the stale cursor in the resume store now. Otherwise, if the# restart finishes within a single page (no fresh next_cursor to save),@@ -187,7 +195,6 @@ def get_rows(if config.paginated:resumable_source_manager.save_state(SquareResumeConfig(cursor=""))cursor = None- restarted_after_invalid_cursor = Truecontinueitems = data.get(config.data_key, [])diff --git a/posthog/temporal/data_imports/sources/square/test_square.py b/posthog/temporal/data_imports/sources/square/test_square.pyindex aaab5b0bb88d..32a039e3a223 100644--- a/posthog/temporal/data_imports/sources/square/test_square.py+++ b/posthog/temporal/data_imports/sources/square/test_square.py@@ -11,6 +11,7 @@ from requests import Responsefrom posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom posthog.temporal.data_imports.sources.square.settings import SQUARE_ENDPOINTSfrom posthog.temporal.data_imports.sources.square.square import (+ MAX_CURSOR_RESTARTS,SQUARE_HOSTS,SquareInvalidCursorError,SquareResumeConfig,@@ -285,7 +286,10 @@ class TestGetRowsPagination:saved = [call.args[0] for call in manager.save_state.call_args_list]assert saved == [SquareResumeConfig(cursor="")]- def test_invalid_cursor_only_restarts_once(self) -> None:+ def test_invalid_cursor_restarts_again_when_re_scan_also_expires(self) -> None:+ # A cursor can expire more than once on a slow full-refresh stream: the first+ # restart re-scans, makes progress, then a later cursor expires too. As long as+ # the restart budget isn't spent, the stream restarts again rather than crashing.manager = MagicMock(spec=ResumableSourceManager)manager.can_resume.return_value = Truemanager.load_state.return_value = SquareResumeConfig(cursor="stale-cursor")@@ -295,7 +299,28 @@ class TestGetRowsPagination:invalid,_make_response({"customers": [{"id": "c1"}], "cursor": "cur-1"}),invalid,+ _make_response({"customers": [{"id": "c2"}]}),]+ sent_params = self._drive("customers", manager, responses)++ # stale cursor rejected -> restart -> page (cur-1) -> cur-1 rejected -> restart -> final page.+ assert sent_params[0] == {"cursor": "stale-cursor"}+ assert "cursor" not in sent_params[1]+ assert sent_params[2] == {"cursor": "cur-1"}+ assert "cursor" not in sent_params[3]++ def test_invalid_cursor_gives_up_after_restart_budget_exhausted(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = SquareResumeConfig(cursor="stale-cursor")++ invalid = _make_response({"errors": [{"field": "cursor", "code": "INVALID_CURSOR"}]}, status_code=400)+ # Each restart re-scans one page then expires again; once the budget is spent+ # the next rejection is surfaced.+ responses = [invalid]+ for _ in range(MAX_CURSOR_RESTARTS):+ responses.append(_make_response({"customers": [{"id": "c"}], "cursor": "cur"}))+ responses.append(invalid)with pytest.raises(SquareInvalidCursorError):self._drive("customers", manager, responses)