: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(chatwoot): add reporting events and membership tables (#102243)
Tom Owers761d1e5ce690
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 3729e9f9449b..d4e830d35d5a 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@@ -1399,13 +1399,13 @@ Note: No machine-readable spec is published; I enumerated the full /reference/\*## Chatwoot — gaps-Today (8): `agents`, `contacts`, `conversations`, `custom_attribute_definitions`, `inboxes`, `labels`, `messages`, `teams`+Today (11): `agents`, `contacts`, `conversations`, `custom_attribute_definitions`, `inbox_members`, `inboxes`, `labels`, `messages`, `reporting_events`, `team_members`, `teams`Diffed against: <https://raw.githubusercontent.com/chatwoot/chatwoot/develop/swagger/swagger.json>-- [ ] `/api/v1/accounts/{account_id}/reporting_events (and .../conversations/{conversation_id}/reporting_events)` — the per-conversation event stream (first_response, conversation_resolved, reply_time) that every support SLA metric is computed from (high)-- [ ] `/api/v1/accounts/{account_id}/teams/{team_id}/team_members` — lookup join table resolving which agents belong to which of the already-synced teams (high)-- [ ] `/api/v1/accounts/{account_id}/inbox_members/{inbox_id}` — lookup join table resolving agent-to-inbox assignment for routing and load analysis (high)+- [x] `/api/v1/accounts/{account_id}/reporting_events (and .../conversations/{conversation_id}/reporting_events)` — the per-conversation event stream (first_response, conversation_resolved, reply_time) that every support SLA metric is computed from (high)+- [x] `/api/v1/accounts/{account_id}/teams/{team_id}/team_members` — lookup join table resolving which agents belong to which of the already-synced teams (high)+- [x] `/api/v1/accounts/{account_id}/inbox_members/{inbox_id}` — lookup join table resolving agent-to-inbox assignment for routing and load analysis (high)- [ ] `/api/v2/accounts/{account_id}/summary_reports/agent | inbox | team | channel` — vendor-computed agent/inbox/team performance rollups (resolution counts, response times) (medium)- [ ] `/api/v2/accounts/{account_id}/reports/conversations and /reports/summary` — conversation volume and first-response-time timeseries, the product's headline dashboard numbers (medium)- [ ] `/api/v1/accounts/{account_id}/conversations/{conversation_id}/labels and /contacts/{id}/labels` — the label-to-conversation and label-to-contact join tables; the labels table alone cannot be joined to anything (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/canonical_descriptions.pyindex 822b4a42cb1f..7667b373c082 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/canonical_descriptions.py@@ -109,6 +109,52 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"show_on_sidebar": "Whether the label is pinned to the sidebar.",},},+ "reporting_events": {+ "description": "A measured support event on a conversation (first response, resolution, or reply time), carrying the duration the metric is computed from.",+ "docs_url": "https://developers.chatwoot.com/api-reference/reports/account-reporting-events",+ "columns": {+ "id": "Unique identifier for the reporting event.",+ "name": "Which metric the event measures: first_response, resolution, reply_time, and similar.",+ "value": "The measured duration in seconds, in wall-clock time.",+ "value_in_business_hours": "The measured duration in seconds, counting only the account's configured business hours.",+ "event_start_time": "When the measured interval started (ISO 8601 string).",+ "event_end_time": "When the measured interval ended (ISO 8601 string).",+ "account_id": "Id of the account the event belongs to.",+ "conversation_id": "Display id of the conversation the event was measured on.",+ "inbox_id": "Id of the inbox the conversation belongs to.",+ "user_id": "Id of the agent the event is attributed to.",+ "created_at": "When the event was recorded (ISO 8601 string).",+ "updated_at": "When the event was last updated (ISO 8601 string).",+ },+ },+ "team_members": {+ "description": "One agent's membership of one team. Join to teams on team_id and to agents on id.",+ "docs_url": "https://developers.chatwoot.com/api-reference/teams/list-agents-in-team",+ "columns": {+ "team_id": "Id of the team the agent belongs to.",+ "id": "Unique identifier for the agent's user.",+ "name": "The agent's full name.",+ "available_name": "Display name shown to contacts.",+ "email": "The agent's email address.",+ "role": "The agent's role in the account: agent or administrator.",+ "availability_status": "Current availability: online, busy, or offline.",+ "confirmed": "Whether the agent's user account is confirmed.",+ },+ },+ "inbox_members": {+ "description": "One agent's assignment to one inbox, which is what routes conversations from that inbox to them. Join to inboxes on inbox_id and to agents on id.",+ "docs_url": "https://developers.chatwoot.com/api-reference/inboxes/list-agents-in-inbox",+ "columns": {+ "inbox_id": "Id of the inbox the agent is assigned to.",+ "id": "Unique identifier for the agent's user.",+ "name": "The agent's full name.",+ "available_name": "Display name shown to contacts.",+ "email": "The agent's email address.",+ "role": "The agent's role in the account: agent or administrator.",+ "availability_status": "Current availability: online, busy, or offline.",+ "confirmed": "Whether the agent's user account is confirmed.",+ },+ },"custom_attribute_definitions": {"description": "Definition of a custom attribute that can be set on conversations, contacts, or companies.","docs_url": "https://developers.chatwoot.com/api-reference/custom-attributes/list-all-custom-attributes-in-an-account",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/chatwoot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/chatwoot.pyindex 9cab0b6a71d4..7852966ac09a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/chatwoot.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/chatwoot.py@@ -14,6 +14,8 @@ from asgiref.sync import async_to_syncfrom structlog.types import FilteringBoundLoggerfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_listfrom products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.settings import (CHATWOOT_ENDPOINTS,@@ -29,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basWebhookDeletionResult,WebhookSyncResult,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_valuefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -45,6 +48,8 @@ MAX_MESSAGE_PAGES_PER_CONVERSATION = 10_000# hostile server multiply requests without bound (conversations × pages). This aggregate ceiling# bounds the total message pages one sync fetches regardless of how many conversations it enumerates.MAX_MESSAGE_PAGES_PER_SYNC = 1_000_000+# Member fan-out issues one request per team / inbox, so the parent list bounds the request count.+MAX_MEMBER_FANOUT_PARENTS = 100_000# The host is customer-controlled (self-hosted Chatwoot), so a malicious or misconfigured server# could stream an unbounded body and exhaust a shared worker (requests buffers the whole body into@@ -61,6 +66,7 @@ HTTP_NOT_ALLOWED_ERROR = "Chatwoot host must use HTTPS"RESPONSE_TOO_LARGE_ERROR = "Chatwoot response body was too large"RESPONSE_TOO_SLOW_ERROR = "Chatwoot response download was too slow"INVALID_ACCOUNT_ID_ERROR = "Chatwoot account ID must be a number"+REPORTING_EVENTS_UNAVAILABLE_ERROR = "Chatwoot reporting events are not available on this instance"# Authority chars that let `urlparse` and the HTTP client disagree on where the host ends. A userinfo# separator or a (raw or percent-encoded) backslash in `https://169.254.169.254\@attacker.example`@@ -85,7 +91,7 @@ class ChatwootResponseTooSlowError(Exception):pass[email protected](frozen=True)class ChatwootResumeConfig:# Next page to fetch for page-number endpoints. Stored as a bare page number (not a URL) so# stale state can never replay against a different host after the source's host is edited.@@ -94,6 +100,20 @@ class ChatwootResumeConfig:# last message id already yielded within it (the next request sends `after=<message_id>`).conversation_id: int | None = Noneafter: int | None = None+ # Member fan-out bookmark: the team / inbox currently being walked.+ parent_id: int | None = None+ # reporting_events only: the window end the interrupted attempt paginated against. Page+ # numbers only line up against the same window, so a resumed attempt must reuse it rather+ # than recompute "now".+ until: int | None = None+++@frozen+class ReportingEventsWindow:+ """The since/until bounds, in unix seconds, of one reporting_events page walk."""++ since: int+ until: intdef normalize_host(host: str | None) -> str:@@ -390,6 +410,132 @@ def _get_message_rows(resumable_source_manager.save_state(ChatwootResumeConfig(conversation_id=remaining[index + 1], after=0))+def _iter_parent_ids(+ session: requests.Session, base_url: str, parent_endpoint: str, logger: FilteringBoundLogger+) -> list[int]:+ """Ids of the rows a member fan-out iterates, read from the parent endpoint."""+ parent = CHATWOOT_ENDPOINTS[parent_endpoint]+ if parent.kind != "single":+ raise ValueError(f"Chatwoot member fan-out parent '{parent_endpoint}' must be an unpaginated endpoint")++ url = _build_url(base_url, parent.path, dict(parent.params))+ items = _extract_items(_fetch_json(session, url, logger), parent.data_path, url)+ ids = [item["id"] for item in items if item.get("id") is not None]+ if len(ids) > MAX_MEMBER_FANOUT_PARENTS:+ logger.warning(+ f"Chatwoot: {parent_endpoint} returned more than the {MAX_MEMBER_FANOUT_PARENTS}-parent "+ "fan-out cap; rows beyond it were skipped"+ )+ return ids[:MAX_MEMBER_FANOUT_PARENTS]+ return ids+++def _get_member_rows(+ session: requests.Session,+ base_url: str,+ config: ChatwootEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChatwootResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """One unpaginated request per team / inbox, stamping the parent id onto each agent row.++ The rows Chatwoot returns are agent records, so `id` repeats across parents and only+ (parent id, agent id) identifies a membership.+ """+ if config.parent is None or config.parent_id_field is None:+ raise ValueError(f"Chatwoot endpoint '{config.name}' is a member fan-out without a parent")++ parent_ids = _iter_parent_ids(session, base_url, config.parent, logger)++ # If the bookmarked parent is gone, start over from the first one — merge dedupes re-pulled+ # rows on the primary key.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = parent_ids+ if resume is not None and resume.parent_id is not None and resume.parent_id in parent_ids:+ remaining = parent_ids[parent_ids.index(resume.parent_id) :]+ logger.debug(f"Chatwoot: resuming {config.name} from {config.parent_id_field}={resume.parent_id}")++ for index, parent_id in enumerate(remaining):+ url = _build_url(base_url, config.path.format(parent_id=parent_id), dict(config.params))+ try:+ items = _extract_items(_fetch_json(session, url, logger), config.data_path, url)+ except requests.HTTPError as exc:+ # A team or inbox deleted between enumeration and this fetch 404s. Skip it rather than+ # failing the whole sync. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Chatwoot: {config.parent} {parent_id} not found while fetching members, skipping")+ items = []+ else:+ raise++ rows = [{**item, config.parent_id_field: parent_id} for item in items if item.get("id") is not None]+ if rows:+ yield rows++ # Advance the bookmark to the next parent so a crash between parents resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(ChatwootResumeConfig(parent_id=remaining[index + 1]))+++def _reporting_events_window(db_incremental_field_last_value: Any) -> ReportingEventsWindow:+ """The unix-second bounds for one reporting_events walk.++ `until` is pinned at the start of the walk because Chatwoot orders this endpoint newest-first+ across page numbers: without a fixed upper bound, an event created mid-walk shifts every later+ page down and the rows at each boundary are never fetched. Chatwoot ignores the filter unless+ both bounds are present, so a full refresh sends epoch 0 rather than omitting `since`.+ """+ watermark = parse_datetime_value(db_incremental_field_last_value)+ return ReportingEventsWindow(+ since=max(0, int(watermark.timestamp())) if watermark is not None else 0,+ until=int(datetime.now(UTC).timestamp()),+ )+++def _get_reporting_event_rows(+ session: requests.Session,+ base_url: str,+ config: ChatwootEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChatwootResumeConfig],+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ window = _reporting_events_window(db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = 1+ if resume is not None and resume.page is not None:+ page = resume.page+ if resume.until is not None:+ window = dataclasses.replace(window, until=resume.until)+ logger.debug(f"Chatwoot: resuming reporting_events from page {page} of the window ending {window.until}")++ while page <= MAX_LIST_PAGES:+ url = _build_url(base_url, config.path, {"since": window.since, "until": window.until, "page": page})+ try:+ data = _fetch_json(session, url, logger)+ except requests.HTTPError as exc:+ # The route only exists on enterprise builds, so a community-edition instance has no+ # endpoint to answer here at all. Say that instead of letting the generic 404 message+ # send the user off to re-check an account id that is fine.+ if exc.response is not None and exc.response.status_code == 404:+ raise Exception(f"{REPORTING_EVENTS_UNAVAILABLE_ERROR}: GET {config.path} returned 404") from exc+ raise++ items = _extract_items(data, config.data_path, url)+ if not items:+ return+ yield items++ total_pages = data.get("meta", {}).get("total_pages") if isinstance(data, dict) else None+ page += 1+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it.+ resumable_source_manager.save_state(ChatwootResumeConfig(page=page, until=window.until))+ if isinstance(total_pages, int) and page > total_pages:+ return+ logger.warning(f"Chatwoot: reporting_events hit the {MAX_LIST_PAGES}-page cap; rows beyond it were skipped")++def get_rows(host: str | None,account_id: str | int | None,@@ -398,6 +544,7 @@ def get_rows(team_id: int,logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[ChatwootResumeConfig],+ db_incremental_field_last_value: Any = None,) -> Iterator[list[dict[str, Any]]]:config = CHATWOOT_ENDPOINTS[endpoint]_ensure_host_allowed(host, team_id)@@ -417,6 +564,16 @@ def get_rows(yield from _get_message_rows(session, base_url, logger, resumable_source_manager)return+ if config.kind == "member_fanout":+ yield from _get_member_rows(session, base_url, config, logger, resumable_source_manager)+ return++ if config.kind == "reporting_events":+ yield from _get_reporting_event_rows(+ session, base_url, config, logger, resumable_source_manager, db_incremental_field_last_value+ )+ return+resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Nonepage = resume.page if resume is not None and resume.page is not None else 1if resume is not None:@@ -712,6 +869,7 @@ def chatwoot_source(logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[ChatwootResumeConfig],webhook_source_manager: Optional[WebhookSourceManager] = None,+ db_incremental_field_last_value: Any = None,) -> SourceResponse:config: ChatwootEndpointConfig = CHATWOOT_ENDPOINTS[endpoint]@@ -733,13 +891,14 @@ def chatwoot_source(team_id=team_id,logger=logger,resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=db_incremental_field_last_value,)return SourceResponse(name=endpoint,items=items,primary_keys=config.primary_keys,- sort_mode="asc",+ sort_mode=config.sort_mode,partition_count=1,partition_size=1,partition_mode="datetime" if config.partition_key else None,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/settings.pyindex 7b3edb5a0da7..1adbf42addbf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/settings.py@@ -1,6 +1,9 @@from dataclasses import dataclass, fieldfrom typing import Literal, Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+DEFAULT_HOST = "https://app.chatwoot.com"# Server-side fixed page sizes — Chatwoot exposes no per-page override param.@@ -12,29 +15,39 @@ MESSAGES_PAGE_SIZE = 100MESSAGE_TYPE_TO_INT = {"incoming": 0, "outgoing": 1, "activity": 2, "template": 3}-@dataclass+@dataclass(frozen=True)class ChatwootEndpointConfig:name: str- # Path under /api/v1/accounts/{account_id}.+ # Path under /api/v1/accounts/{account_id}. Member fan-out paths carry a {parent_id}+ # placeholder filled from the parent endpoint's rows.path: str# "paged": page-number list. "single": one unpaginated response. "messages": the- # per-conversation fan-out with an id-based `after` cursor.- kind: Literal["paged", "single", "messages"]+ # per-conversation fan-out with an id-based `after` cursor. "reporting_events": a+ # page-number list bounded by a since/until window. "member_fanout": one unpaginated+ # request per parent row, stamping the parent id onto each child row.+ kind: Literal["paged", "single", "messages", "reporting_events", "member_fanout"]# Where the row list lives in the response body; () means the body is a bare JSON array.data_path: tuple[str, ...] = ()# Query params sent on every request.params: dict[str, str] = field(default_factory=dict)primary_keys: list[str] = field(default_factory=lambda: ["id"])# Stable creation-time field for datetime partitioning (unix epoch ints in Chatwoot list- # responses). Never an updated_at-style field.+ # responses, ISO 8601 strings on reporting_events). Never an updated_at-style field.partition_key: Optional[str] = Nonesupports_webhooks: bool = Falsedescription: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Order rows arrive in, which the pipeline's watermark handling depends on.+ sort_mode: SortMode = "asc"+ # member_fanout only: the endpoint whose rows supply {parent_id}, and the column each child+ # row records it in. Agent ids repeat across parents, so the column is part of the primary key.+ parent: Optional[str] = None+ parent_id_field: Optional[str] = None-# No endpoint here declares incremental sync: Chatwoot's list endpoints expose no server-side-# timestamp filter (no updated_since/created_since), so every pull is a full walk. Webhooks are-# the delta path for conversations and messages.+# Only reporting_events declares incremental sync: it is the one endpoint with a server-side+# timestamp filter (since/until on created_at). Every other list endpoint is a full walk, and+# webhooks are the delta path for conversations and messages.CHATWOOT_ENDPOINTS: dict[str, ChatwootEndpointConfig] = {"conversations": ChatwootEndpointConfig(name="conversations",@@ -97,6 +110,53 @@ CHATWOOT_ENDPOINTS: dict[str, ChatwootEndpointConfig] = {kind="single",data_path=("payload",),),+ "reporting_events": ChatwootEndpointConfig(+ name="reporting_events",+ path="/reporting_events",+ kind="reporting_events",+ data_path=("payload",),+ partition_key="created_at",+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+ # The controller hardcodes .order(created_at: :desc) with no sort param to override it.+ sort_mode="desc",+ description=(+ "Per-conversation SLA events (first_response, resolution, reply_time), each carrying "+ "the measured duration in seconds, both wall-clock and business-hours. Requires an "+ "administrator token, and the endpoint is absent on Chatwoot community-edition builds."+ ),+ ),+ "team_members": ChatwootEndpointConfig(+ name="team_members",+ path="/teams/{parent_id}/team_members",+ kind="member_fanout",+ parent="teams",+ parent_id_field="team_id",+ primary_keys=["team_id", "id"],+ description=(+ "Which agents belong to which team. One row per team membership, joinable to teams "+ "on team_id and to agents on id."+ ),+ ),+ "inbox_members": ChatwootEndpointConfig(+ name="inbox_members",+ path="/inbox_members/{parent_id}",+ kind="member_fanout",+ data_path=("payload",),+ parent="inboxes",+ parent_id_field="inbox_id",+ primary_keys=["inbox_id", "id"],+ description=(+ "Which agents are assigned to which inbox. One row per inbox assignment, joinable to "+ "inboxes on inbox_id and to agents on id."+ ),+ ),"custom_attribute_definitions": ChatwootEndpointConfig(name="custom_attribute_definitions",path="/custom_attribute_definitions",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/source.pyindex af579424888a..05c3174933b6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/source.py@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.cHOST_NOT_ALLOWED_ERROR,HTTP_NOT_ALLOWED_ERROR,INVALID_ACCOUNT_ID_ERROR,+ REPORTING_EVENTS_UNAVAILABLE_ERROR,RESPONSE_TOO_LARGE_ERROR,RESPONSE_TOO_SLOW_ERROR,ChatwootResumeConfig,@@ -173,6 +174,7 @@ If automatic creation failed, note that only Chatwoot administrators can manage"401 Client Error": "Chatwoot rejected your API access token. Check the token is correct, has not been revoked, and belongs to a member of the configured account, then reconnect.","403 Client Error": "Your Chatwoot API access token does not have permission to read this data. Use an administrator's access token, then reconnect.","404 Client Error": "Chatwoot could not find the configured account. Check the account ID and instance URL, then reconnect.",+ REPORTING_EVENTS_UNAVAILABLE_ERROR: "This Chatwoot instance does not serve reporting events. The endpoint only exists on Chatwoot Cloud and enterprise builds, so deselect the reporting_events table to sync the rest.",INVALID_ACCOUNT_ID_ERROR: "The Chatwoot account ID must be a number (the number in your Chatwoot URL, e.g. app.chatwoot.com/app/accounts/1). Update the source configuration.",HOST_NOT_ALLOWED_ERROR: "The Chatwoot host is not allowed. Please use a publicly reachable instance URL.",HTTP_NOT_ALLOWED_ERROR: "The Chatwoot host must use HTTPS. Please update the instance URL to use https://.",@@ -189,14 +191,17 @@ If automatic creation failed, note that only Chatwoot administrators can manageforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # Chatwoot's list endpoints expose no server-side timestamp filter, so every schema is- # full refresh; conversations and messages additionally support webhook-fed deltas.+ # Only reporting_events has a server-side timestamp filter to sync incrementally against;+ # the rest are full refresh, and conversations and messages also support webhook-fed deltas.schemas = [SourceSchema(name=endpoint,- supports_incremental=False,+ supports_incremental=bool(CHATWOOT_ENDPOINTS[endpoint].incremental_fields),+ # Not append: Chatwoot's since/until bounds are whole seconds while created_at+ # carries sub-seconds, so each run re-reads the watermark's own second. A merge+ # dedupes those rows on the primary key; an append would duplicate them.supports_append=False,- incremental_fields=[],+ incremental_fields=CHATWOOT_ENDPOINTS[endpoint].incremental_fields,supports_webhooks=CHATWOOT_ENDPOINTS[endpoint].supports_webhooks,description=CHATWOOT_ENDPOINTS[endpoint].description,)@@ -282,4 +287,7 @@ If automatic creation failed, note that only Chatwoot administrators can managelogger=inputs.logger,resumable_source_manager=resumable_source_manager,webhook_source_manager=self.get_webhook_source_manager(inputs),+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot.pyindex d3f3ed8f3a5e..9b167c4ff965 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot.py@@ -1,5 +1,7 @@import json+from datetime import UTC, datetimefrom typing import Any+from urllib.parse import parse_qs, urlsplitimport pytestfrom unittest import mock@@ -8,6 +10,7 @@ import requestsfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_listfrom products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot import (+ REPORTING_EVENTS_UNAVAILABLE_ERROR,ChatwootResumeConfig,_normalize_account_id,chatwoot_source,@@ -319,6 +322,214 @@ class TestGetRowsMessages:assert message_urls == ["https://app.chatwoot.com/api/v1/accounts/1/conversations/2/messages?after=20"]+class TestGetRowsMemberFanout:+ @pytest.mark.parametrize(+ "endpoint, parent_id_field, parents, members, expected_rows, expected_path",+ [+ (+ "team_members",+ "team_id",+ [{"id": 10}],+ [{"id": 1, "name": "Ada"}, {"id": 2, "name": "Grace"}],+ [(10, 1), (10, 2)],+ "/teams/10/team_members",+ ),+ # inbox_members hangs off a parent that answers under a payload envelope, answers under+ # one itself, and has a flat path, so the two endpoints exercise different extraction+ # and path formatting.+ (+ "inbox_members",+ "inbox_id",+ {"payload": [{"id": 20}]},+ {"payload": [{"id": 3}]},+ [(20, 3)],+ "/inbox_members/20",+ ),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_parent_id_is_stamped_onto_each_agent_row(+ self, mock_session, endpoint, parent_id_field, parents, members, expected_rows, expected_path+ ):+ # Rows are agent records, so the same agent id comes back under several parents. Without+ # the parent id on the row the composite primary key cannot be built and memberships+ # collapse into one.+ mock_session.return_value.get.side_effect = [_resp(parents), _resp(members)]++ batches = list(get_rows(None, "1", "token", endpoint, TEAM_ID, mock.MagicMock(), _make_manager()))++ rows = [row for batch in batches for row in batch]+ assert [(row[parent_id_field], row["id"]) for row in rows] == expected_rows+ assert mock_session.return_value.get.call_args_list[1].args[0].endswith(expected_path)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_walks_every_parent(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp([{"id": 10}, {"id": 11}]),+ _resp([{"id": 1}]),+ _resp([{"id": 1}]),+ ]+ manager = _make_manager()++ batches = list(get_rows(None, "1", "token", "team_members", TEAM_ID, mock.MagicMock(), manager))++ assert [row["team_id"] for batch in batches for row in batch] == [10, 11]+ # The bookmark advances to the next parent so a crash between parents resumes there.+ assert [call.args[0].parent_id for call in manager.save_state.call_args_list] == [11]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_deleted_parent_404_is_skipped(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp([{"id": 10}, {"id": 11}]),+ _resp({"error": "Resource could not be found"}, status=404),+ _resp([{"id": 2}]),+ ]++ batches = list(get_rows(None, "1", "token", "team_members", TEAM_ID, mock.MagicMock(), _make_manager()))++ assert [row["id"] for batch in batches for row in batch] == [2]++ @pytest.mark.parametrize(+ "bookmarked_parent_id, expected_team_ids",+ # A bookmark for a parent that no longer exists must restart the walk, not skip everything.+ [(11, [11]), (999, [10, 11])],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_resumes_from_bookmarked_parent(self, mock_session, bookmarked_parent_id, expected_team_ids):+ mock_session.return_value.get.side_effect = [+ _resp([{"id": 10}, {"id": 11}]),+ _resp([{"id": 5}]),+ _resp([{"id": 5}]),+ ]+ manager = _make_manager(ChatwootResumeConfig(parent_id=bookmarked_parent_id))++ batches = list(get_rows(None, "1", "token", "team_members", TEAM_ID, mock.MagicMock(), manager))++ assert [row["team_id"] for batch in batches for row in batch] == expected_team_ids++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.MAX_MEMBER_FANOUT_PARENTS",+ 1,+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_parent_fanout_stops_at_the_parent_cap(self, mock_session):+ # A misbehaving server can return an unbounded parent list, and the fan-out issues one+ # request per parent.+ mock_session.return_value.get.side_effect = [_resp([{"id": 10}, {"id": 11}]), _resp([{"id": 1}])]++ batches = list(get_rows(None, "1", "token", "team_members", TEAM_ID, mock.MagicMock(), _make_manager()))++ assert [row["team_id"] for batch in batches for row in batch] == [10]+ assert not any("/teams/11/" in call.args[0] for call in mock_session.return_value.get.call_args_list)+++class TestGetRowsReportingEvents:+ @pytest.mark.parametrize(+ "watermark, expected_since",+ [+ # Chatwoot drops the filter unless both bounds are present, so a full refresh sends+ # epoch 0 rather than omitting `since`.+ (None, 0),+ ("2026-01-02T03:04:05+00:00", 1767323045),+ (datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), 1767323045),+ # An unusable watermark must widen the window, never narrow it to an arbitrary date.+ ("not-a-date", 0),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_walks_pages_within_a_pinned_window_and_stops_at_total_pages(self, mock_session, watermark, expected_since):+ mock_session.return_value.get.side_effect = [+ _resp({"meta": {"count": 3, "current_page": 1, "total_pages": 2}, "payload": [{"id": 1}, {"id": 2}]}),+ _resp({"meta": {"count": 3, "current_page": 2, "total_pages": 2}, "payload": [{"id": 3}]}),+ ]+ manager = _make_manager()++ batches = list(+ get_rows(+ None,+ "1",+ "token",+ "reporting_events",+ TEAM_ID,+ mock.MagicMock(),+ manager,+ db_incremental_field_last_value=watermark,+ )+ )++ assert [row["id"] for batch in batches for row in batch] == [1, 2, 3]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ # total_pages ends the walk, so no third request is made.+ assert len(urls) == 2+ assert all(f"since={expected_since}" in url for url in urls)+ # Chatwoot orders this endpoint newest-first over page numbers, so the window end has to+ # be identical on every page or rows at each boundary are skipped as events arrive.+ untils = {parse_qs(urlsplit(url).query)["until"][0] for url in urls}+ assert len(untils) == 1+ # Saved state carries that window so a resumed attempt paginates the same one.+ assert [(call.args[0].page, call.args[0].until) for call in manager.save_state.call_args_list] == [+ (2, int(untils.pop())),+ (3, mock.ANY),+ ]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_missing_total_pages_falls_back_to_the_empty_page(self, mock_session):+ mock_session.return_value.get.side_effect = [_resp({"payload": [{"id": 1}]}), _resp({"payload": []})]++ batches = list(get_rows(None, "1", "token", "reporting_events", TEAM_ID, mock.MagicMock(), _make_manager()))++ assert [row["id"] for batch in batches for row in batch] == [1]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_resume_reuses_the_saved_window(self, mock_session):+ # Recomputing "now" on a resumed attempt would renumber every remaining page.+ mock_session.return_value.get.return_value = _resp({"meta": {}, "payload": []})+ manager = _make_manager(ChatwootResumeConfig(page=4, until=1767000000))++ list(+ get_rows(+ None,+ "1",+ "token",+ "reporting_events",+ TEAM_ID,+ mock.MagicMock(),+ manager,+ db_incremental_field_last_value="2026-01-02T03:04:05+00:00",+ )+ )++ url = mock_session.return_value.get.call_args.args[0]+ assert "page=4" in url and "until=1767000000" in url++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.chatwoot.chatwoot.make_tracked_session"+ )+ def test_404_reports_the_endpoint_as_unavailable_not_a_missing_account(self, mock_session):+ # The route only exists on enterprise builds. The generic 404 message would send the user+ # off to re-check an account id that is correct.+ mock_session.return_value.get.return_value = _resp({"error": "Not Found"}, status=404)++ with pytest.raises(Exception, match=REPORTING_EVENTS_UNAVAILABLE_ERROR):+ list(get_rows(None, "1", "token", "reporting_events", TEAM_ID, mock.MagicMock(), _make_manager()))++class TestWebhookTableTransformer:def test_message_events_are_normalized_to_the_rest_shape(self):transform = make_webhook_table_transformer("messages")@@ -489,6 +700,13 @@ class TestChatwootSourceResponse:if config.partition_key:assert config.partition_key == "created_at"+ @pytest.mark.parametrize("config", list(CHATWOOT_ENDPOINTS.values()))+ def test_fanout_primary_keys_include_the_parent_id(self, config):+ # A fan-out child aggregates rows from every parent, so a key that is only unique per+ # parent seeds duplicates that every later merge multi-matches.+ if config.parent_id_field:+ assert config.parent_id_field in config.primary_keys+def test_webhook_enabled_schema_reads_from_webhook_manager(self):webhook_manager = mock.MagicMock()webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot_source.pyindex 943a2af55c9f..fd417bdf4b41 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chatwoot/tests/test_chatwoot_source.py@@ -36,13 +36,18 @@ class TestChatwootSource:transient = "500 Server Error for url: https://app.chatwoot.com/api/v1/accounts/1/contacts"assert not any(key in transient for key in self.source.get_non_retryable_errors())- def test_get_schemas_are_full_refresh_with_webhook_deltas(self):+ def test_get_schemas_only_advertise_incremental_where_a_server_filter_exists(self):schemas = self.source.get_schemas(self.config, self.team_id)assert {schema.name for schema in schemas} == set(ENDPOINTS)- # No Chatwoot list endpoint has a server-side timestamp filter, so nothing may advertise- # incremental sync.- assert not any(schema.supports_incremental or schema.supports_append for schema in schemas)+ # reporting_events is the only endpoint with a since/until filter; advertising incremental+ # on any other would re-walk every page and call it a delta sync.+ assert {schema.name for schema in schemas if schema.supports_incremental} == {"reporting_events"}+ # The since/until bounds are whole seconds, so every run re-reads the watermark's own+ # second. Merge dedupes that overlap on the primary key; append would duplicate it.+ assert not any(schema.supports_append for schema in schemas)+ reporting_events = next(schema for schema in schemas if schema.name == "reporting_events")+ assert [field["field"] for field in reporting_events.incremental_fields] == ["created_at"]assert {schema.name for schema in schemas if schema.supports_webhooks} == {"conversations", "messages"}def test_get_schemas_filtered_by_names(self):