: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
feat(data-warehouse): incremental sync for more zendesk endpoints (#64137)
jake sciotto9f89da16998b
diff --git a/posthog/temporal/data_imports/sources/zendesk/settings.py b/posthog/temporal/data_imports/sources/zendesk/settings.pyindex 4daf1b34983d..a0e5647dd989 100644--- a/posthog/temporal/data_imports/sources/zendesk/settings.py+++ b/posthog/temporal/data_imports/sources/zendesk/settings.py@@ -13,7 +13,23 @@ CUSTOM_FIELDS_STATE_KEY = "ticket_custom_fields_v2"# Resources that will always get pulledBASE_ENDPOINTS = ["ticket_fields", "ticket_events", "tickets", "ticket_metric_events"]-INCREMENTAL_ENDPOINTS = ["tickets"]++# Endpoints backed by a Zendesk Incremental Export API, so incremental sync actually+# reduces the data fetched (the `start_time` cursor is filtered server-side) rather than+# only changing the write disposition. Endpoints without an incremental export+# (brands, groups, sla_policies, ticket_fields) stay full-refresh on purpose.+INCREMENTAL_ENDPOINTS = ["tickets", "users", "organizations", "ticket_events", "ticket_metric_events"]+++def _datetime_incremental_field(field: str) -> IncrementalField:+ return {+ "label": field,+ "type": IncrementalFieldType.DateTime,+ "field": field,+ "field_type": IncrementalFieldType.DateTime,+ }++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {"tickets": [{@@ -23,6 +39,14 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {"field_type": IncrementalFieldType.Integer,}],+ # The incremental exports for these resources order by the per-record timestamp below.+ # Zendesk recommends using the response `end_time` as the next `start_time`; using the+ # row-level field is safe because re-fetched boundary rows are upserted by `id`, never+ # skipped.+ "users": [_datetime_incremental_field("updated_at")],+ "organizations": [_datetime_incremental_field("updated_at")],+ "ticket_events": [_datetime_incremental_field("created_at")],+ "ticket_metric_events": [_datetime_incremental_field("time")],}# CLUDGE: refactor this to EndpointConfig like in tiktok_ads/settings.pydiff --git a/posthog/temporal/data_imports/sources/zendesk/tests/test_zendesk.py b/posthog/temporal/data_imports/sources/zendesk/tests/test_zendesk.pyindex 2cda1c0106ab..1ec4811c954f 100644--- a/posthog/temporal/data_imports/sources/zendesk/tests/test_zendesk.py+++ b/posthog/temporal/data_imports/sources/zendesk/tests/test_zendesk.py@@ -1,5 +1,6 @@import json-from typing import Any+from datetime import UTC, datetime+from typing import Any, castimport pytestfrom unittest.mock import patch@@ -7,10 +8,14 @@ from unittest.mock import patchfrom requests import Request, Responsefrom posthog.temporal.data_imports.sources.generated_configs import ZendeskSourceConfig+from posthog.temporal.data_imports.sources.zendesk.settings import INCREMENTAL_ENDPOINTS, INCREMENTAL_FIELDSfrom posthog.temporal.data_imports.sources.zendesk.source import ZendeskSourcefrom posthog.temporal.data_imports.sources.zendesk.zendesk import (- ZendeskTicketsCursorIncrementalPaginator,+ ZendeskCursorIncrementalPaginator,+ ZendeskIncrementalEndpointPaginator,+ get_resource,normalize_subdomain,+ to_zendesk_start_time,)@@ -22,6 +27,11 @@ def _make_response(json_body: dict[str, Any] | None = None) -> Response:return resp+def _endpoint(resource: Any) -> dict[str, Any]:+ # resource["endpoint"] is typed Optional[str | Endpoint]; narrow it for key access.+ return cast(dict[str, Any], resource["endpoint"])++class TestZendeskValidateCredentials:def _config(self) -> ZendeskSourceConfig:return ZendeskSourceConfig(subdomain="nibbles", api_key="token", email_address="[email protected]")@@ -64,9 +74,9 @@ class TestNormalizeSubdomain:assert f"https://{normalize_subdomain('nibbles.zendesk.com')}.zendesk.com/" == "https://nibbles.zendesk.com/"-class TestZendeskTicketsCursorIncrementalPaginator:+class TestZendeskCursorIncrementalPaginator:def test_advances_to_next_cursor(self) -> None:- p = ZendeskTicketsCursorIncrementalPaginator()+ p = ZendeskCursorIncrementalPaginator()resp = _make_response({"tickets": [{"id": 1}], "after_cursor": "abc123", "end_of_stream": False})p.update_state(resp)@@ -83,7 +93,7 @@ class TestZendeskTicketsCursorIncrementalPaginator:assert req.params["per_page"] == 1000def test_first_request_keeps_seed_start_time(self) -> None:- p = ZendeskTicketsCursorIncrementalPaginator()+ p = ZendeskCursorIncrementalPaginator()# 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).@@ -96,6 +106,20 @@ class TestZendeskTicketsCursorIncrementalPaginator:assert req.params["start_time"] == 1591394586assert "cursor" not in req.params+ def test_works_for_any_data_key(self) -> None:+ # The paginator only reads top-level after_cursor/end_of_stream, so the users+ # cursor export (data key "users") paginates identically to tickets.+ p = ZendeskCursorIncrementalPaginator()+ p.update_state(_make_response({"users": [{"id": 1}], "after_cursor": "u1", "end_of_stream": False}))+ assert p.has_next_page is True++ req = Request(method="GET", url="https://x.zendesk.com/api/v2/incremental/users/cursor")+ req.params = {"per_page": 1000, "start_time": 0}+ p.update_request(req)+ assert req.params["cursor"] == "u1"+ # The seed start_time must be dropped once we paginate by cursor, same as tickets.+ assert "start_time" not in req.params+@pytest.mark.parametrize("body",[@@ -104,7 +128,7 @@ class TestZendeskTicketsCursorIncrementalPaginator:],)def test_stops_pagination(self, body: dict[str, Any]) -> None:- p = ZendeskTicketsCursorIncrementalPaginator()+ p = ZendeskCursorIncrementalPaginator()p.update_state(_make_response(body))@@ -118,7 +142,7 @@ class TestZendeskTicketsCursorIncrementalPaginator:],)def test_raises_on_invalid_response(self, body: dict[str, Any]) -> None:- p = ZendeskTicketsCursorIncrementalPaginator()+ p = ZendeskCursorIncrementalPaginator()with pytest.raises(ValueError):p.update_state(_make_response(body))@@ -127,7 +151,7 @@ class TestZendeskTicketsCursorIncrementalPaginator:"""A cursor that never moves while end_of_stream is False is the time-basedexport's failure mode; fail loud so the activity retries instead ofsilently truncating data."""- p = ZendeskTicketsCursorIncrementalPaginator()+ p = ZendeskCursorIncrementalPaginator()first = _make_response({"tickets": [{"id": 1}], "after_cursor": "abc123", "end_of_stream": False})p.update_state(first)@@ -138,7 +162,7 @@ class TestZendeskTicketsCursorIncrementalPaginator:p.update_state(repeated)def test_paginates_across_multiple_pages(self) -> None:- p = ZendeskTicketsCursorIncrementalPaginator()+ p = ZendeskCursorIncrementalPaginator()req = Request(method="GET", url="https://x.zendesk.com/api/v2/incremental/tickets/cursor")req.params = {"per_page": 1000, "start_time": 1591394586}@@ -152,3 +176,127 @@ class TestZendeskTicketsCursorIncrementalPaginator:p.update_state(_make_response({"tickets": [{"id": 3}], "after_cursor": "cursor_3", "end_of_stream": True}))assert p.has_next_page is False+++class TestZendeskIncrementalEndpointPaginator:+ def test_advances_to_next_page(self) -> None:+ p = ZendeskIncrementalEndpointPaginator()+ p.update_state(_make_response({"end_of_stream": False, "next_page": "https://x.zendesk.com/next"}))++ assert p.has_next_page is True++ req = Request(method="GET", url="https://x.zendesk.com/api/v2/incremental/organizations")+ req.params = {"per_page": 1000, "start_time": 0}+ p.update_request(req)+ assert req.url == "https://x.zendesk.com/next"+ # next_page is a full URL carrying its own query string, so existing params are cleared.+ assert req.params == {}++ @pytest.mark.parametrize(+ "body",+ [+ pytest.param({"end_of_stream": True, "next_page": None}, id="end_of_stream"),+ pytest.param({}, id="empty_response"),+ ],+ )+ def test_stops_pagination(self, body: dict[str, Any]) -> None:+ p = ZendeskIncrementalEndpointPaginator()++ p.update_state(_make_response(body))++ assert p.has_next_page is False++ @pytest.mark.parametrize(+ "body",+ [+ pytest.param({"organizations": [{"id": 1}]}, id="missing_end_of_stream"),+ pytest.param({"end_of_stream": False, "next_page": None}, id="missing_next_page"),+ ],+ )+ def test_raises_on_invalid_response(self, body: dict[str, Any]) -> None:+ # organizations now routes through this paginator, so a malformed time-based export+ # response must fail loud (retryable) rather than raise an uncaught KeyError.+ p = ZendeskIncrementalEndpointPaginator()++ with pytest.raises(ValueError):+ p.update_state(_make_response(body))+++class TestToZendeskStartTime:+ @pytest.mark.parametrize(+ "value,expected",+ [+ pytest.param(0, 0, id="initial_value_zero"),+ pytest.param(1591394586, 1591394586, id="passthrough_int"),+ pytest.param(datetime(2020, 6, 5, 21, 23, 6, tzinfo=UTC), 1591392186, id="aware_datetime"),+ # Naive datetimes are interpreted as UTC.+ pytest.param(datetime(2020, 6, 5, 21, 23, 6), 1591392186, id="naive_datetime_as_utc"),+ ],+ )+ def test_converts_to_unix_epoch(self, value: Any, expected: int) -> None:+ assert to_zendesk_start_time(value) == expected+++class TestIncrementalResourceWiring:+ """The four endpoints that have a Zendesk Incremental Export API must declare a server-side+ `start_time` cursor so incremental sync actually filters data, not just flips write disposition."""++ @pytest.mark.parametrize(+ "endpoint,expected_path,expected_paginator,cursor_path",+ [+ pytest.param(+ "users", "/api/v2/incremental/users/cursor", ZendeskCursorIncrementalPaginator, "updated_at", id="users"+ ),+ pytest.param(+ "organizations",+ "/api/v2/incremental/organizations",+ ZendeskIncrementalEndpointPaginator,+ "updated_at",+ id="organizations",+ ),+ pytest.param(+ "ticket_events",+ "/api/v2/incremental/ticket_events",+ ZendeskIncrementalEndpointPaginator,+ "created_at",+ id="ticket_events",+ ),+ pytest.param(+ "ticket_metric_events",+ "/api/v2/incremental/ticket_metric_events",+ ZendeskIncrementalEndpointPaginator,+ "time",+ id="ticket_metric_events",+ ),+ ],+ )+ def test_endpoint_declares_incremental_start_time(+ self, endpoint: str, expected_path: str, expected_paginator: type, cursor_path: str+ ) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=True)+ endpoint_config = _endpoint(resource)++ assert endpoint_config["path"] == expected_path+ assert isinstance(endpoint_config["paginator"], expected_paginator)++ start_time = endpoint_config["params"]["start_time"]+ assert start_time["type"] == "incremental"+ assert start_time["cursor_path"] == cursor_path+ assert start_time["initial_value"] == 0+ # Datetime cursors must convert to the Unix epoch Zendesk expects.+ assert start_time["convert"] is to_zendesk_start_time++ @pytest.mark.parametrize("endpoint", ["users", "organizations", "ticket_events", "ticket_metric_events"])+ def test_write_disposition_follows_incremental_flag(self, endpoint: str) -> None:+ incremental = get_resource(endpoint, should_use_incremental_field=True)+ full_refresh = get_resource(endpoint, should_use_incremental_field=False)++ assert incremental["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ assert full_refresh["write_disposition"] == "replace"++ def test_incremental_fields_cover_incremental_endpoints(self) -> None:+ # Every endpoint advertised as incremental must declare its incremental field(s).+ for endpoint in INCREMENTAL_ENDPOINTS:+ assert INCREMENTAL_FIELDS.get(endpoint), (+ f"{endpoint} is in INCREMENTAL_ENDPOINTS but has no incremental field"+ )diff --git a/posthog/temporal/data_imports/sources/zendesk/zendesk.py b/posthog/temporal/data_imports/sources/zendesk/zendesk.pyindex 294c7cc68f78..cb26ff08fb93 100644--- a/posthog/temporal/data_imports/sources/zendesk/zendesk.py+++ b/posthog/temporal/data_imports/sources/zendesk/zendesk.py@@ -1,5 +1,6 @@import reimport base64+from datetime import UTC, datetimefrom typing import Any, Optionalfrom requests import Request, Response@@ -12,6 +13,16 @@ from posthog.temporal.data_imports.sources.common.rest_source.typing import Endpfrom products.warehouse_sources.backend.models.external_table_definitions import get_dlt_mapping_for_external_table+def to_zendesk_start_time(value: Any) -> int:+ """Convert an incremental cursor value to the Unix epoch seconds Zendesk's incremental+ export `start_time` expects. Applied to both the persisted last value (a `datetime` for+ DateTime incremental fields) and the `initial_value` (0) on the first run / full refresh."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return int(dt.timestamp())+ return int(value)++def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:resources: dict[str, EndpointResource] = {"brands": {@@ -46,10 +57,17 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResou"columns": get_dlt_mapping_for_external_table("zendesk_organizations"),"endpoint": {"data_selector": "organizations",- "path": "/api/v2/organizations",- "paginator": JSONLinkPaginator(next_url_path="links.next"),+ # Time-based incremental export (no cursor variant exists for organizations).+ "path": "/api/v2/incremental/organizations",+ "paginator": ZendeskIncrementalEndpointPaginator(),"params": {- "page[size]": 100,+ "per_page": 1000,+ "start_time": {+ "type": "incremental",+ "cursor_path": "updated_at",+ "initial_value": 0,+ "convert": to_zendesk_start_time,+ },},},"table_format": "delta",@@ -105,15 +123,17 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResou"columns": get_dlt_mapping_for_external_table("zendesk_users"),"endpoint": {"data_selector": "users",- "path": "/api/v2/users",- "paginator": JSONLinkPaginator(next_url_path="links.next"),+ # Cursor-based incremental export (recommended over the time-based variant).+ "path": "/api/v2/incremental/users/cursor",+ "paginator": ZendeskCursorIncrementalPaginator(),"params": {- # the parameters below can optionally be configured- # "role": "OPTIONAL_CONFIG",- # "role[]": "OPTIONAL_CONFIG",- # "permission_set": "OPTIONAL_CONFIG",- # "external_id": "OPTIONAL_CONFIG",- "page[size]": 100,+ "per_page": 1000,+ "start_time": {+ "type": "incremental",+ "cursor_path": "updated_at",+ "initial_value": 0,+ "convert": to_zendesk_start_time,+ },},},"table_format": "delta",@@ -153,18 +173,16 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResou"columns": get_dlt_mapping_for_external_table("zendesk_ticket_events"),"endpoint": {"data_selector": "ticket_events",- "path": "/api/v2/incremental/ticket_events?start_time=0",+ "path": "/api/v2/incremental/ticket_events","paginator": ZendeskIncrementalEndpointPaginator(),"params": {"per_page": 1000,- # Having to use `start_time` in the initial path until incrementality works- # "start_time": 0,- # Incrementality is disabled as we can't access end_time on the root object- # "start_time": {- # "type": "incremental",- # "cursor_path": "end_time",- # "initial_value": 0,- # },+ "start_time": {+ "type": "incremental",+ "cursor_path": "created_at",+ "initial_value": 0,+ "convert": to_zendesk_start_time,+ },},},"table_format": "delta",@@ -187,7 +205,7 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResou# 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(),+ "paginator": ZendeskCursorIncrementalPaginator(),"params": {"per_page": 1000,"start_time": {@@ -211,18 +229,16 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResou"columns": get_dlt_mapping_for_external_table("zendesk_ticket_metric_events"),"endpoint": {"data_selector": "ticket_metric_events",- "path": "/api/v2/incremental/ticket_metric_events?start_time=0",+ "path": "/api/v2/incremental/ticket_metric_events","paginator": ZendeskIncrementalEndpointPaginator(),"params": {"per_page": 1000,- # Having to use `start_time` in the initial path until incrementality works- # "start_time": 0,- # Incrementality is disabled as we can't access end_time on the root object- # "start_time": {- # "type": "incremental",- # "cursor_path": "end_time",- # "initial_value": 0,- # },+ "start_time": {+ "type": "incremental",+ "cursor_path": "time",+ "initial_value": 0,+ "convert": to_zendesk_start_time,+ },},},"table_format": "delta",@@ -232,14 +248,15 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResoureturn resources[name]-class ZendeskTicketsCursorIncrementalPaginator(BasePaginator):- """Cursor-based pagination for Zendesk's incremental tickets export.+class ZendeskCursorIncrementalPaginator(BasePaginator):+ """Cursor-based pagination for Zendesk's cursor incremental exports (tickets, users).The first request is seeded with `start_time` (resolved from the incrementalcursor); 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`.+ than a timestamp, so it can't get pinned when many records share a timestamp.+ Only the top-level `after_cursor`/`end_of_stream` fields are read, so this works+ for any cursor incremental export regardless of the resource's data key."""def __init__(self) -> None:@@ -291,12 +308,22 @@ class ZendeskIncrementalEndpointPaginator(BasePaginator):self._has_next_page = Falsereturn- if not res["end_of_stream"]:- self._has_next_page = True+ if "end_of_stream" not in res:+ raise ValueError("Zendesk incremental export response is missing 'end_of_stream'")- self._next_page = res["next_page"]- else:+ if res["end_of_stream"]:self._has_next_page = False+ return++ # `end_of_stream` is False, so the stream continues and `next_page` must be+ # present. A missing `next_page` is an invalid/partial response — raise so the+ # activity retries instead of committing truncated data as a successful sync.+ next_page = res.get("next_page")+ if not next_page:+ raise ValueError("Zendesk incremental export returned end_of_stream=False without a next_page")++ self._next_page = next_page+ self._has_next_page = Truedef update_request(self, request: Request) -> None:request.url = self._next_page