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): use cursor pagination for zendesk tickets import (#59215)

Tom Owers4484541f5b88
diff --git a/posthog/temporal/data_imports/sources/zendesk/tests/test_zendesk.py b/posthog/temporal/data_imports/sources/zendesk/tests/test_zendesk.py
new file mode 100644
index 000000000000..bf32c8566c21
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/zendesk/tests/test_zendesk.py
@@ -0,0 +1,106 @@
+import json
+from typing import Any
+
+import pytest
+
+from requests import Request, Response
+
+from posthog.temporal.data_imports.sources.zendesk.zendesk import ZendeskTicketsCursorIncrementalPaginator
+
+
+def _make_response(json_body: dict[str, Any] | None = None) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp.headers["Content-Type"] = "application/json"
+ resp._content = json.dumps(json_body or {}).encode()
+ return resp
+
+
+class TestZendeskTicketsCursorIncrementalPaginator:
+ def test_advances_to_next_cursor(self) -> None:
+ p = ZendeskTicketsCursorIncrementalPaginator()
+ resp = _make_response({"tickets": [{"id": 1}], "after_cursor": "abc123", "end_of_stream": False})
+
+ p.update_state(resp)
+
+ assert p.has_next_page is True
+
+ req = Request(method="GET", url="https://x.zendesk.com/api/v2/incremental/tickets/cursor")
+ req.params = {"per_page": 1000, "start_time": 1591394586}
+ p.update_request(req)
+
+ assert req.params["cursor"] == "abc123"
+ # The seed start_time is dropped once we paginate by cursor.
+ assert "start_time" not in req.params
+ assert req.params["per_page"] == 1000
+
+ def test_first_request_keeps_seed_start_time(self) -> None:
+ p = ZendeskTicketsCursorIncrementalPaginator()
+
+ # Before any response, has_next_page is True and no cursor is set, so the
+ # first request must go out untouched (with its seed start_time).
+ assert p.has_next_page is True
+
+ req = Request(method="GET", url="https://x.zendesk.com/api/v2/incremental/tickets/cursor")
+ req.params = {"per_page": 1000, "start_time": 1591394586}
+ p.init_request(req)
+
+ assert req.params["start_time"] == 1591394586
+ assert "cursor" not in req.params
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ pytest.param({"tickets": [], "after_cursor": "abc123", "end_of_stream": True}, id="end_of_stream"),
+ pytest.param({}, id="empty_response"),
+ ],
+ )
+ def test_stops_pagination(self, body: dict[str, Any]) -> None:
+ p = ZendeskTicketsCursorIncrementalPaginator()
+
+ p.update_state(_make_response(body))
+
+ assert p.has_next_page is False
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ pytest.param({"tickets": [{"id": 1}], "after_cursor": None, "end_of_stream": False}, id="missing_cursor"),
+ pytest.param({"tickets": [{"id": 1}], "after_cursor": "abc123"}, id="missing_end_of_stream"),
+ ],
+ )
+ def test_raises_on_invalid_response(self, body: dict[str, Any]) -> None:
+ p = ZendeskTicketsCursorIncrementalPaginator()
+
+ with pytest.raises(ValueError):
+ p.update_state(_make_response(body))
+
+ def test_raises_when_cursor_does_not_advance(self) -> None:
+ """A cursor that never moves while end_of_stream is False is the time-based
+ export's failure mode; fail loud so the activity retries instead of
+ silently truncating data."""
+ p = ZendeskTicketsCursorIncrementalPaginator()
+
+ first = _make_response({"tickets": [{"id": 1}], "after_cursor": "abc123", "end_of_stream": False})
+ p.update_state(first)
+ assert p.has_next_page is True
+
+ repeated = _make_response({"tickets": [{"id": 1}], "after_cursor": "abc123", "end_of_stream": False})
+ with pytest.raises(ValueError):
+ p.update_state(repeated)
+
+ def test_paginates_across_multiple_pages(self) -> None:
+ p = ZendeskTicketsCursorIncrementalPaginator()
+ req = Request(method="GET", url="https://x.zendesk.com/api/v2/incremental/tickets/cursor")
+ req.params = {"per_page": 1000, "start_time": 1591394586}
+
+ p.update_state(_make_response({"tickets": [{"id": 1}], "after_cursor": "cursor_1", "end_of_stream": False}))
+ p.update_request(req)
+ assert req.params["cursor"] == "cursor_1"
+
+ p.update_state(_make_response({"tickets": [{"id": 2}], "after_cursor": "cursor_2", "end_of_stream": False}))
+ p.update_request(req)
+ assert req.params["cursor"] == "cursor_2"
+
+ p.update_state(_make_response({"tickets": [{"id": 3}], "after_cursor": "cursor_3", "end_of_stream": True}))
+ assert p.has_next_page is False
diff --git a/posthog/temporal/data_imports/sources/zendesk/zendesk.py b/posthog/temporal/data_imports/sources/zendesk/zendesk.py
index c20d940ab956..7133bda49c5a 100644
--- a/posthog/temporal/data_imports/sources/zendesk/zendesk.py
+++ b/posthog/temporal/data_imports/sources/zendesk/zendesk.py
@@ -180,8 +180,13 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResou
"columns": get_dlt_mapping_for_external_table("zendesk_tickets"),
"endpoint": {
"data_selector": "tickets",
- "path": "/api/v2/incremental/tickets",
- "paginator": ZendeskTicketsIncrementalEndpointPaginator(),
+ # Cursor-based incremental export. The time-based export
+ # (`/api/v2/incremental/tickets`) deadlocks when >1000 tickets
+ # share a `generated_timestamp`: the page never advances past
+ # that timestamp, so pagination loops forever re-fetching the
+ # same boundary page. Cursor pagination is immune to this.
+ "path": "/api/v2/incremental/tickets/cursor",
+ "paginator": ZendeskTicketsCursorIncrementalPaginator(),
"params": {
"per_page": 1000,
"start_time": {
@@ -226,29 +231,53 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResou
return resources[name]
-class ZendeskTicketsIncrementalEndpointPaginator(BasePaginator):
+class ZendeskTicketsCursorIncrementalPaginator(BasePaginator):
+ """Cursor-based pagination for Zendesk's incremental tickets export.
+
+ The first request is seeded with `start_time` (resolved from the incremental
+ cursor); every subsequent request follows the opaque `after_cursor` token.
+ Unlike the time-based export, the cursor encodes the stream position rather
+ than a timestamp, so it can't get pinned when many tickets share a
+ `generated_timestamp`.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._after_cursor: Optional[str] = None
+
def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
res = response.json()
- self._next_start_time = None
-
if not res:
self._has_next_page = False
return
- if not res["end_of_stream"]:
- self._has_next_page = True
+ if "end_of_stream" not in res:
+ raise ValueError("Zendesk cursor export response is missing 'end_of_stream'")
- last_value_in_response = res["tickets"][-1]["generated_timestamp"]
- self._next_start_time = last_value_in_response
- else:
+ if res["end_of_stream"]:
self._has_next_page = False
+ return
+
+ # `end_of_stream` is False, so the stream continues and a valid, advancing
+ # `after_cursor` must be present. A missing or non-advancing cursor is an
+ # invalid/partial response — raise so the activity retries instead of
+ # committing truncated data as a successful sync.
+ after_cursor = res.get("after_cursor")
+ if not after_cursor or after_cursor == self._after_cursor:
+ raise ValueError("Zendesk cursor export returned end_of_stream=False without an advancing after_cursor")
+
+ self._after_cursor = after_cursor
+ self._has_next_page = True
def update_request(self, request: Request) -> None:
if request.params is None:
request.params = {}
- request.params["start_time"] = self._next_start_time
+ # After the first page we paginate purely by cursor; drop the seed
+ # `start_time` so it doesn't conflict with the `cursor` param.
+ request.params.pop("start_time", None)
+ request.params["cursor"] = self._after_cursor
class ZendeskIncrementalEndpointPaginator(BasePaginator):