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(callrail): add accounts, leads, page_views and lead_timelines (#101620)

Tom Owers040c0ebfc4f3
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 db622260dd2c..9ebd37d3fe86 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
@@ -1180,14 +1180,14 @@ Note: developer.calendly.com is a Gatsby shell with no fetchable spec; the real
## CallRail — gaps
-Today (7): `calls`, `companies`, `form_submissions`, `tags`, `text_messages`, `trackers`, `users`
+Today (11): `accounts`, `calls`, `companies`, `form_submissions`, `lead_timelines`, `leads`, `page_views`, `tags`, `text_messages`, `trackers`, `users`
Diffed against: <https://apidocs.callrail.com/>
-- [ ] `leads (/a/{account_id}/leads.json)` — the conversion object CallRail exists to produce — currently calls and form submissions are synced but not the leads derived from them (high)
-- [ ] `accounts (/a.json)` — lookup resolving the account_id every other resource is scoped under; required for multi-account (agency) reporting (high)
-- [ ] `page_views (/a/{account_id}/calls/{call_id}/page_views.json)` — per-call visitor page-view journey — the attribution path behind each tracked call (high)
-- [ ] `lead_timelines (/a/{account_id}/leads/{id}/timeline.json)` — state/transition history for a lead across calls, texts, and forms (medium)
+- [x] `leads (/a/{account_id}/leads.json)` — the conversion object CallRail exists to produce — currently calls and form submissions are synced but not the leads derived from them (high)
+- [x] `accounts (/a.json)` — lookup resolving the account_id every other resource is scoped under; required for multi-account (agency) reporting (high)
+- [x] `page_views (/a/{account_id}/calls/{call_id}/page_views.json)` — per-call visitor page-view journey — the attribution path behind each tracked call (high)
+- [x] `lead_timelines (/a/{account_id}/leads/{id}/timeline.json)` — state/transition history for a lead across calls, texts, and forms (medium)
- [ ] `sms_threads (/a/{account_id}/sms_threads.json)` — thread-level SMS conversations, the parent grain the text_messages table hangs off (medium)
- [ ] `calls summary and timeseries (/a/{account_id}/calls/summary.json, /calls/timeseries.json)` — vendor-computed call volume breakdowns by source and period, matching what the CallRail UI reports (medium)
- [ ] `form_submissions summary (/a/{account_id}/form_submissions/summary.json)` — vendor-computed form conversion aggregates aligned with the call summary (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/callrail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/callrail.py
index 5131c2c12d06..efddcc514878 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/callrail.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/callrail.py
@@ -1,42 +1,52 @@
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Iterable, Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional, cast
-from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.settings import CALLRAIL_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.settings import (
+ CALLRAIL_ENDPOINTS,
+ PER_PAGE,
+ CallRailEndpointConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
Endpoint,
RESTAPIConfig,
rest_api_resource,
)
+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 (
PageNumberPaginator,
SinglePagePaginator,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ApiKeyAuthConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ApiKeyAuthConfig,
+ ClientConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
CALLRAIL_BASE_URL = "https://api.callrail.com/v3"
-# Max allowed by the API. Larger pages mean fewer requests against the per-account hourly/daily
-# rate limits.
-PER_PAGE = 250
-
# Hard cap so a runaway pagination loop (e.g. the API never signaling the last page) can't scan
# forever. 250 rows/page * this cap bounds a single endpoint sync.
MAX_PAGES = 100_000
[email protected](frozen=True)
class CallRailResumeConfig:
# The resolved account whose data we're pulling. Pinned across a resume so re-resolution can't
- # silently switch accounts mid-sync (an API key can see more than one account).
+ # silently switch accounts mid-sync (an API key can see more than one account). Empty for
+ # /a.json, which is not scoped to an account.
account_id: str
- # Next 1-indexed page to fetch.
- page: int
+ # Next 1-indexed page to fetch, for an endpoint listed once per account.
+ page: Optional[int] = None
+ # Fan-out progress for an endpoint reached once per parent row: which parents are done, which
+ # one was in flight, and that parent's page cursor. Shape owned by the shared fan-out helper.
+ fanout_state: Optional[dict[str, Any]] = None
def _get_headers(api_key: str) -> dict[str, str]:
@@ -58,6 +68,38 @@ def _auth_config(api_key: str) -> ApiKeyAuthConfig:
}
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": CALLRAIL_BASE_URL,
+ "headers": {"Accept": "application/json"},
+ "auth": _auth_config(api_key),
+ # Call and lead bodies carry caller names and phone numbers, SMS message text and submitted
+ # form field values — free text the name-based sample scrubbers aren't guaranteed to catch.
+ # Keep raw bodies out of HTTP sample capture even where an operator enables it. Requests are
+ # still metered and logged.
+ "capture": False,
+ }
+
+
+def _sort_params(config: CallRailEndpointConfig) -> dict[str, Any]:
+ # Ascending on the cursor field so the pipeline watermark advances safely and full-refresh
+ # pages don't skip/duplicate rows inserted mid-sync.
+ if not config.sort_field:
+ return {}
+ return {"sort": config.sort_field, "order": "asc"}
+
+
+def _paginator() -> PageNumberPaginator:
+ # `total_pages` in the body is the number of PAGES, so pagination stops after the last page
+ # without paying an extra empty-page request.
+ return PageNumberPaginator(
+ base_page=1,
+ page_param="page",
+ total_path="total_pages",
+ maximum_page=MAX_PAGES,
+ )
+
+
def _format_start_date(value: Any) -> str | None:
"""Format an incremental cursor value as the YYYY-MM-DD `start_date` the API filters on.
@@ -77,19 +119,15 @@ def _format_start_date(value: Any) -> str | None:
def resolve_account_id(api_key: str, team_id: int, job_id: str, account_id: str | None = None) -> str:
"""Return the account id to scope data requests to.
- CallRail data endpoints are all nested under /v3/a/{account_id}/, so we must resolve one first.
- If the user supplied one we trust it; otherwise we use the first account the key can see.
+ Most CallRail data endpoints are nested under /v3/a/{account_id}/, so we must resolve one
+ first. If the user supplied one we trust it; otherwise we use the first account the key sees.
"""
if account_id:
return account_id
# We only ever read the first account, so request a single row like validate_credentials does.
accounts_config: RESTAPIConfig = {
- "client": {
- "base_url": CALLRAIL_BASE_URL,
- "headers": {"Accept": "application/json"},
- "auth": _auth_config(api_key),
- },
+ "client": _client_config(api_key),
"resources": [
{
"name": "accounts",
@@ -118,6 +156,59 @@ def validate_credentials(api_key: str) -> bool:
return ok
+def _fanout_rows(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CallRailResumeConfig],
+ resolved_account_id: str,
+ initial_fanout_state: Optional[dict[str, Any]],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterable[list[dict[str, Any]]]:
+ """Walk a parent listing and pull the child resource once per parent row.
+
+ Neither child resource exposes a server-side date filter, so the request set is bounded by the
+ parent listing rather than by a time window. The child still merges on its primary key, which
+ is what keeps rows that fall outside a single run's parent window.
+ """
+ config = CALLRAIL_ENDPOINTS[endpoint]
+ assert config.fanout is not None
+ parent_config = CALLRAIL_ENDPOINTS[config.fanout.parent_name]
+
+ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(
+ CallRailResumeConfig(account_id=resolved_account_id, fanout_state=state)
+ )
+
+ return cast(
+ Iterable[list[dict[str, Any]]],
+ build_dependent_resource(
+ endpoint_configs=CALLRAIL_ENDPOINTS,
+ child_endpoint=endpoint,
+ # The parent's sort comes from its own endpoint config rather than being repeated here,
+ # so the two cannot drift.
+ fanout=dataclasses.replace(config.fanout, parent_params=_sort_params(parent_config)),
+ client_config=_client_config(api_key),
+ path_format_values={"account_id": resolved_account_id},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ # No server-side date filter on either child, so there is no request window to build.
+ incremental_config_factory=lambda _cursor_path: None,
+ page_size_param="per_page",
+ child_params_extra=_sort_params(config),
+ parent_endpoint_extra={"paginator": _paginator(), "data_selector": parent_config.response_key},
+ child_endpoint_extra={"paginator": _paginator(), "data_selector": config.response_key},
+ resume_hook=save_fanout_checkpoint,
+ initial_paginator_state=initial_fanout_state,
+ ),
+ )
+
+
def get_rows(
api_key: str,
endpoint: str,
@@ -131,34 +222,38 @@ def get_rows(
config = CALLRAIL_ENDPOINTS[endpoint]
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- initial_paginator_state: Optional[dict[str, Any]] = None
if resume is not None:
resolved_account_id = resume.account_id
- initial_paginator_state = {"page": resume.page}
- else:
+ elif config.requires_account:
resolved_account_id = resolve_account_id(api_key, team_id, job_id, account_id)
+ else:
+ resolved_account_id = ""
+
+ if config.fanout is not None:
+ yield from _fanout_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ team_id=team_id,
+ job_id=job_id,
+ resumable_source_manager=resumable_source_manager,
+ resolved_account_id=resolved_account_id,
+ initial_fanout_state=resume.fanout_state if resume is not None else None,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ return
- params: dict[str, Any] = {"per_page": PER_PAGE}
- if config.sort_field:
- # Ascending on the cursor field so the pipeline watermark advances safely and full-refresh
- # pages don't skip/duplicate rows inserted mid-sync.
- params["sort"] = config.sort_field
- params["order"] = "asc"
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resume is not None and resume.page is not None:
+ initial_paginator_state = {"page": resume.page}
endpoint_config: Endpoint = {
- "path": f"/a/{resolved_account_id}{config.path}",
- "params": params,
+ "path": config.path.replace("{account_id}", resolved_account_id),
+ "params": {"per_page": PER_PAGE, **_sort_params(config)},
# Key the list lives under in the JSON envelope; a missing key reads as an empty page and
# ends pagination, matching the API's "no more data" signal.
"data_selector": config.response_key,
- # `total_pages` in the body is the number of PAGES, so pagination stops after the last page
- # without paying an extra empty-page request.
- "paginator": PageNumberPaginator(
- base_page=1,
- page_param="page",
- total_path="total_pages",
- maximum_page=MAX_PAGES,
- ),
+ "paginator": _paginator(),
}
if config.supports_incremental and should_use_incremental_field:
endpoint_config["incremental"] = {
@@ -168,11 +263,7 @@ def get_rows(
}
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": CALLRAIL_BASE_URL,
- "headers": {"Accept": "application/json"},
- "auth": _auth_config(api_key),
- },
+ "client": _client_config(api_key),
"resources": [{"name": endpoint, "endpoint": endpoint_config}],
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/canonical_descriptions.py
index b1ce9f7cf33f..378a556d3f18 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/canonical_descriptions.py
@@ -6,6 +6,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
# the endpoint name from ENDPOINTS / get_schemas. Partial coverage is fine — anything not listed
# here falls back to LLM enrichment using the docs_url and column data types.
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "accounts": {
+ "description": "CallRail accounts the API key can reach. The top-level object every other resource is scoped under, and the lookup for multi-account (agency) reporting.",
+ "docs_url": "https://apidocs.callrail.com/#accounts",
+ "columns": {
+ "id": "Unique identifier for the account.",
+ "name": "Name of the account.",
+ "outbound_recording_enabled": "Whether recording is enabled for outbound calls placed from the CallRail web application.",
+ "hipaa_account": "Whether the account is a HIPAA account.",
+ },
+ },
"calls": {
"description": "Tracked phone calls captured by CallRail, including caller details, attribution source, and outcome.",
"docs_url": "https://apidocs.callrail.com/#calls",
@@ -57,6 +67,56 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"first_form": "Whether this was the person's first form submission.",
},
},
+ "leads": {
+ "description": "Leads in the CallRail account: the people derived from tracked calls, texts, and form submissions.",
+ "docs_url": "https://apidocs.callrail.com/#leads",
+ "columns": {
+ "id": "Unique identifier for the lead.",
+ "name": "Full name of the lead.",
+ "phone": "Phone number of the lead, in E.164 format.",
+ "email": "Email address of the lead.",
+ "created_at": "When the lead was created (ISO 8601, UTC).",
+ "company_id": "Identifier of the company the lead belongs to.",
+ "company_name": "Name of the company the lead belongs to.",
+ },
+ },
+ "lead_timelines": {
+ "description": "Timeline of every event and interaction recorded for a lead, one row per event, across calls, form submissions, texts, chats, and milestones. Synced once per lead.",
+ "docs_url": "https://apidocs.callrail.com/#lead-timelines",
+ "columns": {
+ "lead_id": "Identifier of the lead this event belongs to. Injected from the parent lead.",
+ "type": "Kind of event: call, form_submission, sms, chat, or milestone.",
+ "id": "Identifier of the underlying object the event refers to, unique within the lead's timeline.",
+ "event_date": "When the event happened (ISO 8601).",
+ "customer_name": "Name of the customer on a call event.",
+ "customer_phone_number": "Phone number of the customer, in E.164 format.",
+ "direction": "Whether a call event was inbound or outbound.",
+ "duration": "Length of a call event in seconds.",
+ "answered": "Whether a call event was answered.",
+ "form_name": "Name of the form on a form_submission event.",
+ "form_url": "URL of the page the form was submitted from.",
+ "form_fields": "Values submitted with the form.",
+ "form_submission_url": "URL the visitor landed on after submitting the form.",
+ "message_content": "Body of an sms event.",
+ "message_phone_number": "Phone number an sms event was exchanged with.",
+ "message_type": "Kind of message on an sms event.",
+ "thread_id": "Identifier of the SMS thread an sms event belongs to.",
+ "chat_subject": "Subject of a chat event.",
+ "chat_id": "Identifier of the chat.",
+ "milestone_type": "Which milestone a milestone event marks, e.g. lead_created.",
+ "touchpoint_type": "Attribution touchpoint behind the event, e.g. organic_search or paid_search.",
+ },
+ },
+ "page_views": {
+ "description": "Browsing history behind a tracked call: the pages a visitor viewed before dialing, newest first. Only recorded for calls placed to a session tracker, and synced once per call.",
+ "docs_url": "https://apidocs.callrail.com/#page-views",
+ "columns": {
+ "call_id": "Identifier of the call this page view belongs to. Injected from the parent call.",
+ "referrer_url": "URL of the referring source or website the visitor was previously viewing.",
+ "page_url": "URL the visitor was viewing, either before navigating on or as the last page seen before calling the tracking number.",
+ "created_at": "When the page view was recorded (ISO 8601).",
+ },
+ },
"text_messages": {
"description": "SMS conversations between callers and the business, captured by CallRail.",
"docs_url": "https://apidocs.callrail.com/#text-messages",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/settings.py
index 401424948154..d6a70881161b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/settings.py
@@ -1,13 +1,27 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+# Max allowed by the API. Larger pages mean fewer requests against the per-account hourly/daily
+# rate limits (1,000/hour and 10,000/day across the whole account).
+PER_PAGE = 250
-@dataclass
+# A parent row deleted or merged between the parent listing and this child fetch answers 404;
+# ignoring it keeps the fan-out going instead of failing the whole table. Page views also only
+# exist for calls placed to a session tracker.
+_CHILD_404_IGNORE: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
+
+
+@dataclass(frozen=True)
class CallRailEndpointConfig:
name: str
- # Path under the account-scoped base (https://api.callrail.com/v3/a/{account_id}).
+ # Full path under https://api.callrail.com/v3, with `{account_id}` left for the resolved
+ # account. Fan-out children also carry the parent's `{...}` placeholder, bound per parent row.
path: str
# Key the list lives under in the JSON envelope, e.g. {"calls": [...], "total_pages": N}.
response_key: str
@@ -24,9 +38,45 @@ class CallRailEndpointConfig:
supports_incremental: bool = False
primary_keys: list[str] = field(default_factory=lambda: ["id"])
should_sync_default: bool = True
+ # Set for endpoints reached once per parent row rather than once per account.
+ fanout: Optional[DependentEndpointConfig] = None
+
+ @property
+ def requires_account(self) -> bool:
+ return "{account_id}" in self.path
+
+ @property
+ def page_size(self) -> int:
+ return PER_PAGE
+
+ @property
+ def default_incremental_field(self) -> Optional[str]:
+ return self.incremental_fields[0]["field"] if self.incremental_fields else None
+
+
+_PAGE_VIEWS_FANOUT = DependentEndpointConfig(
+ parent_name="calls",
+ resolve_param="call_id",
+ resolve_field="id",
+ # Page-view rows carry no id of their own, so the parent call id is both the only link back to
+ # the call and part of the primary key.
+ include_from_parent=["id"],
+ parent_field_renames={"id": "call_id"},
+ child_response_actions=_CHILD_404_IGNORE,
+)
+
+_LEAD_TIMELINE_FANOUT = DependentEndpointConfig(
+ parent_name="leads",
+ resolve_param="lead_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "lead_id"},
+ child_response_actions=_CHILD_404_IGNORE,
+)
-# CallRail v3 REST API. All data endpoints are nested under /v3/a/{account_id}/.
+# CallRail v3 REST API. Most data endpoints are nested under /v3/a/{account_id}/; the account
+# listing itself sits at /v3/a.json.
#
# Incremental support is set only for resources whose list endpoint documents a server-side
# `start_date` date filter that narrows on a stable timestamp (Calls -> start_time,
@@ -35,9 +85,18 @@ class CallRailEndpointConfig:
# The remaining resources are mutable configuration objects or lack a usable server-side date
# filter, so they ship full refresh only.
CALLRAIL_ENDPOINTS: dict[str, CallRailEndpointConfig] = {
+ "accounts": CallRailEndpointConfig(
+ name="accounts",
+ path="/a.json",
+ response_key="accounts",
+ # Accounts carry no timestamp, so there is nothing to partition on. `name` is the only
+ # sortable field, which is enough to keep pagination stable.
+ sort_field="name",
+ incremental_fields=[],
+ ),
"calls": CallRailEndpointConfig(
name="calls",
- path="/calls.json",
+ path="/a/{account_id}/calls.json",
response_key="calls",
partition_key="start_time",
sort_field="start_time",
@@ -53,14 +112,14 @@ CALLRAIL_ENDPOINTS: dict[str, CallRailEndpointConfig] = {
),
"companies": CallRailEndpointConfig(
name="companies",
- path="/companies.json",
+ path="/a/{account_id}/companies.json",
response_key="companies",
partition_key="created_at",
incremental_fields=[],
),
"form_submissions": CallRailEndpointConfig(
name="form_submissions",
- path="/form_submissions.json",
+ path="/a/{account_id}/form_submissions.json",
response_key="form_submissions",
partition_key="submitted_at",
sort_field="submitted_at",
@@ -74,28 +133,89 @@ CALLRAIL_ENDPOINTS: dict[str, CallRailEndpointConfig] = {
},
],
),
+ "leads": CallRailEndpointConfig(
+ name="leads",
+ path="/a/{account_id}/leads.json",
+ response_key="leads",
+ partition_key="created_at",
+ # Sortable, but not filterable: CallRail's date filters cover calls, the call summary, and
+ # conversations only, so leads is full refresh.
+ sort_field="created_at",
+ incremental_fields=[],
+ ),
+ "lead_timelines": CallRailEndpointConfig(
+ name="lead_timelines",
+ path="/a/{account_id}/leads/{lead_id}/timeline.json",
+ # The envelope also carries a `lead` summary object; the timeline events are the row grain.
+ response_key="timeline",
+ partition_key="event_date",
+ sort_field="event_date",
+ # Timeline event ids are only documented as unique within their lead's timeline, and one
+ # lead's history can mix a call, a form submission and a milestone, so the key spans all
+ # three parts.
+ primary_keys=["lead_id", "type", "id"],
+ fanout=_LEAD_TIMELINE_FANOUT,
+ # One request per lead against a 1,000/hour account-wide budget, so leave it to the user
+ # to opt in rather than enabling it on every new connection.
+ should_sync_default=False,
+ # `supports_incremental` stays false: the endpoint takes no date filter, so the request set
+ # is bounded by the parent listing. The cursor exists so the table merges on its primary key
+ # instead of being replaced, which keeps the events that fall outside a run's parent window.
+ incremental_fields=[
+ {
+ "label": "event_date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "event_date",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "page_views": CallRailEndpointConfig(
+ name="page_views",
+ path="/a/{account_id}/calls/{call_id}/page_views.json",
+ response_key="page_views",
+ partition_key="created_at",
+ # Page-view rows have no id of their own. This is the most selective key the response
+ # offers; two views of the same page within the same second would collapse into one row.
+ primary_keys=["call_id", "created_at", "page_url"],
+ fanout=_PAGE_VIEWS_FANOUT,
+ # One request per call against a 1,000/hour account-wide budget, so leave it to the user
+ # to opt in rather than enabling it on every new connection.
+ should_sync_default=False,
+ # Same as lead_timelines: no date filter on the endpoint, so the cursor only buys a merge.
+ # It matters more here because the parent calls listing defaults to CallRail's `recent`
+ # window (the last 7 days), so a replace would leave the table holding only that week.
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
"text_messages": CallRailEndpointConfig(
name="text_messages",
# Returns SMS conversations under the "conversations" key.
- path="/text-messages.json",
+ path="/a/{account_id}/text-messages.json",
response_key="conversations",
incremental_fields=[],
),
"trackers": CallRailEndpointConfig(
name="trackers",
- path="/trackers.json",
+ path="/a/{account_id}/trackers.json",
response_key="trackers",
incremental_fields=[],
),
"users": CallRailEndpointConfig(
name="users",
- path="/users.json",
+ path="/a/{account_id}/users.json",
response_key="users",
incremental_fields=[],
),
"tags": CallRailEndpointConfig(
name="tags",
- path="/tags.json",
+ path="/a/{account_id}/tags.json",
response_key="tags",
incremental_fields=[],
),
@@ -106,3 +226,9 @@ ENDPOINTS = tuple(CALLRAIL_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in CALLRAIL_ENDPOINTS.items()
}
+
+SHOULD_SYNC_DEFAULT: dict[str, bool] = {name: config.should_sync_default for name, config in CALLRAIL_ENDPOINTS.items()}
+
+# A fan-out child accumulates one row per parent row per sync under append, so these tables offer
+# incremental merge only.
+MERGE_ONLY = tuple(name for name, config in CALLRAIL_ENDPOINTS.items() if config.fanout is not None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/source.py
index 8278b86bf6bf..040d9cb70934 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/source.py
@@ -15,6 +15,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.c
from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.settings import (
ENDPOINTS,
INCREMENTAL_FIELDS,
+ MERGE_ONLY,
+ SHOULD_SYNC_DEFAULT,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
@@ -113,7 +115,13 @@ Leave **Account ID** blank to use the first account your key can access, or set
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ merge_only=MERGE_ONLY,
+ should_sync_default=SHOULD_SYNC_DEFAULT,
+ )
def validate_credentials(
self,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail.py
index 2c38e4b59cce..0ca4ead0bdac 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail.py
@@ -307,7 +307,7 @@ class TestCallRailSourceResponse:
def test_partition_keys_are_stable_creation_fields(self, config: Any) -> None:
# Never partition on a mutable field; only stable creation/start timestamps are allowed.
if config.partition_key:
- assert config.partition_key in {"start_time", "submitted_at", "created_at"}
+ assert config.partition_key in {"start_time", "submitted_at", "created_at", "event_date"}
@pytest.mark.parametrize("config", list(CALLRAIL_ENDPOINTS.values()))
def test_incremental_endpoints_have_a_sort_field(self, config: Any) -> None:
@@ -315,3 +315,175 @@ class TestCallRailSourceResponse:
if config.supports_incremental:
assert config.sort_field is not None
assert config.incremental_fields
+
+
+class TestAccountsEndpoint:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_accounts_needs_no_account_resolution(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect("accounts", [_page("accounts", [{"id": "ACC1"}], total_pages=1)], MockSession)
+
+ # /a.json is the one endpoint not nested under an account, so the listing is the only request.
+ assert len(snapshots) == 1
+ assert snapshots[0]["url"].endswith("/a.json")
+ assert snapshots[0]["params"]["sort"] == "name"
+
+
+class TestLeadsEndpoint:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_leads_sorts_ascending_and_never_sends_a_date_filter(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect(
+ "leads",
+ [_page("leads", [{"id": "L1"}], total_pages=1)],
+ MockSession,
+ account_id="ACC",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ assert snapshots[0]["params"]["sort"] == "created_at"
+ assert snapshots[0]["params"]["order"] == "asc"
+ # CallRail's date filters cover calls, the call summary, and conversations only.
+ assert "start_date" not in snapshots[0]["params"]
+
+
+def _page_view(page_url: str, created_at: str) -> dict[str, Any]:
+ return {"referrer_url": "https://example.com/", "page_url": page_url, "created_at": created_at}
+
+
+_CALLS_PARENT = [{"id": "C1"}, {"id": "C2"}]
+_C1_PATH = "/a/ACC/calls/C1/page_views.json"
+_C2_PATH = "/a/ACC/calls/C2/page_views.json"
+
+
+class TestFanoutEndpoints:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_page_views_fan_out_injects_the_parent_call_id(self, MockSession: mock.MagicMock) -> None:
+ batches, snapshots, _ = _collect(
+ "page_views",
+ [
+ _page("calls", _CALLS_PARENT, total_pages=1),
+ _page("page_views", [_page_view("https://example.com/a", "2026-01-01T00:00:00Z")], total_pages=1),
+ _page("page_views", [_page_view("https://example.com/b", "2026-01-02T00:00:00Z")], total_pages=1),
+ ],
+ MockSession,
+ account_id="ACC",
+ )
+
+ rows = [row for batch in batches for row in batch]
+ assert [row["call_id"] for row in rows] == ["C1", "C2"]
+ # Page-view rows carry no id, so call_id is part of the primary key and must not stay
+ # under the framework's `_{parent}_{field}` prefix.
+ assert not any(key.startswith("_calls_") for row in rows for key in row)
+ assert _C1_PATH in snapshots[1]["url"]
+ assert _C2_PATH in snapshots[2]["url"]
+ assert snapshots[1]["params"]["per_page"] == 250
+ # The parent listing walks ascending by its own cursor field so its pagination is stable.
+ assert snapshots[0]["params"]["sort"] == "start_time"
+ # The endpoint takes no sort param of its own.
+ assert "sort" not in snapshots[1]["params"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fan_out_child_never_sends_a_date_filter(self, MockSession: mock.MagicMock) -> None:
+ # The child endpoints take no date filter, so an incremental sync bounds its requests
+ # through the parent listing and relies on the merge to keep earlier rows.
+ _, snapshots, _ = _collect(
+ "page_views",
+ [
+ _page("calls", [{"id": "C1"}], total_pages=1),
+ _page("page_views", [_page_view("https://example.com/a", "2026-01-01T00:00:00Z")], total_pages=1),
+ ],
+ MockSession,
+ account_id="ACC",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ assert "start_date" not in snapshots[1]["params"]
+ assert "created_at" not in snapshots[1]["params"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_lead_timelines_fan_out_reads_the_timeline_key(self, MockSession: mock.MagicMock) -> None:
+ batches, snapshots, _ = _collect(
+ "lead_timelines",
+ [
+ _page("leads", [{"id": "L1"}], total_pages=1),
+ _response(
+ {
+ "lead": {"customer_name": "Ignored summary"},
+ "timeline": [{"type": "call", "id": "CALL1", "event_date": "2026-01-01T00:00:00Z"}],
+ "total_pages": 1,
+ }
+ ),
+ ],
+ MockSession,
+ account_id="ACC",
+ )
+
+ rows = [row for batch in batches for row in batch]
+ # The envelope's `lead` summary object is not the row grain; the timeline events are.
+ assert rows == [
+ {"type": "call", "id": "CALL1", "event_date": "2026-01-01T00:00:00Z", "lead_id": "L1"},
+ ]
+ assert "/a/ACC/leads/L1/timeline.json" in snapshots[1]["url"]
+ assert snapshots[1]["params"]["sort"] == "event_date"
+ assert snapshots[1]["params"]["order"] == "asc"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fan_out_checkpoints_each_completed_parent(self, MockSession: mock.MagicMock) -> None:
+ _, _, manager = _collect(
+ "page_views",
+ [
+ _page("calls", _CALLS_PARENT, total_pages=1),
+ _page("page_views", [_page_view("https://example.com/a", "2026-01-01T00:00:00Z")], total_pages=1),
+ _page("page_views", [_page_view("https://example.com/b", "2026-01-02T00:00:00Z")], total_pages=1),
+ ],
+ MockSession,
+ account_id="ACC",
+ )
+
+ states = [call.args[0] for call in manager.save_state.call_args_list]
+ assert all(state.account_id == "ACC" and state.page is None for state in states)
+ assert states[-1].fanout_state == {"completed": [_C1_PATH, _C2_PATH], "current": None, "child_state": None}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fan_out_resume_skips_completed_parents(self, MockSession: mock.MagicMock) -> None:
+ resume = CallRailResumeConfig(
+ account_id="ACC",
+ fanout_state={"completed": [_C1_PATH], "current": None, "child_state": None},
+ )
+ batches, snapshots, _ = _collect(
+ "page_views",
+ [
+ _page("calls", _CALLS_PARENT, total_pages=1),
+ _page("page_views", [_page_view("https://example.com/b", "2026-01-02T00:00:00Z")], total_pages=1),
+ ],
+ MockSession,
+ manager=_make_manager(resume),
+ account_id="OTHER",
+ )
+
+ # The parent listing is always re-walked, but C1 is already done, so only C2 is fetched —
+ # against the account pinned in the saved state, not the one passed in.
+ assert [row["call_id"] for batch in batches for row in batch] == ["C2"]
+ assert len(snapshots) == 2
+ assert _C2_PATH in snapshots[1]["url"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_child_404_does_not_sink_the_fan_out(self, MockSession: mock.MagicMock) -> None:
+ # Page views only exist for calls placed to a session tracker, and a call can be deleted
+ # between the parent listing and this fetch.
+ missing = Response()
+ missing.status_code = 404
+ missing._content = b"{}"
+ batches, _, _ = _collect(
+ "page_views",
+ [
+ _page("calls", _CALLS_PARENT, total_pages=1),
+ missing,
+ _page("page_views", [_page_view("https://example.com/b", "2026-01-02T00:00:00Z")], total_pages=1),
+ ],
+ MockSession,
+ account_id="ACC",
+ )
+
+ assert [row["call_id"] for batch in batches for row in batch] == ["C2"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail_source.py
index 5a21485d1a79..717a26f2bd13 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail_source.py
@@ -39,11 +39,22 @@ class TestCallRailSource:
non_retryable_errors = self.source.get_non_retryable_errors()
assert not any(key in other_error for key in non_retryable_errors)
- def test_only_documented_filter_endpoints_are_incremental(self) -> None:
+ def test_only_account_listings_with_a_date_filter_offer_append(self) -> None:
schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
incremental = {name for name, s in schemas.items() if s.supports_incremental}
- # Only calls and form_submissions expose CallRail's server-side `start_date` filter.
- assert incremental == {"calls", "form_submissions"}
+ # calls and form_submissions expose CallRail's server-side `start_date` filter; the two
+ # fan-out tables carry a cursor purely so they merge rather than replace.
+ assert incremental == {"calls", "form_submissions", "page_views", "lead_timelines"}
+ # Appending a fan-out child would re-add every parent's rows on each sync.
+ assert {name for name, s in schemas.items() if s.supports_append} == {"calls", "form_submissions"}
+
+ def test_per_call_and_per_lead_tables_are_not_enabled_by_default(self) -> None:
+ # Both fan out one request per parent row against an account-wide budget of 1,000
+ # requests/hour, so enabling them has to be the user's choice.
+ off_by_default = {
+ s.name for s in self.source.get_schemas(self.config, self.team_id) if not s.should_sync_default
+ }
+ assert off_by_default == {"page_views", "lead_timelines"}
@pytest.mark.parametrize(
"mock_return, expected_valid, expected_message",