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): add freshdesk sub-resource and lookup tables (#108312)

Tom Owers311794bf0f4a
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 76d5cf6da738..4526511bb97f 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -589,7 +589,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/freshchat.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/freshdesk.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/freshsales.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/freshservice.py
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.md
index e63680148705..45ca9cf4941c 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
@@ -3355,14 +3355,14 @@ Note: There is no top-level GET /v2/conversations list - conversations are only
## Freshdesk — gaps
-Today (14): `agents`, `business_hours`, `canned_response_folders`, `companies`, `contacts`, `groups`, `products`, `roles`, `satisfaction_ratings`, `skills`, `sla_policies`, `ticket_fields`, `tickets`, `time_entries`
+Today (20): `agents`, `business_hours`, `canned_response_folders`, `canned_responses`, `companies`, `contact_fields`, `contacts`, `conversations`, `groups`, `products`, `roles`, `satisfaction_ratings`, `skills`, `sla_policies`, `solution_articles`, `solution_categories`, `solution_folders`, `ticket_fields`, `tickets`, `time_entries`
Diffed against: <https://developers.freshdesk.com/api/>
-- [ ] `/api/v2/tickets/{id}/conversations` — ticket replies and notes - the actual support conversation behind every ticket row we sync (high)
-- [ ] `/api/v2/contact_fields` — lookup resolving custom contact field IDs and their dropdown choices (high)
-- [ ] `/api/v2/canned_response_folders/{id}/responses` — the canned responses themselves; only their folders are synced today (high)
-- [ ] `/api/v2/solutions/categories (+ /categories/{id}/folders, /folders/{id}/articles)` — knowledge base hierarchy and article stats (hits, thumbs up/down) for deflection analysis (high)
+- [x] `/api/v2/tickets/{id}/conversations` — ticket replies and notes - the actual support conversation behind every ticket row we sync (high)
+- [x] `/api/v2/contact_fields` — lookup resolving custom contact field IDs and their dropdown choices (high)
+- [x] `/api/v2/canned_response_folders/{id}/responses` — the canned responses themselves; only their folders are synced today (high)
+- [x] `/api/v2/solutions/categories (+ /categories/{id}/folders, /folders/{id}/articles)` — knowledge base hierarchy and article stats (hits, thumbs up/down) for deflection analysis (high)
- [ ] `/api/v2/company_fields` — lookup resolving custom company field IDs and choices (medium)
- [ ] `/api/v2/custom_objects/schemas (+ /schemas/{id}/records)` — customer-defined objects linked to tickets; schemas act as the lookup for the records (medium)
- [ ] `/api/v2/customer-satisfaction/surveys/{survey_id}/responses` — new-style CSAT responses; only legacy satisfaction_ratings are synced (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/canonical_descriptions.py
index a0f2bb7bc93f..a94077ada5cd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/canonical_descriptions.py
@@ -194,4 +194,97 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
responses_count="Number of canned responses in the folder.",
),
},
+ "canned_responses": {
+ "description": "A pre-written response an agent can insert into a reply.",
+ "docs_url": "https://developers.freshdesk.com/api/#canned-responses",
+ "columns": _columns(
+ title="Title of the canned response.",
+ folder_id="ID of the folder the canned response belongs to.",
+ content="Plain-text version of the canned response content.",
+ content_html="HTML version of the canned response content.",
+ attachments="Attachments associated with the canned response.",
+ ),
+ },
+ "contact_fields": {
+ "description": "A field on the contact form, including the choices of a dropdown field.",
+ "docs_url": "https://developers.freshdesk.com/api/#contact-fields",
+ "columns": _columns(
+ name="Internal name of the contact field.",
+ label="Display name for the field, as seen by agents.",
+ label_for_customers="Display name for the field, as seen in the customer portal.",
+ type="Type of value the field holds (e.g. custom_text, custom_dropdown).",
+ position="Position of the field on the form.",
+ default="Whether this is a default field rather than a custom one.",
+ required_for_agents="Whether the field is mandatory for agents.",
+ required_for_customers="Whether the field is mandatory for customers.",
+ displayed_for_customers="Whether customers can see the field.",
+ customers_can_edit="Whether customers can edit the field.",
+ editable_in_signup="Whether customers can set the field during signup.",
+ unique="Whether values of this field must be unique across contacts.",
+ choices="Available choices, for a dropdown field.",
+ ),
+ },
+ "conversations": {
+ "description": "A reply or note on a ticket -- the support conversation behind the ticket.",
+ "docs_url": "https://developers.freshdesk.com/api/#conversations",
+ "columns": _columns(
+ ticket_id="ID of the ticket this conversation belongs to.",
+ body="Content of the conversation, in HTML.",
+ body_text="Plain-text version of the conversation content.",
+ incoming="Whether the conversation came from the requester rather than an agent.",
+ private="Whether the conversation is a private note, invisible to the requester.",
+ source="Channel the conversation came through (0=reply, 2=note, 5=tweet, ...).",
+ user_id="ID of the agent or contact who wrote the conversation.",
+ support_email="Support email address the conversation was sent to.",
+ from_email="Email address the conversation was sent from.",
+ to_emails="Email addresses the conversation was sent to.",
+ cc_emails="Email addresses in the 'cc' field.",
+ bcc_emails="Email addresses in the 'bcc' field.",
+ attachments="Attachments on the conversation.",
+ last_edited_at="Time at which the conversation was last edited.",
+ last_edited_user_id="ID of the agent who last edited the conversation.",
+ ),
+ },
+ "solution_categories": {
+ "description": "A top-level grouping of knowledge base solution folders.",
+ "docs_url": "https://developers.freshdesk.com/api/#solution-category-attributes",
+ "columns": _columns(
+ name="The category's name.",
+ description="Description of the category.",
+ ),
+ },
+ "solution_folders": {
+ "description": "A folder of knowledge base articles inside a solution category.",
+ "docs_url": "https://developers.freshdesk.com/api/#solution-folder-attributes",
+ "columns": _columns(
+ name="The folder's name.",
+ description="Description of the folder.",
+ category_id="ID of the solution category the folder belongs to.",
+ parent_folder_id="ID of the folder this one sits inside, for a nested folder.",
+ hierarchy="The category and folder path leading to this folder.",
+ articles_count="Number of articles in the folder.",
+ sub_folders_count="Number of folders nested inside this one.",
+ visibility="Who the folder is visible to (1=all, 2=logged in users, ...).",
+ company_ids="IDs of the companies the folder is visible to.",
+ ),
+ },
+ "solution_articles": {
+ "description": "A knowledge base article, with the view and rating counts used to measure deflection.",
+ "docs_url": "https://developers.freshdesk.com/api/#solution-article-attributes",
+ "columns": _columns(
+ title="Title of the article.",
+ description="Body of the article, in HTML.",
+ description_text="Plain-text version of the article body.",
+ type="Type of the article (1=permanent, 2=workaround).",
+ status="Status of the article (1=draft, 2=published).",
+ category_id="ID of the solution category the article belongs to.",
+ folder_id="ID of the solution folder the article belongs to.",
+ hierarchy="The category and folder path leading to this article.",
+ agent_id="ID of the agent who last edited the article.",
+ hits="Number of times the article has been viewed.",
+ thumbs_up="Number of readers who marked the article helpful.",
+ thumbs_down="Number of readers who marked the article unhelpful.",
+ seo_data="Meta title, description and keywords for the article.",
+ ),
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/freshdesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/freshdesk.py
index e979d8f51c62..1c1816c44bcb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/freshdesk.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/freshdesk.py
@@ -1,6 +1,7 @@
import dataclasses
+from collections.abc import Callable, Iterable
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
from requests.auth import HTTPBasicAuth
@@ -9,14 +10,25 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+ build_chained_resource,
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
HeaderLinkPaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.freshdesk.settings import (
FRESHDESK_ENDPOINTS,
+ IGNORE_DELETED_PARENT,
PER_PAGE,
FreshdeskEndpointConfig,
)
@@ -64,6 +76,152 @@ def _build_params(
return params
+def _client_config(subdomain: str, api_key: str) -> ClientConfig:
+ return {
+ "base_url": _base_url(subdomain),
+ "headers": {"Content-Type": "application/json"},
+ # Freshdesk uses HTTP Basic auth with the API key as the username and any
+ # non-empty string as the password. Supplied via framework auth so the value
+ # is redacted from logs.
+ "auth": {"type": "http_basic", "username": api_key, "password": "X"},
+ # Freshdesk paginates with an RFC 5988 `Link: ...; rel="next"` header.
+ "paginator": HeaderLinkPaginator(),
+ }
+
+
+def _windowed_fanout(
+ fanout: DependentEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> DependentEndpointConfig:
+ """Bound the parent walk of a child endpoint that has no timestamp filter of its own.
+
+ Without this the child re-fetches every parent's full history each sync. Filtering the
+ parent on its own `updated_since` cannot hide a child we still need: Freshdesk touches a
+ parent's `updated_at` whenever one of its children changes, so a child newer than the
+ watermark only ever hangs off a parent the filter keeps.
+ """
+ parent = FRESHDESK_ENDPOINTS[fanout.parent_name]
+ if not (should_use_incremental_field and parent.updated_since_param and db_incremental_field_last_value):
+ return fanout
+
+ return dataclasses.replace(
+ fanout,
+ parent_params={
+ **fanout.parent_params,
+ parent.updated_since_param: _format_updated_since(db_incremental_field_last_value),
+ },
+ )
+
+
+def _fanout_resource(
+ endpoint: str,
+ config: FreshdeskEndpointConfig,
+ client_config: ClientConfig,
+ team_id: int,
+ job_id: str,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: Optional[str],
+ resume_hook: Callable[[Optional[dict[str, Any]]], None],
+ initial_paginator_state: Optional[dict[str, Any]],
+) -> Iterable[Any]:
+ assert config.fanout is not None
+ return cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=FRESHDESK_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=_windowed_fanout(config.fanout, should_use_incremental_field, db_incremental_field_last_value),
+ 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,
+ # No Freshdesk sub-resource takes a timestamp filter, so the cursor binds to no
+ # request param. The child still merges on its primary key.
+ incremental_config_factory=lambda _field: None,
+ page_size_param="per_page",
+ resume_hook=resume_hook,
+ initial_paginator_state=initial_paginator_state,
+ ),
+ )
+
+
+def _chained_fanout_resource(
+ endpoint: str,
+ config: FreshdeskEndpointConfig,
+ client_config: ClientConfig,
+ team_id: int,
+ job_id: str,
+) -> Iterable[Any]:
+ """Build a solution categories -> folders -> articles chain and return the articles child."""
+ chained = config.chained_fanout
+ assert chained is not None
+ middle_config = FRESHDESK_ENDPOINTS[chained.parent_name]
+ middle_fanout = middle_config.fanout
+ if middle_fanout is None:
+ raise ValueError(f"'{chained.parent_name}' does not fan out from a top-level endpoint")
+ root_config = FRESHDESK_ENDPOINTS[middle_fanout.parent_name]
+
+ def _resource(
+ cfg: FreshdeskEndpointConfig,
+ params: dict[str, Any],
+ include_from_parent: list[str] | None = None,
+ ) -> EndpointResource:
+ endpoint_config: Endpoint = {"path": cfg.path, "params": params, "data_selector": cfg.data_key}
+ if include_from_parent is not None:
+ endpoint_config["response_actions"] = IGNORE_DELETED_PARENT
+ resource: EndpointResource = {
+ "name": cfg.name,
+ "table_name": cfg.name,
+ "write_disposition": "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ }
+ if include_from_parent is not None:
+ resource["include_from_parent"] = include_from_parent
+ return resource
+
+ root = _resource(root_config, {"per_page": root_config.page_size})
+ middle = _resource(
+ middle_config,
+ {
+ "per_page": middle_config.page_size,
+ middle_fanout.resolve_param: {
+ "type": "resolve",
+ "resource": root_config.name,
+ "field": middle_fanout.resolve_field,
+ },
+ },
+ )
+ child = _resource(
+ config,
+ {
+ "per_page": config.page_size,
+ chained.resolve_param: {
+ "type": "resolve",
+ "resource": middle_config.name,
+ "field": chained.resolve_field,
+ },
+ },
+ # Article rows already carry `folder_id` and `category_id`.
+ include_from_parent=[],
+ )
+
+ return build_chained_resource(
+ resources=[root, middle, child],
+ child_name=endpoint,
+ parent_name=middle_config.name,
+ parent_field_renames={},
+ client_config=client_config,
+ team_id=team_id,
+ job_id=job_id,
+ )
+
+
def freshdesk_source(
api_key: str,
subdomain: str,
@@ -73,32 +231,10 @@ def freshdesk_source(
resumable_source_manager: ResumableSourceManager[FreshdeskResumeConfig],
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
) -> SourceResponse:
config = FRESHDESK_ENDPOINTS[endpoint]
-
- rest_config: RESTAPIConfig = {
- "client": {
- "base_url": _base_url(subdomain),
- "headers": {"Content-Type": "application/json"},
- # Freshdesk uses HTTP Basic auth with the API key as the username and any
- # non-empty string as the password. Supplied via framework auth so the value
- # is redacted from logs.
- "auth": {"type": "http_basic", "username": api_key, "password": "X"},
- # Freshdesk paginates with an RFC 5988 `Link: ...; rel="next"` header.
- "paginator": HeaderLinkPaginator(),
- },
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": _build_params(config, should_use_incremental_field, db_incremental_field_last_value),
- # Most list endpoints return a bare array; a few (e.g. skills) wrap it in an object.
- "data_selector": config.data_key,
- },
- }
- ],
- }
+ client_config = _client_config(subdomain, api_key)
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
@@ -112,14 +248,45 @@ def freshdesk_source(
if state and state.get("next_url"):
resumable_source_manager.save_state(FreshdeskResumeConfig(next_url=state["next_url"]))
- resource = rest_api_resource(
- rest_config,
- team_id,
- job_id,
- db_incremental_field_last_value if should_use_incremental_field else None,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
- )
+ resource: Iterable[Any]
+ if config.chained_fanout is not None:
+ resource = _chained_fanout_resource(endpoint, config, client_config, team_id, job_id)
+ elif config.fanout is not None:
+ resource = _fanout_resource(
+ endpoint,
+ config,
+ client_config,
+ team_id,
+ job_id,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ incremental_field,
+ save_checkpoint,
+ initial_paginator_state,
+ )
+ else:
+ rest_config: RESTAPIConfig = {
+ "client": client_config,
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": _build_params(config, should_use_incremental_field, db_incremental_field_last_value),
+ # Most list endpoints return a bare array; a few (e.g. skills) wrap it in an object.
+ "data_selector": config.data_key,
+ },
+ }
+ ],
+ }
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
return SourceResponse(
name=endpoint,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/settings.py
index 3ed96cb98a47..0fbffb6e16a9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/settings.py
@@ -3,12 +3,30 @@
from dataclasses import dataclass, field
from typing import Optional
+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.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
PER_PAGE = 100
-@dataclass
+@dataclass(frozen=True)
+class FreshdeskChainedFanoutConfig:
+ """A second-level fan-out whose parent is itself a fan-out child.
+
+ `build_dependent_resource` resolves its path param from a top-level endpoint, so it cannot
+ express `/solutions/folders/{folder_id}/articles`, where the folder rows themselves come
+ from `/solutions/categories/{category_id}/folders`.
+ """
+
+ parent_name: str
+ resolve_param: str
+ resolve_field: str
+
+
+@dataclass(frozen=True)
class FreshdeskEndpointConfig:
name: str
path: str
@@ -24,6 +42,11 @@ class FreshdeskEndpointConfig:
extra_params: dict[str, str] = field(default_factory=dict)
# Key the list lives under when the response is an object rather than a bare array.
data_key: Optional[str] = None
+ # Read by the shared fan-out helper to size parent and child pages.
+ page_size: int = PER_PAGE
+ # Set on a sub-resource that is fetched once per row of a top-level endpoint.
+ fanout: Optional[DependentEndpointConfig] = None
+ chained_fanout: Optional[FreshdeskChainedFanoutConfig] = None
def _datetime_incremental_field(name: str) -> IncrementalField:
@@ -35,8 +58,11 @@ def _datetime_incremental_field(name: str) -> IncrementalField:
}
-# Top-level Freshdesk v2 endpoints. Fan-out resources (ticket conversations, solution
-# articles) are intentionally omitted from this first cut — see source.py module note.
+# A parent row can be deleted between the listing page it arrived on and the child fetch that
+# follows it, which 404s. That must not sink the whole fan-out.
+IGNORE_DELETED_PARENT: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
+
+
FRESHDESK_ENDPOINTS: dict[str, FreshdeskEndpointConfig] = {
"tickets": FreshdeskEndpointConfig(
name="tickets",
@@ -86,6 +112,61 @@ FRESHDESK_ENDPOINTS: dict[str, FreshdeskEndpointConfig] = {
"canned_response_folders": FreshdeskEndpointConfig(
name="canned_response_folders", path="/api/v2/canned_response_folders"
),
+ "contact_fields": FreshdeskEndpointConfig(name="contact_fields", path="/api/v2/contact_fields"),
+ "conversations": FreshdeskEndpointConfig(
+ name="conversations",
+ path="/api/v2/tickets/{ticket_id}/conversations",
+ # The endpoint takes no timestamp filter of its own. Incremental sync instead narrows
+ # the tickets the fan-out walks, so the watermark still has to be a conversation field.
+ default_incremental_field="updated_at",
+ incremental_fields=[_datetime_incremental_field("updated_at")],
+ partition_key="created_at",
+ fanout=DependentEndpointConfig(
+ parent_name="tickets",
+ resolve_param="ticket_id",
+ resolve_field="id",
+ # Conversation rows already carry `ticket_id`; nothing needs injecting from the parent.
+ include_from_parent=[],
+ # Walk the parent oldest-first so the run covers whole tickets in watermark order.
+ parent_params={"order_by": "updated_at", "order_type": "asc"},
+ child_response_actions=IGNORE_DELETED_PARENT,
+ ),
+ ),
+ "canned_responses": FreshdeskEndpointConfig(
+ name="canned_responses",
+ path="/api/v2/canned_response_folders/{folder_id}/responses",
+ fanout=DependentEndpointConfig(
+ parent_name="canned_response_folders",
+ resolve_param="folder_id",
+ resolve_field="id",
+ # Canned response rows already carry `folder_id`.
+ include_from_parent=[],
+ child_response_actions=IGNORE_DELETED_PARENT,
+ ),
+ ),
+ "solution_categories": FreshdeskEndpointConfig(name="solution_categories", path="/api/v2/solutions/categories"),
+ "solution_folders": FreshdeskEndpointConfig(
+ name="solution_folders",
+ path="/api/v2/solutions/categories/{category_id}/folders",
+ fanout=DependentEndpointConfig(
+ parent_name="solution_categories",
+ resolve_param="category_id",
+ resolve_field="id",
+ # A folder row places itself only through the nested `hierarchy` list, so the owning
+ # category has to come from the parent to be queryable as a column.
+ include_from_parent=["id"],
+ parent_field_renames={"id": "category_id"},
+ child_response_actions=IGNORE_DELETED_PARENT,
+ ),
+ ),
+ "solution_articles": FreshdeskEndpointConfig(
+ name="solution_articles",
+ path="/api/v2/solutions/folders/{folder_id}/articles",
+ partition_key="created_at",
+ chained_fanout=FreshdeskChainedFanoutConfig(
+ parent_name="solution_folders", resolve_param="folder_id", resolve_field="id"
+ ),
+ ),
}
ENDPOINTS = tuple(FRESHDESK_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/source.py
index 84c76b274fff..e3d5b6b81ac4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/source.py
@@ -28,10 +28,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
-# This first cut covers Freshdesk's top-level v2 endpoints only. Fan-out resources
-# (ticket conversations, solution articles/folders/categories) and webhook-driven
-# deltas are deliberately left out: Freshdesk has no documented public REST API for
-# programmatic webhook management (webhooks are configured through admin automation
+# Webhook-driven deltas are deliberately left out: Freshdesk has no documented public REST
+# API for programmatic webhook management (webhooks are configured through admin automation
# rules), so they can't be wired up reliably without live verification.
_SUBDOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9-]+$")
@@ -117,10 +115,11 @@ Your **API key** is on your Freshdesk profile settings page (click your profile
schemas = [
SourceSchema(
name=name,
- # Only the endpoints with a genuine server-side `updated_since` filter
- # support incremental sync; everything else is full refresh.
- supports_incremental=endpoint.updated_since_param is not None,
- supports_append=endpoint.updated_since_param is not None,
+ # An endpoint declares incremental fields only when a sync can genuinely be
+ # narrowed server-side -- through the endpoint's own `updated_since` filter, or
+ # through the one on the parent it fans out from. Everything else is full refresh.
+ supports_incremental=bool(endpoint.incremental_fields),
+ supports_append=bool(endpoint.incremental_fields),
incremental_fields=endpoint.incremental_fields,
)
for name, endpoint in FRESHDESK_ENDPOINTS.items()
@@ -182,4 +181,5 @@ Your **API key** is on your Freshdesk profile settings page (click your profile
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/tests/test_freshdesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/tests/test_freshdesk.py
index 56bf75edb9df..2843cad7ed9b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/tests/test_freshdesk.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/tests/test_freshdesk.py
@@ -46,7 +46,7 @@ def _make_manager(resume_state: Optional[FreshdeskResumeConfig] = None) -> mock.
class _Wired:
- def __init__(self, params: list[dict[str, Any]], urls: list[Optional[str]]) -> None:
+ def __init__(self, params: list[dict[str, Any]], urls: list[str]) -> None:
self.params = params
self.urls = urls
@@ -59,11 +59,11 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> _Wired:
"""
session.headers = {}
param_snapshots: list[dict[str, Any]] = []
- url_snapshots: list[Optional[str]] = []
+ url_snapshots: list[str] = []
def _prepare(request: Any) -> mock.MagicMock:
param_snapshots.append(dict(request.params or {}))
- url_snapshots.append(request.url)
+ url_snapshots.append(request.url or "")
return mock.MagicMock()
session.prepare_request.side_effect = _prepare
@@ -293,3 +293,114 @@ class TestValidateCredentials:
def test_connection_error_returns_none(self, mock_session) -> None:
mock_session.return_value.get.side_effect = requests.ConnectionError("nope")
assert validate_credentials("acme", "key") is None
+
+
+class TestFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_conversations_fetch_once_per_ticket(self, MockSession) -> None:
+ session = MockSession.return_value
+ wired = _wire(
+ session,
+ [
+ _response([{"id": 10}, {"id": 11}]),
+ _response([{"id": 100, "ticket_id": 10}]),
+ _response([{"id": 200, "ticket_id": 11}]),
+ ],
+ )
+
+ rows = _rows(_source("conversations"))
+
+ assert [r["id"] for r in rows] == [100, 200]
+ assert wired.urls[0].endswith("/api/v2/tickets")
+ assert [u.rsplit("/api/v2", 1)[1] for u in wired.urls[1:]] == [
+ "/tickets/10/conversations",
+ "/tickets/11/conversations",
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_conversations_incremental_windows_the_parent_walk(self, MockSession) -> None:
+ # The child endpoint takes no timestamp filter, so the watermark has to reach the
+ # tickets request instead -- otherwise every sync re-walks every ticket.
+ session = MockSession.return_value
+ wired = _wire(session, [_response([{"id": 10}]), _response([{"id": 100}])])
+
+ _rows(
+ _source(
+ "conversations",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ )
+
+ assert wired.params[0]["updated_since"] == "2026-03-04T00:00:00Z"
+ assert wired.params[0]["order_type"] == "asc"
+ # The child request carries no watermark param of its own.
+ assert "updated_since" not in wired.params[1]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_conversations_full_refresh_omits_the_parent_window(self, MockSession) -> None:
+ session = MockSession.return_value
+ wired = _wire(session, [_response([{"id": 10}]), _response([{"id": 100}])])
+
+ _rows(_source("conversations"))
+
+ assert "updated_since" not in wired.params[0]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_deleted_parent_404_does_not_fail_the_run(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": 10}, {"id": 11}]),
+ _response({"message": "not found"}, status_code=404),
+ _response([{"id": 200, "ticket_id": 11}]),
+ ],
+ )
+
+ rows = _rows(_source("conversations"))
+
+ assert [r["id"] for r in rows] == [200]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_canned_responses_fan_out_from_folders(self, MockSession) -> None:
+ session = MockSession.return_value
+ wired = _wire(session, [_response([{"id": 1}]), _response([{"id": 5, "folder_id": 1}])])
+
+ rows = _rows(_source("canned_responses"))
+
+ assert [r["id"] for r in rows] == [5]
+ assert wired.urls[1].endswith("/api/v2/canned_response_folders/1/responses")
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_solution_folders_carry_their_category_id(self, MockSession) -> None:
+ # A folder row places itself only through a nested `hierarchy` list, so the owning
+ # category is injected from the parent under a flat, queryable column.
+ session = MockSession.return_value
+ _wire(session, [_response([{"id": 3}]), _response([{"id": 4, "name": "sample folder"}])])
+
+ rows = _rows(_source("solution_folders"))
+
+ assert rows[0]["category_id"] == 3
+ assert "_solution_categories_id" not in rows[0]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_solution_articles_walk_categories_then_folders(self, MockSession) -> None:
+ session = MockSession.return_value
+ wired = _wire(
+ session,
+ [
+ _response([{"id": 3}]),
+ _response([{"id": 4}]),
+ _response([{"id": 1, "folder_id": 4, "category_id": 3}]),
+ ],
+ )
+
+ rows = _rows(_source("solution_articles"))
+
+ assert [r["id"] for r in rows] == [1]
+ assert [u.rsplit("/api/v2", 1)[1] for u in wired.urls] == [
+ "/solutions/categories",
+ "/solutions/categories/3/folders",
+ "/solutions/folders/4/articles",
+ ]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/tests/test_freshdesk_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/tests/test_freshdesk_source.py
index 725cd9621de4..e78cfb17bb6e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/tests/test_freshdesk_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshdesk/tests/test_freshdesk_source.py
@@ -49,9 +49,14 @@ class TestFreshdeskSource:
[
("tickets", True),
("contacts", True),
+ # Narrowed through the tickets parent it fans out from, not its own filter.
+ ("conversations", True),
("companies", False),
("agents", False),
("satisfaction_ratings", False),
+ ("contact_fields", False),
+ ("canned_responses", False),
+ ("solution_articles", False),
],
)
def test_schema_incremental_support(self, name: str, supports_incremental: bool) -> None: