Skip to content

: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.

feat(data-warehouse): add gladly teams, inboxes and work session tables (#109934)

Tom Owers3d95dd5e02f8
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.md
index e51bbb6b9776..14afcc76780a 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
@@ -3640,14 +3640,14 @@ Note: Source is single-project scoped (every path templates {project} into /proj
## Gladly — gaps
-Today (4): `agents`, `conversation_items`, `customers`, `topics`
+Today (10): `agents`, `contact_timestamps`, `conversation_items`, `conversation_timestamps`, `conversations`, `customers`, `inboxes`, `teams`, `topics`, `work_session_events`
Diffed against: <https://developer.gladly.com/rest/>
-- [ ] `/api/v1/customers/{customerId}/conversations` — conversation-header rows (status, channel, timestamps); only item-level rows exist today, so per-conversation handle time and volume are unanswerable (high)
-- [ ] `/api/v1/teams` — lookup resolving the team IDs carried on agents and conversations (high)
-- [ ] `/api/v1/inboxes` — lookup resolving the inbox IDs carried on conversation items (high)
-- [ ] `/api/v1/reports/work-session-events` — agent work-session and status history — the vendor's own agent-productivity metric (high)
+- [x] `/api/v1/customers/{customerId}/conversations` — conversation-header rows (status, channel, timestamps); only item-level rows exist today, so per-conversation handle time and volume are unanswerable (high). Covered by `conversations` (Conversation Export report, with status, channels, handle time, and lifecycle timestamps). The per-customer endpoint itself is skipped: it is unpaginated, returns at most 100 conversations, and would need one request per customer.
+- [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)
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.py
index 2f11d84116fc..98867f9e2927 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
@@ -173,4 +173,53 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"times_reopened": "Number of times the conversation was reopened.",
},
},
+ # One row per contact and agent from the WorkSessionEventsReportV4 metric set;
+ # column names are the report's CSV headers, snake_cased.
+ "work_session_events": {
+ "description": "A work session: the time one agent spent on one ended contact (a call, chat, or email session). Ended contacts no agent handled appear with a blank agent, and open contacts appear once they end. From Gladly's work session report.",
+ "docs_url": "https://help.gladly.com/docs/work-sessions",
+ "columns": {
+ "timezone_filter": "Timezone the report was generated in (always UTC).",
+ "id": "Work session identifier. Blank until the contact ends, and not unique for sessions before October 2022.",
+ "contact_session_id": "Identifier of the contact the agent worked on.",
+ "contact_session_created_at": "Time at which the contact started (incremental cursor).",
+ "customer_id": "Identifier of the customer the contact is with.",
+ "conversation_id": "Identifier of the conversation the contact belongs to.",
+ "inbox_id": "Identifier of the inbox the contact was routed to.",
+ "channel": "Channel of the contact, e.g. CHAT, EMAIL, PHONE_CALL, SMS.",
+ "company_address": "Company address the customer contacted, such as a phone number or email address.",
+ "direction": "Whether the contact was inbound or outbound.",
+ "agent_accepted_at": "Time at which the agent accepted the contact.",
+ "contact_session_routed_at": "Time at which the contact was routed to the agent.",
+ "agent_id": "Identifier of the agent who worked the contact. Blank if no agent handled it.",
+ "sla_fulfilled_at": "Time at which the contact's service level was fulfilled.",
+ "contact_session_ended_at": "Time at which the contact ended.",
+ "status": "Outcome status of the contact.",
+ "within_sla": "Whether the contact was fulfilled within its service level.",
+ "work_session_handle_time_sec": "Seconds the agent spent handling the contact. Available after the contact ends.",
+ "work_session_after_contact_time_sec": "Seconds the agent spent on the customer after the contact ended.",
+ "work_session_unknown_time_sec": "Seconds of agent time on the customer that could not be attributed to a contact state.",
+ "accepted_inbox_id": "Identifier of the inbox the contact was in when the agent accepted it.",
+ "_row_id": "Hash of contact_session_id and agent_id, injected as the primary key.",
+ },
+ },
+ "teams": {
+ "description": "A team of agents in Gladly.",
+ "docs_url": "https://developer.gladly.com/rest/#tag/Teams",
+ "columns": {
+ "id": "Unique identifier for the team.",
+ "name": "Name of the team.",
+ "description": "Description of the team.",
+ "agentIds": "Identifiers of the agents in the team.",
+ },
+ },
+ "inboxes": {
+ "description": "An inbox in Gladly, which conversations and contacts are routed to.",
+ "docs_url": "https://developer.gladly.com/rest/#tag/Inboxes",
+ "columns": {
+ "id": "Unique identifier for the inbox.",
+ "name": "Name of the inbox.",
+ "disabled": "Whether the inbox is disabled.",
+ },
+ },
}
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.py
index c517dbb7d38b..644aa3e9a2ea 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
@@ -191,15 +191,17 @@ def _report_csv_lines(stream: io.TextIOBase) -> Iterator[str]:
yield line
-def _report_row_id(row: dict[str, Any]) -> str:
+def _report_row_id(row: dict[str, Any], key_columns: Sequence[str] = ()) -> 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.
+ stay distinct. Rows that restate in place hash only their identifying
+ ``key_columns`` instead, so the newer version replaces the older one.
"""
- return hashlib.sha256(json.dumps(row, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+ keyed = {column: row.get(column) for column in key_columns} if key_columns else row
+ return hashlib.sha256(json.dumps(keyed, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
def _report_start_date(
@@ -308,10 +310,6 @@ def get_rows(
)
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),
@@ -332,6 +330,19 @@ def get_rows(
return response
+ if config.list_path is not None:
+ body = fetch(f"{base_url}{config.list_path}").json()
+ rows = body if isinstance(body, list) else []
+ if rows:
+ yield rows
+ return
+
+ filename = config.filename
+ if filename is None:
+ raise ValueError(
+ f"Gladly endpoint {endpoint} declares neither an export filename, a list path, nor a report metric set"
+ )
+
# The cutoff is the later of the incremental watermark and the resume
# state, so retried syncs skip already-processed jobs either way.
cutoff: Optional[str] = None
@@ -437,6 +448,9 @@ def _report_rows(
# The columns the stream is keyed on. An injected `_row_id` is built from the row
# rather than read from the report, so it is never required of the header.
required_columns = {incremental_field["field"] for incremental_field in config.incremental_fields}
+ required_columns.update(config.report_row_id_columns)
+ if config.report_final_row_column is not None:
+ required_columns.add(config.report_final_row_column)
if not inject_row_id:
required_columns.add(config.primary_key)
@@ -482,20 +496,22 @@ def _report_rows(
if not is_first_request:
time.sleep(REPORT_REQUEST_INTERVAL_SECONDS)
is_first_request = False
+ payload = {
+ "metricSet": metric_set,
+ # Explicit UTC keeps window boundaries and rendered timestamps
+ # stable even if the organization's default timezone changes.
+ "timezone": "UTC",
+ }
+ if config.report_uses_time_range:
+ # endAtTime is inclusive through the 59th second of the minute given.
+ payload["startAtTime"] = f"{window_start.isoformat()}T00:00Z"
+ payload["endAtTime"] = f"{window_end.isoformat()}T23:59Z"
+ else:
+ # endAt is inclusive: the report covers through the end of that day.
+ payload["startAt"] = window_start.isoformat()
+ payload["endAt"] = window_end.isoformat()
try:
- reader = open_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(),
- },
- window_start,
- window_end,
- )
+ reader = open_report(payload, window_start, window_end)
except GladlyReportUnavailableError as e:
if report_never_served:
raise GladlyReportNotAvailableForAccountError(metric_set, e.header) from e
@@ -513,10 +529,12 @@ def _report_rows(
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
+ row_count += 1
+ if config.report_final_row_column is not None and row.get(config.report_final_row_column) is None:
+ continue
if inject_row_id:
- row[REPORT_ROW_ID_COLUMN] = _report_row_id(row)
+ row[REPORT_ROW_ID_COLUMN] = _report_row_id(row, config.report_row_id_columns)
chunk.append(row)
- row_count += 1
if len(chunk) >= CHUNK_SIZE:
yield chunk
chunk = []
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.py
index 57f0cb4c8dc5..66562c2cfc37 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,18 @@ _REPORT_INCREMENTAL_FIELDS: list[IncrementalField] = [
},
]
+# 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.
+_WORK_SESSION_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "contact_session_created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "contact_session_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
@@ -47,14 +59,30 @@ REPORT_ROW_ID_COLUMN = "_row_id"
# refresh.
REPORT_INCREMENTAL_LOOKBACK_SECONDS = 30 * 24 * 60 * 60
+# After-contact and unknown time keep accumulating on a work session after its
+# contact ends, until the next contact begins or the conversation closes.
+WORK_SESSION_INCREMENTAL_LOOKBACK_SECONDS = 7 * 24 * 60 * 60
+
-@dataclass
+@dataclass(frozen=True)
class GladlyEndpointConfig:
name: str
# Filename inside each export job (e.g. customers.jsonl) for job-export streams.
filename: str | None = None
+ # Path of a non-paginated JSON array endpoint for lookup streams.
+ list_path: str | None = None
# 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
+ # date range (startAt/endAt).
+ report_uses_time_range: bool = False
+ # Columns that together identify a row when the report has no usable id. The
+ # injected `_row_id` then hashes only these, so a restated row merges onto its
+ # earlier version. Left empty, it hashes the whole row.
+ report_row_id_columns: tuple[str, ...] = ()
+ # Rows with this column blank are provisional and are skipped. They come back
+ # in a later window once the column is filled in.
+ report_final_row_column: 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.
@@ -68,9 +96,10 @@ class GladlyEndpointConfig:
should_sync_default: bool = True
primary_key: str = "id"
incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_JOB_INCREMENTAL_FIELDS))
+ default_incremental_lookback_seconds: int | None = None
-# Gladly has no list-all REST surface — bulk data ships as JSONL files inside
+# Gladly has no paginated list-all REST surface — bulk data ships as JSONL files inside
# vendor-scheduled export jobs (hourly/daily, 14-day retention). Every stream
# maps to one file per job; jobs are processed oldest-first so the watermark
# advances monotonically, and merge-on-id dedupes records that appear in
@@ -105,6 +134,7 @@ GLADLY_ENDPOINTS: dict[str, GladlyEndpointConfig] = {
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.
@@ -126,6 +156,39 @@ GLADLY_ENDPOINTS: dict[str, GladlyEndpointConfig] = {
should_sync_default=False,
incremental_fields=list(_TIMESTAMPS_REPORT_INCREMENTAL_FIELDS),
),
+ # One row per contact and agent who worked it, from the work session report
+ # (the WorkSessionEventsReportV4 metric set returns the same data as
+ # POST /api/v1/reports/work-session-events). The report's `id` column is
+ # blank until the contact ends and was not unique before late 2022, so the
+ # key is built from contact_session_id + agent_id, the pair Gladly documents
+ # as unique. agent_id is blank for a contact no agent has handled. It is also
+ # blank while a contact is open, so open contacts are skipped: their row key
+ # would never match the row the contact gets once it ends. An ended contact
+ # moves to the window of its end time, so a later sync picks it up.
+ "work_session_events": GladlyEndpointConfig(
+ name="work_session_events",
+ report_metric_set="WorkSessionEventsReportV4",
+ report_uses_time_range=True,
+ report_row_id_columns=("contact_session_id", "agent_id"),
+ report_final_row_column="contact_session_ended_at",
+ primary_key=REPORT_ROW_ID_COLUMN,
+ should_sync_default=False,
+ incremental_fields=list(_WORK_SESSION_INCREMENTAL_FIELDS),
+ default_incremental_lookback_seconds=WORK_SESSION_INCREMENTAL_LOOKBACK_SECONDS,
+ ),
+ # Small lookups that resolve the team and inbox ids on other tables. Both
+ # return the whole collection unpaginated with no change filter, so they
+ # only full-refresh.
+ "teams": GladlyEndpointConfig(
+ name="teams",
+ list_path="/teams",
+ incremental_fields=[],
+ ),
+ "inboxes": GladlyEndpointConfig(
+ name="inboxes",
+ list_path="/inboxes",
+ incremental_fields=[],
+ ),
}
ENDPOINTS = tuple(GLADLY_ENDPOINTS.keys())
@@ -140,3 +203,9 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
}
SHOULD_SYNC_DEFAULT: dict[str, bool] = {name: config.should_sync_default for name, config in GLADLY_ENDPOINTS.items()}
+
+INCREMENTAL_LOOKBACK_SECONDS: dict[str, int] = {
+ name: config.default_incremental_lookback_seconds
+ for name, config in GLADLY_ENDPOINTS.items()
+ if config.default_incremental_lookback_seconds is not None
+}
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.py
index 5b0bc347ebdd..badf14066c28 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,8 +29,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.gla
from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.settings import (
ENDPOINTS,
INCREMENTAL_FIELDS,
+ INCREMENTAL_LOOKBACK_SECONDS,
REPORT_ENDPOINTS,
- REPORT_INCREMENTAL_LOOKBACK_SECONDS,
SHOULD_SYNC_DEFAULT,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -115,7 +115,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, and the conversation and contact timestamps tables come from Gladly's reports as well, reaching 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. 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.""",
iconPath="/static/services/gladly.png",
docsUrl="https://posthog.com/docs/cdp/sources/gladly",
releaseStatus=ReleaseStatus.ALPHA,
@@ -179,11 +179,11 @@ Your organization is the part of your Gladly URL before `.gladly.com`. For `myor
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.
+ # Conversation and work-session report rows restate in place as records
+ # change, so their 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
+ schema.default_incremental_lookback_seconds = INCREMENTAL_LOOKBACK_SECONDS.get(schema.name)
return schemas
def validate_credentials(
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.py
index ece2d82c6f95..084de7145d60 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
@@ -350,6 +350,37 @@ class TestGetRows:
assert [len(batch) for batch in batches] == [CHUNK_SIZE, 1]
+ @pytest.mark.parametrize(
+ "endpoint, path, body",
+ [
+ ("teams", "teams", [{"id": "team-1", "name": "Tier 1", "agentIds": ["agent-1"]}]),
+ ("inboxes", "inboxes", [{"id": "inbox-1", "name": "Support", "disabled": False}]),
+ ],
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_lookup_streams_read_the_whole_list_and_ignore_the_watermark(self, mock_session, endpoint, path, body):
+ mock_session.return_value.get.return_value = _jobs_response(body)
+
+ manager = _make_manager()
+ batches = list(
+ get_rows(
+ "myorg",
+ "token",
+ endpoint,
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-03-14T05:00:00.000Z",
+ )
+ )
+
+ assert batches == [body]
+ assert [call.args[0] for call in mock_session.return_value.get.call_args_list] == [
+ f"https://myorg.gladly.com/api/v1/{path}"
+ ]
+ manager.save_state.assert_not_called()
+
class TestNormalizeReportColumn:
@pytest.mark.parametrize(
@@ -529,6 +560,64 @@ class TestGetReportRows:
"2024-03-15",
]
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
+ @mock.patch(f"{_MODULE}.REPORT_REQUEST_INTERVAL_SECONDS", 0)
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_work_session_report_uses_a_time_range_and_keys_rows_on_contact_and_agent(self, mock_session):
+ header = (
+ "Timezone Filter,id,contact_session_id,contact_session_created_at,agent_id,"
+ "contact_session_ended_at,work_session_handle_time_sec\n"
+ )
+ mock_session.return_value.post.side_effect = [
+ _csv_response(
+ header
+ + "UTC,,cs-open,2024-03-14T08:00:00.000Z,,,\n"
+ + "UTC,ws-2,cs-2,2024-03-14T08:30:00.000Z,,2024-03-14T08:45:00.000Z,\n"
+ + "UTC,,cs-1,2024-03-14T09:00:00.000Z,agent-1,2024-03-14T23:00:00.000Z,100\n"
+ ),
+ _csv_response(header + "UTC,ws-1,cs-1,2024-03-14T09:00:00.000Z,agent-1,2024-03-14T23:00:00.000Z,120\n"),
+ ]
+
+ manager = _make_manager()
+ batches = list(
+ get_rows(
+ "myorg",
+ "token",
+ "work_session_events",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-03-15T00:30:00.000Z",
+ )
+ )
+
+ assert [call.kwargs["json"] for call in mock_session.return_value.post.call_args_list] == [
+ {
+ "metricSet": "WorkSessionEventsReportV4",
+ "timezone": "UTC",
+ "startAtTime": "2024-03-14T00:00Z",
+ "endAtTime": "2024-03-14T23:59Z",
+ },
+ {
+ "metricSet": "WorkSessionEventsReportV4",
+ "timezone": "UTC",
+ "startAtTime": "2024-03-15T00:00Z",
+ "endAtTime": "2024-03-15T23:59Z",
+ },
+ ]
+
+ # The open contact has no agent yet, so its key would never match the row it
+ # gets once it ends. It is skipped, while the ended unhandled contact stays.
+ unhandled, first_read, restated = [row for batch in batches for row in batch]
+ assert unhandled["contact_session_id"] == "cs-2"
+ assert unhandled["agent_id"] is None
+ # A restated session must merge onto its earlier row even though its id
+ # and handle time changed.
+ assert first_read["_row_id"] == restated["_row_id"]
+ assert unhandled["_row_id"] != first_read["_row_id"]
+ assert restated["work_session_handle_time_sec"] == "120"
+
@time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@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.py
index 35d2dbe778ff..8aa6e57c3982 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
@@ -5,6 +5,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.set
ENDPOINTS,
REPORT_ENDPOINTS,
REPORT_INCREMENTAL_LOOKBACK_SECONDS,
+ WORK_SESSION_INCREMENTAL_LOOKBACK_SECONDS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.source import GladlySource
@@ -69,11 +70,13 @@ class TestGladlySource:
schemas = self.source.get_schemas(self.config, self.team_id)
assert {schema.name for schema in schemas} == set(ENDPOINTS)
- assert all(schema.supports_incremental 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.
+ # Lookup lists have no change filter, so they only full-refresh. Report
+ # windows are re-read on resume and behind the watermark, so appending
+ # would duplicate rows — report streams are merge-only.
+ lookups = {"teams", "inboxes"}
for schema in schemas:
- assert schema.supports_append is (schema.name not in REPORT_ENDPOINTS)
+ assert schema.supports_incremental is (schema.name not in lookups)
+ assert schema.supports_append is (schema.name not in {*REPORT_ENDPOINTS, *lookups})
def test_schemas_advertise_the_expected_cursor(self):
schemas = self.source.get_schemas(self.config, self.team_id)
@@ -86,6 +89,9 @@ class TestGladlySource:
"conversations": ["created_at"],
"conversation_timestamps": ["timestamp"],
"contact_timestamps": ["timestamp"],
+ "work_session_events": ["contact_session_created_at"],
+ "teams": [],
+ "inboxes": [],
}.get(schema.name, ["_job_updated_at"])
assert [f["field"] for f in schema.incremental_fields] == expected
@@ -96,15 +102,18 @@ class TestGladlySource:
# 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 {"conversation_timestamps", "contact_timestamps"})
+ assert schema.should_sync_default is (
+ schema.name not in {"conversation_timestamps", "contact_timestamps", "work_session_events"}
+ )
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.
+ # Conversation and work-session report rows restate in place, so only
+ # those schemas re-read 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 lookbacks.pop("work_session_events") == WORK_SESSION_INCREMENTAL_LOOKBACK_SECONDS
assert all(seconds is None for seconds in lookbacks.values())
def test_get_schemas_filtered_by_names(self):