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.

feat(data-warehouse): enable incremental sync for Gorgias (#64558)

Daniel RC8a75b9452124
diff --git a/posthog/temporal/data_imports/sources/gorgias/gorgias.py b/posthog/temporal/data_imports/sources/gorgias/gorgias.py
index 1e0461ddf565..cffe00627e66 100644
--- a/posthog/temporal/data_imports/sources/gorgias/gorgias.py
+++ b/posthog/temporal/data_imports/sources/gorgias/gorgias.py
@@ -2,7 +2,8 @@ import re
import base64
import dataclasses
from collections.abc import Iterator
-from typing import Any
+from datetime import UTC, date, datetime
+from typing import Any, Optional
import requests
from structlog.types import FilteringBoundLogger
@@ -11,7 +12,7 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from posthog.temporal.data_imports.sources.common.http import make_tracked_session
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from posthog.temporal.data_imports.sources.gorgias.settings import GORGIAS_ENDPOINTS
+from posthog.temporal.data_imports.sources.gorgias.settings import GORGIAS_ENDPOINTS, GorgiasEndpointConfig
# Gorgias caps `limit` at 100 on every list endpoint.
PAGE_SIZE = 100
@@ -59,6 +60,42 @@ def get_base_url(domain: str) -> str:
return f"https://{subdomain}.gorgias.com/api"
+def _coerce_to_utc(value: Any) -> datetime | None:
+ """Best-effort parse of a Gorgias datetime (ISO string) or a DB watermark (datetime)."""
+ if isinstance(value, datetime):
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, str):
+ try:
+ parsed = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+ return None
+
+
+def _page_newest(items: list[Any], field: str) -> datetime | None:
+ """Newest value of `field` across a page; None if nothing parses."""
+ parsed = [dt for item in items if isinstance(item, dict) and (dt := _coerce_to_utc(item.get(field))) is not None]
+ return max(parsed) if parsed else None
+
+
+def _incremental_sort_field(
+ config: GorgiasEndpointConfig, should_use_incremental_field: bool, incremental_field: Optional[str]
+) -> str | None:
+ """The field to sort `<field>:desc` for an incremental sync, or None for full refresh.
+
+ Guards against sending a sort the endpoint does not accept: an `order_by` Gorgias
+ rejects (or silently ignores) would break the newest-first ordering the watermark
+ stop condition relies on, so anything not in `sortable_datetime_fields` falls back
+ to full refresh.
+ """
+ if should_use_incremental_field and incremental_field in config.sortable_datetime_fields:
+ return incremental_field
+ return None
+
+
def _get_auth_header(email: str, api_key: str) -> str:
token = base64.b64encode(f"{email}:{api_key}".encode()).decode()
return f"Basic {token}"
@@ -102,11 +139,21 @@ def get_rows(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[GorgiasResumeConfig],
+ should_use_incremental_field: bool = False,
+ incremental_field: Optional[str] = None,
+ db_incremental_field_last_value: Optional[Any] = None,
) -> Iterator[Any]:
config = GORGIAS_ENDPOINTS[endpoint]
url = f"{get_base_url(domain)}{config.path}"
session = make_tracked_session(headers=get_headers(email, api_key), redact_values=(api_key,))
+ # Gorgias has no server-side time filter. For incremental we sort the chosen field
+ # newest-first and stop paginating once a whole page predates the watermark, so a
+ # steady-state sync only pulls the changed prefix instead of every page.
+ sort_field = _incremental_sort_field(config, should_use_incremental_field, incremental_field)
+ order_by = f"{sort_field}:desc" if sort_field else config.order_by
+ watermark = _coerce_to_utc(db_incremental_field_last_value) if sort_field else None
+
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
cursor = resume_config.cursor if resume_config else None
if cursor:
@@ -121,7 +168,12 @@ def get_rows(
reraise=True,
)
def fetch_page(request_cursor: str | None) -> dict[str, Any]:
- params: dict[str, Any] = {"limit": PAGE_SIZE, "order_by": config.order_by}
+ # `cursor` is documented as "position in the list of resources" — the list is
+ # defined by `order_by`/`limit`, so we re-send them on every page to keep the
+ # sort stable. The docs list `cursor` and `order_by` as coexisting params (no
+ # mutual exclusion); dropping order_by on follow-up pages could reset to the
+ # endpoint default and corrupt the newest-first order incremental relies on.
+ params: dict[str, Any] = {"limit": PAGE_SIZE, "order_by": order_by}
if request_cursor:
params["cursor"] = request_cursor
@@ -144,6 +196,13 @@ def get_rows(
if items:
yield items
+ # Rows arrive newest-first under incremental sort; once an entire page predates the
+ # watermark, everything further back is already synced, so stop.
+ if watermark is not None and sort_field is not None and items:
+ page_newest = _page_newest(items, sort_field)
+ if page_newest is not None and page_newest < watermark:
+ break
+
next_cursor = (data.get("meta") or {}).get("next_cursor")
if not next_cursor:
break
@@ -161,8 +220,12 @@ def gorgias_source(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[GorgiasResumeConfig],
+ should_use_incremental_field: bool = False,
+ incremental_field: Optional[str] = None,
+ db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = GORGIAS_ENDPOINTS[endpoint]
+ incremental = _incremental_sort_field(config, should_use_incremental_field, incremental_field) is not None
return SourceResponse(
name=endpoint,
@@ -173,6 +236,9 @@ def gorgias_source(
endpoint=endpoint,
logger=logger,
resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
),
primary_keys=["id"],
partition_count=1,
@@ -180,5 +246,7 @@ def gorgias_source(
partition_mode="datetime",
partition_format="month",
partition_keys=[config.partition_key],
- sort_mode="asc",
+ # Incremental sort returns newest-first; full refresh stays ascending on the
+ # stable creation field. sort_mode must match the order rows actually arrive in.
+ sort_mode="desc" if incremental else "asc",
)
diff --git a/posthog/temporal/data_imports/sources/gorgias/settings.py b/posthog/temporal/data_imports/sources/gorgias/settings.py
index 0859cf31b756..48b62d8a8328 100644
--- a/posthog/temporal/data_imports/sources/gorgias/settings.py
+++ b/posthog/temporal/data_imports/sources/gorgias/settings.py
@@ -12,6 +12,10 @@ def _datetime_field(name: str) -> IncrementalField:
}
+CREATED = "created_datetime"
+UPDATED = "updated_datetime"
+
+
@dataclass
class GorgiasEndpointConfig:
name: str
@@ -19,14 +23,28 @@ class GorgiasEndpointConfig:
# Stable creation-time field used for datetime partitioning. Gorgias exposes
# `created_datetime` on every list resource and it never changes once set —
# never partition on `updated_datetime`, which rewrites partitions on each sync.
- partition_key: str = "created_datetime"
+ partition_key: str = CREATED
# Explicit ascending sort on the stable creation field keeps page boundaries
# stable across a full-refresh sync even if rows are inserted while we paginate.
# Every list endpoint accepts `created_datetime:asc` (verified against the docs).
- order_by: str = "created_datetime:asc"
- # Candidate cursor fields surfaced for documentation/forward-compat only. Gorgias
- # list endpoints expose NO server-side timestamp filter (only `order_by`), so true
- # incremental sync is impossible today — every endpoint runs as a full refresh.
+ order_by: str = f"{CREATED}:asc"
+ # Datetime attributes this endpoint actually accepts in `order_by` — verified
+ # per-endpoint against the Gorgias docs, because they differ: `users` exposes no
+ # `updated_datetime` (only name/email/role), `messages` is created-only, etc.
+ # Drives both the advertised incremental fields and a runtime guard that refuses to
+ # send a sort the API would reject (a rejected/ignored sort silently corrupts the
+ # newest-first ordering that incremental relies on).
+ sortable_datetime_fields: frozenset[str] = frozenset({CREATED})
+ # Whether this endpoint can sync incrementally. Gorgias has no server-side time
+ # filter, so incremental relies on sorting the cursor `<field>:desc` and halting
+ # once a whole page predates the watermark. Only safe when the cursor field both
+ # reflects the change we care about AND is server-sortable: `updated_datetime` for
+ # mutable resources, `created_datetime` for append-only ones. Mutable resources that
+ # expose only `created_datetime` (users/tags/views/teams) stay full-refresh, since
+ # `created_datetime` incremental would silently miss edits to existing rows.
+ supports_incremental: bool = False
+ # Cursor fields offered to the user. Only advertise a field whose desc-sort yields
+ # correct incremental semantics for this resource (must be in sortable_datetime_fields).
incremental_fields: list[IncrementalField] = field(default_factory=list)
@@ -34,47 +52,62 @@ GORGIAS_ENDPOINTS: dict[str, GorgiasEndpointConfig] = {
"tickets": GorgiasEndpointConfig(
name="tickets",
path="/tickets",
- incremental_fields=[_datetime_field("created_datetime"), _datetime_field("updated_datetime")],
+ sortable_datetime_fields=frozenset({CREATED, UPDATED}),
+ supports_incremental=True,
+ incremental_fields=[_datetime_field(UPDATED)],
),
"messages": GorgiasEndpointConfig(
name="messages",
path="/messages",
- incremental_fields=[_datetime_field("created_datetime")],
+ sortable_datetime_fields=frozenset({CREATED}),
+ supports_incremental=True,
+ incremental_fields=[_datetime_field(CREATED)],
),
"customers": GorgiasEndpointConfig(
name="customers",
path="/customers",
- incremental_fields=[_datetime_field("created_datetime"), _datetime_field("updated_datetime")],
+ sortable_datetime_fields=frozenset({CREATED, UPDATED}),
+ supports_incremental=True,
+ incremental_fields=[_datetime_field(UPDATED)],
),
+ # `users` is mutable but Gorgias does not expose `updated_datetime` in its order_by
+ # (only created_datetime/name/email/role), so there is no correct incremental cursor —
+ # full refresh only. The table is small, so this is cheap.
"users": GorgiasEndpointConfig(
name="users",
path="/users",
- incremental_fields=[_datetime_field("created_datetime"), _datetime_field("updated_datetime")],
+ sortable_datetime_fields=frozenset({CREATED}),
),
"satisfaction_surveys": GorgiasEndpointConfig(
name="satisfaction_surveys",
path="/satisfaction-surveys",
- incremental_fields=[_datetime_field("created_datetime")],
+ sortable_datetime_fields=frozenset({CREATED}),
+ supports_incremental=True,
+ incremental_fields=[_datetime_field(CREATED)],
+ ),
+ "macros": GorgiasEndpointConfig(
+ name="macros",
+ path="/macros",
+ sortable_datetime_fields=frozenset({CREATED, UPDATED}),
+ supports_incremental=True,
+ incremental_fields=[_datetime_field(UPDATED)],
),
+ # tags/views/teams are mutable config but expose only `created_datetime` for sorting,
+ # so incremental would miss edits — full refresh only.
"tags": GorgiasEndpointConfig(
name="tags",
path="/tags",
- incremental_fields=[_datetime_field("created_datetime")],
+ sortable_datetime_fields=frozenset({CREATED}),
),
"views": GorgiasEndpointConfig(
name="views",
path="/views",
- incremental_fields=[_datetime_field("created_datetime")],
+ sortable_datetime_fields=frozenset({CREATED}),
),
"teams": GorgiasEndpointConfig(
name="teams",
path="/teams",
- incremental_fields=[_datetime_field("created_datetime")],
- ),
- "macros": GorgiasEndpointConfig(
- name="macros",
- path="/macros",
- incremental_fields=[_datetime_field("created_datetime")],
+ sortable_datetime_fields=frozenset({CREATED}),
),
}
diff --git a/posthog/temporal/data_imports/sources/gorgias/source.py b/posthog/temporal/data_imports/sources/gorgias/source.py
index 29884526e2d3..95d870e719d0 100644
--- a/posthog/temporal/data_imports/sources/gorgias/source.py
+++ b/posthog/temporal/data_imports/sources/gorgias/source.py
@@ -20,7 +20,7 @@ from posthog.temporal.data_imports.sources.gorgias.gorgias import (
gorgias_source,
validate_credentials as validate_gorgias_credentials,
)
-from posthog.temporal.data_imports.sources.gorgias.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.gorgias.settings import ENDPOINTS, GORGIAS_ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@@ -45,13 +45,14 @@ class GorgiasSource(ResumableSource[GorgiasSourceConfig, GorgiasResumeConfig]):
names: list[str] | None = None,
force_refresh: bool = False,
) -> list[SourceSchema]:
- # Gorgias list endpoints have no server-side timestamp filter (only client-side
- # ordering), so every endpoint is full-refresh only. Cursor pagination still lets
- # an interrupted sync resume mid-stream via the ResumableSourceManager.
+ # Gorgias has no server-side timestamp filter. Incremental-capable endpoints sort
+ # their cursor field newest-first and stop paginating at the watermark; the rest
+ # stay full-refresh. Cursor pagination lets any sync resume mid-stream via the
+ # ResumableSourceManager.
schemas = [
SourceSchema(
name=endpoint,
- supports_incremental=False,
+ supports_incremental=GORGIAS_ENDPOINTS[endpoint].supports_incremental,
supports_append=False,
incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
)
@@ -85,6 +86,9 @@ class GorgiasSource(ResumableSource[GorgiasSourceConfig, GorgiasResumeConfig]):
endpoint=inputs.schema_name,
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ incremental_field=inputs.incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,
)
@property
diff --git a/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias.py b/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias.py
index 55a826651997..e408580e5b11 100644
--- a/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias.py
+++ b/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias.py
@@ -1,4 +1,5 @@
import base64
+from datetime import UTC, datetime
import pytest
from unittest.mock import MagicMock, patch
@@ -190,6 +191,216 @@ class TestGetRows:
assert manager.saved == []
+class TestIncrementalSync:
+ def _run(self, session: MagicMock, **kwargs):
+ manager = _FakeManager()
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ return list(
+ get_rows(
+ "acme",
+ "key",
+ "tickets",
+ MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ incremental_field="updated_datetime",
+ **kwargs,
+ )
+ )
+
+ def test_incremental_sorts_chosen_field_descending(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(json_body={"data": [], "meta": {"next_cursor": None}})
+ self._run(session, db_incremental_field_last_value=None)
+
+ _, kwargs = session.get.call_args
+ assert kwargs["params"]["order_by"] == "updated_datetime:desc"
+
+ def test_first_incremental_sync_walks_all_pages(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(
+ json_body={
+ "data": [{"id": 2, "updated_datetime": "2023-07-01T00:00:00+00:00"}],
+ "meta": {"next_cursor": "c2"},
+ }
+ ),
+ _response(
+ json_body={
+ "data": [{"id": 1, "updated_datetime": "2023-01-01T00:00:00+00:00"}],
+ "meta": {"next_cursor": None},
+ }
+ ),
+ ]
+ batches = self._run(session, db_incremental_field_last_value=None)
+
+ assert [item["id"] for batch in batches for item in batch] == [2, 1]
+ assert session.get.call_count == 2
+
+ def test_stops_once_page_predates_watermark(self) -> None:
+ # Rows arrive newest-first; the third page is never fetched because the second
+ # page is entirely older than the watermark.
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(
+ json_body={
+ "data": [{"id": 3, "updated_datetime": "2023-07-01T00:00:00+00:00"}],
+ "meta": {"next_cursor": "c2"},
+ }
+ ),
+ _response(
+ json_body={
+ "data": [{"id": 2, "updated_datetime": "2023-05-01T00:00:00+00:00"}],
+ "meta": {"next_cursor": "c3"},
+ }
+ ),
+ _response(
+ json_body={
+ "data": [{"id": 1, "updated_datetime": "2023-04-01T00:00:00+00:00"}],
+ "meta": {"next_cursor": None},
+ }
+ ),
+ ]
+ batches = self._run(session, db_incremental_field_last_value=datetime(2023, 6, 1, tzinfo=UTC))
+
+ # The over-the-watermark page is still yielded (merge dedupes), then we stop.
+ assert [item["id"] for batch in batches for item in batch] == [3, 2]
+ assert session.get.call_count == 2
+
+ def test_unknown_incremental_field_falls_back_to_full_refresh(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(json_body={"data": [], "meta": {"next_cursor": None}})
+ manager = _FakeManager()
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ list(
+ get_rows(
+ "acme",
+ "key",
+ "tickets",
+ MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ incremental_field="not_a_sortable_field",
+ db_incremental_field_last_value=datetime(2023, 6, 1, tzinfo=UTC),
+ )
+ )
+
+ _, kwargs = session.get.call_args
+ assert kwargs["params"]["order_by"] == "created_datetime:asc"
+
+ def test_incremental_field_not_sortable_on_endpoint_falls_back(self) -> None:
+ # `users` does not accept `updated_datetime` in order_by; forcing it must not send
+ # an order_by Gorgias would reject — fall back to the full-refresh sort instead.
+ session = MagicMock()
+ session.get.return_value = _response(json_body={"data": [], "meta": {"next_cursor": None}})
+ manager = _FakeManager()
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ list(
+ get_rows(
+ "acme",
+ "key",
+ "users",
+ MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ incremental_field="updated_datetime",
+ db_incremental_field_last_value=datetime(2023, 6, 1, tzinfo=UTC),
+ )
+ )
+
+ _, kwargs = session.get.call_args
+ assert kwargs["params"]["order_by"] == "created_datetime:asc"
+
+ def test_order_by_persists_across_pages_alongside_cursor(self) -> None:
+ # Gorgias' cursor only makes sense within the same sorted list, so order_by must
+ # ride along on every follow-up page, not just the first.
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(
+ json_body={
+ "data": [{"id": 2, "updated_datetime": "2023-07-01T00:00:00+00:00"}],
+ "meta": {"next_cursor": "c2"},
+ }
+ ),
+ _response(
+ json_body={
+ "data": [{"id": 1, "updated_datetime": "2023-06-15T00:00:00+00:00"}],
+ "meta": {"next_cursor": None},
+ }
+ ),
+ ]
+ self._run(session, db_incremental_field_last_value=None)
+
+ first_params = session.get.call_args_list[0].kwargs["params"]
+ second_params = session.get.call_args_list[1].kwargs["params"]
+ assert "cursor" not in first_params
+ assert first_params["order_by"] == "updated_datetime:desc"
+ assert second_params["cursor"] == "c2"
+ assert second_params["order_by"] == "updated_datetime:desc"
+ assert second_params["limit"] == 100
+
+
+# Per-endpoint `order_by` enums quoted from the Gorgias API docs (the `.md` reference for
+# each list endpoint). This is the external contract our config must not drift from: if an
+# endpoint is configured to sort by a field absent here, Gorgias would reject or ignore it.
+DOCUMENTED_ORDER_BY_DATETIME_FIELDS: dict[str, set[str]] = {
+ "tickets": {"created_datetime", "updated_datetime"},
+ "messages": {"created_datetime"},
+ "customers": {"created_datetime", "updated_datetime"},
+ "users": {"created_datetime"}, # also name/email/role, but no updated_datetime
+ "satisfaction_surveys": {"created_datetime"},
+ "macros": {"created_datetime", "updated_datetime"},
+ "tags": {"created_datetime"},
+ "views": {"created_datetime"},
+ "teams": {"created_datetime"},
+}
+
+
+class TestApiContract:
+ """Pin the endpoint config to the documented Gorgias API so it can't silently drift."""
+
+ def test_sortable_fields_match_documented_api(self) -> None:
+ assert {name: set(config.sortable_datetime_fields) for name, config in GORGIAS_ENDPOINTS.items()} == (
+ DOCUMENTED_ORDER_BY_DATETIME_FIELDS
+ )
+
+ @parameterized.expand([(name,) for name in ENDPOINTS])
+ def test_full_refresh_order_by_is_accepted_by_endpoint(self, endpoint: str) -> None:
+ config = GORGIAS_ENDPOINTS[endpoint]
+ field, _, direction = config.order_by.partition(":")
+ assert field in DOCUMENTED_ORDER_BY_DATETIME_FIELDS[endpoint]
+ assert direction in {"asc", "desc"}
+
+ @parameterized.expand([(name,) for name in ENDPOINTS])
+ def test_advertised_incremental_fields_are_sortable(self, endpoint: str) -> None:
+ config = GORGIAS_ENDPOINTS[endpoint]
+ advertised = {f["field"] for f in config.incremental_fields}
+ # Every advertised cursor field must be one Gorgias actually accepts in order_by.
+ assert advertised <= DOCUMENTED_ORDER_BY_DATETIME_FIELDS[endpoint]
+ # supports_incremental and the field list must agree.
+ assert bool(advertised) == config.supports_incremental
+
+ def test_incremental_endpoints_use_updated_when_available_else_created(self) -> None:
+ # Mutable resources must track updates when the API lets them; append-only ones
+ # track creation. This guards the core correctness decision per endpoint.
+ expected = {
+ "tickets": "updated_datetime",
+ "customers": "updated_datetime",
+ "macros": "updated_datetime",
+ "messages": "created_datetime",
+ "satisfaction_surveys": "created_datetime",
+ }
+ actual = {
+ name: config.incremental_fields[0]["field"]
+ for name, config in GORGIAS_ENDPOINTS.items()
+ if config.supports_incremental
+ }
+ assert actual == expected
+
+
class TestGorgiasSource:
@parameterized.expand([(name,) for name in ENDPOINTS])
def test_source_response_shape(self, endpoint: str) -> None:
@@ -200,6 +411,26 @@ class TestGorgiasSource:
assert response.partition_keys == [GORGIAS_ENDPOINTS[endpoint].partition_key]
assert response.sort_mode == "asc"
+ @parameterized.expand(
+ [
+ (name, config.incremental_fields[0]["field"])
+ for name, config in GORGIAS_ENDPOINTS.items()
+ if config.supports_incremental
+ ]
+ )
+ def test_incremental_source_response_sorts_descending(self, endpoint: str, incremental_field: str) -> None:
+ response = gorgias_source(
+ "acme",
+ "key",
+ endpoint,
+ MagicMock(),
+ _FakeManager(),
+ should_use_incremental_field=True,
+ incremental_field=incremental_field,
+ )
+ assert response.sort_mode == "desc"
+
def test_every_endpoint_partitions_on_created_datetime(self) -> None:
for config in GORGIAS_ENDPOINTS.values():
assert config.partition_key == "created_datetime"
diff --git a/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias_source.py b/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias_source.py
index 601ed5b81d62..7dcadbc87725 100644
--- a/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias_source.py
+++ b/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias_source.py
@@ -8,7 +8,7 @@ from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInput
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from posthog.temporal.data_imports.sources.generated_configs import GorgiasSourceConfig
from posthog.temporal.data_imports.sources.gorgias.gorgias import GorgiasResumeConfig
-from posthog.temporal.data_imports.sources.gorgias.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.gorgias.settings import ENDPOINTS, GORGIAS_ENDPOINTS
from posthog.temporal.data_imports.sources.gorgias.source import GorgiasSource
from products.data_warehouse.backend.types import ExternalDataSourceType
@@ -53,12 +53,17 @@ class TestGorgiasSource:
assert fields["email"].type == SourceFieldInputConfigType.EMAIL
assert all(fields[name].required for name in fields)
- def test_get_schemas_lists_every_endpoint_as_full_refresh(self) -> None:
- schemas = GorgiasSource().get_schemas(_config(), team_id=1)
- assert {s.name for s in schemas} == set(ENDPOINTS)
- # Gorgias has no server-side timestamp filter, so nothing supports incremental.
- assert all(s.supports_incremental is False for s in schemas)
- assert all(s.supports_append is False for s in schemas)
+ def test_get_schemas_marks_incremental_per_endpoint(self) -> None:
+ schemas = {s.name: s for s in GorgiasSource().get_schemas(_config(), team_id=1)}
+ assert set(schemas) == set(ENDPOINTS)
+ # Incremental support mirrors the endpoint catalog: mutable/append-only resources
+ # are incremental-capable, mutable config tables stay full-refresh.
+ assert {name: s.supports_incremental for name, s in schemas.items()} == {
+ name: GORGIAS_ENDPOINTS[name].supports_incremental for name in ENDPOINTS
+ }
+ assert schemas["tickets"].supports_incremental is True
+ assert schemas["tags"].supports_incremental is False
+ assert all(s.supports_append is False for s in schemas.values())
def test_get_schemas_filters_by_names(self) -> None:
schemas = GorgiasSource().get_schemas(_config(), team_id=1, names=["tickets", "customers"])
@@ -86,6 +91,15 @@ class TestGorgiasSource:
response = GorgiasSource().source_for_pipeline(_config(), manager, _inputs(schema_name="customers"))
assert response.name == "customers"
assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+
+ def test_source_for_pipeline_uses_desc_sort_when_incremental(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ inputs = _inputs(schema_name="tickets")
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "updated_datetime"
+ response = GorgiasSource().source_for_pipeline(_config(), manager, inputs)
+ assert response.sort_mode == "desc"
def test_non_retryable_errors_cover_auth_failures(self) -> None:
errors = GorgiasSource().get_non_retryable_errors()