: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): reach Twilio Verify and Usage tables (#79102)
posthog[bot]5fb4da6f1a3c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/canonical_descriptions.pyindex e985192ecb3a..4a513c976ec2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/canonical_descriptions.py@@ -163,4 +163,49 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {price_unit="Currency of the price, as an ISO 4217 code.",),},+ "usage_records": {+ "description": "Aggregated usage and cost for a single category on the account.",+ "docs_url": "https://www.twilio.com/docs/usage/api/usage-record",+ "columns": {+ "account_sid": "SID of the account that owns the usage record.",+ "category": "Usage category the record covers (e.g. sms, calls, recordings).",+ "description": "Human-readable description of the usage category.",+ "start_date": "First date in the usage period, as YYYY-MM-DD.",+ "end_date": "Last date in the usage period, as YYYY-MM-DD.",+ "count": "Number of usage events in the period.",+ "count_unit": "Unit the count is measured in.",+ "usage": "Amount of usage in the period.",+ "usage_unit": "Unit the usage is measured in.",+ "price": "Total price of the usage in the period.",+ "price_unit": "Currency of the price, as an ISO 4217 code.",+ "uri": "URI of the resource relative to the API base.",+ },+ },+ "verification_services": {+ "description": "A Twilio Verify service that groups the settings for a set of verifications.",+ "docs_url": "https://www.twilio.com/docs/verify/api/service",+ "columns": _columns(+ date_created="Time at which the service was created (ISO 8601 format).",+ date_updated="Time at which the service was last updated (ISO 8601 format).",+ friendly_name="User-provided name shown in verification message bodies.",+ code_length="Length of the verification code generated by the service.",+ lookup_enabled="Whether phone-number lookup is enabled for the service.",+ psd2_enabled="Whether PSD2 secure customer authentication is enabled.",+ do_not_share_warning_enabled="Whether the do-not-share security warning is enabled.",+ ),+ },+ "verification_attempts": {+ "description": "A single Twilio Verify attempt to deliver a verification code to an end user.",+ "docs_url": "https://www.twilio.com/docs/verify/api/attempt",+ "columns": _columns(+ date_created="Time at which the attempt was created (ISO 8601 format).",+ date_updated="Time at which the attempt was last updated (ISO 8601 format).",+ service_sid="SID of the Verify service that generated the attempt.",+ verification_sid="SID of the verification that generated the attempt.",+ conversion_status="Whether the attempt converted (converted or unconverted).",+ channel="Channel used for the attempt (e.g. sms, call, email, whatsapp).",+ price="Cost of the attempt, with value and currency.",+ channel_data="Channel-specific data for the attempt, including delivery status.",+ ),+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.pyindex 114fd7607a79..af81aceb7630 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py@@ -1,9 +1,14 @@from dataclasses import dataclass, field-from typing import Optional+from typing import Literal, Optionalfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortModefrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+# Twilio serves resources from several hosts. The legacy 2010-04-01 Account API lives on the main host;+# newer product APIs (Verify, Messaging Services, Conversations) each sit on their own subdomain.+TWILIO_API_HOST = "https://api.twilio.com"+TWILIO_VERIFY_HOST = "https://verify.twilio.com"+def _datetime_field(name: str, nullable: bool = False) -> IncrementalField:return {@@ -18,17 +23,31 @@ def _datetime_field(name: str, nullable: bool = False) -> IncrementalField:@dataclassclass TwilioEndpointConfig:name: str- # Resource path appended after `/2010-04-01/Accounts/{account_sid}/`, e.g. "Messages.json".+ # For account-scoped endpoints, the suffix after `/2010-04-01/Accounts/{account_sid}/`, e.g.+ # "Messages.json". For endpoints on another host, the full root-relative path, e.g. "/v2/Services".path: str# JSON key wrapping the array of resources in a list response, e.g. "messages".response_key: strprimary_key: str = "sid"- # Stable, never-changing timestamp used for partitioning (Twilio returns these as RFC 2822 strings).+ # Host serving this resource. Defaults to the legacy Account API host.+ base_url: str = TWILIO_API_HOST+ # Whether `path` is prefixed with the `/2010-04-01/Accounts/{account_sid}/` Account resource path.+ # The newer subdomain APIs are not account-scoped, so they carry their full path instead.+ account_scoped: bool = True+ # Stable, never-changing timestamp used for partitioning (Twilio returns these as RFC 2822 strings on+ # the legacy API, ISO 8601 on the newer ones).partition_key: Optional[str] = Noneincremental_fields: list[IncrementalField] = field(default_factory=list)# Maps an advertised incremental field to the Twilio query-filter base name (operator appended at request time).# e.g. {"date_sent": "DateSent"} produces `DateSent>=<date>`.incremental_filter_params: dict[str, str] = field(default_factory=dict)+ # Operator appended to the filter base name. The legacy API takes an inclusive `>=` (encoded via a+ # `DateSent>` param name + `=` separator); the Verify API takes a bare `DateCreatedAfter` param, so+ # it uses no operator.+ filter_operator: str = ">"+ # How to format the incremental watermark for the filter value. The legacy API takes a day-granular+ # date; the Verify API takes an ISO 8601 GMT datetime.+ date_filter_format: Literal["date", "datetime"] = "date"# Twilio list endpoints that filter by date return rows newest-first and offer no ascending option.sort_mode: SortMode = "asc"@@ -117,6 +136,37 @@ TWILIO_ENDPOINTS: dict[str, TwilioEndpointConfig] = {response_key="transcriptions",partition_key="date_created",),+ # Aggregated usage per category on the account. Records have no `sid`; each category appears once.+ "usage_records": TwilioEndpointConfig(+ name="usage_records",+ path="Usage/Records.json",+ response_key="usage_records",+ primary_key="category",+ ),+ # Verify API (verify.twilio.com/v2), not account-scoped and paginated via `meta.next_page_url`.+ "verification_services": TwilioEndpointConfig(+ name="verification_services",+ path="/v2/Services",+ response_key="services",+ base_url=TWILIO_VERIFY_HOST,+ account_scoped=False,+ partition_key="date_created",+ ),+ # Verification attempts are retained by Twilio for only 30 days, so this is synced incrementally on+ # `DateCreatedAfter` to keep pulling the freshest data every run.+ "verification_attempts": TwilioEndpointConfig(+ name="verification_attempts",+ path="/v2/Attempts",+ response_key="attempts",+ base_url=TWILIO_VERIFY_HOST,+ account_scoped=False,+ partition_key="date_created",+ incremental_fields=[_datetime_field("date_created")],+ incremental_filter_params={"date_created": "DateCreatedAfter"},+ filter_operator="",+ date_filter_format="datetime",+ sort_mode="desc",+ ),}ENDPOINTS = tuple(TWILIO_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.pyindex 1c469706de74..8bdcf61c6d85 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.py@@ -144,6 +144,18 @@ class TestBuildInitialParams:)assert params["DateSent>"] == "2026-03-04"+ def test_verify_attempts_uses_datecreatedafter_with_iso_datetime(self):+ # Verify names the filter param outright (no `>` operator) and wants an ISO 8601 GMT datetime,+ # anchored to the start of the watermark's day so the boundary day is re-fetched and deduped.+ params = _build_initial_params(+ TWILIO_ENDPOINTS["verification_attempts"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 15, 0, tzinfo=UTC),+ incremental_field="date_created",+ )+ assert params["DateCreatedAfter"] == "2026-03-04T00:00:00Z"+ assert not any(key.endswith(">") for key in params)+def test_full_refresh_endpoint_never_filters(self):# `transcriptions` exposes no server-side filter even if incremental is requested.params = _build_initial_params(@@ -238,13 +250,20 @@ class TestValidateCredentials:assert (is_valid, msg) == (False, expected_message)assert getter.call_count == 1+ @pytest.mark.parametrize(+ "schema_name, expected_url",+ [+ ("messages", f"https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/Messages.json?PageSize=1"),+ # A Verify table is probed on its own host at its non-account path — not the Account API.+ ("verification_services", "https://verify.twilio.com/v2/Services?PageSize=1"),+ ],+ )@mock.patch(TWILIO_SESSION_PATCH)- def test_specific_schema_probes_endpoint_path(self, mock_session):+ def test_specific_schema_probes_endpoint_path(self, mock_session, schema_name, expected_url):getter = mock_session.return_value.getgetter.return_value = mock.MagicMock(status_code=200)- validate_credentials((ACCOUNT_SID, "token"), ACCOUNT_SID, "messages")- probed_url = getter.call_args.args[0]- assert probed_url == f"https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/Messages.json?PageSize=1"+ validate_credentials((ACCOUNT_SID, "token"), ACCOUNT_SID, schema_name)+ assert getter.call_args.args[0] == expected_url@pytest.mark.parametrize("schema_name, expected_message",@@ -333,6 +352,30 @@ class TestPagination:assert isinstance(saved, TwilioResumeConfig)assert saved.next_url == "https://api.twilio.com/2010-04-01/Accounts/x/Messages.json?Page=1"+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_verify_endpoint_targets_its_host_and_paginates_via_meta(self, MockSession):+ # The Verify API lives on its own host and paginates on absolute `meta.next_page_url` rather+ # than the legacy root-relative `next_page_uri`. Getting either wrong makes Verify tables+ # unreachable (wrong host) or stops the sync after page one (missed next link).+ session = MockSession.return_value+ next_url = "https://verify.twilio.com/v2/Services?PageSize=1000&Page=1&PageToken=abc"+ snapshots = _wire(+ session,+ [+ _response({"services": [{"sid": "VA1"}], "meta": {"next_page_url": next_url}}),+ _response({"services": [{"sid": "VA2"}], "meta": {"next_page_url": None}}),+ ],+ )+ manager = _make_manager()++ rows = _rows(_source("verification_services", manager))++ assert [r["sid"] for r in rows] == ["VA1", "VA2"]+ assert snapshots[0]["url"] == "https://verify.twilio.com/v2/Services"+ assert snapshots[1]["url"] == next_url+ saved = manager.save_state.call_args.args[0]+ assert saved.next_url == next_url+@mock.patch(CLIENT_SESSION_PATCH)def test_resumes_from_saved_state(self, MockSession):session = MockSession.return_value@@ -379,20 +422,24 @@ class TestPagination:class TestTwilioSource:@pytest.mark.parametrize(- "endpoint, expected_sort, expects_partition",+ "endpoint, expected_sort, expects_partition, expected_primary_key",[- ("messages", "desc", True),- ("calls", "desc", True),- ("recordings", "desc", True),- ("conferences", "desc", True),- ("addresses", "asc", False),- ("transcriptions", "asc", True),+ ("messages", "desc", True, "sid"),+ ("calls", "desc", True, "sid"),+ ("recordings", "desc", True, "sid"),+ ("conferences", "desc", True, "sid"),+ ("addresses", "asc", False, "sid"),+ ("transcriptions", "asc", True, "sid"),+ # Usage records have no `sid`; each category appears once, so it's the primary key.+ ("usage_records", "asc", False, "category"),+ ("verification_services", "asc", True, "sid"),+ ("verification_attempts", "desc", True, "sid"),],)- def test_source_response_shape(self, endpoint, expected_sort, expects_partition):+ def test_source_response_shape(self, endpoint, expected_sort, expects_partition, expected_primary_key):response = _source(endpoint, _make_manager())assert response.name == endpoint- assert response.primary_keys == ["sid"]+ assert response.primary_keys == [expected_primary_key]assert response.sort_mode == expected_sortif expects_partition:assert response.partition_mode == "datetime"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.pyindex 5c3c0aa5458b..cd8b4badf7c8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.py@@ -101,7 +101,7 @@ class TestTwilioSource:schemas = self.source.get_schemas(self.config, self.team_id)assert {s.name for s in schemas} == set(ENDPOINTS)incremental = {s.name for s in schemas if s.supports_incremental}- assert incremental == {"messages", "calls", "recordings", "conferences"}+ assert incremental == {"messages", "calls", "recordings", "conferences", "verification_attempts"}def test_incremental_schemas_advertise_their_fields(self):schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.pyindex e119dd11afbd..29650e35ede2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py@@ -19,11 +19,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.soufrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.twilio.settings import (MAIN_KEY_ONLY_ENDPOINTS,+ TWILIO_API_HOST,TWILIO_ENDPOINTS,TwilioEndpointConfig,)-TWILIO_BASE_URL = "https://api.twilio.com"+# The legacy Account API host. Kept as an alias so the legacy paginator can resolve that API's+# root-relative `next_page_uri` links, which are always served from this host.+TWILIO_BASE_URL = TWILIO_API_HOSTTWILIO_API_VERSION = "2010-04-01"DEFAULT_PAGE_SIZE = 1000@@ -70,24 +73,32 @@ class TwilioResumeConfig:class TwilioNextPageUriPaginator(BaseNextUrlPaginator):- """Follow Twilio's body-level ``next_page_uri`` link.+ """Follow Twilio's body-level next-page link, in either of the two shapes Twilio uses.- Twilio returns ``next_page_uri`` as a root-relative path (null/absent on the last page). The- self-contained next link already carries every query param (PageSize, filters, Page token), so- we resolve it to an absolute URL on the API host and let ``BaseNextUrlPaginator`` retarget the- request to it — dropping the original params so they aren't re-appended each page.+ The legacy 2010-04-01 API returns a root-relative ``next_page_uri`` (null/absent on the last+ page), which we resolve to an absolute URL on the legacy host. The newer subdomain APIs (Verify,+ Messaging Services) return an absolute ``meta.next_page_url`` instead. Either link is+ self-contained — it already carries every query param (PageSize, filters, Page token) — so we let+ ``BaseNextUrlPaginator`` retarget the request to it and drop the original params."""def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:try:- next_page_uri = response.json().get("next_page_uri")+ body = response.json()except Exception:- next_page_uri = None+ body = None+ if not isinstance(body, dict):+ self._advance_to(None)+ return++ next_page_uri = body.get("next_page_uri")if next_page_uri:- self._next_url = f"{TWILIO_BASE_URL}{next_page_uri}"- self._has_next_page = True- else:- self._has_next_page = False+ self._advance_to(f"{TWILIO_BASE_URL}{next_page_uri}")+ return++ meta = body.get("meta")+ next_page_url = meta.get("next_page_url") if isinstance(meta, dict) else None+ self._advance_to(next_page_url)def _format_filter_date(value: Any) -> str:@@ -108,6 +119,19 @@ def _format_filter_date(value: Any) -> str:raise ValueError(f"Cannot build a Twilio date filter from incremental value {value!r}") from e+def _format_filter_value(config: TwilioEndpointConfig, value: Any) -> str:+ """Format the incremental watermark for this endpoint's date filter.++ The legacy API takes a day-granular date. The Verify API's `DateCreatedAfter` wants an ISO 8601+ GMT datetime and is exclusive, so we anchor it to the start of the watermark's day: the whole+ boundary day is re-fetched and de-duplicated on `sid` rather than dropping same-instant rows.+ """+ day = _format_filter_date(value)+ if config.date_filter_format == "datetime":+ return f"{day}T00:00:00Z"+ return day++def _build_initial_params(config: TwilioEndpointConfig,should_use_incremental_field: bool,@@ -123,16 +147,25 @@ def _build_initial_params(chosen = next(iter(config.incremental_filter_params))if chosen is not None:filter_base = config.incremental_filter_params[chosen]- # The operator lives in the parameter NAME (e.g. `DateSent>`); the query separator `=`- # then yields Twilio's documented `DateSent>=<date>` (inclusive, on-or-after) form. The- # date value must stay plain — inlining the operator into the value triggers error 20001.- params[f"{filter_base}>"] = _format_filter_date(db_incremental_field_last_value)+ # On the legacy API the operator lives in the parameter NAME (e.g. `DateSent>`); the query+ # separator `=` then yields Twilio's documented `DateSent>=<date>` (inclusive, on-or-after)+ # form. The Verify API instead names its param `DateCreatedAfter` outright and takes no+ # operator. Either way the value stays plain — inlining an operator triggers error 20001.+ params[f"{filter_base}{config.filter_operator}"] = _format_filter_value(+ config, db_incremental_field_last_value+ )return paramsdef _build_resource_path(config: TwilioEndpointConfig, account_sid: str) -> str:- return f"/{TWILIO_API_VERSION}/Accounts/{account_sid}/{config.path}"+ if config.account_scoped:+ return f"/{TWILIO_API_VERSION}/Accounts/{account_sid}/{config.path}"+ return config.path+++def _endpoint_url(config: TwilioEndpointConfig, account_sid: str) -> str:+ return f"{config.base_url}{_build_resource_path(config, account_sid)}"def _unexpected_status_message(status: int) -> str:@@ -151,7 +184,7 @@ def _endpoint_denied_message(schema_name: str) -> str:def _probe_status(auth: TwilioAuth, account_sid: str, schema_name: str) -> int | None:"""GET one list resource with PageSize=1 and report the HTTP status, or None on transport failure."""config = TWILIO_ENDPOINTS[schema_name]- url = f"{TWILIO_BASE_URL}{_build_resource_path(config, account_sid)}?PageSize=1"+ url = f"{_endpoint_url(config, account_sid)}?PageSize=1"_ok, status = validate_via_probe(lambda: make_tracked_session(redact_values=(auth[1],)),url,@@ -229,7 +262,7 @@ def twilio_source(rest_config: RESTAPIConfig = {"client": {- "base_url": TWILIO_BASE_URL,+ "base_url": config.base_url,# HTTP basic auth via the framework so the secret is redacted from logs and errors."auth": {"type": "http_basic", "username": auth[0], "password": auth[1]},"paginator": TwilioNextPageUriPaginator(),