: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(warehouse-sources): sync babelforce conversation events and outbound dialer (#99674)
Tom Owerse151080e28dc
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 533d2da8bbbe..658d881ca4a9 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@@ -684,14 +684,14 @@ Note: Azure DevOps is one of the largest APIs in this batch (47 spec areas in th## Babelforce — gaps-Today (8): `agent_groups`, `agents`, `calls`, `conversations`, `numbers`, `queues`, `recordings`, `sms`+Today (14): `agent_groups`, `agents`, `calls`, `conversation_events`, `conversations`, `event_definitions`, `numbers`, `outbound_campaign_statistics`, `outbound_campaigns`, `outbound_leads`, `outbound_lists`, `queues`, `recordings`, `sms`Diffed against: <https://apps.babelforce.com/developer-hub/manager/>-- [ ] `GET /api/v2/conversations/{conversationId}/events` — per-conversation event timeline - the transition history behind the conversations we already sync (high)-- [ ] `GET /api/v2/events` — workspace-wide event stream; the core analytical fact table for a contact-center source (high)-- [ ] `GET /api/v2/outbound/campaigns and /{id}/statistics` — outbound dialer campaigns plus their performance stats - a whole product area with no coverage (high)-- [ ] `GET /api/v2/outbound/lists and /{id}/leads` — dialer lists and the leads dialed, joinable to calls (medium)+- [x] `GET /api/v2/conversations/{conversationId}/events` — per-conversation event timeline - the transition history behind the conversations we already sync (high)+- [x] `GET /api/v2/events` — workspace-wide event stream; the core analytical fact table for a contact-center source (high)+- [x] `GET /api/v2/outbound/campaigns and /{id}/statistics` — outbound dialer campaigns plus their performance stats - a whole product area with no coverage (high)+- [x] `GET /api/v2/outbound/lists and /{id}/leads` — dialer lists and the leads dialed, joinable to calls (medium)- [ ] `GET /api/v2/calls/reporting/simple/{reportType}` — pre-aggregated call report dimensions the vendor exposes alongside the raw reporting feed (medium)- [ ] `GET /api/v2/queues/{queueId}/selections` — queue-to-agent/group/tag routing membership - resolves which agents serve which queue (medium)- [ ] `GET /api/v2/users and /api/v2/users/roles` — user and role lookup distinct from agents, resolving actor IDs on events and audit rows (medium)@@ -701,7 +701,7 @@ Diffed against: <https://apps.babelforce.com/developer-hub/manager/>- [ ] `GET /api/v2/audit/request` — API audit trail of who changed what (low)- [ ] `GET /api/v2/logs` — platform logs for call-flow debugging (low)-Note: The developer hub serves a Swagger UI whose visible initializer points at the petstore default; the real spec (babelforce API 0.7.0, ~110 paths) is embedded in https://apps.babelforce.com/developer-hub/manager/swagger-ui-init.js. Excluded config surfaces: applications, routings, triggers, business-hours, calendars, prompts, integrations, settings, babeldesk dashboards/widgets, sessions.+Note: The developer hub serves a Swagger UI whose visible initializer points at the petstore default; the real spec (babelforce API 0.7.0, ~110 paths) is embedded in https://apps.babelforce.com/developer-hub/manager/swagger-ui-init.js. Excluded config surfaces: applications, routings, triggers, business-hours, calendars, prompts, integrations, settings, babeldesk dashboards/widgets, sessions. `GET /api/v2/events` turned out to be the catalog of event types available for automations (id, type, name, code, label), not a stream of events that happened, so it landed as the `event_definitions` lookup table; the per-conversation timeline in `conversation_events` is the fact table the note was reaching for.## BambooHR — **thin**diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/babelforce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/babelforce.pyindex cde18a81947c..18fbbcbe39d3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/babelforce.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/babelforce.py@@ -1,8 +1,9 @@import reimport timeimport dataclasses+from collections.abc import Callable, Iterablefrom datetime import UTC, date, datetime-from typing import Any, Optional+from typing import Any, Optional, castfrom requests import PreparedRequest, Request, Response, Session@@ -16,13 +17,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBase-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponseDEFAULT_ENVIRONMENT = "services"-PAGE_SIZE = 100# The environment is the babelforce subdomain the customer's account lives on (usually# "services", or a custom subdomain for dedicated environments). It becomes part of the@@ -30,12 +37,15 @@ PAGE_SIZE = 100_ENVIRONMENT_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9-]*$")[email protected](frozen=True)class BabelforceResumeConfig:# Page index of the next unfetched page and the frozen request window; both are persisted# so a resumed run reissues the identical query (same date window, next page).- next_page: int- params: dict[str, Any]+ next_page: Optional[int] = None+ params: dict[str, Any] = dataclasses.field(default_factory=dict)+ # Fan-out checkpoint for a child endpoint: which parents are done, which one was in flight+ # and how far its pages had been read. Round-tripped into `initial_paginator_state`.+ fanout: Optional[dict[str, Any]] = Noneclass BabelforceAuth(AuthConfigBase):@@ -195,7 +205,9 @@ def _to_epoch(value: Any) -> Optional[int]:def _build_params(config: BabelforceEndpointConfig, from_timestamp: Optional[int], to_timestamp: Optional[int]) -> dict[str, Any]:- params: dict[str, Any] = {"max": PAGE_SIZE}+ params: dict[str, Any] = {}+ if config.paginated:+ params["max"] = config.page_sizeif config.supports_date_created_filter:# Documented on the call reporting endpoint as unix-second filters. The upper bound is# frozen at sync start so page contents stay stable while new calls arrive mid-sync;@@ -207,6 +219,23 @@ def _build_params(return params+def _paginator_for(config: BabelforceEndpointConfig) -> BasePaginator:+ return BabelforcePaginator() if config.paginated else SinglePagePaginator()+++def _client_config(environment: str, access_id: str, access_token: str, paginator: BasePaginator) -> ClientConfig:+ return {+ "base_url": _base_url(environment),+ "headers": {"Accept": "application/json"},+ "auth": BabelforceAuth(access_id, access_token),+ # Pre-built session so responses (SMS bodies, phone numbers, recording URLs) stay out+ # of sample capture and both credentials are value-redacted; redirects are pinned off.+ "session": _make_session(access_id, access_token),+ "allow_redirects": False,+ "paginator": paginator,+ }++def validate_credentials(environment: str, access_id: str, access_token: str) -> bool:"""Confirm the access ID/token pair is valid with a one-row agents listing."""ok, _status = validate_via_probe(@@ -217,6 +246,44 @@ def validate_credentials(environment: str, access_id: str, access_token: str) ->return ok+def _fanout_resource(+ config: BabelforceEndpointConfig,+ environment: str,+ access_id: str,+ access_token: str,+ team_id: int,+ job_id: str,+ save_checkpoint: Callable[[Optional[dict[str, Any]]], None],+ initial_paginator_state: Optional[dict[str, Any]],+) -> Iterable[Any]:+ """Fetch a per-parent endpoint once for every row of its parent listing."""+ assert config.fanout is not None+ parent_config = BABELFORCE_ENDPOINTS[config.fanout.parent_name]++ return cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=BABELFORCE_ENDPOINTS,+ child_endpoint=config.name,+ fanout=config.fanout,+ client_config=_client_config(environment, access_id, access_token, _paginator_for(parent_config)),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ # No per-parent endpoint documents a time filter, so a fan-out is always full refresh.+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ # Both halves of every fan-out pair share a pagination style, so one page-size param+ # (or none, for the outbound endpoints that take no paging params) covers both.+ page_size_param="max" if parent_config.paginated else None,+ parent_endpoint_extra={"paginator": _paginator_for(parent_config), "data_selector": "items"},+ child_endpoint_extra={"paginator": _paginator_for(config), "data_selector": "items"},+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ ),+ )++def babelforce_source(environment: str,access_id: str,@@ -229,76 +296,88 @@ def babelforce_source(db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = BABELFORCE_ENDPOINTS[endpoint]-- initial_paginator_state: Optional[dict[str, Any]] = Noneresume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- if resume is not None:- # Reuse the saved window and page so the resumed run continues the identical query.- params = dict(resume.params)- initial_paginator_state = {"next_page": resume.next_page}- else:- from_timestamp = _to_epoch(db_incremental_field_last_value) if should_use_incremental_field else None- to_timestamp = int(time.time()) if config.supports_date_created_filter else None- params = _build_params(config, from_timestamp, to_timestamp)-- session = _make_session(access_id, access_token)-- rest_config: RESTAPIConfig = {- "client": {- "base_url": _base_url(environment),- "headers": {"Accept": "application/json"},- "auth": BabelforceAuth(access_id, access_token),- # Pre-built session so responses (SMS bodies, phone numbers, recording URLs) stay out- # of sample capture and both credentials are value-redacted; redirects are pinned off.- "session": session,- "allow_redirects": False,- "paginator": BabelforcePaginator(),- },- "resource_defaults": {},- "resources": [- {- "name": endpoint,- "endpoint": {- "path": config.path,- "params": params,- "data_selector": "items",- },- }- ],- }- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:- # Persist only while a next page remains; save AFTER the page is yielded so a crash- # re-yields the last page (merge dedupes on primary key) rather than skipping it.- if state and state.get("next_page") is not None:- resumable_source_manager.save_state(- BabelforceResumeConfig(next_page=int(state["next_page"]), params=params)- )-- resource = rest_api_resource(- rest_config,- team_id,- job_id,- # The date window is baked into ``params`` above (frozen at sync start), so the framework's- # server-side incremental injection is intentionally not used.- db_incremental_field_last_value=None,- resume_hook=save_checkpoint,- initial_paginator_state=initial_paginator_state,- )+ if config.fanout is not None:++ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Saved AFTER each child page is yielded, so a crash re-yields the last page (merge+ # dedupes on primary key) rather than skipping it.+ if state:+ resumable_source_manager.save_state(BabelforceResumeConfig(fanout=dict(state)))++ items: Iterable[Any] = _fanout_resource(+ config,+ environment,+ access_id,+ access_token,+ team_id,+ job_id,+ save_fanout_checkpoint,+ resume.fanout if resume is not None else None,+ )+ column_hints = None+ else:+ initial_paginator_state: Optional[dict[str, Any]] = None+ if resume is not None and resume.next_page is not None:+ # Reuse the saved window and page so the resumed run continues the identical query.+ params = dict(resume.params)+ initial_paginator_state = {"next_page": resume.next_page}+ else:+ from_timestamp = _to_epoch(db_incremental_field_last_value) if should_use_incremental_field else None+ to_timestamp = int(time.time()) if config.supports_date_created_filter else None+ params = _build_params(config, from_timestamp, to_timestamp)++ rest_config: RESTAPIConfig = {+ "client": _client_config(environment, access_id, access_token, _paginator_for(config)),+ "resource_defaults": {},+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": params,+ "data_selector": "items",+ },+ }+ ],+ }++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while a next page remains; save AFTER the page is yielded so a crash+ # re-yields the last page (merge dedupes on primary key) rather than skipping it.+ if state and state.get("next_page") is not None:+ resumable_source_manager.save_state(+ BabelforceResumeConfig(next_page=int(state["next_page"]), params=params)+ )++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ # The date window is baked into ``params`` above (frozen at sync start), so the framework's+ # server-side incremental injection is intentionally not used.+ db_incremental_field_last_value=None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ items = resource+ column_hints = resource.column_hintsreturn SourceResponse(name=endpoint,- items=lambda: resource,- primary_keys=[config.primary_key],- # The reporting API doesn't document a sort order or expose a sort param, so we can't- # assume ascending arrival. "desc" makes the pipeline finalize the incremental watermark- # only after a fully successful sync, which is correct for any actual ordering; the- # server-side dateCreated window bounds what each run re-reads.+ items=lambda: items,+ primary_keys=config.primary_keys,+ # The reporting API doesn't document a sort order or expose a sort param, and a fan-out+ # returns rows grouped by parent, so we can't assume ascending arrival. "desc" makes the+ # pipeline finalize the incremental watermark only after a fully successful sync, which is+ # correct for any actual ordering; the server-side dateCreated window bounds what each run+ # re-reads.sort_mode="desc",partition_count=1,partition_size=1,partition_mode="datetime" if config.partition_key else None,partition_format="month" if config.partition_key else None,partition_keys=[config.partition_key] if config.partition_key else None,- column_hints=resource.column_hints,+ column_hints=column_hints,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/canonical_descriptions.pyindex 993fcd80b051..2c4bab733c61 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/canonical_descriptions.py@@ -127,4 +127,88 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"phone": "The customer phone number the conversation is with.",},},+ "conversation_events": {+ "description": "Timeline of everything that happened in a conversation: the calls, messages, queue and application steps it passed through.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier (UUID) of the event.",+ "conversationId": "Identifier of the conversation the event belongs to.",+ "type": "What the event concerns: call, sms, queue, application, integration, agent or external.",+ "name": "The specific event within its type.",+ "lod": "Level of detail of the event.",+ "dateCreated": "When the event happened.",+ "call": "The call the event relates to.",+ "agent": "The agent the event relates to.",+ },+ },+ "event_definitions": {+ "description": "Catalog of the event types available on the account, including custom ones, used to trigger automations. Not a stream of events that happened - see conversation_events for that.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier (UUID) of the event definition.",+ "type": "The event category: AGENT, CALL, CUSTOM, MESSAGE, RECORDING, SMS or TRANSACTION.",+ "name": "The specific event within its type category.",+ "code": "Unique code of the event, e.g. `call.inbound`.",+ "label": "Display label of the event.",+ "tags": "Tags assigned to the event definition.",+ },+ },+ "outbound_campaigns": {+ "description": "Outbound dialer campaigns and their dialing configuration.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier (UUID) of the campaign.",+ "name": "Name of the campaign.",+ "active": "Whether the campaign is currently dialing.",+ "displayNumber": "The number shown to the person being called.",+ "testMode": "Whether the campaign runs in test mode.",+ "leadList": "The lead list the campaign dials.",+ "listOrder": "The order leads are dialed in (DOWN, UP, UP RANK or DOWN RANK).",+ "callRatio": "How many calls are placed per available agent.",+ "recording": "Recording policy for the campaign (NEVER, ONDEMAND, ALLCALLS or ALLFORCE).",+ },+ },+ "outbound_campaign_statistics": {+ "description": "Per-agent time breakdown for an outbound campaign.",+ "docs_url": _DOCS_URL,+ "columns": {+ "campaignId": "Identifier of the campaign the statistics belong to.",+ "agent": "The agent the statistics describe.",+ "login_at": "When the agent logged in to the campaign.",+ "pause_in_seconds": "Seconds the agent spent paused.",+ "wait_in_seconds": "Seconds the agent spent waiting for a call.",+ "talk_in_seconds": "Seconds the agent spent talking.",+ },+ },+ "outbound_lists": {+ "description": "Lead lists the outbound dialer works through.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier (UUID) of the list.",+ "name": "Name of the list.",+ "count": "Number of leads on the list.",+ "campaignId": "Identifier of the campaign the list is assigned to.",+ },+ },+ "outbound_leads": {+ "description": "The leads on an outbound dialer list, with their dialing outcome so far.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier (UUID) of the lead.",+ "listId": "Identifier of the list the lead belongs to.",+ "uid": "Your own identifier for the lead.",+ "number": "Primary phone number dialed.",+ "number2": "Second phone number to try.",+ "number3": "Third phone number to try.",+ "callerId": "The number shown to the lead when dialing.",+ "status": "Current dialing status of the lead.",+ "callCount": "How many times the lead has been called.",+ "duration": "Total seconds spent on calls to the lead.",+ "calledSinceReset": "Whether the lead has been called since the list was last reset.",+ "rank": "Dialing rank of the lead within the list.",+ "dateCreated": "When the lead was added to the list.",+ "lastUpdated": "When the lead was last updated.",+ "data": "Custom fields carried with the lead.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/settings.pyindex 2281153580a4..c4735e818d3c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/settings.py@@ -1,14 +1,21 @@from dataclasses import dataclass, fieldfrom typing import Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+PAGE_SIZE = 100-@dataclass++# frozen=False: the shared FanoutEndpointLike protocol declares mutable attributes, which a+# frozen dataclass cannot satisfy. The instances are treated as immutable by convention.+@dataclass(frozen=False)class BabelforceEndpointConfig:name: strpath: str- primary_key: str = "id"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])incremental_fields: list[IncrementalField] = field(default_factory=list)# Stable creation-time field used for datetime partitioning. Never an updated_at-style# field, which would rewrite partitions on every sync.@@ -16,10 +23,20 @@ class BabelforceEndpointConfig:# Whether the endpoint accepts the `dateCreated.start` / `dateCreated.end` unix-timestamp# filters documented on the Manager API's call reporting endpoint.supports_date_created_filter: bool = False+ # Whether the endpoint's documented response carries a `pagination` object. The outbound+ # and event endpoints return the whole collection as `{"items": [...], "success": true}`+ # and take no `page`/`max` params, so they are read as a single page.+ paginated: bool = True+ # When set, the endpoint is fetched once per row of `fanout.parent_name`.+ fanout: Optional[DependentEndpointConfig] = None+ page_size: int = PAGE_SIZE+ # Unused: no fan-out child documents a server-side time filter, so they all sync as full+ # refresh. Kept so the config satisfies FanoutEndpointLike.+ default_incremental_field: Optional[str] = None-# babelforce's Manager API (https://apps.babelforce.com/developer-hub/manager) paginates every-# list endpoint with `page` + `max` params and wraps rows as {"items": [...], "pagination": {...}}.+# babelforce's Manager API (https://apps.babelforce.com/developer-hub/manager) paginates its+# `page` + `max` list endpoints and wraps rows as {"items": [...], "pagination": {...}}.# Only call reporting documents a server-side timestamp filter (`dateCreated.start`/`dateCreated.end`,# unix seconds), so incremental sync is enabled there and everything else is full refresh.BABELFORCE_ENDPOINTS: dict[str, BabelforceEndpointConfig] = {@@ -66,6 +83,68 @@ BABELFORCE_ENDPOINTS: dict[str, BabelforceEndpointConfig] = {name="conversations",path="/conversations",),+ "conversation_events": BabelforceEndpointConfig(+ name="conversation_events",+ path="/conversations/{conversationId}/events",+ # The API only documents the event id as unique inside its conversation, so the parent+ # id is part of the key. It is taken from the parent row, which always has one - the+ # event's own `conversationId` is optional in the response schema.+ primary_keys=["conversationId", "id"],+ partition_key="dateCreated",+ fanout=DependentEndpointConfig(+ parent_name="conversations",+ resolve_param="conversationId",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "conversationId"},+ ),+ ),+ "event_definitions": BabelforceEndpointConfig(+ name="event_definitions",+ path="/events",+ paginated=False,+ ),+ "outbound_campaigns": BabelforceEndpointConfig(+ name="outbound_campaigns",+ path="/outbound/campaigns",+ paginated=False,+ ),+ "outbound_campaign_statistics": BabelforceEndpointConfig(+ name="outbound_campaign_statistics",+ path="/outbound/campaigns/{id}/statistics",+ # Statistics rows carry no id of their own. The grain is undocumented beyond the fields+ # themselves, so the key is every field that identifies the row: the campaign it belongs+ # to, the agent it describes, and when that agent logged in.+ primary_keys=["campaignId", "agent", "login_at"],+ paginated=False,+ fanout=DependentEndpointConfig(+ parent_name="outbound_campaigns",+ resolve_param="id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "campaignId"},+ ),+ ),+ "outbound_lists": BabelforceEndpointConfig(+ name="outbound_lists",+ path="/outbound/lists",+ paginated=False,+ ),+ "outbound_leads": BabelforceEndpointConfig(+ name="outbound_leads",+ path="/outbound/lists/{id}/leads",+ # Lead ids are only documented as unique inside their list, so the list is part of the key.+ primary_keys=["listId", "id"],+ partition_key="dateCreated",+ paginated=False,+ fanout=DependentEndpointConfig(+ parent_name="outbound_lists",+ resolve_param="id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "listId"},+ ),+ ),}ENDPOINTS = tuple(BABELFORCE_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/tests/test_babelforce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/tests/test_babelforce.pyindex 394cc9767700..2f410393bf95 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/tests/test_babelforce.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/tests/test_babelforce.py@@ -47,16 +47,19 @@ def _page(items: list[dict[str, Any]], current: Optional[int], pages: Optional[ireturn resp-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+def _wire(session: mock.MagicMock, responses: list[Response], urls: Optional[list[str]] = None) -> list[dict[str, Any]]:"""Wire a mock session and capture each request's params AT SEND TIME.``request.params`` is one dict the paginator mutates in place across pages, so snapshot a copy- when each request is prepared rather than inspecting the final state.+ when each request is prepared rather than inspecting the final state. Pass ``urls`` to collect+ each request's URL alongside them."""session.headers = {}param_snapshots: list[dict[str, Any]] = []def _prepare(request: Any) -> mock.MagicMock:+ if urls is not None:+ urls.append(request.url)param_snapshots.append(dict(request.params or {}))return mock.MagicMock()@@ -129,6 +132,11 @@ class TestBuildParams:assert "dateCreated.start" not in paramsassert "dateCreated.end" not in params+ def test_unpaginated_endpoint_omits_the_page_size(self):+ # The outbound and event endpoints document no paging params; sending `max` could cap a+ # response that otherwise carries the whole collection.+ assert _build_params(BABELFORCE_ENDPOINTS["outbound_campaigns"], None, None) == {}+def test_no_watermark_omits_start(self):params = _build_params(BABELFORCE_ENDPOINTS["calls"], from_timestamp=None, to_timestamp=1700000100)assert "dateCreated.start" not in params@@ -308,7 +316,7 @@ class TestBabelforceSourceResponse:)assert response.name == endpoint- assert response.primary_keys == [config.primary_key]+ assert response.primary_keys == config.primary_keys# Reporting order is undocumented, so the watermark must only finalize on completion.assert response.sort_mode == "desc"if config.partition_key:@@ -321,3 +329,118 @@ class TestBabelforceSourceResponse:@pytest.mark.parametrize("config", [c for c in BABELFORCE_ENDPOINTS.values() if c.partition_key])def test_partition_keys_are_stable_creation_fields(self, config):assert config.partition_key == "dateCreated"+++# Each fan-out child, the path its parent id resolves into, and the field that id is injected as.+FANOUT_CASES = [+ ("conversation_events", "/conversations/p1/events", "conversationId"),+ ("outbound_leads", "/outbound/lists/p1/leads", "listId"),+ ("outbound_campaign_statistics", "/outbound/campaigns/p1/statistics", "campaignId"),+]+++class TestFanout:+ @pytest.mark.parametrize("endpoint, child_path, parent_key", FANOUT_CASES)+ @mock.patch(SESSION_PATCH)+ def test_child_rows_carry_the_parent_key(self, mock_session, endpoint, child_path, parent_key):+ # Child rows are keyed by their parent, so the injected field has to be the one the+ # primary key names - otherwise rows from different parents collide on merge.+ session = mock_session.return_value+ urls: list[str] = []+ _wire(session, [_page([{"id": "p1"}], current=1, pages=1), _page([{"probe": "row"}], current=1, pages=1)], urls)++ rows = _rows(+ babelforce_source(+ "services", "id", "token", endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager()+ )+ )++ assert urls[1].endswith(child_path)+ assert rows == [{"probe": "row", parent_key: "p1"}]+ assert parent_key in BABELFORCE_ENDPOINTS[endpoint].primary_keys++ @mock.patch(SESSION_PATCH)+ def test_unpaginated_fan_out_reads_one_page_without_paging_params(self, mock_session):+ # Both pages advertise more to come. The outbound endpoints document no `pagination`+ # object and take no `page`/`max` params, so neither is sent and neither is followed.+ session = mock_session.return_value+ params = _wire(session, [_page([{"id": "l1"}], current=1, pages=3), _page([{"id": "d1"}], current=1, pages=3)])++ rows = _rows(+ babelforce_source(+ "services",+ "id",+ "token",+ "outbound_leads",+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ )+ )++ assert params == [{}, {}]+ assert session.send.call_count == 2+ assert [row["id"] for row in rows] == ["d1"]++ @mock.patch(SESSION_PATCH)+ def test_fan_out_checkpoints_each_parent(self, mock_session):+ session = mock_session.return_value+ _wire(+ session,+ [+ _page([{"id": "c1"}, {"id": "c2"}], current=1, pages=1),+ _page([{"id": "e1"}], current=1, pages=1),+ _page([{"id": "e2"}], current=1, pages=1),+ ],+ )++ manager = _make_manager()+ rows = _rows(+ babelforce_source(+ "services",+ "id",+ "token",+ "conversation_events",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )+ )++ assert [row["id"] for row in rows] == ["e1", "e2"]+ assert manager.save_state.call_args.args[0].fanout["completed"] == [+ "/conversations/c1/events",+ "/conversations/c2/events",+ ]++ @mock.patch(SESSION_PATCH)+ def test_fan_out_resume_skips_completed_parents(self, mock_session):+ session = mock_session.return_value+ _wire(+ session,+ [+ _page([{"id": "c1"}, {"id": "c2"}], current=1, pages=1),+ _page([{"id": "e2"}], current=1, pages=1),+ ],+ )++ manager = _make_manager(+ BabelforceResumeConfig(+ fanout={"completed": ["/conversations/c1/events"], "current": None, "child_state": None}+ )+ )+ rows = _rows(+ babelforce_source(+ "services",+ "id",+ "token",+ "conversation_events",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )+ )++ # The parent list is re-read, but only the unfinished conversation is fetched again.+ assert [row["id"] for row in rows] == ["e2"]+ assert session.send.call_count == 2