: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 gladly conversations table (#80010)
jake sciottoe41e2f206f7e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/canonical_descriptions.pyindex 68d85a86a2ad..2f11d84116fc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/canonical_descriptions.py@@ -137,4 +137,40 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"_row_id": "Deterministic hash of the row, injected as the primary key (the report has no event id).",},},+ # One row per conversation from the Conversation Export report metric set;+ # column names are the report's CSV headers, snake_cased.+ "conversations": {+ "description": "A customer conversation, with its current status, assignment, and lifecycle timestamps. One row per conversation, from Gladly's Conversation Export report.",+ "docs_url": "https://help.gladly.com/docs/conversation-export",+ "columns": {+ "conversation_id": "Unique identifier for the conversation.",+ "created_at": "Time at which the conversation was created (incremental cursor).",+ "customer_id": "Identifier of the customer the conversation is with.",+ "conversation_link": "Link to the conversation in Gladly.",+ "status": "Current status of the conversation: OPEN, CLOSED, or MERGED.",+ "assigned_agent_id_current": "Identifier of the agent currently assigned to the conversation.",+ "assigned_agent_name_current": "Name of the agent currently assigned to the conversation.",+ "inbox_id_current": "Identifier of the inbox the conversation is currently assigned to.",+ "inbox_name_current": "Name of the inbox the conversation is currently assigned to.",+ "first_closed_at": "Time at which the conversation was first closed, if ever closed.",+ "last_closed_at": "Time at which the conversation was most recently closed, if ever closed.",+ "initiator_type_created": "Who created the conversation: Agent, Application, Customer, or System.",+ "initiator_agent_id_created": "Identifier of the agent who created the conversation, when agent-initiated.",+ "inbox_id_created": "Identifier of the inbox the conversation was created in.",+ "assigned_agent_id_created": "Identifier of the agent assigned when the conversation was created.",+ "topics": "Names of the topics applied to the conversation.",+ "topics_with_hierarchy": "Topics applied to the conversation, including their parent topics.",+ "first_contact_id": "Identifier of the first contact in the conversation.",+ "first_channel": "Channel of the first contact in the conversation.",+ "last_channel": "Channel of the most recent contact in the conversation.",+ "created_to_first_closed_time": "Seconds from creation until the conversation was first closed.",+ "created_to_last_closed_time": "Seconds from creation until the conversation was most recently closed.",+ "conversation_handle_time": "Total agent handle time on the conversation, in seconds.",+ "count_of_contacts": "Number of contacts in the conversation.",+ "count_of_agents": "Number of agents who worked the conversation.",+ "count_of_inboxes_assigned": "Number of inboxes the conversation was assigned to.",+ "times_closed": "Number of times the conversation was closed.",+ "times_reopened": "Number of times the conversation was reopened.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/settings.pyindex 9d51c9240faf..57f0cb4c8dc5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/settings.py@@ -24,12 +24,29 @@ _TIMESTAMPS_REPORT_INCREMENTAL_FIELDS: list[IncrementalField] = [},]+# Conversation-report rows carry the conversation's own creation timestamp (the+# report's date filter is anchored on it), so that column is the incremental cursor.+_REPORT_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+]+# Injected primary key for report streams whose rows have no natural unique id# (event-grain reports ship no event id column): a deterministic hash of the# whole normalized row. The transport injects it when an endpoint declares it# as the primary key.REPORT_ROW_ID_COLUMN = "_row_id"+# Conversation-report rows restate as records change (e.g. a conversation closes+# after its row was first synced), so incremental runs re-read a trailing window;+# merge on the primary key dedupes the overlap. Older rows only refresh on a full+# refresh.+REPORT_INCREMENTAL_LOOKBACK_SECONDS = 30 * 24 * 60 * 60+@dataclassclass GladlyEndpointConfig:@@ -75,6 +92,20 @@ GLADLY_ENDPOINTS: dict[str, GladlyEndpointConfig] = {name="topics",filename="topics.jsonl",),+ # Export jobs ship no conversations file and the REST API only lists+ # conversations per customer, so conversation-level rows come from the+ # Conversation Export report (one row per conversation, anchored on its+ # creation date). Column names are the report's CSV headers, snake_cased.+ # One row per conversation keeps 7-day windows clear of the row cap, and+ # the 730-day backfill is a cost bound, not a vendor limit.+ "conversations": GladlyEndpointConfig(+ name="conversations",+ report_metric_set="ConversationExportReport",+ primary_key="conversation_id",+ report_window_days=7,+ report_backfill_days=730,+ incremental_fields=list(_REPORT_INCREMENTAL_FIELDS),+ ),# Handle-time, first-response, and wait-time analytics need Gladly's# purpose-built timestamps reports — export jobs ship no equivalent files.# Both reports are event-grain (one row per conversation/contact event)@@ -99,8 +130,9 @@ GLADLY_ENDPOINTS: dict[str, GladlyEndpointConfig] = {ENDPOINTS = tuple(GLADLY_ENDPOINTS.keys())-# Report windows are re-read on resume and behind the incremental watermark, so-# appending would duplicate rows — these streams only support incremental merge.+# Report windows are re-read on resume and behind the incremental watermark, and+# conversation rows restate in place (status, closed timestamps), so appending+# would duplicate rows — these streams only support incremental merge.REPORT_ENDPOINTS = tuple(name for name, config in GLADLY_ENDPOINTS.items() if config.report_metric_set)INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.pyindex f1ab2ab7ae01..cb41e70342cd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.setENDPOINTS,INCREMENTAL_FIELDS,REPORT_ENDPOINTS,+ REPORT_INCREMENTAL_LOOKBACK_SECONDS,SHOULD_SYNC_DEFAULT,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -76,7 +77,7 @@ class GladlySource(ResumableSource[GladlySourceConfig, GladlyResumeConfig]):label="Gladly",caption="""Connect your Gladly account to pull your customer service data into the PostHog Data warehouse.-Your organization is the part of your Gladly URL before `.gladly.com`. For `myorg.gladly.com` enter `myorg`, and for `myorg.us-1.gladly.com` enter `myorg.us-1`. The API token must belong to an agent with the API User permission (Settings > API Tokens). Leave the domain on Production unless you are connecting a Gladly sandbox, which is served on `gladly.qa`. Data comes from Gladly's scheduled export jobs, which retain files for 14 days. History older than that requires asking Gladly support to regenerate exports. The conversation and contact timestamps tables come from Gladly's reports instead and reach back 90 days on their first sync.""",+Your organization is the part of your Gladly URL before `.gladly.com`. For `myorg.gladly.com` enter `myorg`, and for `myorg.us-1.gladly.com` enter `myorg.us-1`. The API token must belong to an agent with the API User permission (Settings > API Tokens). Leave the domain on Production unless you are connecting a Gladly sandbox, which is served on `gladly.qa`. Data comes from Gladly's scheduled export jobs, which retain files for 14 days. History older than that requires asking Gladly support to regenerate exports. The conversations table is built from Gladly's Conversation Export report instead, so it is not limited to the 14-day export window, and the conversation and contact timestamps tables come from Gladly's reports as well, reaching back 90 days on their first sync.""",iconPath="/static/services/gladly.png",docsUrl="https://posthog.com/docs/cdp/sources/gladly",releaseStatus=ReleaseStatus.ALPHA,@@ -133,13 +134,19 @@ Your organization is the part of your Gladly URL before `.gladly.com`. For `myor# Report windows are re-read on resume and behind the watermark, so# appending would duplicate rows (merge_only). The event-grain report# tables are high-volume, so they start opt-in (should_sync_default).- return build_endpoint_schemas(+ schemas = build_endpoint_schemas(ENDPOINTS,INCREMENTAL_FIELDS,names,merge_only=REPORT_ENDPOINTS,should_sync_default=SHOULD_SYNC_DEFAULT,)+ # Conversation-report rows restate in place as records change, so its+ # incremental runs re-read a trailing window to catch the restatements.+ for schema in schemas:+ if schema.name == "conversations":+ schema.default_incremental_lookback_seconds = REPORT_INCREMENTAL_LOOKBACK_SECONDS+ return schemasdef validate_credentials(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.pyindex 7612d932864e..7670b0383943 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py@@ -359,6 +359,11 @@ class TestNormalizeReportColumn:("Transferred To Inbox Name", "transferred_to_inbox_name"),("Final IVR Selection", "final_ivr_selection"),(" Fulfilled by Contact ID ", "fulfilled_by_contact_id"),+ ("Conversation ID", "conversation_id"),+ ("Assigned Agent ID - Current", "assigned_agent_id_current"),+ ("Created-to-First Closed Time", "created_to_first_closed_time"),+ ("Billable Resolution (Y/N)", "billable_resolution_y_n"),+ (" Topics with Hierarchy ", "topics_with_hierarchy"),],)def test_headers_become_stable_snake_case_columns(self, header, expected):@@ -444,6 +449,84 @@ class TestGetReportRows:"2024-03-15",]+ @freeze_time("2024-03-15T10:00:00Z")+ @mock.patch(f"{_MODULE}.REPORT_REQUEST_INTERVAL_SECONDS", 0)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_conversations_report_uses_weekly_windows_and_keeps_the_natural_key(self, mock_session):+ header = (+ "Created At,Conversation ID,Customer ID,Status,"+ "Assigned Agent ID - Current,Inbox ID - Current,First Closed At,Last Closed At\n"+ )+ mock_session.return_value.post.side_effect = [+ _csv_response(+ header+ + "2024-03-04T10:00:00.000Z,conv-1,cust-1,CLOSED,agent-1,inbox-1,"+ + "2024-03-05T00:00:00.000Z,2024-03-05T00:00:00.000Z\n"+ ),+ _csv_response(header + '2024-03-11T10:00:00.000Z,conv-2,"cust, 2",OPEN,,inbox-1,,\n'),+ ]++ manager = _make_manager()+ batches = list(+ get_rows(+ "myorg",+ "[email protected]",+ "token",+ "conversations",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-03-10T05:00:00.000Z",+ )+ )++ # One window per the endpoint's 7-day report_window_days, oldest first,+ # starting one full window behind the watermark date.+ calls = mock_session.return_value.post.call_args_list+ assert [call.kwargs["json"] for call in calls] == [+ {+ "metricSet": "ConversationExportReport",+ "timezone": "UTC",+ "startAt": "2024-03-03",+ "endAt": "2024-03-09",+ },+ {+ "metricSet": "ConversationExportReport",+ "timezone": "UTC",+ "startAt": "2024-03-10",+ "endAt": "2024-03-15",+ },+ ]++ # Conversations carry a natural key, so no _row_id is injected.+ flat = [row for batch in batches for row in batch]+ assert flat == [+ {+ "created_at": "2024-03-04T10:00:00.000Z",+ "conversation_id": "conv-1",+ "customer_id": "cust-1",+ "status": "CLOSED",+ "assigned_agent_id_current": "agent-1",+ "inbox_id_current": "inbox-1",+ "first_closed_at": "2024-03-05T00:00:00.000Z",+ "last_closed_at": "2024-03-05T00:00:00.000Z",+ },+ {+ "created_at": "2024-03-11T10:00:00.000Z",+ "conversation_id": "conv-2",+ "customer_id": "cust, 2",+ "status": "OPEN",+ "assigned_agent_id_current": None,+ "inbox_id_current": "inbox-1",+ "first_closed_at": None,+ "last_closed_at": None,+ },+ ]+ assert [call.args[0].last_report_window_end for call in manager.save_state.call_args_list] == [+ "2024-03-09",+ "2024-03-15",+ ]+@freeze_time("2024-03-15T10:00:00Z")@mock.patch(f"{_MODULE}.make_tracked_session")def test_first_sync_starts_at_the_backfill_horizon(self, mock_session):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.pyindex 29929f18f7aa..f0c0737a5e18 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py@@ -6,7 +6,11 @@ from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInpfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.gladly import GladlySourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.gladly.gladly import GladlyResumeConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.settings import ENDPOINTS, REPORT_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.settings import (+ ENDPOINTS,+ REPORT_ENDPOINTS,+ REPORT_INCREMENTAL_LOOKBACK_SECONDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.source import GladlySourcefrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -74,17 +78,32 @@ class TestGladlySource:for schema in schemas:# Job-export streams cursor on the injected job watermark; report- # streams cursor on the event's own recorded time.- expected = ["timestamp"] if schema.name in REPORT_ENDPOINTS else ["_job_updated_at"]+ # streams cursor on the event's own recorded time, and the+ # conversations report on the conversation's creation timestamp.+ expected = {+ "conversations": ["created_at"],+ "conversation_timestamps": ["timestamp"],+ "contact_timestamps": ["timestamp"],+ }.get(schema.name, ["_job_updated_at"])assert [f["field"] for f in schema.incremental_fields] == expected- def test_report_schemas_start_opt_in(self):+ def test_event_grain_report_schemas_start_opt_in(self):schemas = self.source.get_schemas(self.config, self.team_id)# Event-grain report tables are high-volume, so enabling them must be- # an explicit choice; job-export streams keep syncing by default.+ # an explicit choice; the conversations report and job-export streams+ # keep syncing by default.for schema in schemas:- assert schema.should_sync_default is (schema.name not in REPORT_ENDPOINTS)+ assert schema.should_sync_default is (schema.name not in {"conversation_timestamps", "contact_timestamps"})++ def test_conversations_schema_defaults_to_a_restatement_lookback(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ # Conversation-report rows restate in place, so only that schema+ # re-reads a trailing window on incremental runs.+ lookbacks = {schema.name: schema.default_incremental_lookback_seconds for schema in schemas}+ assert lookbacks.pop("conversations") == REPORT_INCREMENTAL_LOOKBACK_SECONDS+ assert all(seconds is None for seconds in lookbacks.values())def test_get_schemas_filtered_by_names(self):schemas = self.source.get_schemas(self.config, self.team_id, names=["customers"])