: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 timestamps report tables (#80027)
jake sciottod00105443e1b
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 82a340b1c340..68d85a86a2ad 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@@ -64,4 +64,77 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"_job_updated_at": "updatedAt of the export job that produced this row (incremental cursor).",},},+ # One row per conversation event from the Conversation Timestamps report+ # metric set; column names are the report's CSV headers, snake_cased.+ "conversation_timestamps": {+ "description": "A conversation lifecycle event (created, closed, reopened, topic change, assignee change, note, merge). One row per event, from Gladly's Conversation Timestamps report.",+ "docs_url": "https://help.gladly.com/docs/conversation-timestamps",+ "columns": {+ "timestamp": "Time at which the event was recorded (incremental cursor).",+ "event_type": "Kind of event, e.g. CONVERSATION/CREATED, CONVERSATION/CLOSED, CONVERSATION/REOPENED, CONVERSATION_ASSIGNEE/UPDATED.",+ "conversation_id": "Identifier of the conversation the event belongs to.",+ "customer_id": "Identifier of the customer the conversation is with.",+ "initiator_type": "Who performed the action: CUSTOMER, AGENT, AUTOMATION, INTERNAL, EXTERNAL, APPLICATION, or SYSTEM.",+ "initiator_id": "Identifier of the acting agent or rule, where applicable.",+ "initiator_agent_name": "Name of the acting agent, if the initiator is an agent.",+ "assigned_inbox_id": "Identifier of the inbox assigned before the event.",+ "assigned_inbox_name": "Name of the inbox assigned before the event.",+ "assigned_agent_id": "Identifier of the agent assigned before the event.",+ "assigned_agent_name": "Name of the agent assigned before the event.",+ "topic_id": "Identifier of the topic added or removed, for topic events.",+ "topic_name": "Current name of the topic added or removed.",+ "newly_assigned_inbox_id": "Identifier of the inbox assigned after the event.",+ "newly_assigned_inbox_name": "Name of the inbox assigned after the event.",+ "newly_assigned_agent_id": "Identifier of the agent assigned after the event.",+ "newly_assigned_agent_name": "Name of the agent assigned after the event.",+ "assignment_update_reason": "Why the assigned agent changed, for assignment events.",+ "merged_customer_id": "Identifier of the customer profile merged into another profile, for merge events.",+ "merged_conversation_id": "Identifier of the conversation from the merged profile, for merge events.",+ "_row_id": "Deterministic hash of the row, injected as the primary key (the report has no event id).",+ },+ },+ # One row per contact event from the Contact Timestamps report metric set;+ # column names are the report's CSV headers, snake_cased.+ "contact_timestamps": {+ "description": "A contact lifecycle event (started, offered, transferred, held, fulfilled, ended) across channels. One row per event, from Gladly's Contact Timestamps report.",+ "docs_url": "https://help.gladly.com/docs/contact-timestamps",+ "columns": {+ "timestamp": "Time at which the event was recorded (incremental cursor).",+ "event_type": "Kind of event, e.g. CONTACT/STARTED, CONTACT/OFFERED, CONTACT/TRANSFERRED, CONTACT/FULFILLED, CONTACT/ENDED.",+ "contact_id": "Identifier of the contact the event belongs to.",+ "conversation_id": "Identifier of the conversation the contact belongs to.",+ "customer_id": "Identifier of the customer the contact is with.",+ "channel": "Channel of the contact, e.g. CHAT, EMAIL, PHONE_CALL, SMS, VOICEMAIL, WHATSAPP.",+ "initiator_type": "Who performed the action: CUSTOMER, AGENT, AUTOMATION, INTERNAL, EXTERNAL, APPLICATION, or SYSTEM.",+ "initiator_id": "Identifier of the acting agent or rule, where applicable.",+ "initiator_agent_name": "Name of the acting agent, if the initiator is an agent.",+ "assigned_inbox_id": "Identifier of the inbox the contact was assigned to before the event.",+ "assigned_inbox_name": "Name of the inbox the contact was assigned to before the event.",+ "assigned_agent_id": "Identifier of the agent assigned to the contact before the event.",+ "assigned_agent_name": "Name of the agent assigned to the contact before the event.",+ "target_agent_id": "Identifier of the agent targeted by the event action, e.g. the agent receiving an offer.",+ "target_agent_name": "Name of the agent targeted by the event action.",+ "transferred_to_agent_id": "Identifier of the agent receiving a transfer.",+ "transferred_to_agent_name": "Name of the agent receiving a transfer.",+ "transferred_to_inbox_id": "Identifier of the inbox receiving a transfer.",+ "transferred_to_inbox_name": "Name of the inbox receiving a transfer.",+ "transferred_type": "Type of transfer: COLD or WARM.",+ "transferred_reason": "Why the contact was transferred: AUTOMATION, MANUAL, MERGE, or UNKNOWN.",+ "due_at": "The contact's target due date.",+ "fulfilled_type": "How the contact was fulfilled: RESPONDED or CANCELED.",+ "ended_reason": "Why the contact ended, e.g. AGENT_ENDED, CONVERSATION_CLOSED, CUSTOMER_NO_REPLY, TIME_EXPIRED.",+ "ended_status": "Status of the contact when it ended: ABANDONED, ANSWERED, UNANSWERED, or UNKNOWN.",+ "hold_reason": "Why the contact was put on hold: COLD_TRANSFER, CONFERENCE, MANUAL, or WARM_TRANSFER.",+ "rejected_reason": "Why an offer was rejected: DECLINED, MISSED, TRANSFER_CANCELED, or DEVICE_ERROR.",+ "message_id": "Identifier of the message sent or received, for message events.",+ "payment_currency": "Currency of the payment request, for payment events.",+ "payment_amount": "Amount of the payment request, for payment events.",+ "payment_status": "Status of the payment request, e.g. REQUESTING, SUBMITTED, COMPLETED, DECLINED.",+ "match_reasons": "How the contact was matched for routing; options vary by configuration.",+ "fulfilled_by_contact_id": "Identifier of the contact that fulfilled this one, if any.",+ "entry_point": "Destination address the customer contacted (phone number, email address, chat identifier) for inbound contacts.",+ "final_ivr_selection": "Last IVR choice made before queueing, for phone contacts.",+ "_row_id": "Deterministic hash of the row, injected as the primary key (the report has no event id).",+ },+ },}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 cb0812d0e79d..012a2038e909 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@@ -1,9 +1,13 @@+import ioimport re+import csvimport json+import time+import hashlibimport dataclassesfrom collections.abc import Iterator-from datetime import UTC, date, datetime-from typing import Any, Optional+from datetime import UTC, date, datetime, timedelta+from typing import IO, Any, Optional, castfrom urllib.parse import quote, urlencodeimport requests@@ -13,13 +17,23 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exfrom 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-from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.settings import GLADLY_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.settings import (+ GLADLY_ENDPOINTS,+ REPORT_ROW_ID_COLUMN,+ GladlyEndpointConfig,+)REQUEST_TIMEOUT_SECONDS = 300# 10 req/s per org; back off on 429.MAX_RETRY_ATTEMPTS = 5# Yield JSONL rows in chunks so big files don't build one giant list.CHUNK_SIZE = 5000+# Gladly caps report CSVs (100k rows for most reports) and truncates silently,+# so a window this full is likely missing rows.+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.0class GladlyRetryableError(Exception):@@ -30,7 +44,10 @@ class GladlyRetryableError(Exception):class GladlyResumeConfig:# Jobs are processed oldest-first; persisting the last fully-processed# job's updatedAt lets a retried sync skip straight past it.- last_job_updated_at: str+ last_job_updated_at: str | None = None+ # 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 = Nonedef _get_session(agent_email: str, api_token: str) -> requests.Session:@@ -72,6 +89,62 @@ def _format_timestamp(value: Any) -> str:return str(value)+def _normalize_report_column(name: str) -> str:+ """Turn a report CSV header like "Assigned Agent ID" into a stable warehouse+ column name ("assigned_agent_id"). Output is limited to [a-z0-9_] so the+ pipeline's own identifier normalization leaves it unchanged, keeping the+ declared primary key and incremental field aligned with the data.+ """+ return re.sub(r"[^a-z0-9]+", "_", name.strip().lower()).strip("_")+++def _report_row_id(row: dict[str, Any]) -> str:+ """Deterministic id for report rows that carry no natural key.++ Timestamps-report rows are immutable events with no event id column, so the+ id is a hash of the whole normalized row: the same row re-read from an+ overlapping window merges onto itself, while rows differing in any field+ stay distinct.+ """+ return hashlib.sha256(json.dumps(row, sort_keys=True, separators=(",", ":")).encode()).hexdigest()+++def _report_start_date(+ today: date,+ incremental_last_value: Any,+ resume_window_end: str | None,+ window_days: int,+ backfill_days: int,+ logger: FilteringBoundLogger,+) -> date:+ start = today - timedelta(days=backfill_days)++ if incremental_last_value is not None:+ try:+ watermark = date.fromisoformat(_format_timestamp(incremental_last_value)[:10])+ except ValueError:+ logger.warning(+ f"Gladly: could not parse incremental watermark {incremental_last_value!r}; "+ f"re-reading the full report history"+ )+ else:+ # Rows inside a window arrive in no guaranteed order and report data+ # trails live activity, so a crashed sync can leave the watermark past+ # rows it never loaded. Starting one full window behind covers them;+ # merge dedupes the overlap.+ start = max(start, watermark - timedelta(days=window_days))++ if resume_window_end is not None:+ try:+ # The saved window is re-read rather than skipped: its endAt day was+ # still accumulating rows when the window was first processed.+ start = max(start, date.fromisoformat(resume_window_end))+ except ValueError:+ logger.warning(f"Gladly: ignoring malformed resume state {resume_window_end!r}")++ return min(start, today)++def validate_credentials(organization: str, agent_email: str, api_token: str) -> tuple[bool, str | None]:"""Confirm the credentials are valid with a cheap agents probe.@@ -124,6 +197,23 @@ def get_rows(session = _get_session(agent_email, api_token)base_url = _base_url(organization)+ if config.report_metric_set is not None:+ yield from _report_rows(+ session=session,+ base_url=base_url,+ config=config,+ metric_set=config.report_metric_set,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ return++ filename = config.filename+ if filename is None:+ raise ValueError(f"Gladly endpoint {endpoint} declares neither an export filename nor a report metric set")+@retry(retry=retry_if_exception_type((GladlyRetryableError, requests.ReadTimeout, requests.ConnectionError)),stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),@@ -150,7 +240,11 @@ def get_rows(if should_use_incremental_field and db_incremental_field_last_value is not None:cutoff = _format_timestamp(db_incremental_field_last_value)resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- if resume_config is not None and (cutoff is None or resume_config.last_job_updated_at > cutoff):+ if (+ resume_config is not None+ and resume_config.last_job_updated_at is not None+ and (cutoff is None or resume_config.last_job_updated_at > cutoff)+ ):cutoff = resume_config.last_job_updated_atlogger.debug(f"Gladly: resuming {endpoint} after job updatedAt {cutoff}")@@ -168,14 +262,14 @@ def get_rows(continuefiles = job.get("files") or []- if config.filename not in files:+ 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.job_id = job["id"]- response = fetch(f"{base_url}/export/jobs/{quote(job_id)}/files/{quote(config.filename)}")+ response = fetch(f"{base_url}/export/jobs/{quote(job_id)}/files/{quote(filename)}")chunk: list[dict[str, Any]] = []for line in response.iter_lines(decode_unicode=True):if not line or not line.strip():@@ -183,7 +277,7 @@ def get_rows(try:row = json.loads(line)except json.JSONDecodeError:- logger.warning(f"Gladly: skipping malformed JSONL line in job {job_id} {config.filename}")+ logger.warning(f"Gladly: skipping malformed JSONL line in job {job_id} {filename}")continuechunk.append({**row, "_job_id": job_id, "_job_updated_at": job_updated_at})if len(chunk) >= CHUNK_SIZE:@@ -197,6 +291,108 @@ def get_rows(resumable_source_manager.save_state(GladlyResumeConfig(last_job_updated_at=job_updated_at))+def _report_rows(+ session: requests.Session,+ base_url: str,+ config: GladlyEndpointConfig,+ metric_set: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GladlyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> 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 generate_report(payload: dict[str, str]) -> requests.Response:+ # stream=True so the CSV body is parsed off the wire instead of loaded whole.+ response = session.post(f"{base_url}/reports", json=payload, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)++ if response.status_code == 429 or response.status_code >= 500:+ raise GladlyRetryableError(+ f"Gladly API error (retryable): status={response.status_code}, metricSet={metric_set}"+ )++ if not response.ok:+ logger.error(+ f"Gladly API error: status={response.status_code}, body={response.text[:500]}, metricSet={metric_set}"+ )+ response.raise_for_status()++ return response++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ today = datetime.now(UTC).date()+ window_start = _report_start_date(+ today=today,+ incremental_last_value=db_incremental_field_last_value if should_use_incremental_field else None,+ resume_window_end=resume_config.last_report_window_end if resume_config is not None else None,+ window_days=config.report_window_days,+ backfill_days=config.report_backfill_days,+ logger=logger,+ )+ inject_row_id = config.primary_key == REPORT_ROW_ID_COLUMN++ is_first_request = True+ while window_start <= today:+ window_end = min(window_start + timedelta(days=config.report_window_days - 1), today)+ if not is_first_request:+ time.sleep(REPORT_REQUEST_INTERVAL_SECONDS)+ is_first_request = False+ response = generate_report(+ {+ "metricSet": metric_set,+ # Explicit UTC keeps window boundaries and rendered timestamps+ # stable even if the organization's default timezone changes.+ "timezone": "UTC",+ # endAt is inclusive: the report covers through the end of that day.+ "startAt": window_start.isoformat(),+ "endAt": window_end.isoformat(),+ }+ )++ response.raw.decode_content = True+ # Wrap the raw stream rather than iterating lines: CSV values can contain+ # newlines inside quoted fields, which line-splitting would tear apart.+ text_stream = io.TextIOWrapper(cast(IO[bytes], response.raw), encoding="utf-8-sig", newline="")+ reader = csv.DictReader(text_stream)+ columns = {name: _normalize_report_column(name) for name in reader.fieldnames or []}++ row_count = 0+ chunk: list[dict[str, Any]] = []+ for csv_row in reader:+ row: dict[str, Any] = {}+ for raw_name, column in columns.items():+ if not column:+ continue+ value = csv_row.get(raw_name)+ # Blank CSV cells become NULL (e.g. topic columns of non-topic events).+ row[column] = None if value == "" else value+ if inject_row_id:+ row[REPORT_ROW_ID_COLUMN] = _report_row_id(row)+ chunk.append(row)+ row_count += 1+ if len(chunk) >= CHUNK_SIZE:+ yield chunk+ chunk = []+ if chunk:+ yield chunk++ if row_count >= REPORT_ROW_WARNING_THRESHOLD:+ logger.warning(+ f"Gladly: {config.name} report window {window_start} - {window_end} returned {row_count} rows "+ f"and may have been truncated at Gladly's report row cap"+ )++ # Save state AFTER the window is fully yielded so a crash re-reads this+ # window (merge dedupes on primary key) rather than skipping it.+ resumable_source_manager.save_state(GladlyResumeConfig(last_report_window_end=window_end.isoformat()))+ window_start = window_end + timedelta(days=1)++def gladly_source(organization: str,agent_email: 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 513c9107aee4..9d51c9240faf 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@@ -13,12 +13,42 @@ _JOB_INCREMENTAL_FIELDS: list[IncrementalField] = [},]+# Timestamps-report rows carry the event's own recorded time (the report's date+# filter is anchored on it), so that column is the incremental cursor.+_TIMESTAMPS_REPORT_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "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"+@dataclassclass GladlyEndpointConfig:name: str- # Filename inside each export job (e.g. customers.jsonl).- filename: str+ # Filename inside each export job (e.g. customers.jsonl) for job-export streams.+ filename: str | None = None+ # Metric set generated via POST /api/v1/reports for report streams.+ report_metric_set: str | None = None+ # Report streams request one date window at a time, oldest first. Event-grain+ # reports default to 1-day windows to stay clear of Gladly's 100k-row report+ # cap, which truncates silently.+ report_window_days: int = 1+ # How far back the first sync of a report stream reaches. Reports can be+ # generated for any past window, so this is a cost bound (the reports+ # endpoint allows 10 requests per minute per org), not a vendor limit.+ report_backfill_days: int = 90+ # Default-off in the schema picker; used for high-volume event-grain tables+ # so enabling them is an explicit choice.+ should_sync_default: bool = Trueprimary_key: str = "id"incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_JOB_INCREMENTAL_FIELDS))@@ -45,10 +75,36 @@ GLADLY_ENDPOINTS: dict[str, GladlyEndpointConfig] = {name="topics",filename="topics.jsonl",),+ # 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)+ # with no natural row id, so the transport injects a deterministic+ # full-row hash as the primary key. Column names are the report's CSV+ # headers, snake_cased.+ "conversation_timestamps": GladlyEndpointConfig(+ name="conversation_timestamps",+ report_metric_set="ConversationTimestampsReport",+ primary_key=REPORT_ROW_ID_COLUMN,+ should_sync_default=False,+ incremental_fields=list(_TIMESTAMPS_REPORT_INCREMENTAL_FIELDS),+ ),+ "contact_timestamps": GladlyEndpointConfig(+ name="contact_timestamps",+ report_metric_set="ContactTimestampsReport",+ primary_key=REPORT_ROW_ID_COLUMN,+ should_sync_default=False,+ incremental_fields=list(_TIMESTAMPS_REPORT_INCREMENTAL_FIELDS),+ ),}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_ENDPOINTS = tuple(name for name, config in GLADLY_ENDPOINTS.items() if config.report_metric_set)+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in GLADLY_ENDPOINTS.items() if config.incremental_fields}++SHOULD_SYNC_DEFAULT: dict[str, bool] = {name: config.should_sync_default for name, config in GLADLY_ENDPOINTS.items()}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 328a642eadf1..2359a9fb0081 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,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.glafrom products.warehouse_sources.backend.temporal.data_imports.sources.gladly.settings import (ENDPOINTS,INCREMENTAL_FIELDS,+ REPORT_ENDPOINTS,+ SHOULD_SYNC_DEFAULT,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -72,7 +74,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). 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.""",+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). 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.""",iconPath="/static/services/gladly.png",docsUrl="https://posthog.com/docs/cdp/sources/gladly",releaseStatus=ReleaseStatus.ALPHA,@@ -116,7 +118,16 @@ Your organization is the part of your Gladly URL before `.gladly.com`. For `myorforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ # 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(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ merge_only=REPORT_ENDPOINTS,+ should_sync_default=SHOULD_SYNC_DEFAULT,+ )def 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 74deb098e404..19b11f113471 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@@ -1,7 +1,10 @@+import ioimport json+from datetime import date, timedeltafrom typing import Anyimport pytest+from freezegun import freeze_timefrom unittest import mockimport requests@@ -9,8 +12,10 @@ import requestsfrom products.warehouse_sources.backend.temporal.data_imports.sources.gladly.gladly import (CHUNK_SIZE,GladlyResumeConfig,+ GladlyRetryableError,_base_url,_clean_organization,+ _normalize_report_column,get_rows,gladly_source,validate_credentials,@@ -48,6 +53,27 @@ def _job(job_id: str, updated_at: str, files: list[str] | None = None) -> dict[sreturn {"id": job_id, "updatedAt": updated_at, "files": files or ["customers.jsonl", "agents.jsonl"]}+class _RawBytes(io.BytesIO):+ """BytesIO subclass, so the transport can set decode_content on it."""+++def _csv_response(text: str) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.raw = _RawBytes(text.encode())+ resp.status_code = 200+ resp.ok = True+ return resp+++def _error_response(status_code: int) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status_code+ resp.ok = False+ resp.text = "error body"+ resp.raise_for_status.side_effect = requests.HTTPError(f"{status_code} Client Error", response=resp)+ return resp++class TestCleanOrganization:@pytest.mark.parametrize("value, expected",@@ -272,6 +298,218 @@ class TestGetRows:assert [len(batch) for batch in batches] == [CHUNK_SIZE, 1]+class TestNormalizeReportColumn:+ @pytest.mark.parametrize(+ "header, expected",+ [+ ("Timestamp", "timestamp"),+ ("Event Type", "event_type"),+ ("Newly Assigned Agent ID", "newly_assigned_agent_id"),+ ("Transferred To Inbox Name", "transferred_to_inbox_name"),+ ("Final IVR Selection", "final_ivr_selection"),+ (" Fulfilled by Contact ID ", "fulfilled_by_contact_id"),+ ],+ )+ def test_headers_become_stable_snake_case_columns(self, header, expected):+ assert _normalize_report_column(header) == expected+++class TestGetReportRows:+ @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_incremental_windows_start_one_window_behind_watermark_and_rows_are_normalized(self, mock_session):+ header = "Timestamp,Event Type,Conversation ID,Customer ID,Topic Name\n"+ mock_session.return_value.post.side_effect = [+ _csv_response(header + "2024-03-13T09:00:00.000Z,CONVERSATION/CREATED,conv-1,cust-1,\n"),+ _csv_response(header),+ _csv_response(header + '2024-03-15T08:00:00.000Z,CONVERSATION/CLOSED,conv-1,"cust, 1",Returns\n'),+ ]++ manager = _make_manager()+ batches = list(+ get_rows(+ "myorg",+ "[email protected]",+ "token",+ "conversation_timestamps",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-03-14T05:00:00.000Z",+ )+ )++ # One report request per day, oldest first, starting one full window+ # behind the watermark date.+ calls = mock_session.return_value.post.call_args_list+ assert all(call.args[0] == "https://myorg.gladly.com/api/v1/reports" for call in calls)+ assert [call.kwargs["json"] for call in calls] == [+ {+ "metricSet": "ConversationTimestampsReport",+ "timezone": "UTC",+ "startAt": "2024-03-13",+ "endAt": "2024-03-13",+ },+ {+ "metricSet": "ConversationTimestampsReport",+ "timezone": "UTC",+ "startAt": "2024-03-14",+ "endAt": "2024-03-14",+ },+ {+ "metricSet": "ConversationTimestampsReport",+ "timezone": "UTC",+ "startAt": "2024-03-15",+ "endAt": "2024-03-15",+ },+ ]++ flat = [row for batch in batches for row in batch]+ row_ids = [row.pop("_row_id") for row in flat]+ assert flat == [+ {+ "timestamp": "2024-03-13T09:00:00.000Z",+ "event_type": "CONVERSATION/CREATED",+ "conversation_id": "conv-1",+ "customer_id": "cust-1",+ "topic_name": None,+ },+ {+ "timestamp": "2024-03-15T08:00:00.000Z",+ "event_type": "CONVERSATION/CLOSED",+ "conversation_id": "conv-1",+ "customer_id": "cust, 1",+ "topic_name": "Returns",+ },+ ]+ assert len(set(row_ids)) == 2+ assert all(len(row_id) == 64 for row_id in row_ids)++ # State saved after each fully-processed window, empty ones included.+ assert [call.args[0].last_report_window_end for call in manager.save_state.call_args_list] == [+ "2024-03-13",+ "2024-03-14",+ "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):+ mock_session.return_value.post.side_effect = [+ _csv_response("Timestamp,Contact ID\n2024-01-01T00:00:00.000Z,ct-1\n")+ ]++ manager = _make_manager()+ rows_iterator = get_rows("myorg", "[email protected]", "token", "contact_timestamps", mock.MagicMock(), manager)++ first_batch = next(rows_iterator)+ assert [(row["timestamp"], row["contact_id"]) for row in first_batch] == [("2024-01-01T00:00:00.000Z", "ct-1")]+ config = GLADLY_ENDPOINTS["contact_timestamps"]+ horizon = date(2024, 3, 15) - timedelta(days=config.report_backfill_days)+ payload = mock_session.return_value.post.call_args.kwargs["json"]+ assert payload["metricSet"] == "ContactTimestampsReport"+ assert payload["startAt"] == horizon.isoformat()+ assert payload["endAt"] == (horizon + timedelta(days=config.report_window_days - 1)).isoformat()++ @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_resume_state_restarts_at_the_saved_window_and_supersedes_the_watermark(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _csv_response("Timestamp,Conversation ID\n"),+ _csv_response("Timestamp,Conversation ID\n"),+ ]++ # Resume state (mid-March) supersedes the older watermark, and the saved+ # window end itself is re-read rather than skipped.+ manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-14"))+ batches = list(+ get_rows(+ "myorg",+ "[email protected]",+ "token",+ "conversation_timestamps",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-03-01T00:00:00.000Z",+ )+ )++ assert batches == []+ payloads = [call.kwargs["json"] for call in mock_session.return_value.post.call_args_list]+ assert [(p["startAt"], p["endAt"]) for p in payloads] == [+ ("2024-03-14", "2024-03-14"),+ ("2024-03-15", "2024-03-15"),+ ]+ assert [call.args[0].last_report_window_end for call in manager.save_state.call_args_list] == [+ "2024-03-14",+ "2024-03-15",+ ]++ @freeze_time("2024-03-15T10:00:00Z")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_row_ids_are_deterministic_across_syncs(self, mock_session):+ csv_text = "Timestamp,Conversation ID\n2024-03-15T01:00:00.000Z,conv-1\n"++ row_ids = []+ for _ in range(2):+ mock_session.return_value.post.side_effect = [_csv_response(csv_text)]+ manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))+ batches = list(+ get_rows("myorg", "[email protected]", "token", "conversation_timestamps", mock.MagicMock(), manager)+ )+ row_ids.append(batches[0][0]["_row_id"])++ # Re-read windows must merge onto the previous sync's rows.+ assert row_ids[0] == row_ids[1]++ @freeze_time("2024-03-15T10:00:00Z")+ @mock.patch(f"{_MODULE}.MAX_RETRY_ATTEMPTS", 1)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ @pytest.mark.parametrize(+ "status_code, expected_error",+ [+ (429, GladlyRetryableError),+ (500, GladlyRetryableError),+ (400, requests.HTTPError),+ ],+ )+ def test_report_errors_are_classified(self, mock_session, status_code, expected_error):+ mock_session.return_value.post.return_value = _error_response(status_code)++ manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))+ with pytest.raises(expected_error):+ list(get_rows("myorg", "[email protected]", "token", "conversation_timestamps", mock.MagicMock(), manager))++ # A failed window is not recorded as processed.+ manager.save_state.assert_not_called()++ @freeze_time("2024-03-15T10:00:00Z")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_large_report_windows_are_chunked(self, mock_session):+ csv_text = "Conversation ID\n" + "\n".join(f"conv-{i}" for i in range(CHUNK_SIZE + 1)) + "\n"+ mock_session.return_value.post.side_effect = [_csv_response(csv_text)]++ manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))+ batches = list(get_rows("myorg", "[email protected]", "token", "conversation_timestamps", mock.MagicMock(), manager))++ assert [len(batch) for batch in batches] == [CHUNK_SIZE, 1]++ @freeze_time("2024-03-15T10:00:00Z")+ @mock.patch(f"{_MODULE}.REPORT_ROW_WARNING_THRESHOLD", 2)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_windows_near_the_report_row_cap_log_a_truncation_warning(self, mock_session):+ mock_session.return_value.post.side_effect = [_csv_response("Conversation ID\nconv-1\nconv-2\n")]++ manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))+ logger = mock.MagicMock()+ list(get_rows("myorg", "[email protected]", "token", "conversation_timestamps", logger, manager))++ logger.warning.assert_called_once()++class TestGladlySourceResponse:@pytest.mark.parametrize("endpoint", list(ENDPOINTS))def test_response_metadata_per_endpoint(self, endpoint):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 c3826f5173f5..870d647b5966 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,7 @@ 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+from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.settings import ENDPOINTS, REPORT_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.gladly.source import GladlySourcefrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -63,15 +63,28 @@ class TestGladlySource:schemas = self.source.get_schemas(self.config, self.team_id)assert {schema.name for schema in schemas} == set(ENDPOINTS)- # Every stream carries the injected job watermark, so all are incremental.assert all(schema.supports_incremental for schema in schemas)- assert all(schema.supports_append for schema in schemas)+ # Report windows are re-read on resume and behind the watermark, so+ # appending would duplicate rows — report streams are merge-only.+ for schema in schemas:+ assert schema.supports_append is (schema.name not in REPORT_ENDPOINTS)++ def test_schemas_advertise_the_expected_cursor(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ 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"]+ assert [f["field"] for f in schema.incremental_fields] == expected- def test_schemas_advertise_the_injected_job_cursor(self):+ def test_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.for schema in schemas:- assert [f["field"] for f in schema.incremental_fields] == ["_job_updated_at"]+ assert schema.should_sync_default is (schema.name not in REPORT_ENDPOINTS)def test_get_schemas_filtered_by_names(self):schemas = self.source.get_schemas(self.config, self.team_id, names=["customers"])