: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 freshchat roles, conversations and messages tables (#108307)
Tom Owers28b0f3fb5546
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 45ca9cf4941c..ccf9f4279991 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@@ -3340,14 +3340,14 @@ Note: Freshcaller's public API is genuinely small - calls, call_metrics (with in## Freshchat — gaps-Today (5): `accounts_configuration`, `agents`, `channels`, `groups`, `users`+Today (8): `accounts_configuration`, `agents`, `channels`, `conversation_messages`, `groups`, `roles`, `user_conversations`, `users`Diffed against: <https://developers.freshchat.com/api/>-- [ ] `/v2/users/{user_id}/conversations` — conversations are the product's core analytical object and are entirely absent today (high)-- [ ] `/v2/conversations/{conversation_id}/messages` — message-level data for response time, volume and agent workload analysis (high)-- [ ] `/v2/roles` — lookup resolving the role IDs carried on agents (high)-- [ ] `/v2/reports/raw` — bulk raw data export - the practical way to land conversation/agent history at scale (medium)+- [x] `/v2/users/{user_id}/conversations` — conversations are the product's core analytical object and are entirely absent today (high)+- [x] `/v2/conversations/{conversation_id}/messages` — message-level data for response time, volume and agent workload analysis (high)+- [x] `/v2/roles` — lookup resolving the role IDs carried on agents (high)+- [ ] `/v2/reports/raw` — bulk raw data export - the practical way to land conversation/agent history at scale (medium) — not a readable collection: `POST /reports/raw` submits an async extraction job and `GET /reports/raw/{id}` returns a status plus a link to a generated CSV/JSON file. It needs a mandatory `event` type from a fixed enum, each of which yields a different report schema, over a window capped at one month (24 hours for chat transcripts) and no earlier than 15 months back. There is no single stable table behind it.- [ ] `/v2/outbound-messages` — outbound campaign message sends and their delivery state (medium)- [ ] `/v2/metrics/historical` — vendor-computed historical conversation/agent metrics (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/canonical_descriptions.pyindex 13140849a70f..72dd3e4b36bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/canonical_descriptions.py@@ -77,6 +77,50 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_time": "Time at which the channel was last updated.",},},+ "roles": {+ "description": "A role configured in your Freshchat account, resolving the role IDs carried on agents.",+ "docs_url": "https://developers.freshchat.com/api/#roles",+ "columns": {+ "id": "Unique identifier for the role. Built-in roles use a fixed name such as ACCOUNT_ADMIN.",+ "name": "The role's name.",+ "is_custom_role": "Whether the role was created for this account rather than built in.",+ "description": "Description of what the role covers.",+ },+ },+ "user_conversations": {+ "description": (+ "Links each user to the conversations they take part in. Freshchat lists conversations "+ "only per user, so this table is the way to enumerate them."+ ),+ "docs_url": "https://developers.freshchat.com/api/#retrieve_all_conversations_for_a_user",+ "columns": {+ "id": "Unique identifier for the conversation.",+ "user_id": "Identifier of the user the conversation is listed under.",+ },+ },+ "conversation_messages": {+ "description": "A single message posted to a conversation by a user, agent, bot or the system.",+ "docs_url": "https://developers.freshchat.com/api/#message_object",+ "columns": {+ "id": "Unique identifier for the message.",+ "created_time": "Time at which the message was created.",+ "conversation_id": "Identifier of the conversation the message belongs to.",+ "channel_id": "Identifier of the channel the message was created under.",+ "app_id": "Identifier of the Freshchat app (widget) the message belongs to.",+ "actor_type": "Who sent the message: user, agent, bot or system.",+ "actor_id": "Identifier of the user or agent who sent the message.",+ "org_actor_id": "Organisation-level identifier of the sender.",+ "user_id": "Identifier of the user in the conversation, when the sender is a user.",+ "message_type": "Whether the message is normal, private or system generated.",+ "message_parts": "The content of the message, such as text, images and buttons.",+ "reply_parts": "Response enablers attached to an agent or bot message, such as quick replies.",+ "interaction_id": "Identifier of the interaction, reassigned each time the conversation reopens.",+ "in_reply_to": "Identifier of the message this message replies to.",+ "meta_data": "Extra key-value information about the message.",+ "restrictResponse": "Whether the user is restricted to the offered reply options.",+ "botsPrivateNote": "Whether the message is a bot note not visible to the user.",+ },+ },"accounts_configuration": {"description": "Account-level Freshchat configuration for your app.","docs_url": "https://developers.freshchat.com/api/#accounts",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/freshchat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/freshchat.pyindex 35de22f93b4f..f43b1db52609 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/freshchat.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/freshchat.py@@ -1,4 +1,5 @@import dataclasses+from collections.abc import Callable, Iterablefrom typing import Any, Optionalfrom requests import Response@@ -8,6 +9,10 @@ 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_chained_resource,+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BasePaginator,PageNumberPaginator,@@ -16,12 +21,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (_looks_like_json,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ ResponseAction,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.settings import (FRESHCHAT_ENDPOINTS,PER_PAGE,PRIMARY_KEYS,+ SKIP_MISSING_PARENT,FreshchatEndpointConfig,)@@ -39,11 +51,12 @@ class FreshchatHostNotAllowedError(Exception):pass[email protected](frozen=True)class FreshchatResumeConfig:# The next page number to fetch. Freshchat uses page/items_per_page pagination, so a single# integer is enough to pick back up. Endpoints are full refresh (no time window), so re-entering- # a page and deduping on the primary key is safe.+ # a page and deduping on the primary key is safe. Does not cover the chained fan-out, which+ # `build_chained_resource` cannot checkpoint.page: int@@ -80,22 +93,173 @@ def build_base_params(config: FreshchatEndpointConfig) -> dict[str, Any]:params: dict[str, Any] = {}if config.paginated:params["items_per_page"] = str(PER_PAGE)- # Explicit stable sort so page boundaries don't skip/duplicate rows if the API's implicit- # default order shifts while we page.- params["sort_order"] = "asc"+ if config.accepts_sort_order:+ # Explicit stable sort so page boundaries don't skip/duplicate rows if the API's+ # implicit default order shifts while we page.+ params["sort_order"] = "asc"params.update(config.extra_params)return paramsdef _paginator_for(config: FreshchatEndpointConfig) -> BasePaginator:if not config.paginated:- # Single-object endpoints (accounts/configuration) are one request, no pagination params.+ # Single-object and whole-collection endpoints are one request, no pagination params.return SinglePagePaginator()- # Freshchat pages by 1-based page number and reports the page count under- # ``pagination.total_pages``; the paginator stops right after the last page (no extra empty- # request) and is resumable by page number. When the count is absent it falls back to stopping- # on the first empty page.- return PageNumberPaginator(base_page=1, page=1, page_param="page", total_path="pagination.total_pages")+ # Freshchat pages by 1-based page number. Where the response reports the page count the+ # paginator stops right after the last page (no extra empty request); otherwise it stops on+ # the first empty page. Either way it is resumable by page number.+ return PageNumberPaginator(base_page=1, page=1, page_param="page", total_path=config.total_pages_path)+++def _client_config(api_key: str, domain: str) -> ClientConfig:+ return {+ "base_url": _base_url(domain),+ # Auth (Bearer) is supplied via the framework auth config so its value is redacted from+ # logs and error messages; only the non-secret Accept header is set here so the API+ # returns JSON rather than an HTML error page.+ "headers": {"Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ # Pin every request (including any paginator/resume URL) to the account host and reject+ # redirects — a 3xx from the allowed host could otherwise carry the token off-host (SSRF).+ "allowed_hosts": [],+ "allow_redirects": False,+ }+++def _endpoint_config(+ config: FreshchatEndpointConfig,+ extra_params: Optional[dict[str, Any]] = None,+ response_actions: Optional[list[ResponseAction]] = None,+) -> Endpoint:+ endpoint: Endpoint = {+ "path": config.path,+ "params": {**build_base_params(config), **(extra_params or {})},+ # Freshchat wraps list rows (and the single configuration object) under a resource key;+ # the extractor unwraps a single matched object into one row.+ "data_selector": config.data_key,+ "paginator": _paginator_for(config),+ }+ if response_actions:+ endpoint["response_actions"] = response_actions+ return endpoint+++def _resource(config: FreshchatEndpointConfig, endpoint: Endpoint) -> EndpointResource:+ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": endpoint,+ "table_format": "delta",+ }+++def _resolve_param(resource_name: str, field_name: str) -> dict[str, Any]:+ return {"type": "resolve", "resource": resource_name, "field": field_name}+++def _fanout_resource(+ config: FreshchatEndpointConfig,+ client_config: ClientConfig,+ team_id: int,+ job_id: str,+ resume_hook: Callable[[Optional[dict[str, Any]]], None],+ initial_paginator_state: Optional[dict[str, Any]],+) -> Iterable[Any]:+ """Build a users -> per-user child fan-out and return the child."""+ fanout = config.fanout+ assert fanout is not None+ parent_config = FRESHCHAT_ENDPOINTS[fanout.parent_name]+ # The parent's mandatory filter and page-size params live on its own endpoint config.+ fanout = dataclasses.replace(fanout, parent_params=build_base_params(parent_config))++ return build_dependent_resource(+ endpoint_configs=FRESHCHAT_ENDPOINTS,+ child_endpoint=config.name,+ fanout=fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ # Freshchat's page-size param rides in each endpoint's own params.+ page_size_param=None,+ parent_endpoint_extra={+ "paginator": _paginator_for(parent_config),+ "data_selector": parent_config.data_key,+ },+ child_endpoint_extra={+ "paginator": _paginator_for(config),+ "data_selector": config.data_key,+ },+ resume_hook=resume_hook,+ initial_paginator_state=initial_paginator_state,+ )+++def _chained_fanout_resource(+ config: FreshchatEndpointConfig,+ client_config: ClientConfig,+ team_id: int,+ job_id: str,+) -> Iterable[Any]:+ """Build a users -> conversations -> messages chain and return the child."""+ chained = config.chained_fanout+ assert chained is not None+ middle_config = FRESHCHAT_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 = FRESHCHAT_ENDPOINTS[middle_fanout.parent_name]++ root_resource = _resource(root_config, _endpoint_config(root_config))+ middle_resource = _resource(+ middle_config,+ _endpoint_config(+ middle_config,+ extra_params={middle_fanout.resolve_param: _resolve_param(root_config.name, middle_fanout.resolve_field)},+ response_actions=SKIP_MISSING_PARENT,+ ),+ )+ child_resource = _resource(+ config,+ _endpoint_config(+ config,+ extra_params={chained.resolve_param: _resolve_param(middle_config.name, chained.resolve_field)},+ response_actions=SKIP_MISSING_PARENT,+ ),+ )+ child_resource["include_from_parent"] = chained.include_from_parent++ return build_chained_resource(+ resources=[root_resource, middle_resource, child_resource],+ child_name=config.name,+ parent_name=middle_config.name,+ parent_field_renames=chained.parent_field_renames,+ client_config=client_config,+ team_id=team_id,+ job_id=job_id,+ )+++def _source_response(+ config: FreshchatEndpointConfig,+ items: Callable[[], Iterable[Any]],+ supports_resume: bool = True,+) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items,+ primary_keys=PRIMARY_KEYS[config.name],+ supports_resume=supports_resume,+ # Every endpoint is full refresh, so this only describes the order rows arrive in.+ sort_mode="asc",+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )def freshchat_source(@@ -116,34 +280,7 @@ def freshchat_source(if not is_allowed_host(normalized):raise FreshchatHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)- rest_config: RESTAPIConfig = {- "client": {- "base_url": _base_url(domain),- # Auth (Bearer) is supplied via the framework auth config so its value is redacted from- # logs and error messages; only the non-secret Accept header is set here so the API- # returns JSON rather than an HTML error page.- "headers": {"Accept": "application/json"},- "auth": {"type": "bearer", "token": api_key},- "paginator": _paginator_for(config),- # Pin every request (including any paginator/resume URL) to the account host and reject- # redirects — a 3xx from the allowed host could otherwise carry the token off-host (SSRF).- "allowed_hosts": [],- "allow_redirects": False,- },- "resource_defaults": {},- "resources": [- {- "name": endpoint,- "endpoint": {- "path": config.path,- "params": build_base_params(config),- # Freshchat wraps list rows (and the single configuration object) under a- # resource key; the extractor unwraps a single matched object into one row.- "data_selector": config.data_key,- },- }- ],- }+ client_config = _client_config(api_key, domain)initial_paginator_state: Optional[dict[str, Any]] = Noneif resumable_source_manager.can_resume():@@ -157,6 +294,21 @@ def freshchat_source(if state and state.get("page") is not None:resumable_source_manager.save_state(FreshchatResumeConfig(page=int(state["page"])))+ if config.chained_fanout is not None:+ # A two-level chain takes no resume state: one hook consumed at two levels would corrupt+ # the saved page. The table is full refresh, so a retry restarts it.+ chained = _chained_fanout_resource(config, client_config, team_id, job_id)+ return _source_response(config, lambda: chained, supports_resume=False)++ if config.fanout is not None:+ dependent = _fanout_resource(config, client_config, team_id, job_id, save_checkpoint, initial_paginator_state)+ return _source_response(config, lambda: dependent)++ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {},+ "resources": [_resource(config, _endpoint_config(config))],+ }resource = rest_api_resource(rest_config,team_id,@@ -166,13 +318,7 @@ def freshchat_source(initial_paginator_state=initial_paginator_state,)- return SourceResponse(- name=endpoint,- items=lambda: resource,- primary_keys=PRIMARY_KEYS[endpoint],- # All endpoints are full refresh; we page with an explicit ascending sort.- sort_mode="asc",- )+ return _source_response(config, lambda: resource)def _returned_json(response: Response) -> bool:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/settings.pyindex c824628cdc63..6352267b6f08 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/settings.py@@ -3,6 +3,12 @@from dataclasses import dataclass, fieldfrom 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+# Freshchat caps `items_per_page` at 50 (default 20). Pull the max to keep the request# count — and therefore rate-limit pressure — as low as possible.PER_PAGE = 50@@ -12,8 +18,48 @@ PER_PAGE = 50# user without excluding anyone. This is a full-refresh floor, not an incremental cursor.USERS_CREATED_FROM = "2000-01-01T00:00:00.000Z"+# A parent row can disappear between its listing page and the child fetch that follows it;+# that must not sink the whole fan-out.+SKIP_MISSING_PARENT: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]+++@dataclass(frozen=True)+class FreshchatChainedFanoutConfig:+ """A second-level fan-out whose parent is itself a fan-out child.++ Freshchat exposes no top-level conversations list, so messages are only reachable as+ users -> that user's conversations -> that conversation's messages, which+ `build_dependent_resource` (one hop, one resolved param) cannot express.+ """++ parent_name: str+ resolve_param: str+ resolve_field: str+ include_from_parent: list[str]+ parent_field_renames: dict[str, str]+++USER_CONVERSATIONS_FANOUT = DependentEndpointConfig(+ parent_name="users",+ resolve_param="user_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "user_id"},+ child_response_actions=SKIP_MISSING_PARENT,+)-@dataclass+CONVERSATION_MESSAGES_FANOUT = FreshchatChainedFanoutConfig(+ parent_name="user_conversations",+ resolve_param="conversation_id",+ resolve_field="id",+ # A message object already carries `conversation_id`, but projecting it from the parent row+ # guarantees the primary-key column is populated on every row.+ include_from_parent=["id"],+ parent_field_renames={"id": "conversation_id"},+)+++@dataclass(frozen=True)class FreshchatEndpointConfig:name: str# Path relative to the `/v2` base (e.g. `/agents`).@@ -31,16 +77,28 @@ class FreshchatEndpointConfig:single_object: bool = False# Extra static query params (e.g. the mandatory `created_from` filter on users).extra_params: dict[str, str] = field(default_factory=dict)+ # Path to the page count in the response body, which lets the paginator stop without paying+ # an extra empty request. `None` falls back to stopping on the first empty page.+ total_pages_path: Optional[str] = "pagination.total_pages"+ # Only the top-level list endpoints document `sort_order`.+ accepts_sort_order: bool = True+ partition_key: Optional[str] = None+ fanout: Optional[DependentEndpointConfig] = None+ # Two hops down, where the parent is itself a fan-out child.+ chained_fanout: Optional[FreshchatChainedFanoutConfig] = None+ # Freshchat's page-size param rides in each endpoint's own params rather than through the+ # fan-out helper, so these three only satisfy the helper's structural typing.+ page_size: int = PER_PAGE+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None-# Freshchat v2 top-level endpoints.+# Freshchat v2 endpoints.#-# The public REST API exposes no server-side updated_since / created_since cursor on these-# core list endpoints, so every endpoint is full refresh only (no `supports_incremental`).-# Pagination is resumable by page number via the ResumableSource manager. Conversations,-# messages and per-user conversation fan-out require object IDs (there is no top-level list-# endpoint for them) and are intentionally left out of this first cut; outbound-messages and-# the raw report endpoints require time-window params and are likewise deferred.+# The public REST API exposes no server-side updated_since / created_since cursor on the top-level+# list endpoints, so every endpoint is full refresh only (no `supports_incremental`). Pagination is+# resumable by page number via the ResumableSource manager. The outbound-messages and metrics+# endpoints require time-window params and are not covered.FRESHCHAT_ENDPOINTS: dict[str, FreshchatEndpointConfig] = {"agents": FreshchatEndpointConfig(name="agents",@@ -64,6 +122,11 @@ FRESHCHAT_ENDPOINTS: dict[str, FreshchatEndpointConfig] = {path="/channels",data_key="channels",),+ "roles": FreshchatEndpointConfig(+ name="roles",+ path="/roles",+ data_key="roles",+ ),"accounts_configuration": FreshchatEndpointConfig(name="accounts_configuration",path="/accounts/configuration",@@ -71,16 +134,38 @@ FRESHCHAT_ENDPOINTS: dict[str, FreshchatEndpointConfig] = {paginated=False,single_object=True,),+ "user_conversations": FreshchatEndpointConfig(+ name="user_conversations",+ path="/users/{user_id}/conversations",+ data_key="conversations",+ # The endpoint documents no page / items_per_page params.+ paginated=False,+ fanout=USER_CONVERSATIONS_FANOUT,+ ),+ "conversation_messages": FreshchatEndpointConfig(+ name="conversation_messages",+ path="/conversations/{conversation_id}/messages",+ data_key="messages",+ total_pages_path=None,+ accepts_sort_order=False,+ partition_key="created_time",+ chained_fanout=CONVERSATION_MESSAGES_FANOUT,+ ),}ENDPOINTS = tuple(FRESHCHAT_ENDPOINTS.keys())-# `id` is the auto-generated primary key on agents / users / groups / channels. The single-# account-configuration row is keyed on its stable Freshchat app id.+# `id` is the auto-generated primary key on the top-level collections; the single+# account-configuration row is keyed on its stable Freshchat app id. The fan-out children carry the+# parent id too: a conversation can be listed under more than one user, and Freshchat documents no+# global uniqueness for message ids.PRIMARY_KEYS: dict[str, list[str]] = {"agents": ["id"],"users": ["id"],"groups": ["id"],"channels": ["id"],+ "roles": ["id"],"accounts_configuration": ["app_id"],+ "user_conversations": ["user_id", "id"],+ "conversation_messages": ["conversation_id", "id"],}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/source.pyindex 0c3511a6791c..66b6f1a22df2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/source.py@@ -33,11 +33,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)from products.warehouse_sources.backend.types import ExternalDataSourceType-# This first cut covers Freshchat's top-level v2 list endpoints (Agents, Users, Groups, Channels)-# plus the single-row account configuration. Conversations and messages require object IDs (no-# top-level list endpoint exists), and outbound-messages / raw reports require time-window params;-# all are intentionally left out of this first cut. Freshchat has no server-side incremental-# cursor on the core list endpoints, so every endpoint is full refresh, resumable by page number.+# Covers Freshchat's top-level v2 list endpoints (Agents, Users, Groups, Channels, Roles), the+# single-row account configuration, and the two fan-out tables that reach conversations and their+# messages — Freshchat exposes no top-level conversations list, so both hang off Users. The+# outbound-messages and metrics endpoints require time-window params and are not covered.+# Freshchat has no server-side incremental cursor on these endpoints, so every endpoint is full+# refresh, resumable by page number.# Shape check on the normalized host (the Freshworks-suffix allowlist in `is_allowed_host` is the# actual security boundary).diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat.pyindex c6d125a46dc5..78a378fbd040 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat.py@@ -1,5 +1,7 @@import json+from collections.abc import Callablefrom typing import Any, Optional+from urllib.parse import urlsplitimport pytestfrom unittest import mock@@ -90,6 +92,29 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,return param_snapshots+def _wire_routed(+ session: mock.MagicMock, handler: Callable[[str, dict[str, Any]], Response]+) -> list[tuple[str, dict[str, Any]]]:+ """Wire a mock session whose response is chosen by the request path.++ Fan-out interleaves parent and child requests, so a fixed response list cannot express+ "this path answers with that page". Returns the (path, params) log in call order.+ """+ session.headers = {}+ calls: list[tuple[str, dict[str, Any]]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ prepared = mock.MagicMock()+ prepared.url = request.url+ prepared.fc_call = (urlsplit(request.url).path, dict(request.params or {}))+ calls.append(prepared.fc_call)+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = lambda prepared, **kwargs: handler(*prepared.fc_call)+ return calls++def _rows(source_response) -> list[dict[str, Any]]:return [row for page in source_response.items() for row in page]@@ -141,6 +166,12 @@ class TestBuildBaseParams:params = build_base_params(FRESHCHAT_ENDPOINTS["users"])assert params["created_from"] == USERS_CREATED_FROM+ def test_messages_endpoint_omits_the_undocumented_sort_order(self) -> None:+ # `sort_order` is documented on the top-level list endpoints but not on the per-conversation+ # messages endpoint, so it must not ride along there.+ params = build_base_params(FRESHCHAT_ENDPOINTS["conversation_messages"])+ assert params == {"items_per_page": str(PER_PAGE)}+def test_non_paginated_endpoint_has_no_pagination_params(self) -> None:params = build_base_params(FRESHCHAT_ENDPOINTS["accounts_configuration"])assert params == {}@@ -337,6 +368,133 @@ class TestGetRows:assert session.send.call_args.kwargs.get("allow_redirects") is False+class TestFanout:+ """Freshchat exposes no top-level conversations list, so both conversation tables are reached+ by fanning out from Users."""++ @staticmethod+ def _call(endpoint: str, session: mock.MagicMock) -> list[dict[str, Any]]:+ return _rows(+ freshchat_source(+ "key", BASE_HOST, endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager()+ )+ )++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_user_conversations_carries_the_parent_user_id(self, MockSession) -> None:+ session = MockSession.return_value+ pages = {+ "/v2/users": _page("users", [{"id": "u1"}, {"id": "u2"}], current=1, total_pages=1),+ "/v2/users/u1/conversations": _resp({"conversations": [{"id": "c1"}]}),+ "/v2/users/u2/conversations": _resp({"conversations": [{"id": "c2"}, {"id": "c3"}]}),+ }+ calls = _wire_routed(session, lambda path, params: pages[path])++ rows = self._call("user_conversations", session)++ # A conversation can be listed under more than one user, so the row has to name its parent+ # — the primary key is (user_id, id).+ assert rows == [+ {"id": "c1", "user_id": "u1"},+ {"id": "c2", "user_id": "u2"},+ {"id": "c3", "user_id": "u2"},+ ]+ assert calls[0][1]["created_from"] == USERS_CREATED_FROM+ # The child endpoint documents no query params; sending page-size or sort params there+ # would be undocumented guesswork.+ assert calls[1][1] == {}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_user_conversations_skips_a_user_deleted_mid_sync(self, MockSession) -> None:+ # A user removed between the Users page and this fetch must not sink the whole table.+ session = MockSession.return_value+ pages = {+ "/v2/users": _page("users", [{"id": "gone"}, {"id": "u2"}], current=1, total_pages=1),+ "/v2/users/gone/conversations": _resp({"error": "not found"}, status=404),+ "/v2/users/u2/conversations": _resp({"conversations": [{"id": "c2"}]}),+ }+ _wire_routed(session, lambda path, params: pages[path])++ assert self._call("user_conversations", session) == [{"id": "c2", "user_id": "u2"}]++ def test_conversation_messages_is_not_resumable(self) -> None:+ response = freshchat_source(+ "key",+ BASE_HOST,+ "conversation_messages",+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(FreshchatResumeConfig(page=2)),+ )++ assert response.supports_resume is False++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_conversation_messages_chains_through_users_and_conversations(self, MockSession) -> None:+ session = MockSession.return_value+ # The messages response carries no pagination envelope, so paging has to stop on the first+ # empty page rather than on a reported page count.+ message_pages = {+ "1": _resp({"messages": [{"id": "m1", "conversation_id": "c1"}]}),+ "2": _resp({"messages": []}),+ }++ def handler(path: str, params: dict[str, Any]) -> Response:+ if path == "/v2/users":+ return _page("users", [{"id": "u1"}], current=1, total_pages=1)+ if path == "/v2/users/u1/conversations":+ return _resp({"conversations": [{"id": "c1"}]})+ return message_pages[str(params["page"])]++ calls = _wire_routed(session, handler)++ rows = self._call("conversation_messages", session)++ assert rows == [{"id": "m1", "conversation_id": "c1"}]+ message_calls = [params for path, params in calls if path.endswith("/messages")]+ assert [params["page"] for params in message_calls] == [1, 2]+ assert message_calls[0]["items_per_page"] == str(PER_PAGE)+ assert "sort_order" not in message_calls[0]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_conversation_messages_skips_a_conversation_deleted_mid_sync(self, MockSession) -> None:+ # The chain skips a missing parent at both levels, so a conversation removed after the+ # users fan-out must not sink the messages table either.+ session = MockSession.return_value++ def handler(path: str, params: dict[str, Any]) -> Response:+ if path == "/v2/users":+ return _page("users", [{"id": "u1"}], current=1, total_pages=1)+ if path == "/v2/users/u1/conversations":+ return _resp({"conversations": [{"id": "gone"}, {"id": "c2"}]})+ if path == "/v2/conversations/gone/messages":+ return _resp({"error": "not found"}, status=404)+ return _resp({"messages": [{"id": "m2"}]} if params["page"] == 1 else {"messages": []})++ _wire_routed(session, handler)++ assert self._call("conversation_messages", session) == [{"id": "m2", "conversation_id": "c2"}]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_conversation_messages_key_column_comes_from_the_parent(self, MockSession) -> None:+ # The message object documents `conversation_id`, but projecting it from the parent row+ # keeps the primary-key column populated even when a response omits it.+ session = MockSession.return_value+ pages = {+ "/v2/users": _page("users", [{"id": "u1"}], current=1, total_pages=1),+ "/v2/users/u1/conversations": _resp({"conversations": [{"id": "c1"}]}),+ }++ def handler(path: str, params: dict[str, Any]) -> Response:+ if path in pages:+ return pages[path]+ return _resp({"messages": [{"id": "m1"}]} if params["page"] == 1 else {"messages": []})++ _wire_routed(session, handler)++ assert self._call("conversation_messages", session) == [{"id": "m1", "conversation_id": "c1"}]++class TestValidateCredentials:@pytest.mark.parametrize("status_code", [200, 401, 403])def test_returns_status_code(self, status_code: int) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat_source.pyindex 6e92bd3fef26..8e373dbe4d4a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat_source.py@@ -89,7 +89,13 @@ class TestFreshchatSource:("users", ["id"]),("groups", ["id"]),("channels", ["id"]),+ ("roles", ["id"]),("accounts_configuration", ["app_id"]),+ # The fan-out children aggregate rows from every parent, so the parent id is part of+ # the key: a conversation can be listed under more than one user, and Freshchat+ # documents no global uniqueness for message ids.+ ("user_conversations", ["user_id", "id"]),+ ("conversation_messages", ["conversation_id", "id"]),],)def test_schema_primary_keys(self, name: str, primary_keys: list[str]) -> None:@@ -150,14 +156,25 @@ class TestFreshchatSource:assert matches and matches[0] is not None- def test_source_for_pipeline_plumbing(self) -> None:- inputs = _make_inputs("agents")+ @pytest.mark.parametrize(+ "schema_name, primary_keys, partition_keys",+ [+ ("agents", ["id"], None),+ # Messages is the one endpoint with a stable creation timestamp and real volume, so it+ # is the one that partitions.+ ("conversation_messages", ["conversation_id", "id"], ["created_time"]),+ ],+ )+ def test_source_for_pipeline_plumbing(+ self, schema_name: str, primary_keys: list[str], partition_keys: Optional[list[str]]+ ) -> None:+ inputs = _make_inputs(schema_name)manager = self.source.get_resumable_source_manager(inputs)response = self.source.source_for_pipeline(self.config, manager, inputs)- assert response.name == "agents"- assert response.primary_keys == ["id"]- # Full refresh, paged with an explicit ascending sort.+ assert response.name == schema_name+ assert response.primary_keys == primary_keysassert response.sort_mode == "asc"- assert response.partition_mode is None+ assert response.partition_keys == partition_keys+ assert response.partition_mode == ("datetime" if partition_keys else None)