: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 4 missing tables to the Gladly source (#117494)
Tom Owers24268b1de065
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 30bb3521adce..943e6711fec6 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@@ -5300,10 +5300,10 @@ Diffed against: <https://developer.gladly.com/rest/>- [x] `/api/v1/teams` — lookup resolving the team IDs carried on agents and conversations (high). Added as `teams` (full refresh).- [x] `/api/v1/inboxes` — lookup resolving the inbox IDs carried on conversation items (high). Added as `inboxes` (full refresh).- [x] `/api/v1/reports/work-session-events` — agent work-session and status history — the vendor's own agent-productivity metric (high). Added as `work_session_events` via the equivalent `WorkSessionEventsReportV4` metric set of `POST /api/v1/reports`.-- [ ] `/api/v1/events` — org-wide event stream, the closest thing Gladly has to an activity log (medium)-- [ ] `/api/v1/customers/{customerId}/tasks` — customer tasks with assignment and completion state, a distinct work object from conversations (medium)-- [ ] `/api/v1/answers` — knowledge-base answer catalog, needed to analyze self-service deflection (medium)-- [ ] `/api/v1/conversation-items/{itemId}/voice-transcript` — voice transcripts for call-content analysis; the export ships item metadata only (medium)+- [x] `/api/v1/events` — org-wide event stream, the closest thing Gladly has to an activity log (medium). Added as `events` (incremental merge on `timestamp`, all eight entity types). Gladly serves only the last 24 hours, so history builds up through daily or more frequent syncs.+- [x] `/api/v1/customers/{customerId}/tasks` — customer tasks with assignment and completion state, a distinct work object from conversations (medium). Covered by `tasks` (Task Export report via `POST /api/v1/reports`, one row per task with assignment and closure columns). The per-customer endpoint itself is skipped: it is unpaginated, returns at most 2000 tasks, and would need one request per customer.+- [x] `/api/v1/answers` — knowledge-base answer catalog, needed to analyze self-service deflection (medium). Added as `answers` (full refresh).+- [x] `/api/v1/conversation-items/{itemId}/voice-transcript` — voice transcripts for call-content analysis; the export ships item metadata only (medium). Added as `voice_transcripts` (fan-out over the phone call and voicemail items of each export job, incremental on the job watermark).- [ ] `/api/v1/audiences` — lookup resolving audience IDs on answers (low)- [ ] `/api/v1/tasks/{taskId}/comments` — task discussion thread (low)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 98867f9e2927..2bc2d056b59f 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@@ -222,4 +222,65 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"disabled": "Whether the inbox is disabled.",},},+ "answers": {+ "description": "A knowledge base answer in Gladly, across every content type and language.",+ "docs_url": "https://developer.gladly.com/rest/#tag/Answer-Management",+ "columns": {+ "id": "Unique identifier for the answer.",+ "name": "Customer-facing name of the answer.",+ "description": "Description of the answer, shown in the UI for some content types.",+ "audienceIds": "Identifiers of the audiences the answer is for.",+ "availableContents": "Content variations authored for the answer, keyed by language.",+ "createdAt": "Time at which the answer was added.",+ "updatedAt": "Time at which the answer was last modified.",+ },+ },+ "events": {+ "description": "An event recorded in Gladly for an agent, contact, conversation, customer, payment request, or task.",+ "docs_url": "https://developer.gladly.com/rest/#tag/Events",+ "columns": {+ "id": "Unique identifier for the event.",+ "type": "Type of the event, e.g. AGENT_STATUS/LOGGED_IN or CONVERSATION/CLOSED.",+ "timestamp": "Time at which Gladly recorded the event (incremental cursor).",+ "initiator": "Type and identifier of the entity that triggered the event.",+ "content": "Event details, such as the agent, conversation, or task the event is about.",+ },+ },+ "tasks": {+ "description": "A customer task in Gladly, one row per task from the Task Export report.",+ "docs_url": "https://help.gladly.com/docs/task-export",+ "columns": {+ "task_id": "Unique identifier for the task.",+ "created_at": "Time at which the task was created (incremental cursor).",+ "customer_id": "Identifier of the customer the task is for.",+ "task_link": "Direct link to the task in Gladly.",+ "status": "Status of the task, either Open or Closed.",+ "first_closed_at": "Time at which the task was first closed.",+ "last_closed_at": "Time at which the task was last closed.",+ "first_assigned_to_agent_at": "Time at which the task was first assigned to an agent.",+ "inbox_id_current": "Identifier of the inbox the task is assigned to now.",+ "assigned_agent_id_current": "Identifier of the agent the task is assigned to now.",+ "due_date_current": "Current due date of the task.",+ "times_closed": "Number of times the task was closed.",+ "times_reopened": "Number of times the task was reopened.",+ "count_of_comments": "Number of comments on the task.",+ "task_handle_time": "Seconds agents spent viewing the task panel.",+ },+ },+ "voice_transcripts": {+ "description": "The transcript of a phone call or voicemail in Gladly.",+ "docs_url": "https://developer.gladly.com/rest/#operation/getVoiceTranscript",+ "columns": {+ "conversation_item_id": "Identifier of the phone call or voicemail conversation item.",+ "conversation_id": "Identifier of the conversation the call or voicemail belongs to.",+ "item_type": "Type of the conversation item, PHONE_CALL or VOICEMAIL.",+ "paragraphs": "Transcript paragraphs, each with its text, speaker number, and start and end times.",+ "customerId": "Identifier of the customer the transcript is associated with.",+ "numberOfSpeakers": "Number of speakers in the recording.",+ "language": "Language of the transcript.",+ "createdAt": "Time at which the transcript was created.",+ "updatedAt": "Time at which the transcript was last updated.",+ "_job_updated_at": "updatedAt of the export job that listed the call or voicemail (incremental cursor).",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.pyindex 644aa3e9a2ea..74ce843e884d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py@@ -4,8 +4,7 @@ import csvimport jsonimport timeimport hashlib-import dataclasses-from collections.abc import Buffer, Iterator, Sequence+from collections.abc import Buffer, Callable, Iterator, Sequencefrom datetime import UTC, date, datetime, timedeltafrom typing import Any, Optionalfrom urllib.parse import quote, urlencode@@ -14,6 +13,8 @@ import requestsfrom 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.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -36,6 +37,11 @@ REPORT_ROW_WARNING_THRESHOLD = 90_000# The reports endpoint allows 10 requests per minute per org, so backfill# windows are paced instead of riding the 429 backoff.REPORT_REQUEST_INTERVAL_SECONDS = 6.0+# Gladly rejects an events startAt older than 24 hours. The margin keeps the+# first window inside that limit by the time its request arrives.+EVENTS_RETENTION = timedelta(hours=24) - timedelta(minutes=5)+EVENTS_WINDOW = timedelta(hours=1)+VOICE_ITEM_TYPES = ("PHONE_CALL", "VOICEMAIL")# Gladly serves production on gladly.com and the testing sandbox on gladly.qa. The# config field is typed as a Literal, but nothing validates Literal membership at@@ -109,7 +115,7 @@ class _ResponseByteStream(io.RawIOBase):return take+@frozenclass GladlyResumeConfig:# Jobs are processed oldest-first; persisting the last fully-processed# job's updatedAt lets a retried sync skip straight past it.@@ -117,6 +123,8 @@ class GladlyResumeConfig:# Report streams persist the end date (YYYY-mm-dd) of the last fully-processed# window; a retried sync restarts at that date and merge dedupes the overlap.last_report_window_end: str | None = None+ # The events stream persists the end timestamp of the last fully-processed window.+ last_event_window_end: str | None = Nonedef _get_session(agent_email: str, api_token: str) -> requests.Session:@@ -165,6 +173,16 @@ def _format_timestamp(value: Any) -> str:return str(value)+def _parse_timestamp(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value if value.tzinfo else value.replace(tzinfo=UTC)+ try:+ parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)++def _normalize_report_column(name: str) -> str:"""Turn a report CSV header like "Assigned Agent ID" into a stable warehousecolumn name ("assigned_agent_id"). Output is limited to [a-z0-9_] so the@@ -330,6 +348,17 @@ def get_rows(return response+ if config.event_entities:+ yield from _event_rows(+ fetch=fetch,+ base_url=base_url,+ entities=config.event_entities,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ incremental_last_value=db_incremental_field_last_value if should_use_incremental_field else None,+ )+ return+if config.list_path is not None:body = fetch(f"{base_url}{config.list_path}").json()rows = body if isinstance(body, list) else []@@ -359,20 +388,32 @@ def get_rows(jobs_body = fetch(f"{base_url}/export/jobs?{urlencode({'status': 'COMPLETED'})}").json()jobs = jobs_body if isinstance(jobs_body, list) else []- jobs = [job for job in jobs if job.get("updatedAt")]+ # Jobs sharing the cutoff timestamp are re-yielded rather than skipped, so a+ # late-arriving job with the same updatedAt as the watermark isn't lost.+ # Merge-on-id dedupes the boundary job's re-yielded rows.+ jobs = [+ job+ for job in jobs+ if job.get("updatedAt")+ and (cutoff is None or job["updatedAt"] >= cutoff)+ and filename in (job.get("files") or [])+ ]jobs.sort(key=lambda job: job["updatedAt"])+ if config.voice_transcripts:+ yield from _voice_transcript_rows(+ session=session,+ base_url=base_url,+ jobs=jobs,+ filename=filename,+ fetch=fetch,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ )+ return+for job in jobs:job_updated_at = job["updatedAt"]- # Strict less-than: jobs sharing the cutoff timestamp are re-yielded rather- # than skipped, so a late-arriving job with the same updatedAt as the- # watermark isn't lost. Merge-on-id dedupes the boundary job's re-yielded rows.- if cutoff is not None and job_updated_at < cutoff:- continue-- files = job.get("files") or []- if filename not in files:- continue# id is required per the export contract and is needed for the download# URL — a missing one is a broken API response, so fail loud.@@ -400,6 +441,148 @@ def get_rows(resumable_source_manager.save_state(GladlyResumeConfig(last_job_updated_at=job_updated_at))+def _event_rows(+ fetch: Callable[[str], requests.Response],+ base_url: str,+ entities: Sequence[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GladlyResumeConfig],+ incremental_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ now = datetime.now(UTC)+ earliest = now - EVENTS_RETENTION+ window_start = earliest++ if incremental_last_value is not None:+ watermark = _parse_timestamp(incremental_last_value)+ if watermark is None:+ logger.warning(+ f"Gladly: could not parse events watermark {incremental_last_value!r}; reading the last 24 hours"+ )+ else:+ if watermark < earliest:+ logger.warning(+ f"Gladly: events watermark {watermark.isoformat()} is older than the 24 hours Gladly retains, "+ f"so events between it and {earliest.isoformat()} could not be synced"+ )+ # Events arrive in no documented order and trail live activity by up to+ # 15 seconds, so one window is re-read behind the watermark. Merge on id+ # dedupes the overlap.+ window_start = max(window_start, watermark - EVENTS_WINDOW)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and resume_config.last_event_window_end is not None:+ resume_end = _parse_timestamp(resume_config.last_event_window_end)+ if resume_end is None:+ logger.warning(f"Gladly: ignoring malformed resume state {resume_config.last_event_window_end!r}")+ else:+ window_start = max(window_start, resume_end)++ while window_start < now:+ window_end = min(window_start + EVENTS_WINDOW, now)+ params = [+ ("startAt", _format_timestamp(window_start)),+ ("endAt", _format_timestamp(window_end)),+ *(("entities", entity) for entity in entities),+ ]+ response = fetch(f"{base_url}/events?{urlencode(params)}")+ chunk: list[dict[str, Any]] = []+ for line in response.iter_lines(decode_unicode=True):+ if not line or not line.strip():+ continue+ try:+ row = json.loads(line)+ except json.JSONDecodeError:+ logger.warning(f"Gladly: skipping malformed events line in window {window_start} - {window_end}")+ continue+ chunk.append(row)+ if len(chunk) >= CHUNK_SIZE:+ yield chunk+ chunk = []++ resumable_source_manager.save_state(GladlyResumeConfig(last_event_window_end=_format_timestamp(window_end)))+ if chunk:+ yield chunk+ else:+ resumable_source_manager.safe_point()+ window_start = window_end+++def _voice_transcript_rows(+ session: requests.Session,+ base_url: str,+ jobs: Sequence[dict[str, Any]],+ filename: str,+ fetch: Callable[[str], requests.Response],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GladlyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ @retry(+ retry=retry_if_exception_type((GladlyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+ )+ def fetch_transcript(item_id: str) -> dict[str, Any] | None:+ url = f"{base_url}/conversation-items/{quote(item_id)}/voice-transcript"+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)+ # Gladly answers 404 for a call or voicemail that has no transcript.+ if response.status_code == 404:+ return None+ if response.status_code == 429 or response.status_code >= 500:+ raise GladlyRetryableError(f"Gladly API error (retryable): status={response.status_code}, url={url}")+ if not response.ok:+ logger.error(f"Gladly API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()+ body = response.json()+ return body if isinstance(body, dict) else None++ for job in jobs:+ job_id = job["id"]+ job_updated_at = job["updatedAt"]+ response = fetch(f"{base_url}/export/jobs/{quote(job_id)}/files/{quote(filename)}")+ # One transcript is held back, so the job's cursor can be staged before+ # the last transcript of the job is yielded.+ pending: dict[str, Any] | None = None+ for line in response.iter_lines(decode_unicode=True):+ if not line or not line.strip():+ continue+ try:+ item = json.loads(line)+ except json.JSONDecodeError:+ logger.warning(f"Gladly: skipping malformed JSONL line in job {job_id} {filename}")+ continue+ content = item.get("content") or {}+ if content.get("type") not in VOICE_ITEM_TYPES or not item.get("id"):+ continue++ transcript = fetch_transcript(item["id"])+ if transcript is None:+ if pending is not None:+ yield [pending]+ pending = None+ else:+ resumable_source_manager.safe_point()+ continue++ if pending is not None:+ yield [pending]+ pending = {+ **transcript,+ "conversation_item_id": item["id"],+ "conversation_id": item.get("conversationId"),+ "item_type": content.get("type"),+ "_job_id": job_id,+ "_job_updated_at": job_updated_at,+ }++ resumable_source_manager.save_state(GladlyResumeConfig(last_job_updated_at=job_updated_at))+ if pending is not None:+ yield [pending]+ else:+ resumable_source_manager.safe_point()++def _report_rows(session: requests.Session,base_url: str,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 66562c2cfc37..2e40f2aed54a 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@@ -35,6 +35,17 @@ _REPORT_INCREMENTAL_FIELDS: list[IncrementalField] = [},]+# Events carry the time Gladly recorded them, and the events endpoint filters+# on that same field, so it is the incremental cursor.+_EVENT_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+]+# The work session report windows a row on its contact's end time, or on the# creation time while the contact is open. Ending only moves a row to a later# window, so the creation time is a safe incremental cursor.@@ -71,6 +82,11 @@ class GladlyEndpointConfig:filename: str | None = None# Path of a non-paginated JSON array endpoint for lookup streams.list_path: str | None = None+ # Entity types requested from GET /api/v1/events for the event stream.+ event_entities: tuple[str, ...] = ()+ # Reads the export file for its phone call and voicemail items, then fetches+ # the voice transcript of each one instead of yielding the items.+ voice_transcripts: bool = False# Metric set generated via POST /api/v1/reports for report streams.report_metric_set: str | None = None# Some metric sets only accept a time range (startAtTime/endAtTime), not a@@ -117,6 +133,16 @@ GLADLY_ENDPOINTS: dict[str, GladlyEndpointConfig] = {name="agents",filename="agents.jsonl",),+ # Transcripts exist only per conversation item, so this stream walks the+ # conversation items of each export job and makes one request per call or+ # voicemail. That is costly for busy voice teams, so it starts opt-in.+ "voice_transcripts": GladlyEndpointConfig(+ name="voice_transcripts",+ filename="conversation_items.jsonl",+ voice_transcripts=True,+ primary_key="conversation_item_id",+ should_sync_default=False,+ ),"topics": GladlyEndpointConfig(name="topics",filename="topics.jsonl",@@ -136,6 +162,19 @@ GLADLY_ENDPOINTS: dict[str, GladlyEndpointConfig] = {incremental_fields=list(_REPORT_INCREMENTAL_FIELDS),default_incremental_lookback_seconds=REPORT_INCREMENTAL_LOOKBACK_SECONDS,),+ # The REST API only lists tasks per customer (capped at 2000, one request+ # per customer), so task rows come from the Task Export report: one row per+ # task, anchored on its creation date, with assignment and closure columns+ # that restate as the task changes. Sized like the conversations report.+ "tasks": GladlyEndpointConfig(+ name="tasks",+ report_metric_set="TaskExportReport",+ primary_key="task_id",+ report_window_days=7,+ report_backfill_days=730,+ incremental_fields=list(_REPORT_INCREMENTAL_FIELDS),+ default_incremental_lookback_seconds=REPORT_INCREMENTAL_LOOKBACK_SECONDS,+ ),# 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)@@ -189,6 +228,30 @@ GLADLY_ENDPOINTS: dict[str, GladlyEndpointConfig] = {list_path="/inboxes",incremental_fields=[],),+ # Every answer in the org in one unpaginated response, with no change filter.+ "answers": GladlyEndpointConfig(+ name="answers",+ list_path="/answers",+ incremental_fields=[],+ ),+ # Gladly serves events from the last 24 hours only, so history builds up+ # through incremental syncs that run more often than once a day. Windows are+ # re-read with an overlap, so the stream is merge-only.+ "events": GladlyEndpointConfig(+ name="events",+ event_entities=(+ "AGENT_AVAILABILITY",+ "AGENT_STATUS",+ "CONTACT",+ "CONVERSATION",+ "CUSTOMER",+ "CUSTOMER_PROFILE",+ "PAYMENT_REQUEST",+ "TASK",+ ),+ should_sync_default=False,+ incremental_fields=list(_EVENT_INCREMENTAL_FIELDS),+ ),}ENDPOINTS = tuple(GLADLY_ENDPOINTS.keys())@@ -198,6 +261,8 @@ ENDPOINTS = tuple(GLADLY_ENDPOINTS.keys())# 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)+EVENT_ENDPOINTS = tuple(name for name, config in GLADLY_ENDPOINTS.items() if config.event_entities)+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in GLADLY_ENDPOINTS.items() if config.incremental_fields}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 02ecedbfb45b..bad7183b4c71 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@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.gla)from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.settings import (ENDPOINTS,+ EVENT_ENDPOINTS,INCREMENTAL_FIELDS,INCREMENTAL_LOOKBACK_SECONDS,REPORT_ENDPOINTS,@@ -118,7 +119,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 conversations table is built from Gladly's Conversation Export report instead, so it is not limited to the 14-day export window. The conversation timestamps, contact timestamps, and work session events tables also come from Gladly's reports and reach back 90 days on their first sync. The teams and inboxes tables are read in full on every 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 voice transcripts table reads the calls and voicemails in those same exports and makes one request per call. The conversations and tasks tables are built from Gladly's Conversation Export and Task Export reports instead, so they are not limited to the 14-day export window. The conversation timestamps, contact timestamps, and work session events tables also come from Gladly's reports and reach back 90 days on their first sync. The teams, inboxes, and answers tables are read in full on every sync. Gladly keeps events for 24 hours only, so the events table needs to sync more often than once a day, for example every 12 hours, to keep a full history.""",iconPath="/static/services/gladly.png",docsUrl="https://posthog.com/docs/cdp/sources/gladly",releaseStatus=ReleaseStatus.ALPHA,@@ -172,14 +173,15 @@ Your organization is the part of your Gladly URL before `.gladly.com`. For `myorforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # 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).+ # Report and event windows are re-read on resume and behind the+ # watermark, so appending would duplicate rows (merge_only). The+ # event-grain tables are high-volume, so they start opt-in+ # (should_sync_default).schemas = build_endpoint_schemas(ENDPOINTS,INCREMENTAL_FIELDS,names,- merge_only=REPORT_ENDPOINTS,+ merge_only=(*REPORT_ENDPOINTS, *EVENT_ENDPOINTS),should_sync_default=SHOULD_SYNC_DEFAULT,)# Conversation and work-session report rows restate in place as recordsdiff --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 c37648e6dcd7..38f4ef4c828f 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@@ -251,6 +251,166 @@ class TestGetRows:assert result.saved_states == []+class TestGetEventRows:+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)+ def test_walks_hourly_windows_from_one_window_behind_the_watermark(self) -> None:+ result = _driver().run(+ "events",+ [+ _jsonl_response(+ [{"id": "e1", "type": "AGENT_STATUS/LOGGED_IN", "timestamp": "2024-03-15T07:45:00.000Z"}],+ junk_lines=["{not json"],+ ),+ _jsonl_response([]),+ _jsonl_response([{"id": "e2", "type": "TASK/CREATED", "timestamp": "2024-03-15T09:40:00.000Z"}]),+ ],+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-03-15T08:30:00.000Z",+ )++ assert result.raised is None+ assert result.paths == ["/api/v1/events"] * 3+ assert [(query["startAt"], query["endAt"]) for query in result.queries] == [+ (("2024-03-15T07:30:00.000Z",), ("2024-03-15T08:30:00.000Z",)),+ (("2024-03-15T08:30:00.000Z",), ("2024-03-15T09:30:00.000Z",)),+ (("2024-03-15T09:30:00.000Z",), ("2024-03-15T10:00:00.000Z",)),+ ]+ assert set(result.queries[0]["entities"]) == set(GLADLY_ENDPOINTS["events"].event_entities)+ assert [row["id"] for row in result.rows] == ["e1", "e2"]+ # The empty window still advances the cursor, so a resumed run skips it.+ assert [state.last_event_window_end for state in result.committed_states] == [+ "2024-03-15T08:30:00.000Z",+ "2024-03-15T09:30:00.000Z",+ "2024-03-15T10:00:00.000Z",+ ]++ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)+ @pytest.mark.parametrize(+ "watermark, resume_state, expected_first_start, expected_windows, expect_warning",+ [+ (None, None, "2024-03-14T10:05:00.000Z", 24, False),+ ("2024-03-10T00:00:00.000Z", None, "2024-03-14T10:05:00.000Z", 24, True),+ ("not a timestamp", None, "2024-03-14T10:05:00.000Z", 24, True),+ (+ "2024-03-15T06:00:00.000Z",+ GladlyResumeConfig(last_event_window_end="2024-03-15T08:00:00.000Z"),+ "2024-03-15T08:00:00.000Z",+ 2,+ False,+ ),+ (+ "2024-03-15T10:00:00.000Z",+ GladlyResumeConfig(last_event_window_end="2024-03-15T10:00:00.000Z"),+ None,+ 0,+ False,+ ),+ ],+ ids=[+ "first_sync_reads_the_retained_24_hours",+ "stale_watermark_is_clamped_to_the_retention_limit",+ "unparseable_watermark_reads_the_retained_24_hours",+ "resume_state_supersedes_an_older_watermark",+ "caught_up_run_makes_no_request",+ ],+ )+ def test_start_of_the_first_window(+ self, watermark, resume_state, expected_first_start, expected_windows, expect_warning+ ) -> None:+ logger = mock.MagicMock()+ result = _driver().run(+ "events",+ always(_jsonl_response([])),+ resume_state=resume_state,+ should_use_incremental_field=watermark is not None,+ db_incremental_field_last_value=watermark,+ logger=logger,+ )++ assert result.raised is None+ assert len(result.requests) == expected_windows+ if expected_first_start is not None:+ assert result.params("startAt")[0] == expected_first_start+ assert result.params("endAt")[-1] == "2024-03-15T10:00:00.000Z"+ assert logger.warning.called is expect_warning+++class TestGetVoiceTranscriptRows:+ def test_fetches_transcripts_for_voice_items_only_and_skips_missing_ones(self) -> None:+ def item(item_id: str, item_type: str) -> dict[str, Any]:+ return {"id": item_id, "conversationId": f"conv-{item_id}", "content": {"type": item_type}}++ files = ["conversation_items.jsonl"]+ result = _driver().run(+ "voice_transcripts",+ [+ ScriptedResponse(+ json=[+ _job("j2", "2024-01-02T00:00:00.000Z", files=files),+ _job("j1", "2024-01-01T00:00:00.000Z", files=files),+ _job("j0", "2024-01-01T12:00:00.000Z", files=["customers.jsonl"]),+ ]+ ),+ _jsonl_response(+ [item("chat-1", "CHAT_MESSAGE"), item("call-1", "PHONE_CALL"), item("vm-1", "VOICEMAIL")],+ junk_lines=["{not json"],+ ),+ ScriptedResponse(json={"paragraphs": [{"transcript": "Hello", "speaker": 0}], "language": "en"}),+ ScriptedResponse(status=404),+ _jsonl_response([item("vm-2", "VOICEMAIL")]),+ ScriptedResponse(status=404),+ ],+ )++ assert result.raised is None+ assert result.paths == [+ "/api/v1/export/jobs",+ "/api/v1/export/jobs/j1/files/conversation_items.jsonl",+ "/api/v1/conversation-items/call-1/voice-transcript",+ "/api/v1/conversation-items/vm-1/voice-transcript",+ "/api/v1/export/jobs/j2/files/conversation_items.jsonl",+ "/api/v1/conversation-items/vm-2/voice-transcript",+ ]+ assert result.rows == [+ {+ "paragraphs": [{"transcript": "Hello", "speaker": 0}],+ "language": "en",+ "conversation_item_id": "call-1",+ "conversation_id": "conv-call-1",+ "item_type": "PHONE_CALL",+ "_job_id": "j1",+ "_job_updated_at": "2024-01-01T00:00:00.000Z",+ }+ ]+ # A job whose voice items have no transcript still advances the cursor.+ assert [state.last_job_updated_at for state in result.committed_states] == [+ "2024-01-01T00:00:00.000Z",+ "2024-01-02T00:00:00.000Z",+ ]++ @mock.patch(f"{_MODULE}.MAX_RETRY_ATTEMPTS", 1)+ @pytest.mark.parametrize(+ "status_code, expected_error",+ [(429, GladlyRetryableError), (500, GladlyRetryableError), (403, requests.HTTPError)],+ )+ def test_transcript_errors_other_than_not_found_fail_the_job(self, status_code, expected_error) -> None:+ answers = {+ "/api/v1/export/jobs": ScriptedResponse(+ json=[_job("j1", "2024-01-01T00:00:00.000Z", files=["conversation_items.jsonl"])]+ ),+ "/api/v1/export/jobs/j1/files/conversation_items.jsonl": _jsonl_response(+ [{"id": "call-1", "content": {"type": "PHONE_CALL"}}]+ ),+ }+ # The transport retries a 429 and a 5xx, so the transcript answers every attempt.+ result = _driver().run(+ "voice_transcripts", lambda request: answers.get(request.path, ScriptedResponse(status=status_code))+ )++ assert isinstance(result.raised, expected_error)+ assert result.saved_states == []++class TestGetReportRows:@time_machine.travel("2024-03-15T10:00:00Z", tick=False)def test_work_session_report_uses_a_time_range_and_keys_rows_on_contact_and_agent(self) -> None: