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(square): restart pagination when Square expires the cursor (#64704)

Tom Owers21945bd6a634
diff --git a/posthog/temporal/data_imports/sources/square/square.py b/posthog/temporal/data_imports/sources/square/square.py
index afca56df66de..731118c3e68c 100644
--- a/posthog/temporal/data_imports/sources/square/square.py
+++ b/posthog/temporal/data_imports/sources/square/square.py
@@ -30,6 +30,23 @@ class SquareRetryableError(Exception):
pass
+class SquareInvalidCursorError(Exception):
+ pass
+
+
+def _is_invalid_cursor_error(response: requests.Response) -> bool:
+ """A 400 whose error payload points at the pagination cursor. Square cursors
+ have a ~5 minute lifetime, so a resumed or slowly-paginated cursor can expire
+ mid-stream and Square then rejects it as invalid/incompatible."""
+ if response.status_code != 400:
+ return False
+ try:
+ errors = response.json().get("errors") or []
+ except ValueError:
+ return False
+ return any(error.get("field") == "cursor" or error.get("code") == "INVALID_CURSOR" for error in errors)
+
+
@dataclasses.dataclass
class SquareResumeConfig:
# The next-page pagination cursor returned by Square. Square cursors expire
@@ -139,17 +156,39 @@ def get_rows(
if response.status_code == 429 or response.status_code >= 500:
raise SquareRetryableError(f"Square API error (retryable): status={response.status_code}, url={url}")
+ if _is_invalid_cursor_error(response):
+ raise SquareInvalidCursorError(f"Square rejected the pagination cursor for {endpoint}")
+
if not response.ok:
logger.error(f"Square API error: status={response.status_code}, body={response.text}, url={url}")
response.raise_for_status()
return response.json()
+ restarted_after_invalid_cursor = False
while True:
# Square encodes the original query in the cursor, so subsequent pages are
# requested with the cursor alone — re-sending filters/sort can error.
params = {"cursor": cursor} if cursor else initial_params
- data = fetch_page(params)
+ try:
+ 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:
+ raise
+ logger.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),
+ # the expired cursor lingers until its TTL and every later sync re-scans
+ # the whole stream. An empty cursor is falsy, so the next load resumes
+ # from the start rather than replaying the bad value.
+ if config.paginated:
+ resumable_source_manager.save_state(SquareResumeConfig(cursor=""))
+ cursor = None
+ restarted_after_invalid_cursor = True
+ continue
items = data.get(config.data_key, [])
next_cursor = data.get("cursor")
diff --git a/posthog/temporal/data_imports/sources/square/test_square.py b/posthog/temporal/data_imports/sources/square/test_square.py
index 522a5438a955..aaab5b0bb88d 100644
--- a/posthog/temporal/data_imports/sources/square/test_square.py
+++ b/posthog/temporal/data_imports/sources/square/test_square.py
@@ -2,6 +2,7 @@ import json
from datetime import UTC, date, datetime
from typing import Any
+import pytest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -11,9 +12,11 @@ from posthog.temporal.data_imports.sources.common.resumable import ResumableSour
from posthog.temporal.data_imports.sources.square.settings import SQUARE_ENDPOINTS
from posthog.temporal.data_imports.sources.square.square import (
SQUARE_HOSTS,
+ SquareInvalidCursorError,
SquareResumeConfig,
_build_initial_params,
_format_rfc3339,
+ _is_invalid_cursor_error,
get_rows,
validate_credentials,
)
@@ -112,6 +115,27 @@ class TestBuildInitialParams:
assert key not in params
+class TestIsInvalidCursorError:
+ @parameterized.expand(
+ [
+ ("cursor_field", 400, {"errors": [{"field": "cursor", "code": "INVALID_VALUE"}]}, True),
+ ("invalid_cursor_code", 400, {"errors": [{"code": "INVALID_CURSOR"}]}, True),
+ ("unrelated_400", 400, {"errors": [{"field": "sort_field", "code": "INVALID_VALUE"}]}, False),
+ ("empty_400", 400, {}, False),
+ ("null_errors", 400, {"errors": None}, False),
+ ("not_a_400", 404, {"errors": [{"field": "cursor"}]}, False),
+ ]
+ )
+ def test_detection(self, _name: str, status_code: int, body: dict[str, Any], expected: bool) -> None:
+ assert _is_invalid_cursor_error(_make_response(body, status_code=status_code)) is expected
+
+ def test_non_json_body_is_not_invalid_cursor(self) -> None:
+ resp = Response()
+ resp.status_code = 400
+ resp._content = b"<html>Bad Request</html>"
+ assert _is_invalid_cursor_error(resp) is False
+
+
class TestValidateCredentials:
@parameterized.expand(
[
@@ -224,6 +248,57 @@ class TestGetRowsPagination:
assert len(sent_params) == 1
manager.save_state.assert_not_called()
+ def test_invalid_cursor_restarts_stream_from_beginning(self) -> None:
+ # A resumed cursor that Square has expired (~5 min lifetime) 400s; the stream
+ # should restart from the beginning rather than crash.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SquareResumeConfig(cursor="stale-cursor")
+
+ responses = [
+ _make_response({"errors": [{"field": "cursor", "code": "INVALID_CURSOR"}]}, status_code=400),
+ _make_response({"customers": [{"id": "c1"}], "cursor": "cur-1"}),
+ _make_response({"customers": [{"id": "c2"}]}),
+ ]
+ sent_params = self._drive("customers", manager, responses)
+
+ # First request uses the stale cursor and is rejected; the retry drops the
+ # cursor and re-issues the original query, then pages normally.
+ assert sent_params[0] == {"cursor": "stale-cursor"}
+ assert "cursor" not in sent_params[1]
+ assert sent_params[2] == {"cursor": "cur-1"}
+
+ def test_invalid_cursor_restart_evicts_stale_cursor_within_single_page(self) -> None:
+ # When the restart finishes within a single page there's no fresh next_cursor
+ # to persist, so the restart must explicitly overwrite the stale cursor — else
+ # it would linger until its TTL and force a full re-scan on every later sync.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SquareResumeConfig(cursor="stale-cursor")
+
+ responses = [
+ _make_response({"errors": [{"field": "cursor", "code": "INVALID_CURSOR"}]}, status_code=400),
+ _make_response({"customers": [{"id": "c1"}]}),
+ ]
+ self._drive("customers", manager, responses)
+
+ 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:
+ 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)
+ responses = [
+ invalid,
+ _make_response({"customers": [{"id": "c1"}], "cursor": "cur-1"}),
+ invalid,
+ ]
+ with pytest.raises(SquareInvalidCursorError):
+ self._drive("customers", manager, responses)
+
def test_yields_rows_using_endpoint_data_key(self) -> None:
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False