: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(warehouse-sources): add four gorgias endpoint tables (#110733)
Tom Owersf58557f8b1b8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 9a8dc2b063f5..68514917b2eb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -3771,14 +3771,14 @@ Today (9): `customers`, `macros`, `messages`, `satisfaction_surveys`, `tags`, `tDiffed against: <https://developers.gorgias.com/llms.txt>-- [ ] `events (/api/events)` — the account-wide event stream, including ticket state transitions and assignment changes - the only way to do time-in-status or SLA analysis (high)+- [x] `events (/api/events)` — the account-wide event stream, including ticket state transitions and assignment changes - the only way to do time-in-status or SLA analysis (high)- [x] `ticket_tags (/api/tickets/{id}/tags)` — the ticket-to-tag join; we sync tags and tickets but not the mapping between them (high)- [x] `voice_calls` — phone channel fact table, entirely absent today (high)- [x] `custom_fields` — lookup resolving the custom field IDs used on tickets and customers (high)- [x] `ticket_field_values (/api/tickets/{id}/custom-fields)` — per-ticket custom field values, including system fields like AI Intent and AI Agent Outcome (high)-- [ ] `customer_field_values (/api/customers/{id}/custom-fields)` — per-customer custom field values (medium)-- [ ] `voice_call_events` — per-call state transitions (ringing, answered, transferred) for phone queue analysis (medium)-- [ ] `voice_call_recordings` — recording metadata joined to voice calls (medium)+- [x] `customer_field_values (/api/customers/{id}/custom-fields)` — per-customer custom field values (medium)+- [x] `voice_call_events` — per-call state transitions (ringing, answered, transferred) for phone queue analysis (medium)+- [x] `voice_call_recordings` — recording metadata joined to voice calls (medium)- [ ] `statistics (/api/statistics/{slug} and metric cards)` — Gorgias' own precomputed support metrics, useful as a benchmark against derived numbers (medium)- [ ] `view_items (/api/views/{id}/items)` — the ticket membership of each saved view; we sync views but not their contents (low)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/canonical_descriptions.pyindex fc7a6f7a0ae7..95f5738515ae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/canonical_descriptions.py@@ -184,4 +184,61 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"prediction": "Value predicted by Gorgias for the field, if any.",},},+ "customer_field_values": {+ "description": "One row per custom field value set on a customer.",+ "docs_url": "https://developers.gorgias.com/reference/list-customer-custom-fields-values",+ "columns": {+ "customer_id": "ID of the customer.",+ "customer_created_datetime": "Time at which the customer was created.",+ "field_id": "ID of the custom field. Joins to the custom_fields table.",+ "field": "Definition of the custom field.",+ "value": "Value of the field on the customer, as text.",+ },+ },+ "events": {+ "description": "Audit log of actions in the Gorgias account, such as ticket status changes and assignments. Gorgias keeps the last 12 months.",+ "docs_url": "https://developers.gorgias.com/reference/the-event-object",+ "columns": {+ "id": "ID of the event.",+ "created_datetime": "Time at which the event was created.",+ "type": "Type of the event, e.g. ticket-created or ticket-closed.",+ "object_type": "Type of the object the event is about, e.g. Ticket or Customer.",+ "object_id": "ID of the object the event is about.",+ "user_id": "ID of the user who triggered the event. Empty when a rule or automation triggered it.",+ "context": "UUID shared by a sequence of events where one event triggered the next.",+ "data": "Key-value data attached to the event.",+ "uri": "API URI of the event.",+ },+ },+ "voice_call_events": {+ "description": "A state change during a voice call, such as ringing, answered, or transferred.",+ "docs_url": "https://developers.gorgias.com/reference/the-voicecallevent-object",+ "columns": {+ "id": "ID of the event.",+ "created_datetime": "Time at which the event was created.",+ "type": "Type of the voice call event.",+ "call_id": "ID of the call. Joins to the voice_calls table.",+ "account_id": "ID of the account the event belongs to.",+ "user_id": "ID of the agent related to the event.",+ "customer_id": "ID of the customer related to the event.",+ "meta": "Data attached to the event.",+ },+ },+ "voice_call_recordings": {+ "description": "A voicemail or call recording attached to a voice call.",+ "docs_url": "https://developers.gorgias.com/reference/the-voicecallrecording-object",+ "columns": {+ "id": "ID of the voicemail or call recording.",+ "created_datetime": "Time at which the recording was created.",+ "call_id": "ID of the call. Joins to the voice_calls table.",+ "external_id": "ID of the recording at the telephony provider.",+ "url": "Direct access URL of the recording.",+ "duration": "Duration of the recording in seconds.",+ "type": "Whether this is a voicemail or a call recording.",+ "deleted_datetime": "Time at which the recording was deleted, if deleted.",+ "deleted_by_user_id": "ID of the agent who deleted the recording, if deleted.",+ "error_code": "Reason the URL could not be provided.",+ "transcription_status": "Status of the recording's transcription.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/gorgias.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/gorgias.pyindex ebc6faaae3b7..fff7685c5d18 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/gorgias.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/gorgias.py@@ -102,6 +102,16 @@ def _incremental_sort_field(return None+def _uses_server_filter(config: GorgiasEndpointConfig, sort_field: str | None) -> bool:+ return sort_field is not None and sort_field in config.filterable_datetime_fields+++def _field_value_as_text(value: Any) -> Any:+ # Values are text, number, or boolean depending on the field, so keep the column one type+ # rather than mixing them across rows.+ return value if value is None or isinstance(value, str) else json.dumps(value)++def _flatten_ticket_child(tickets: list[Any], child: str) -> list[dict[str, Any]]:rows: list[dict[str, Any]] = []for ticket in tickets:@@ -117,15 +127,12 @@ def _flatten_ticket_child(tickets: list[Any], child: str) -> list[dict[str, Any]for field_id, field_value in (ticket.get("custom_fields") or {}).items():if not isinstance(field_value, dict):continue- value = field_value.get("value")rows.append({**field_value,**parent,"field_id": int(field_id) if str(field_id).isdigit() else field_id,- # Values are text, number, or boolean depending on the field, so keep the- # column one type rather than mixing them across rows.- "value": value if value is None or isinstance(value, str) else json.dumps(value),+ "value": _field_value_as_text(field_value.get("value")),})else:@@ -133,6 +140,20 @@ def _flatten_ticket_child(tickets: list[Any], child: str) -> list[dict[str, Any]return rows+def _flatten_customer_field_values(customer: dict[str, Any], items: list[Any]) -> list[dict[str, Any]]:+ parent = {"customer_id": customer.get("id"), "customer_created_datetime": customer.get("created_datetime")}+ rows: list[dict[str, Any]] = []+ for item in items:+ if not isinstance(item, dict):+ continue+ field = item.get("field")+ field_id = field.get("id") if isinstance(field, dict) else None+ if field_id is None:+ continue+ rows.append({**item, **parent, "field_id": field_id, "value": _field_value_as_text(item.get("value"))})+ return rows++def _get_auth_header(email: str, api_key: str) -> str:token = base64.b64encode(f"{email}:{api_key}".encode()).decode()return f"Basic {token}"@@ -181,15 +202,28 @@ def get_rows(db_incremental_field_last_value: Optional[Any] = None,) -> Iterator[Any]:config = GORGIAS_ENDPOINTS[endpoint]- url = f"{get_base_url(domain)}{config.path}"+ base_url = get_base_url(domain)+ url = f"{base_url}{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+ # Most endpoints have 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.+ # steady-state sync only pulls the changed prefix instead of every page. Endpoints that do+ # filter server-side sort ascending and request only rows from the watermark onwards.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+ server_filtered = _uses_server_filter(config, sort_field)watermark = _coerce_to_utc(db_incremental_field_last_value) if sort_field else None+ filter_params: dict[str, str] = {}+ stop_watermark: datetime | None = None+ if server_filtered:+ order_by: str | None = f"{sort_field}:asc"+ if watermark is not None:+ filter_params[f"{sort_field}[gte]"] = watermark.isoformat()+ elif sort_field:+ order_by = f"{sort_field}:desc"+ stop_watermark = watermark+ else:+ order_by = config.order_byresume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Nonecursor = resume_config.cursor if resume_config else None@@ -205,30 +239,59 @@ def get_rows(wait=wait_exponential_jitter(initial=1, max=30),reraise=True,)+ def fetch(request_url: str, params: dict[str, Any]) -> requests.Response:+ # The tracked adapter already retries 429/5xx while honoring the Retry-After+ # header; this guard re-raises anything that slips through so tenacity can back off.+ response = session.get(request_url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)+ if response.status_code == 429 or response.status_code >= 500:+ raise GorgiasRetryableError(+ f"Gorgias API error (retryable): status={response.status_code}, endpoint={endpoint}"+ )+ return response++ def raise_for_error(response: requests.Response) -> None:+ if not response.ok:+ logger.error(f"Gorgias API error: status={response.status_code}, body={response.text}, endpoint={endpoint}")+ response.raise_for_status()+def fetch_page(request_cursor: str | None, variant_params: dict[str, str]) -> Any:# `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, **variant_params}+ params: dict[str, Any] = {"limit": PAGE_SIZE, **variant_params, **filter_params}if order_by:params["order_by"] = order_byif request_cursor:params["cursor"] = request_cursor- # The tracked adapter already retries 429/5xx while honoring the Retry-After- # header; this guard re-raises anything that slips through so tenacity can back off.- response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)- if response.status_code == 429 or response.status_code >= 500:- raise GorgiasRetryableError(- f"Gorgias API error (retryable): status={response.status_code}, endpoint={endpoint}"- )- if not response.ok:- logger.error(f"Gorgias API error: status={response.status_code}, body={response.text}, endpoint={endpoint}")- response.raise_for_status()+ response = fetch(url, params)+ raise_for_error(response)return response.json()+ def fetch_child_rows(child_path: str, parents: list[Any]) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for parent in parents:+ if not isinstance(parent, dict) or not isinstance(parent.get("id"), int):+ continue+ response = fetch(f"{base_url}{child_path.format(id=parent['id'])}", {})+ # The parent can be deleted between listing it and fetching its children.+ if response.status_code == 404:+ continue+ raise_for_error(response)+ data = response.json()+ items = data.get("data", []) if isinstance(data, dict) else data+ rows.extend(_flatten_customer_field_values(parent, items or []))+ return rows++ def page_rows(items: list[Any]) -> list[Any]:+ if config.child_path:+ return fetch_child_rows(config.child_path, items)+ if config.ticket_child:+ return _flatten_ticket_child(items, config.ticket_child)+ return items+for variant_index in range(start_variant, len(config.param_variants)):variant_params = config.param_variants[variant_index]while True:@@ -240,9 +303,11 @@ def get_rows(# Rows arrive newest-first under incremental sort; once an entire page predates the# watermark, everything further back is already synced, so stop.reached_watermark = False- if watermark is not None and sort_field is not None and items:+ if stop_watermark is not None and sort_field is not None and items:page_newest = _page_newest(items, sort_field)- reached_watermark = page_newest is not None and page_newest < watermark+ reached_watermark = page_newest is not None and page_newest < stop_watermark++ rows = page_rows(items) if items else []# Stage the position after this page before yielding it. A resumed full refresh# appends, so a cursor that lags one page behind would write that page twice. The@@ -252,8 +317,12 @@ def get_rows(else:resumable_source_manager.save_state(GorgiasResumeConfig(cursor=None, variant=variant_index + 1))- if items:- yield _flatten_ticket_child(items, config.ticket_child) if config.ticket_child else items+ if rows:+ yield rows+ else:+ # A fan-out page whose parents have no children yields nothing, and many in a row+ # would otherwise hold off a worker shutdown.+ resumable_source_manager.safe_point()if not next_cursor or reached_watermark:break@@ -274,7 +343,8 @@ def gorgias_source(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+ sort_field = _incremental_sort_field(config, should_use_incremental_field, incremental_field)+ newest_first = sort_field is not None and not _uses_server_filter(config, sort_field)return SourceResponse(name=endpoint,@@ -295,7 +365,7 @@ def gorgias_source(partition_mode="datetime",partition_format="month",partition_keys=[config.partition_key],- # 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",+ # Incremental without a server-side filter returns newest-first; everything else is+ # ascending. sort_mode must match the order rows actually arrive in.+ sort_mode="desc" if newest_first else "asc",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/settings.pyindex 790b2ff0ea1d..aead20b27b27 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/settings.py@@ -36,6 +36,10 @@ class GorgiasEndpointConfig:# 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})+ # Datetime fields the endpoint filters server-side with `<field>[gte]`. Incremental on one+ # of these sorts ascending and requests only rows from the watermark onwards, rather than+ # walking newest-first and stopping client-side.+ filterable_datetime_fields: frozenset[str] = frozenset()# 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@@ -55,6 +59,10 @@ class GorgiasEndpointConfig:# ticket list already embeds `tags` and `custom_fields`, so this avoids one request per# ticket against the per-ticket `/tickets/{id}/tags` and `/tickets/{id}/custom-fields`.ticket_child: str | None = None+ # Per-row child path (`{id}` is the row id of `path`), fetched for every row and flattened+ # into one row per child item. Costs one request per parent row, so only for collections+ # the parent list does not embed.+ child_path: str | None = NoneGORGIAS_ENDPOINTS: dict[str, GorgiasEndpointConfig] = {@@ -131,6 +139,27 @@ GORGIAS_ENDPOINTS: dict[str, GorgiasEndpointConfig] = {order_by=None,sortable_datetime_fields=frozenset(),),+ "voice_call_events": GorgiasEndpointConfig(+ name="voice_call_events",+ path="/phone/voice-call-events",+ order_by=None,+ sortable_datetime_fields=frozenset(),+ ),+ "voice_call_recordings": GorgiasEndpointConfig(+ name="voice_call_recordings",+ path="/phone/voice-call-recordings",+ order_by=None,+ sortable_datetime_fields=frozenset(),+ ),+ # Append-only audit log. Gorgias keeps only the last 12 months of events.+ "events": GorgiasEndpointConfig(+ name="events",+ path="/events",+ sortable_datetime_fields=frozenset({CREATED}),+ filterable_datetime_fields=frozenset({CREATED}),+ supports_incremental=True,+ incremental_fields=[_datetime_field(CREATED)],+ ),# Derived from the ticket list, so they stay full refresh: a removed tag or cleared field# value has no ticket-level row left to delete it on merge."ticket_tags": GorgiasEndpointConfig(@@ -149,6 +178,16 @@ GORGIAS_ENDPOINTS: dict[str, GorgiasEndpointConfig] = {primary_keys=("ticket_id", "field_id"),ticket_child="custom_fields",),+ # The customer list does not embed custom field values, so this fans out one request per+ # customer. Full refresh for the same reason as the ticket-derived tables.+ "customer_field_values": GorgiasEndpointConfig(+ name="customer_field_values",+ path="/customers",+ partition_key=f"customer_{CREATED}",+ sortable_datetime_fields=frozenset({CREATED, UPDATED}),+ primary_keys=("customer_id", "field_id"),+ child_path="/customers/{id}/custom-fields",+ ),}ENDPOINTS = tuple(GORGIAS_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/source.pyindex 7624656ae396..c761bad938e0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/source.py@@ -123,7 +123,7 @@ class GorgiasSource(ResumableSource[GorgiasSourceConfig, GorgiasResumeConfig]):Create an API key in your Gorgias account under **Settings → REST API**. Use the email of the account that owns the key together with the key itself.-This source authenticates with HTTP Basic Auth (email + API key) and requires read access to the endpoints you want to sync (tickets, messages, customers, users, satisfaction surveys, tags, views, teams, macros, custom fields, voice calls).""",+This source authenticates with HTTP Basic Auth (email + API key) and requires read access to the endpoints you want to sync (tickets, messages, customers, users, satisfaction surveys, tags, views, teams, macros, custom fields, events, voice calls, voice call events, voice call recordings).""",iconPath="/static/services/gorgias.png",docsUrl="https://posthog.com/docs/cdp/sources/gorgias",releaseStatus=ReleaseStatus.GA,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/tests/test_gorgias.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/tests/test_gorgias.pyindex 03959b2db3d6..74aa2feabe43 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/tests/test_gorgias.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/tests/test_gorgias.py@@ -4,6 +4,7 @@ from datetime import UTC, datetimeimport pytestfrom unittest.mock import MagicMock, patch+import requestsfrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -233,14 +234,21 @@ class TestParamVariants:assert params["object_type"] == "Customer"assert params["cursor"] == "c9"- def test_voice_calls_sends_no_order_by(self) -> None:+ @parameterized.expand(+ [+ ("voice_calls", "phone/voice-calls"),+ ("voice_call_events", "phone/voice-call-events"),+ ("voice_call_recordings", "phone/voice-call-recordings"),+ ]+ )+ def test_voice_endpoints_send_no_order_by(self, endpoint: str, path: str) -> None:session = MagicMock()session.get.return_value = _response(json_body={"data": [], "meta": {"next_cursor": None}})with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):- list(get_rows("acme", "[email protected]", "key", "voice_calls", MagicMock(), _FakeManager()))+ list(get_rows("acme", "[email protected]", "key", endpoint, MagicMock(), _FakeManager()))url = session.get.call_args.args[0]- assert url == "https://acme.gorgias.com/api/phone/voice-calls"+ assert url == f"https://acme.gorgias.com/api/{path}"assert "order_by" not in session.get.call_args.kwargs["params"]@@ -297,6 +305,151 @@ class TestTicketChildTables:assert all(r["ticket_created_datetime"] == "2024-01-01T00:00:00+00:00" for r in rows)+class TestCustomerFieldValues:+ def test_fans_out_per_customer_and_skips_deleted_customers(self) -> None:+ session = MagicMock()+ session.get.side_effect = [+ _response(+ json_body={+ "data": [+ {"id": 1, "created_datetime": "2024-01-01T00:00:00"},+ {"id": 2, "created_datetime": "2024-02-01T00:00:00"},+ {"id": 3, "created_datetime": "2024-03-01T00:00:00"},+ ],+ "meta": {"next_cursor": None},+ }+ ),+ _response(+ json_body={+ "data": [+ {"field": {"id": 5, "label": "Plan"}, "value": "pro"},+ {"field": {"id": 6, "label": "Seats"}, "value": 12},+ ]+ }+ ),+ _response(status_code=404, ok=False),+ # Some list endpoints return a bare array rather than a `data` envelope.+ _response(json_body=[{"field": {"id": 5, "label": "Plan"}, "value": None}]), # type: ignore[arg-type]+ ]+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("acme", "[email protected]", "key", "customer_field_values", MagicMock(), _FakeManager()))++ urls = [c.args[0] for c in session.get.call_args_list]+ assert urls == [+ "https://acme.gorgias.com/api/customers",+ "https://acme.gorgias.com/api/customers/1/custom-fields",+ "https://acme.gorgias.com/api/customers/2/custom-fields",+ "https://acme.gorgias.com/api/customers/3/custom-fields",+ ]+ rows = [row for batch in batches for row in batch]+ assert [(r["customer_id"], r["field_id"], r["value"], r["customer_created_datetime"]) for r in rows] == [+ (1, 5, "pro", "2024-01-01T00:00:00"),+ (1, 6, "12", "2024-01-01T00:00:00"),+ (3, 5, None, "2024-03-01T00:00:00"),+ ]++ def test_child_error_other_than_404_fails_the_sync(self) -> None:+ session = MagicMock()+ forbidden = _response(status_code=403, ok=False)+ forbidden.raise_for_status.side_effect = requests.HTTPError(+ "403 Client Error: Forbidden for url", response=forbidden+ )+ session.get.side_effect = [+ _response(json_body={"data": [{"id": 1}], "meta": {"next_cursor": None}}),+ forbidden,+ ]+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):+ with pytest.raises(requests.HTTPError):+ list(get_rows("acme", "[email protected]", "key", "customer_field_values", MagicMock(), _FakeManager()))++ def test_stages_parent_cursor_and_reaches_safe_point_on_pages_without_values(self) -> None:+ session = MagicMock()+ session.get.side_effect = [+ _response(json_body={"data": [{"id": 1}], "meta": {"next_cursor": "c2"}}),+ _response(json_body={"data": []}),+ _response(json_body={"data": [{"id": 2}], "meta": {"next_cursor": None}}),+ _response(json_body={"data": [{"field": {"id": 5}, "value": "x"}]}),+ ]+ manager = _FakeManager()+ with (+ patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session),+ patch.object(manager, "safe_point") as safe_point,+ ):+ rows = get_rows("acme", "[email protected]", "key", "customer_field_values", MagicMock(), manager)+ assert [r["customer_id"] for r in next(rows)] == [2]+ assert manager.saved == [+ GorgiasResumeConfig(cursor="c2", variant=0),+ GorgiasResumeConfig(cursor=None, variant=1),+ ]+ safe_point.assert_called_once()+ assert list(rows) == []+++class TestServerFilteredIncremental:+ def _run(self, session: MagicMock, watermark: datetime | None) -> list:+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):+ return list(+ get_rows(+ "acme",+ "[email protected]",+ "key",+ "events",+ MagicMock(),+ _FakeManager(),+ should_use_incremental_field=True,+ incremental_field="created_datetime",+ db_incremental_field_last_value=watermark,+ )+ )++ def test_filters_from_watermark_ascending_on_every_page(self) -> None:+ session = MagicMock()+ session.get.side_effect = [+ _response(+ json_body={+ "data": [{"id": 1, "created_datetime": "2023-06-01T00:00:00"}],+ "meta": {"next_cursor": "c2"},+ }+ ),+ _response(+ json_body={+ "data": [{"id": 2, "created_datetime": "2023-06-02T00:00:00"}],+ "meta": {"next_cursor": None},+ }+ ),+ ]+ batches = self._run(session, datetime(2023, 6, 1, tzinfo=UTC))++ assert [item["id"] for batch in batches for item in batch] == [1, 2]+ params = [c.kwargs["params"] for c in session.get.call_args_list]+ assert [(p["order_by"], p["created_datetime[gte]"], p.get("cursor")) for p in params] == [+ ("created_datetime:asc", "2023-06-01T00:00:00+00:00", None),+ ("created_datetime:asc", "2023-06-01T00:00:00+00:00", "c2"),+ ]++ def test_first_sync_sends_no_filter(self) -> None:+ session = MagicMock()+ session.get.return_value = _response(json_body={"data": [], "meta": {"next_cursor": None}})+ self._run(session, None)++ params = session.get.call_args.kwargs["params"]+ assert params["order_by"] == "created_datetime:asc"+ assert "created_datetime[gte]" not in params++ def test_source_response_sorts_ascending(self) -> None:+ response = gorgias_source(+ "acme",+ "[email protected]",+ "key",+ "events",+ MagicMock(),+ _FakeManager(),+ should_use_incremental_field=True,+ incremental_field="created_datetime",+ )+ assert response.sort_mode == "asc"++class TestIncrementalSync:def _run(self, session: MagicMock, **kwargs):manager = _FakeManager()@@ -466,6 +619,10 @@ DOCUMENTED_ORDER_BY_DATETIME_FIELDS: dict[str, set[str]] = {"voice_calls": set(), # accepts no order_by"ticket_tags": {"created_datetime", "updated_datetime"},"ticket_field_values": {"created_datetime", "updated_datetime"},+ "events": {"created_datetime"},+ "voice_call_events": set(), # accepts no order_by+ "voice_call_recordings": set(), # accepts no order_by+ "customer_field_values": {"created_datetime", "updated_datetime"},}DOCUMENTED_NON_DATETIME_ORDER_BY: dict[str, set[str]] = {"custom_fields": {"priority:asc", "priority:desc"},@@ -511,6 +668,7 @@ class TestApiContract:"macros": "updated_datetime","messages": "created_datetime","satisfaction_surveys": "created_datetime",+ "events": "created_datetime",}actual = {name: config.incremental_fields[0]["field"]@@ -534,7 +692,7 @@ class TestGorgiasSource:[(name, config.incremental_fields[0]["field"])for name, config in GORGIAS_ENDPOINTS.items()- if config.supports_incremental+ if config.supports_incremental and not config.filterable_datetime_fields])def test_incremental_source_response_sorts_descending(self, endpoint: str, incremental_field: str) -> None:@@ -552,5 +710,5 @@ class TestGorgiasSource:def test_every_endpoint_partitions_on_created_datetime(self) -> None:for config in GORGIAS_ENDPOINTS.values():- assert config.partition_key in ("created_datetime", "ticket_created_datetime")+ assert config.partition_key in ("created_datetime", "ticket_created_datetime", "customer_created_datetime")assert "updated" not in config.partition_key