: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): add 25 tables to the Zendesk source (#73855)
Tom Owers6c0babb88c0c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/canonical_descriptions.pyindex 9c6ce80f2361..e982c0fb5cc1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/canonical_descriptions.py@@ -160,4 +160,403 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {policy_metrics="The metric targets (e.g. first reply time) for each priority level.",),},+ "satisfaction_ratings": {+ "description": "A customer satisfaction rating left on a ticket, with its score and optional comment.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/ticket-management/satisfaction_ratings/",+ "columns": _columns(+ score='The rating: "offered", "unoffered", "good" or "bad".',+ comment="The comment received with this rating, if available.",+ reason="The reason for a bad rating given by the requester in a follow-up question.",+ reason_code="The default reason the user selected from the list for giving a negative rating.",+ reason_id="Id for the reason the user gave a negative rating.",+ ticket_id="The id of the ticket being rated.",+ requester_id="The id of the ticket requester submitting the rating.",+ assignee_id="The id of the agent assigned at the time of rating.",+ group_id="The id of the group assigned at the time of rating.",+ ),+ },+ "ticket_metrics": {+ "description": "Rolled-up timing and volume metrics for a single ticket, such as first reply and full resolution time.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/tickets/ticket_metrics/",+ "columns": _columns(+ ticket_id="Id of the associated ticket.",+ reply_time_in_minutes="Number of minutes to the first reply during calendar and business hours.",+ reply_time_in_seconds="Number of seconds to the first reply during calendar hours; Messaging tickets only.",+ first_resolution_time_in_minutes="Number of minutes to the first resolution during calendar and business hours.",+ full_resolution_time_in_minutes="Number of minutes to the full resolution during calendar and business hours.",+ agent_wait_time_in_minutes="Number of minutes the agent spent waiting during calendar and business hours.",+ requester_wait_time_in_minutes="Number of minutes the requester spent waiting during calendar and business hours.",+ on_hold_time_in_minutes="Number of minutes the ticket was on hold.",+ replies="The number of public replies added to the ticket by an agent.",+ reopens="Total number of times the ticket was reopened.",+ assignee_stations="Number of assignees the ticket had.",+ group_stations="Number of groups the ticket passed through.",+ assigned_at="When the ticket was assigned.",+ initially_assigned_at="When the ticket was initially assigned.",+ assignee_updated_at="When the assignee last updated the ticket.",+ requester_updated_at="When the requester last updated the ticket.",+ status_updated_at="When the status of the ticket was last updated.",+ custom_status_updated_at="When the ticket's custom status was last updated.",+ latest_comment_added_at="When the latest comment was added.",+ solved_at="When the ticket was solved.",+ ),+ },+ "ticket_audits": {+ "description": "An immutable record of every change made to a ticket, including the events that made it up.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/tickets/ticket_audits/",+ "columns": {+ "id": "Automatically assigned when creating audits.",+ "ticket_id": "The id of the associated ticket.",+ "author_id": "The user who created the audit.",+ "created_at": "The time the audit was created.",+ "events": "The events that happened in this audit, such as comments and field changes.",+ "metadata": "Metadata for the audit, custom and system data.",+ "via": "Describes how the object was created.",+ },+ },+ "ticket_comments": {+ "description": "A comment on a ticket: a public reply to the requester or an internal note between agents.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/tickets/ticket_comments/",+ "columns": {+ "id": "Automatically assigned when the comment is created.",+ "ticket_id": "Id of the ticket this comment belongs to.",+ "type": "`Comment` or `VoiceComment`.",+ "body": "The comment string.",+ "html_body": "The comment formatted as HTML.",+ "plain_body": "The comment presented as plain text.",+ "public": "True if a public comment, false if an internal note.",+ "author_id": "The id of the comment author.",+ "audit_id": "The id of the ticket audit record this comment came from.",+ "attachments": "Attachments on the comment, if any.",+ "metadata": "System information (web client, IP address, and so on) and comment flags, if any.",+ "via": "Describes how the object was created.",+ "created_at": "The time the comment was created.",+ },+ },+ "group_memberships": {+ "description": "The assignment of an agent to a group.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/groups/group_memberships/",+ "columns": _columns(+ user_id="The id of an agent.",+ group_id="The id of a group.",+ default="If true, tickets assigned directly to the agent assume this membership's group.",+ ),+ },+ "organization_memberships": {+ "description": "The assignment of a user to an organization.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/organizations/organization_memberships/",+ "columns": _columns(+ user_id="The id of the user this membership belongs to.",+ organization_id="The id of the organization associated with this user.",+ organization_name="The name of the organization associated with this user.",+ default="Whether this is the default organization membership for the user.",+ view_tickets="Whether the user can access all of the organization's tickets.",+ ),+ },+ "macros": {+ "description": "A predefined set of actions an agent can apply to a ticket in one click.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/business-rules/macros/",+ "columns": _columns(+ title="The title of the macro.",+ raw_title="The raw format of the title of the macro.",+ description="The description of the macro.",+ actions="Each action describes what the macro will do.",+ active="Useful for determining if the macro should be displayed.",+ default="If true, the macro is a default macro.",+ position="The position of the macro.",+ restriction="Access to this macro; null allows unrestricted access for all users in the account.",+ categories="The macro categories.",+ usage_1h="The number of times the macro has been used in the past hour.",+ usage_24h="The number of times the macro has been used in the past day.",+ usage_7d="The number of times the macro has been used in the past week.",+ usage_30d="The number of times the macro has been used in the past thirty days.",+ ),+ },+ "views": {+ "description": "A saved collection of tickets defined by a set of conditions.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/business-rules/views/",+ "columns": _columns(+ title="The title of the view.",+ description="The description of the view.",+ conditions="Describes how the view is constructed.",+ execution="Describes how the view should be executed.",+ active="Whether the view is active.",+ default="If true, the view is a default view.",+ position="The position of the view.",+ restriction="Who may access this view; null when everyone in the account can access it.",+ ),+ },+ "triggers": {+ "description": "A business rule that runs immediately after a ticket is created or updated.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/business-rules/triggers/",+ "columns": _columns(+ title="The title of the ticket trigger.",+ raw_title="The raw format of the title of the ticket trigger.",+ description="The description of the ticket trigger.",+ conditions="Describes the circumstances under which the trigger performs its actions.",+ actions="Describes what the ticket trigger will do.",+ active="Whether the ticket trigger is active.",+ default="If true, the ticket trigger is a standard trigger.",+ position="Position of the ticket trigger, determining the order they execute in.",+ category_id="The id of the category the ticket trigger belongs to.",+ brand_id="The id of the brand the ticket trigger belongs to.",+ restriction="Access restriction for this trigger; null allows unrestricted access.",+ ),+ },+ "automations": {+ "description": "A time-based business rule that runs hourly against tickets matching its conditions.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/business-rules/automations/",+ "columns": _columns(+ title="The title of the automation.",+ raw_title="The raw title of the automation.",+ conditions="Describes the conditions under which the automation will execute.",+ actions="Describes what the automation will do.",+ active="Whether the automation is active.",+ default="If true, the automation is a default automation.",+ position="The position of the automation, which specifies the order it is executed in.",+ ),+ },+ "custom_roles": {+ "description": "A custom agent role and the permissions granted to the team members assigned to it.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/account-configuration/custom_roles/",+ "columns": _columns(+ name="Name of the custom role.",+ description="A description of the role.",+ role_type="The role type: 0 custom agent, 1 light agent, 2 chat agent, 3 contributor.",+ configuration="Configuration settings for the role.",+ team_member_count="The number of team members assigned to this role.",+ ),+ },+ "user_fields": {+ "description": "A custom field that appears on user profiles.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/users/user_fields/",+ "columns": _columns(+ key="A unique key that identifies this custom field.",+ title="The title of the custom field.",+ raw_title="The dynamic content placeholder, if present, or the title value.",+ description="User-defined description of this field's purpose.",+ raw_description="The dynamic content placeholder, if present, or the description value.",+ type='The custom field type, such as "checkbox", "date", "dropdown", or "text".',+ active="If true, this field is available for use.",+ system="If true, only the active and position values of this field can be changed.",+ position="Ordering of the field relative to other fields.",+ custom_field_options='Selectable options, for a custom field of type "dropdown".',+ regexp_for_validation="The validation pattern for a regular expression field.",+ tag='Optional for a custom field of type "checkbox".',+ relationship_target_type="What type of object a lookup field references.",+ relationship_filter="A filter definition that narrows the autocomplete results.",+ ),+ },+ "organization_fields": {+ "description": "A custom field that appears on organizations.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/organizations/organization_fields/",+ "columns": _columns(+ key="A unique key that identifies this custom field.",+ title="The title of the custom field.",+ raw_title="The dynamic content placeholder, if present, or the title value.",+ description="User-defined description of this field's purpose.",+ raw_description="The dynamic content placeholder, if present, or the description value.",+ type='The custom field type, such as "checkbox", "date", "dropdown", or "text".',+ active="If true, this field is available for use.",+ system="If true, only the active and position values of this field can be changed.",+ position="Ordering of the field relative to other fields.",+ custom_field_options='Selectable options, for a custom field of type "dropdown".',+ regexp_for_validation="The validation pattern for a regular expression field.",+ tag='Optional for a custom field of type "checkbox".',+ relationship_target_type="What type of object a lookup field references.",+ relationship_filter="A filter definition that narrows the autocomplete results.",+ ),+ },+ "ticket_forms": {+ "description": "A configurable set of ticket fields presented to agents and end users.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/tickets/ticket_forms/",+ "columns": _columns(+ name="The name of the form.",+ raw_name="The dynamic content placeholder, if present, or the name value.",+ display_name="The name of the form that is displayed to an end user.",+ raw_display_name="The dynamic content placeholder, if present, or the display_name value.",+ active="If the form is set as active.",+ default="Is the form the default form for this account.",+ end_user_visible="Is the form visible to the end user.",+ in_all_brands="Is the form available for use in all brands on this account.",+ restricted_brand_ids="Ids of all brands that this ticket form is restricted to.",+ ticket_field_ids="Ids of all ticket fields in this form, in display order.",+ agent_conditions="Condition sets for agent workspaces.",+ end_user_conditions="Condition sets for end user products.",+ position="The position of this form among the other forms in the account.",+ deleted_at="The time the ticket form was deleted.",+ ),+ },+ "custom_statuses": {+ "description": "A custom ticket status and the system status category it belongs to.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/tickets/custom_ticket_statuses/",+ "columns": {+ "id": "Automatically assigned when the custom ticket status is created.",+ "status_category": "The status category the custom ticket status belongs to.",+ "agent_label": "The label displayed to agents.",+ "raw_agent_label": "The dynamic content placeholder, if present, or the agent_label value.",+ "end_user_label": "The label displayed to end users.",+ "raw_end_user_label": "The dynamic content placeholder, if present, or the end_user_label value.",+ "description": "The description of when the user should select this custom ticket status.",+ "raw_description": "The dynamic content placeholder, if present, or the description value.",+ "end_user_description": "The description displayed to end users.",+ "raw_end_user_description": "The dynamic content placeholder, if present, or the end_user_description value.",+ "active": "If true, the custom status is active.",+ "default": "If true, the custom status is the default for its category.",+ "created_at": "The date and time the custom ticket status was created.",+ "updated_at": "The date and time the custom ticket status was last updated.",+ },+ },+ "tags": {+ "description": "A tag in use on the account, with how many times it has been applied.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/ticket-management/tags/",+ "columns": {+ "name": "A name for the tag.",+ "count": "The number of times the tag has been applied.",+ },+ },+ "custom_objects": {+ "description": "A custom object type defined on the account, describing records outside the standard Zendesk objects.",+ "docs_url": "https://developer.zendesk.com/api-reference/custom-data/custom-objects/custom_objects/",+ "columns": {+ "key": "A user-defined unique identifier for the object. Writable on create only.",+ "url": "Direct link to the specific custom object.",+ "title": "User-defined display name for the object.",+ "title_pluralized": "User-defined pluralized version of the object's title.",+ "raw_title": "The dynamic content placeholder, if present, or the title value.",+ "raw_title_pluralized": "The dynamic content placeholder, if present, or the pluralized title value.",+ "description": "User-defined description of the object.",+ "raw_description": "The dynamic content placeholder, if present, or the description value.",+ "allows_attachments": "If true, file attachments can be added to the object's records.",+ "allows_photos": "If true, photos can be uploaded to the object's records.",+ "include_in_list_view": "Whether the object is visible in the agent's list view.",+ "created_by_user_id": "Id of the user who created the object.",+ "updated_by_user_id": "Id of the last user who updated the object.",+ "created_at": "The time the object type was created.",+ "updated_at": "The time of the last update of the object.",+ },+ },+ "audit_logs": {+ "description": "An account-level record of a configuration or access change, and who made it.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/account-configuration/audit_logs/",+ "columns": {+ "id": "The id automatically assigned upon creation.",+ "url": "The URL to access the audit log.",+ "action": 'Type of change made: "create", "destroy", "exported", "login", or "update".',+ "action_label": "Localized string of the action field.",+ "actor_id": "Id of the user or system that initiated the change.",+ "actor_name": "Name of the user or system that initiated the change.",+ "change_description": "The description of the change that occurred.",+ "source_id": "The id of the item being audited.",+ "source_label": "The name of the item being audited.",+ "source_type": "Item type being audited.",+ "ip_address": "The IP address of the user doing the audit.",+ "created_at": "The time the audit got created.",+ },+ },+ "activities": {+ "description": "An entry in the agent activity stream, such as a ticket assignment or comment.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/tickets/activity_stream/",+ "columns": _columns(+ title="Description of the activity.",+ verb='The type of activity, such as "tickets.assignment" or "tickets.comment".',+ actor_id="The id of the user responsible for the ticket activity; -1 is a Zendesk system user.",+ actor="The full user record of the user responsible for the ticket activity.",+ user_id="The id of the agent the activity is for.",+ user="The full user record of the agent the activity is for.",+ object="The content of the activity; a ticket, comment, or change.",+ target="The target of the activity, a ticket.",+ ),+ },+ "requests": {+ "description": "A ticket as the end user who submitted it sees it, with only end-user-visible fields.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/tickets/ticket-requests/",+ "columns": _columns(+ subject="The value of the subject field, if the subject field is visible to end users.",+ description="Read-only first comment on the request.",+ status='The state of the request: "new", "open", "pending", "hold", "solved", or "closed".',+ priority='The priority of the request: "low", "normal", "high", or "urgent".',+ type='The type of the request: "question", "incident", "problem", or "task".',+ requester_id="The id of the requester.",+ assignee_id="The id of the assignee, if the field is visible to end users.",+ group_id="The id of the assigned group, if the field is visible to end users.",+ organization_id="The organization of the requester.",+ collaborator_ids="The ids of users currently CC'ed on the ticket.",+ email_cc_ids="The ids of users who are currently email CCs on the ticket.",+ custom_fields="Custom fields for the request.",+ custom_status_id="The custom ticket status id of the ticket.",+ ticket_form_id="The numeric id of the ticket form associated with this request.",+ followup_source_id="The id of the original ticket if this request is a follow-up.",+ is_public="True if any comments are public.",+ solved="Whether the request is solved.",+ can_be_solved_by_me="If true, an end user can mark the request as solved.",+ recipient="The original recipient email address of the request.",+ due_at='When the task is due; only applies to requests of type "task".',+ via="Describes how the object was created.",+ ),+ },+ "suspended_tickets": {+ "description": "An inbound message held for review instead of becoming a ticket, with the reason it was suspended.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/tickets/suspended_tickets/",+ "columns": _columns(+ subject="The value of the subject field for this ticket.",+ content="The content that was flagged.",+ content_html="Sanitized HTML content, when the suspended ticket came from rich content.",+ cause="Why the ticket was suspended.",+ cause_id="The id of the cause.",+ author="The author id (if available), name, and email.",+ recipient="The original recipient email address of the ticket.",+ brand_id="The id of the brand this ticket is associated with.",+ ticket_id="The ticket id this suspended email is associated with, if available.",+ message_id="The id of the email, if available.",+ error_messages="The error messages associated with this suspended ticket, if any.",+ attachments="The attachments associated with this suspended ticket, if any.",+ via="Explains how the ticket was created.",+ ),+ },+ "deleted_tickets": {+ "description": "A ticket that has been deleted and is recoverable from the trash.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/tickets/tickets/",+ "columns": {+ "id": "The id of the deleted ticket.",+ "subject": "The subject of the deleted ticket.",+ "deleted_at": "When the ticket was deleted.",+ "previous_state": "The status the ticket was in before it was deleted.",+ "actor": "The user who deleted the ticket.",+ },+ },+ "saved_searches": {+ "description": "A search query an agent saved for reuse.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/ticket-management/saved_searches/",+ "columns": {+ "id": "Automatically assigned UUID when the saved search is created.",+ "name": "The name given by the agent to the saved search.",+ "query": "The search query string.",+ "type": "The type of object the search applies to.",+ "filters": "A JSON-stringified array of filter field ids persisted alongside the search.",+ "created_at": "The time the saved search was created.",+ "updated_at": "The time the saved search was last updated.",+ },+ },+ "queues": {+ "description": "An omnichannel routing queue and the conditions that route work into it.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/omnichannel-routing/queues/",+ "columns": _columns(+ name="The name of the queue.",+ description="The description of the queue.",+ definition="Conditions under which the queue applies.",+ order="The order the queue is applied in.",+ priority="The priority the queue applies.",+ primary_groups="Primary group ids linked to the queue.",+ secondary_groups="Secondary group ids linked to the queue.",+ ),+ },+ "brand_agents": {+ "description": "The membership of an agent in a brand.",+ "docs_url": "https://developer.zendesk.com/api-reference/ticketing/account-configuration/brand_agent/",+ "columns": _columns(+ user_id="The id of an agent.",+ brand_id="The id of a brand.",+ ),+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/settings.pyindex e65c37f79927..7c66c1ddfdf8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/settings.py@@ -1,7 +1,14 @@"""Zendesk source settings and constants"""+from dataclasses import dataclass, fieldfrom datetime import UTC, datetime+from typing import Any+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortModefrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldTypeDEFAULT_START_DATE = datetime(year=2000, month=1, day=1, tzinfo=UTC)@@ -121,3 +128,257 @@ INCREMENTAL_TALK_ENDPOINTS = {"calls": "/api/v2/channels/voice/stats/incremental/calls.json","legs": "/api/v2/channels/voice/stats/incremental/legs.json",}+++# Page size for Zendesk's cursor-based pagination (`page[size]`), which the Support API caps at 100.+CURSOR_PAGE_SIZE = 100+++@dataclass+class ZendeskEndpointConfig:+ """Declarative config for a Zendesk Support API list endpoint.++ The nine original endpoints keep their hand-written resources in `zendesk.py` (they ride the+ Incremental Export API and each needs its own paginator); everything listed in+ `ZENDESK_ENDPOINTS` below is built from this config instead.+ """++ name: str+ path: str+ data_selector: str+ primary_key: list[str]+ # Zendesk's cursor-based pagination: `page[size]` on the request, `links.next` on the response.+ # False for endpoints the API returns as a single unpaginated collection.+ paginated: bool = True+ # Response path holding the next page URL. `ticket_audits` returns `after_url` instead.+ next_url_path: str = "links.next"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ # Query param carrying the server-side time filter, when the endpoint has one.+ incremental_start_param: str | None = None+ partition_key: str | None = None+ sort_mode: SortMode = "asc"+ page_size: int = CURSOR_PAGE_SIZE+ fanout: DependentEndpointConfig | None = None+ params: dict[str, Any] = field(default_factory=dict)+++# Parent that drives the `ticket_comments` fan-out. It is deliberately kept out of+# `ZENDESK_ENDPOINTS` so it never becomes a schema of its own — tickets already sync through the+# cursor incremental export.+TICKET_COMMENTS_PARENT_NAME = "tickets_for_comments"+TICKET_COMMENTS_PARENT = ZendeskEndpointConfig(+ name=TICKET_COMMENTS_PARENT_NAME,+ path="/api/v2/tickets",+ data_selector="tickets",+ primary_key=["id"],+)++# Parent endpoints referenced by `ZendeskEndpointConfig.fanout`, looked up by `fanout.parent_name`.+FANOUT_PARENTS: dict[str, ZendeskEndpointConfig] = {TICKET_COMMENTS_PARENT_NAME: TICKET_COMMENTS_PARENT}+++ZENDESK_ENDPOINTS: dict[str, ZendeskEndpointConfig] = {+ "satisfaction_ratings": ZendeskEndpointConfig(+ name="satisfaction_ratings",+ path="/api/v2/satisfaction_ratings",+ data_selector="satisfaction_ratings",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "ticket_metrics": ZendeskEndpointConfig(+ name="ticket_metrics",+ path="/api/v2/ticket_metrics",+ data_selector="ticket_metrics",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "ticket_audits": ZendeskEndpointConfig(+ name="ticket_audits",+ path="/api/v2/ticket_audits",+ data_selector="audits",+ primary_key=["id"],+ # This endpoint predates `links.next` and returns its cursor as `after_url`.+ next_url_path="after_url",+ partition_key="created_at",+ ),+ "ticket_comments": ZendeskEndpointConfig(+ name="ticket_comments",+ path="/api/v2/tickets/{ticket_id}/comments",+ data_selector="comments",+ # Comments are listed per ticket, so the parent id is part of the key to keep it unique+ # across the whole table.+ primary_key=["ticket_id", "id"],+ partition_key="created_at",+ fanout=DependentEndpointConfig(+ parent_name=TICKET_COMMENTS_PARENT_NAME,+ resolve_param="ticket_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "ticket_id"},+ ),+ ),+ "group_memberships": ZendeskEndpointConfig(+ name="group_memberships",+ path="/api/v2/group_memberships",+ data_selector="group_memberships",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "organization_memberships": ZendeskEndpointConfig(+ name="organization_memberships",+ path="/api/v2/organization_memberships",+ data_selector="organization_memberships",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "macros": ZendeskEndpointConfig(+ name="macros",+ path="/api/v2/macros",+ data_selector="macros",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "views": ZendeskEndpointConfig(+ name="views",+ path="/api/v2/views",+ data_selector="views",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "triggers": ZendeskEndpointConfig(+ name="triggers",+ path="/api/v2/triggers",+ data_selector="triggers",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "automations": ZendeskEndpointConfig(+ name="automations",+ path="/api/v2/automations",+ data_selector="automations",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "custom_roles": ZendeskEndpointConfig(+ name="custom_roles",+ path="/api/v2/custom_roles",+ data_selector="custom_roles",+ primary_key=["id"],+ paginated=False,+ partition_key="created_at",+ ),+ "user_fields": ZendeskEndpointConfig(+ name="user_fields",+ path="/api/v2/user_fields",+ data_selector="user_fields",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "organization_fields": ZendeskEndpointConfig(+ name="organization_fields",+ path="/api/v2/organization_fields",+ data_selector="organization_fields",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "ticket_forms": ZendeskEndpointConfig(+ name="ticket_forms",+ path="/api/v2/ticket_forms",+ data_selector="ticket_forms",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "custom_statuses": ZendeskEndpointConfig(+ name="custom_statuses",+ path="/api/v2/custom_statuses",+ data_selector="custom_statuses",+ primary_key=["id"],+ paginated=False,+ partition_key="created_at",+ ),+ "tags": ZendeskEndpointConfig(+ name="tags",+ path="/api/v2/tags",+ data_selector="tags",+ # A tag row is just `{name, count}` — the name is the identity.+ primary_key=["name"],+ # No timestamp on the row, so nothing stable to partition on.+ ),+ "custom_objects": ZendeskEndpointConfig(+ name="custom_objects",+ path="/api/v2/custom_objects",+ data_selector="custom_objects",+ # Custom objects are identified by their user-defined key; there is no numeric id.+ primary_key=["key"],+ paginated=False,+ partition_key="created_at",+ ),+ "audit_logs": ZendeskEndpointConfig(+ name="audit_logs",+ path="/api/v2/audit_logs",+ data_selector="audit_logs",+ primary_key=["id"],+ # `filter[created_at]` must be sent twice (start *and* end) to be valid, which a single+ # start-param cursor can't express — so this stays full refresh.+ partition_key="created_at",+ ),+ "activities": ZendeskEndpointConfig(+ name="activities",+ path="/api/v2/activities",+ data_selector="activities",+ primary_key=["id"],+ incremental_fields=[incremental_field("created_at")],+ default_incremental_field="created_at",+ incremental_start_param="since",+ partition_key="created_at",+ # The activity stream returns newest first and takes no sort param we can pin, so the+ # watermark is only committed once the whole sync finishes.+ sort_mode="desc",+ ),+ "requests": ZendeskEndpointConfig(+ name="requests",+ path="/api/v2/requests",+ data_selector="requests",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "suspended_tickets": ZendeskEndpointConfig(+ name="suspended_tickets",+ path="/api/v2/suspended_tickets",+ data_selector="suspended_tickets",+ primary_key=["id"],+ partition_key="created_at",+ ),+ "deleted_tickets": ZendeskEndpointConfig(+ name="deleted_tickets",+ path="/api/v2/deleted_tickets",+ data_selector="deleted_tickets",+ primary_key=["id"],+ # Deleted tickets carry no created_at; deleted_at is set once and never moves.+ partition_key="deleted_at",+ ),+ "saved_searches": ZendeskEndpointConfig(+ name="saved_searches",+ path="/api/v2/saved_searches",+ data_selector="saved_searches",+ primary_key=["id"],+ paginated=False,+ partition_key="created_at",+ ),+ "queues": ZendeskEndpointConfig(+ name="queues",+ path="/api/v2/queues",+ data_selector="queues",+ primary_key=["id"],+ paginated=False,+ partition_key="created_at",+ ),+ "brand_agents": ZendeskEndpointConfig(+ name="brand_agents",+ path="/api/v2/brand_agents",+ data_selector="brand_agents",+ primary_key=["id"],+ partition_key="created_at",+ ),+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.pyindex ab64e96a6ecb..134090806e22 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.seINCREMENTAL_FIELDS as ZENDESK_INCREMENTAL_FIELDS,PARTITION_FIELDS,SUPPORT_ENDPOINTS,+ ZENDESK_ENDPOINTS,)from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.zendesk import (normalize_subdomain,@@ -79,6 +80,15 @@ class ZendeskSource(SimpleSource[ZendeskSourceConfig]):for endpoint in list(BASE_ENDPOINTS)+ [resource for resource, endpoint_url, data_key, cursor_paginated in SUPPORT_ENDPOINTS]]+ schemas += [+ SourceSchema(+ name=endpoint_config.name,+ supports_incremental=bool(endpoint_config.incremental_fields),+ supports_append=bool(endpoint_config.incremental_fields),+ incremental_fields=endpoint_config.incremental_fields,+ )+ for endpoint_config in ZENDESK_ENDPOINTS.values()+ ]if names is not None:names_set = set(names)schemas = [s for s in schemas if s.name in names_set]@@ -157,15 +167,22 @@ class ZendeskSource(SimpleSource[ZendeskSourceConfig]):db_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fieldelse None,+ incremental_field_name=inputs.incremental_field,)+ # The original nine endpoints aren't in the declarative catalog; they keep the `id`+ # primary key and ascending sort they have always used.+ endpoint_config = ZENDESK_ENDPOINTS.get(inputs.schema_name)response = SourceResponse(name=resource.name,items=lambda: resource,- primary_keys=["id"],+ primary_keys=endpoint_config.primary_key if endpoint_config else ["id"],column_hints=resource.column_hints,+ sort_mode=endpoint_config.sort_mode if endpoint_config else "asc",)partition_key = PARTITION_FIELDS.get(inputs.schema_name, None)+ if partition_key is None and endpoint_config is not None:+ partition_key = endpoint_config.partition_key# All partition keys are datetimeif partition_key:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.pyindex 3b3f468c2822..44e381f8fc7a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.py@@ -1,26 +1,40 @@import json-from datetime import UTC, datetime+from datetime import UTC, datetime, timedelta, timezone+from types import SimpleNamespacefrom typing import Any, castimport pytest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom requests import Request, Response+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONLinkPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zendesk import (ZendeskSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.settings import (+ CURSOR_PAGE_SIZE,+ FANOUT_PARENTS,INCREMENTAL_ENDPOINTS,INCREMENTAL_FIELDS,+ TICKET_COMMENTS_PARENT_NAME,+ ZENDESK_ENDPOINTS,)from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.source import ZendeskSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.zendesk import (+ ZendeskAfterUrlPaginator,ZendeskCursorIncrementalPaginator,ZendeskIncrementalEndpointPaginator,+ get_declarative_resource,get_resource,normalize_subdomain,+ to_zendesk_iso8601,to_zendesk_start_time,+ zendesk_source,)@@ -327,3 +341,328 @@ class TestIncrementalResourceWiring:assert INCREMENTAL_FIELDS.get(endpoint), (f"{endpoint} is in INCREMENTAL_ENDPOINTS but has no incremental field")+++def _source_inputs(schema_name: str, should_use_incremental_field: bool = False) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++# Path + data key for every declaratively configured endpoint, transcribed from Zendesk's+# published OpenAPI description. A drifted path 404s and a drifted data key syncs 0 rows, and+# neither shows up until a customer's sync breaks — so they are pinned here rather than read+# back out of the config under test.+EXPECTED_ENDPOINTS: dict[str, tuple[str, str]] = {+ "satisfaction_ratings": ("/api/v2/satisfaction_ratings", "satisfaction_ratings"),+ "ticket_metrics": ("/api/v2/ticket_metrics", "ticket_metrics"),+ "ticket_audits": ("/api/v2/ticket_audits", "audits"),+ "ticket_comments": ("/api/v2/tickets/{ticket_id}/comments", "comments"),+ "group_memberships": ("/api/v2/group_memberships", "group_memberships"),+ "organization_memberships": ("/api/v2/organization_memberships", "organization_memberships"),+ "macros": ("/api/v2/macros", "macros"),+ "views": ("/api/v2/views", "views"),+ "triggers": ("/api/v2/triggers", "triggers"),+ "automations": ("/api/v2/automations", "automations"),+ "custom_roles": ("/api/v2/custom_roles", "custom_roles"),+ "user_fields": ("/api/v2/user_fields", "user_fields"),+ "organization_fields": ("/api/v2/organization_fields", "organization_fields"),+ "ticket_forms": ("/api/v2/ticket_forms", "ticket_forms"),+ "custom_statuses": ("/api/v2/custom_statuses", "custom_statuses"),+ "tags": ("/api/v2/tags", "tags"),+ "custom_objects": ("/api/v2/custom_objects", "custom_objects"),+ "audit_logs": ("/api/v2/audit_logs", "audit_logs"),+ "activities": ("/api/v2/activities", "activities"),+ "requests": ("/api/v2/requests", "requests"),+ "suspended_tickets": ("/api/v2/suspended_tickets", "suspended_tickets"),+ "deleted_tickets": ("/api/v2/deleted_tickets", "deleted_tickets"),+ "saved_searches": ("/api/v2/saved_searches", "saved_searches"),+ "queues": ("/api/v2/queues", "queues"),+ "brand_agents": ("/api/v2/brand_agents", "brand_agents"),+}++# Endpoints Zendesk returns as one unpaginated collection — sending `page[size]` there would be+# an undocumented param.+UNPAGINATED_ENDPOINTS = {"custom_roles", "custom_statuses", "custom_objects", "saved_searches", "queues"}+++class TestZendeskDeclarativeEndpoints:+ def test_catalog_matches_the_published_api(self) -> None:+ assert {name: (c.path, c.data_selector) for name, c in ZENDESK_ENDPOINTS.items()} == EXPECTED_ENDPOINTS++ @pytest.mark.parametrize("endpoint", sorted(set(EXPECTED_ENDPOINTS) - {"ticket_comments"}))+ def test_resource_wiring(self, endpoint: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=False)+ endpoint_config = _endpoint(resource)+ path, data_selector = EXPECTED_ENDPOINTS[endpoint]++ assert resource["name"] == endpoint+ assert endpoint_config["path"] == path+ assert endpoint_config["data_selector"] == data_selector+ # The wrapper key is documented for all of these, so a response without it is a changed+ # API shape and must fail loud rather than sync 0 rows.+ assert endpoint_config["data_selector_required"] is True++ if endpoint in UNPAGINATED_ENDPOINTS:+ assert isinstance(endpoint_config["paginator"], SinglePagePaginator)+ assert "page[size]" not in endpoint_config["params"]+ else:+ assert isinstance(endpoint_config["paginator"], JSONLinkPaginator)+ assert endpoint_config["params"]["page[size]"] == CURSOR_PAGE_SIZE++ def test_ticket_audits_paginates_on_its_own_cursor_field(self) -> None:+ # ticket_audits predates `links.next`; reading the wrong field would stop after one page.+ endpoint_config = _endpoint(get_resource("ticket_audits", should_use_incremental_field=False))+ paginator = endpoint_config["paginator"]++ assert isinstance(paginator, ZendeskAfterUrlPaginator)+ assert paginator.next_url_path == "after_url"++ def test_fanout_endpoint_is_not_built_as_a_top_level_resource(self) -> None:+ with pytest.raises(ValueError):+ get_declarative_resource(ZENDESK_ENDPOINTS["ticket_comments"], should_use_incremental_field=False)++ def test_every_fanout_parent_is_registered(self) -> None:+ for config in ZENDESK_ENDPOINTS.values():+ if config.fanout is not None:+ assert config.fanout.parent_name in FANOUT_PARENTS++ def test_fanout_supplies_the_parent_derived_primary_key_columns(self) -> None:+ # ticket_comments is keyed on (ticket_id, id); ticket_id only exists on the row because+ # the fan-out injects the parent's id, so dropping the rename would seed duplicate rows.+ config = ZENDESK_ENDPOINTS["ticket_comments"]+ assert config.fanout is not None+ assert set(config.primary_key) - {"id"} <= set(config.fanout.parent_field_renames.values())+++class TestZendeskAfterUrlPaginator:+ def test_follows_after_url(self) -> None:+ p = ZendeskAfterUrlPaginator()+ p.update_state(+ _make_response({"audits": [{"id": 1}], "after_url": "https://x.zendesk.com/next"}), data=[{"id": 1}]+ )++ assert p.has_next_page is True++ req = Request(method="GET", url="https://x.zendesk.com/api/v2/ticket_audits")+ req.params = {"page[size]": 100}+ p.update_request(req)+ assert req.url == "https://x.zendesk.com/next"+ assert req.params == {}++ @pytest.mark.parametrize(+ "body,data",+ [+ pytest.param({"audits": [], "after_url": "https://x.zendesk.com/next"}, [], id="empty_page_with_cursor"),+ pytest.param({"audits": [{"id": 1}], "after_url": None}, [{"id": 1}], id="no_cursor"),+ pytest.param({"audits": [{"id": 1}]}, [{"id": 1}], id="cursor_absent"),+ ],+ )+ def test_stops_pagination(self, body: dict[str, Any], data: list[dict[str, Any]]) -> None:+ # The endpoint keeps handing back a cursor URL past the end of the stream, so an empty+ # page has to terminate too — otherwise the sync loops forever on the last page.+ p = ZendeskAfterUrlPaginator()++ p.update_state(_make_response(body), data=data)++ assert p.has_next_page is False+++class TestZendeskDeclarativeIncremental:+ def test_activities_uses_the_server_side_since_filter(self) -> None:+ endpoint_config = _endpoint(get_resource("activities", should_use_incremental_field=True))+ incremental = endpoint_config["incremental"]++ assert incremental["start_param"] == "since"+ assert incremental["cursor_path"] == "created_at"+ # The plain list endpoints take ISO 8601, not the Unix epoch the incremental exports use.+ assert incremental["convert"] is to_zendesk_iso8601++ def test_activities_honors_the_users_chosen_cursor_field(self) -> None:+ endpoint_config = _endpoint(+ get_resource("activities", should_use_incremental_field=True, incremental_field_name="updated_at")+ )++ assert endpoint_config["incremental"]["cursor_path"] == "updated_at"++ @pytest.mark.parametrize(+ "endpoint,should_use_incremental_field,expects_incremental",+ [+ pytest.param("activities", True, True, id="activities_incremental"),+ pytest.param("activities", False, False, id="activities_full_refresh"),+ # No server-side time filter is documented for these, so they must stay full refresh+ # even when the schema is flagged incremental.+ pytest.param("satisfaction_ratings", True, False, id="satisfaction_ratings_stays_full_refresh"),+ pytest.param("audit_logs", True, False, id="audit_logs_stays_full_refresh"),+ ],+ )+ def test_write_disposition_follows_server_side_filter_support(+ self, endpoint: str, should_use_incremental_field: bool, expects_incremental: bool+ ) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=should_use_incremental_field)+ endpoint_config = _endpoint(resource)++ assert ("incremental" in endpoint_config) is expects_incremental+ assert resource["write_disposition"] == (+ {"disposition": "merge", "strategy": "upsert"} if expects_incremental else "replace"+ )+++class TestToZendeskIso8601:+ @pytest.mark.parametrize(+ "value,expected",+ [+ pytest.param("1970-01-01T00:00:00Z", "1970-01-01T00:00:00Z", id="initial_value_passthrough"),+ pytest.param(datetime(2020, 6, 5, 21, 23, 6, tzinfo=UTC), "2020-06-05T21:23:06Z", id="aware_datetime"),+ pytest.param(datetime(2020, 6, 5, 21, 23, 6), "2020-06-05T21:23:06Z", id="naive_datetime_as_utc"),+ pytest.param(+ datetime(2020, 6, 5, 21, 23, 6, tzinfo=timezone(timedelta(hours=2))),+ "2020-06-05T19:23:06Z",+ id="offset_datetime_converted_to_utc",+ ),+ ],+ )+ def test_formats_for_the_since_filter(self, value: Any, expected: str) -> None:+ assert to_zendesk_iso8601(value) == expected+++class _FakeResource:+ def __init__(self, name: str) -> None:+ self.name = name+ self.maps: list[Any] = []++ def add_map(self, fn: Any) -> "_FakeResource":+ self.maps.append(fn)+ return self+++class TestZendeskTicketCommentsFanout:+ def _build(self) -> tuple[_FakeResource, list[Any]]:+ child = _FakeResource("ticket_comments")++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources",+ return_value=[_FakeResource("tickets_for_comments"), child],+ ) as mock_resources:+ zendesk_source(+ subdomain="nibbles",+ api_key="token",+ email_address="[email protected]",+ endpoint="ticket_comments",+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ )++ return child, mock_resources.call_args[0]++ def test_parent_and_child_endpoints(self) -> None:+ _, args = self._build()+ parent, child = args[0]["resources"]++ assert parent["endpoint"]["path"] == "/api/v2/tickets"+ assert parent["endpoint"]["params"]["page[size]"] == CURSOR_PAGE_SIZE+ assert child["endpoint"]["path"] == "/api/v2/tickets/{ticket_id}/comments"+ # The ticket id is bound from the parent row into the child path.+ assert child["endpoint"]["params"]["ticket_id"] == {+ "type": "resolve",+ "resource": TICKET_COMMENTS_PARENT_NAME,+ "field": "id",+ }+ assert child["include_from_parent"] == ["id"]++ def test_comment_rows_carry_the_parent_ticket_id(self) -> None:+ # Without this rename a comment row has no ticket_id, so the (ticket_id, id) primary key+ # would never match and every sync would seed duplicates.+ child, _ = self._build()++ row = child.maps[0]({f"_{TICKET_COMMENTS_PARENT_NAME}_id": 42, "id": 7, "body": "hi"})++ assert row == {"ticket_id": 42, "id": 7, "body": "hi"}+++class TestZendeskSchemas:+ def _schemas(self) -> dict[str, Any]:+ config = ZendeskSourceConfig(subdomain="nibbles", api_key="token", email_address="[email protected]")+ return {schema.name: schema for schema in ZendeskSource().get_schemas(config, team_id=1)}++ def test_every_declared_endpoint_is_offered_exactly_once(self) -> None:+ config = ZendeskSourceConfig(subdomain="nibbles", api_key="token", email_address="[email protected]")+ names = [schema.name for schema in ZendeskSource().get_schemas(config, team_id=1)]++ assert len(names) == len(set(names))+ assert set(ZENDESK_ENDPOINTS).issubset(names)+ # The endpoints that shipped first must keep being offered.+ assert {"tickets", "users", "organizations", "brands", "groups", "sla_policies"}.issubset(names)++ def test_only_endpoints_with_a_server_side_filter_advertise_incremental(self) -> None:+ schemas = self._schemas()+ incremental = {name for name in ZENDESK_ENDPOINTS if schemas[name].supports_incremental}++ assert incremental == {"activities"}+ assert schemas["activities"].incremental_fields[0]["field"] == "created_at"++ def test_canonical_descriptions_cover_every_new_table(self) -> None:+ descriptions = ZendeskSource().get_canonical_descriptions()++ for name in ZENDESK_ENDPOINTS:+ assert name in descriptions, f"{name} has no canonical description"+ assert descriptions[name]["description"]+ assert descriptions[name]["docs_url"].startswith("https://developer.zendesk.com/")+++class TestZendeskSourceForPipeline:+ def _response(self, schema_name: str) -> Any:+ config = ZendeskSourceConfig(subdomain="nibbles", api_key="token", email_address="[email protected]")+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.source.zendesk_source",+ return_value=SimpleNamespace(name=schema_name, column_hints=None),+ ):+ return ZendeskSource().source_for_pipeline(config, _source_inputs(schema_name))++ @pytest.mark.parametrize(+ "schema_name,primary_keys,partition_key",+ [+ # The original endpoints keep the key and partition they have always synced with.+ pytest.param("tickets", ["id"], "created_at", id="tickets_unchanged"),+ pytest.param("ticket_metric_events", ["id"], "time", id="ticket_metric_events_unchanged"),+ # A tag row is just {name, count} — keying it on `id` would collapse the whole table.+ pytest.param("tags", ["name"], None, id="tags_keyed_on_name"),+ pytest.param("custom_objects", ["key"], "created_at", id="custom_objects_keyed_on_key"),+ pytest.param("ticket_comments", ["ticket_id", "id"], "created_at", id="ticket_comments_composite_key"),+ pytest.param("deleted_tickets", ["id"], "deleted_at", id="deleted_tickets_partitioned_on_deleted_at"),+ pytest.param("satisfaction_ratings", ["id"], "created_at", id="satisfaction_ratings"),+ ],+ )+ def test_primary_keys_and_partitioning(+ self, schema_name: str, primary_keys: list[str], partition_key: str | None+ ) -> None:+ response = self._response(schema_name)++ assert response.primary_keys == primary_keys+ assert response.partition_keys == ([partition_key] if partition_key else None)+ assert response.partition_mode == ("datetime" if partition_key else None)++ @pytest.mark.parametrize(+ "schema_name,sort_mode",+ [+ pytest.param("tickets", "asc", id="tickets_unchanged"),+ # The activity stream returns newest first, so the watermark must only be committed+ # once the sync completes.+ pytest.param("activities", "desc", id="activities_desc"),+ pytest.param("macros", "asc", id="macros_asc"),+ ],+ )+ def test_sort_mode(self, schema_name: str, sort_mode: str) -> None:+ assert self._response(schema_name).sort_mode == sort_modediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.pyindex 5e9a7adf16fa..cac3f9a6de5b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.py@@ -1,7 +1,7 @@import reimport base64from datetime import UTC, datetime-from typing import Any, Optional+from typing import Any, Optional, castfrom requests import Request, Response@@ -11,11 +11,30 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BasePaginator,JSONLinkPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ IncrementalConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.settings import (+ FANOUT_PARENTS,+ ZENDESK_ENDPOINTS,+ ZendeskEndpointConfig,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource++# Lower bound for the ISO 8601 time filters on the first run / full refresh, mirroring the `0`+# epoch seed the incremental exports use.+ZENDESK_EPOCH_START = "1970-01-01T00:00:00Z"def to_zendesk_start_time(value: Any) -> int:@@ -28,7 +47,78 @@ def to_zendesk_start_time(value: Any) -> int:return int(value)-def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:+def to_zendesk_iso8601(value: Any) -> str:+ """Format an incremental cursor value for the ISO 8601 UTC filters (`since`) on the plain+ Support list endpoints, which — unlike the incremental exports — don't take Unix epochs."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def zendesk_incremental_window(start_param: str, cursor_path: str) -> IncrementalConfig:+ return {+ "start_param": start_param,+ "cursor_path": cursor_path,+ "initial_value": ZENDESK_EPOCH_START,+ "convert": to_zendesk_iso8601,+ }+++def paginator_for(config: ZendeskEndpointConfig) -> BasePaginator:+ if not config.paginated:+ return SinglePagePaginator()+ if config.next_url_path == "after_url":+ return ZendeskAfterUrlPaginator()+ return JSONLinkPaginator(next_url_path=config.next_url_path)+++def get_declarative_resource(+ config: ZendeskEndpointConfig,+ should_use_incremental_field: bool,+ incremental_field_name: str | None = None,+) -> EndpointResource:+ """Build a resource for one of the plain Support API list endpoints in `ZENDESK_ENDPOINTS`."""+ if config.fanout:+ raise ValueError(f"Fan-out endpoint '{config.name}' must be built through the fan-out path")++ params: dict[str, Any] = dict(config.params)+ if config.paginated:+ params["page[size]"] = config.page_size++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": params,+ "data_selector": config.data_selector,+ # Every one of these responses wraps its rows in a documented key, so a response without+ # it means the API shape changed — fail loud rather than silently syncing 0 rows.+ "data_selector_required": True,+ "paginator": paginator_for(config),+ }++ use_incremental = should_use_incremental_field and bool(config.incremental_fields)+ if use_incremental:+ if config.incremental_start_param is None:+ raise ValueError(f"Endpoint '{config.name}' advertises incremental fields but has no start param")+ endpoint_config["incremental"] = zendesk_incremental_window(+ config.incremental_start_param,+ incremental_field_name or config.default_incremental_field or "created_at",+ )++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def get_resource(+ name: str,+ should_use_incremental_field: bool,+ incremental_field_name: str | None = None,+) -> EndpointResource:resources: dict[str, EndpointResource] = {"brands": {"name": "brands",@@ -253,7 +343,10 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResou},}- return resources[name]+ if name in resources:+ return resources[name]++ return get_declarative_resource(ZENDESK_ENDPOINTS[name], should_use_incremental_field, incremental_field_name)class ZendeskCursorIncrementalPaginator(BasePaginator):@@ -340,6 +433,24 @@ class ZendeskIncrementalEndpointPaginator(BasePaginator):request.params = {}+class ZendeskAfterUrlPaginator(JSONLinkPaginator):+ """Cursor pagination for `/api/v2/ticket_audits`, which returns its next-page link as+ `after_url` rather than the `links.next` the newer list endpoints use.++ An empty page also terminates: the endpoint keeps handing back a cursor URL once the stream+ is exhausted, so the link on its own isn't a reliable stop condition.+ """++ def __init__(self) -> None:+ super().__init__(next_url_path="after_url")++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ if data is not None and len(data) == 0:+ self._has_next_page = False+ return+ super().update_state(response, data)++def normalize_subdomain(subdomain: str) -> str:"""Reduce whatever the user entered to the bare Zendesk subdomain label.@@ -357,6 +468,55 @@ def normalize_subdomain(subdomain: str) -> str:return re.sub(r"\.zendesk\.com$", "", subdomain, flags=re.IGNORECASE)+def zendesk_client_config(subdomain: str, api_key: str, email_address: str) -> ClientConfig:+ return {+ "base_url": f"https://{normalize_subdomain(subdomain)}.zendesk.com/",+ "auth": {+ "type": "http_basic",+ "username": f"{email_address}/token",+ "password": api_key,+ },+ }+++def zendesk_fanout_source(+ client_config: ClientConfig,+ config: ZendeskEndpointConfig,+ team_id: int,+ job_id: str,+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+ incremental_field_name: str | None = None,+) -> Resource:+ """Fan out over a parent list endpoint, then page the child endpoint per parent row."""+ assert config.fanout is not None+ parent = FANOUT_PARENTS[config.fanout.parent_name]+ return cast(+ Resource,+ build_dependent_resource(+ endpoint_configs={config.name: config, parent.name: parent},+ child_endpoint=config.name,+ fanout=config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ incremental_field=incremental_field_name,+ page_size_param="page[size]",+ parent_endpoint_extra={+ "paginator": JSONLinkPaginator(next_url_path="links.next"),+ "data_selector": parent.data_selector,+ },+ child_endpoint_extra={+ "paginator": paginator_for(config),+ "data_selector": config.data_selector,+ },+ ),+ )++def zendesk_source(subdomain: str,api_key: str,@@ -366,16 +526,24 @@ def zendesk_source(job_id: str,db_incremental_field_last_value: Optional[Any],should_use_incremental_field: bool = False,+ incremental_field_name: str | None = None,):+ client_config = zendesk_client_config(subdomain, api_key, email_address)++ endpoint_config = ZENDESK_ENDPOINTS.get(endpoint)+ if endpoint_config is not None and endpoint_config.fanout is not None:+ return zendesk_fanout_source(+ client_config,+ endpoint_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ should_use_incremental_field,+ incremental_field_name,+ )+config: RESTAPIConfig = {- "client": {- "base_url": f"https://{normalize_subdomain(subdomain)}.zendesk.com/",- "auth": {- "type": "http_basic",- "username": f"{email_address}/token",- "password": api_key,- },- },+ "client": client_config,"resource_defaults": {"write_disposition": {"disposition": "merge",@@ -384,7 +552,7 @@ def zendesk_source(if should_use_incremental_fieldelse "replace",},- "resources": [get_resource(endpoint, should_use_incremental_field)],+ "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field_name)],}return rest_api_resource(config, team_id, job_id, db_incremental_field_last_value)