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.

fix(warehouse-sources): stop sending PageSize on Twilio verify tables (#81492)

Kyle Swankbef204aabc21
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
index 39a5400c00b0..2c5f6ccd6461 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
@@ -1,3 +1,4 @@
+import re
import copy
import logging
from collections.abc import Callable, Iterator
@@ -67,6 +68,81 @@ def _looks_like_json(content: bytes) -> bool:
return bool(stripped) and stripped[0] in _JSON_START_BYTES
+# Keys an API conventionally uses for the machine-readable identity of an error, and for the docs
+# link explaining it. The human-readable siblings — `message`, `detail`, `reason`, `title` — are
+# deliberately absent: that's where an API puts the account, billing, or record detail that has no
+# business in a persisted, logged error message.
+_ERROR_CODE_KEYS = ("code", "error_code", "errorCode", "error", "type")
+_ERROR_LINK_KEYS = ("more_info", "documentation_url", "doc_url", "type")
+# Wrappers the error object commonly sits inside, e.g. {"errors": [{"code": ...}]}.
+_ERROR_WRAPPER_KEYS = ("error", "errors", "meta")
+# An identifier: digits, a slug, a dotted or namespaced token. Anything with a space is prose.
+_ERROR_CODE_PATTERN = re.compile(r"^[A-Za-z0-9_.:/-]{1,64}$")
+_ERROR_LINK_LIMIT = 200
+
+
+def _error_code_value(value: Any) -> Optional[str]:
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int | float):
+ return str(value)
+ if isinstance(value, str) and _ERROR_CODE_PATTERN.match(value):
+ return value
+ return None
+
+
+def _error_link_value(value: Any) -> Optional[str]:
+ if not isinstance(value, str) or len(value) > _ERROR_LINK_LIMIT:
+ return None
+ parts = urlsplit(value)
+ # A docs link is a bare https URL. A query string or userinfo would be carrying state, which is
+ # exactly what must not reach the error message.
+ if parts.scheme != "https" or parts.query or parts.fragment or "@" in parts.netloc:
+ return None
+ return value
+
+
+def _error_identity(response: Response) -> str:
+ """The machine-readable identity of an API error: its code, and the docs link explaining it.
+
+ `requests` builds its HTTPError message from the status, reason, and URL alone, so the part of
+ the response that names the cause never reaches `latest_error` and a 4xx can only be diagnosed
+ by its status code. This reads back the code and the docs link, and nothing else — no free
+ text, so no customer data, whatever the API chose to put in its error body.
+ """
+ try:
+ body = response.json()
+ except Exception:
+ return ""
+
+ candidates: list[dict[str, Any]] = []
+ if isinstance(body, dict):
+ candidates.append(body)
+ for key in _ERROR_WRAPPER_KEYS:
+ nested = body.get(key)
+ if isinstance(nested, list):
+ nested = nested[0] if nested else None
+ if isinstance(nested, dict):
+ candidates.append(nested)
+
+ parts: list[str] = []
+ for candidate in candidates:
+ for key in _ERROR_CODE_KEYS:
+ code = _error_code_value(candidate.get(key))
+ if code is not None:
+ parts.append(f"code={code}")
+ break
+ for key in _ERROR_LINK_KEYS:
+ link = _error_link_value(candidate.get(key))
+ if link is not None:
+ parts.append(link)
+ break
+ if parts:
+ break
+
+ return " ".join(parts)
+
+
def _safe_url(url: str) -> str:
"""Scheme, host, and path only — never the query string, fragment, or userinfo.
@@ -459,7 +535,13 @@ class RESTClient:
try:
response.raise_for_status()
except HTTPError as e:
- raise HTTPError(self._redact(str(e)), response=e.response, request=e.request) from None
+ message = str(e)
+ # Appended after the stock message, so non-retryable-error patterns — which match
+ # the message as a substring — keep matching.
+ identity = _error_identity(response)
+ if identity:
+ message = f"{message} | api error: {identity}"
+ raise HTTPError(self._redact(message), response=e.response, request=e.request) from None
# Parse inside the retry so a truncated/partial body is reissued like a 429/5xx
# instead of bubbling up uncaught and failing the import.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py
index 1b26eb463ecd..517658f4621e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py
@@ -88,6 +88,64 @@ class TestExceptionRedaction:
assert "***" in message
assert "400" in message
+ @parameterized.expand(
+ [
+ # Twilio's shape: the code and the docs link are what name the cause.
+ (
+ "code_and_link",
+ b'{"code": 20001, "message": "Invalid parameter",'
+ b' "more_info": "https://www.twilio.com/docs/errors/20001"}',
+ "code=20001 https://www.twilio.com/docs/errors/20001",
+ ),
+ # A slug code, wrapped one level down, as GitHub and Linode return it.
+ ("wrapped_slug", b'{"errors": [{"code": "missing_field"}]}', "code=missing_field"),
+ ("oauth_style", b'{"error": "invalid_grant"}', "code=invalid_grant"),
+ ]
+ )
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_client_error_names_the_api_error(self, _name: str, content: bytes, expected: str, MockSession) -> None:
+ mock_session = _make_client(SECRET, MockSession)
+ mock_session.send.return_value = _make_response(400, SECRET, reason="Bad Request", content=content)
+ client = RESTClient(
+ base_url="https://api.example.com",
+ auth=APIKeyAuth(api_key=SECRET, name="api_key", location="query"),
+ max_retry_attempts=1,
+ )
+ with pytest.raises(Exception) as excinfo:
+ list(client.paginate(path="/items"))
+ message = str(excinfo.value)
+ assert f"api error: {expected}" in message
+ # The stock prefix stays intact ahead of it — non-retryable-error patterns match on that.
+ assert message.startswith("400 Client Error: Bad Request for url:")
+
+ @parameterized.expand(
+ [
+ # Free text is where an API puts account, billing, and record detail. It never travels,
+ # whichever key it sits under, since this message is persisted and logged.
+ ("prose_message", b'{"message": "card ending 4021 was declined for Acme Inc"}'),
+ ("prose_reason", b'{"errors": [{"reason": "account 4021 is past due"}]}'),
+ ("prose_in_a_code_key", b'{"code": "account 4021 is past due"}'),
+ # A link that carries state is not a docs link.
+ ("link_with_query", b'{"more_info": "https://api.example.com/docs?account=4021"}'),
+ ("html_error_page", b"<html><body>account 4021 is past due</body></html>"),
+ ("empty", b""),
+ ]
+ )
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_client_error_never_carries_free_text(self, _name: str, content: bytes, MockSession) -> None:
+ mock_session = _make_client(SECRET, MockSession)
+ mock_session.send.return_value = _make_response(400, SECRET, reason="Bad Request", content=content)
+ client = RESTClient(
+ base_url="https://api.example.com",
+ auth=APIKeyAuth(api_key=SECRET, name="api_key", location="query"),
+ max_retry_attempts=1,
+ )
+ with pytest.raises(Exception) as excinfo:
+ list(client.paginate(path="/items"))
+ message = str(excinfo.value)
+ assert "4021" not in message
+ assert "api error" not in message
+
@parameterized.expand([("raw", SECRET), ("reserved_chars", SPECIAL_SECRET)])
@patch(f"{MODULE}.make_tracked_session")
def test_retryable_5xx_drops_query_so_no_secret_leaks(self, _name: str, secret: str, MockSession) -> None:
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.py
index af81aceb7630..5564182dc2d8 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
@@ -9,6 +9,11 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
TWILIO_API_HOST = "https://api.twilio.com"
TWILIO_VERIFY_HOST = "https://verify.twilio.com"
+# The ceiling the legacy Account API documents and honors. The Verify API documents the same
+# ceiling but does not honor it: its error 60373 ("Invalid page size") puts the real range at 1-25.
+# https://www.twilio.com/docs/api/errors/60373
+DEFAULT_PAGE_SIZE = 1000
+
def _datetime_field(name: str, nullable: bool = False) -> IncrementalField:
return {
@@ -50,6 +55,8 @@ class TwilioEndpointConfig:
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"
+ # Rows per page. `None` sends no `PageSize` at all, leaving Twilio on its default of 50.
+ page_size: Optional[int] = DEFAULT_PAGE_SIZE
TWILIO_ENDPOINTS: dict[str, TwilioEndpointConfig] = {
@@ -144,6 +151,10 @@ TWILIO_ENDPOINTS: dict[str, TwilioEndpointConfig] = {
primary_key="category",
),
# Verify API (verify.twilio.com/v2), not account-scoped and paginated via `meta.next_page_url`.
+ # Neither Verify endpoint sends a page size: Twilio answers `PageSize=1000` with a 400 here, and
+ # the range it actually accepts is contested between its own reference (1-1000) and its error
+ # dictionary (1-25). A page size we never send can't be rejected, so both take the server
+ # default instead of us picking a number off whichever doc is wrong.
"verification_services": TwilioEndpointConfig(
name="verification_services",
path="/v2/Services",
@@ -151,6 +162,7 @@ TWILIO_ENDPOINTS: dict[str, TwilioEndpointConfig] = {
base_url=TWILIO_VERIFY_HOST,
account_scoped=False,
partition_key="date_created",
+ page_size=None,
),
# 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.
@@ -166,6 +178,7 @@ TWILIO_ENDPOINTS: dict[str, TwilioEndpointConfig] = {
filter_operator="",
date_filter_format="datetime",
sort_mode="desc",
+ page_size=None,
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py
index 7901d7296a9b..a3163fae5ac8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py
@@ -27,6 +27,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.twilio.set
ENDPOINTS,
INCREMENTAL_FIELDS,
SHOULD_SYNC_DEFAULT,
+ TWILIO_API_HOST,
+ TWILIO_VERIFY_HOST,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.twilio.twilio import (
TwilioAuth,
@@ -137,13 +139,26 @@ Create the key in the same Twilio account as the Account SID above, in Twilio's
return CANONICAL_DESCRIPTIONS
def get_non_retryable_errors(self) -> dict[str, str | None]:
- return {
+ # Each pattern is scoped to a Twilio host so an unrelated 401 elsewhere in the same job can't
+ # false-match. The catalog spans two hosts, so both need covering.
+ unauthorized = (
# Twilio returns 401 both for a bad secret and for a valid credential that isn't allowed to
# read the resource (error 20003), and the two are indistinguishable from the status alone,
# so this message has to cover both rather than asserting the credentials are invalid.
- "401 Client Error: Unauthorized for url: https://api.twilio.com": "Twilio rejected these credentials for this table. Either the Account SID and secret are wrong, or the credential can't read this resource. A Restricted API key needs read access granted for it, and the keys table needs your Auth token or a Main API key. Fix the credential, then reconnect the source.",
- "403 Client Error: Forbidden for url: https://api.twilio.com": "Your Twilio credentials lack permission for this resource. Please check the credential's permissions and try again.",
- }
+ "Twilio rejected these credentials for this table. Either the Account SID and secret are wrong, "
+ "or the credential can't read this resource. A Restricted API key needs read access granted for "
+ "it, and the keys table needs your Auth token or a Main API key. Fix the credential, then "
+ "reconnect the source."
+ )
+ forbidden = (
+ "Your Twilio credentials lack permission for this resource. Please check the credential's "
+ "permissions and try again."
+ )
+ errors: dict[str, str | None] = {}
+ for host in (TWILIO_API_HOST, TWILIO_VERIFY_HOST):
+ errors[f"401 Client Error: Unauthorized for url: {host}"] = unauthorized
+ errors[f"403 Client Error: Forbidden for url: {host}"] = forbidden
+ return errors
def _get_auth(self, config: TwilioSourceConfig) -> TwilioAuth:
if config.auth_method.selection == "auth_token":
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.py
index 8bdcf61c6d85..da38ed34efa2 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
@@ -106,14 +106,24 @@ class TestFormatFilterDate:
class TestBuildInitialParams:
- def test_full_refresh_only_sends_page_size(self):
+ @pytest.mark.parametrize(
+ "endpoint,expected",
+ [
+ ("messages", {"PageSize": 1000}),
+ # Twilio answers PageSize=1000 on Verify with a 400, so neither Verify endpoint sends
+ # one; a page size we don't send can't be rejected.
+ ("verification_services", {}),
+ ("verification_attempts", {}),
+ ],
+ )
+ def test_full_refresh_sends_only_the_endpoints_page_size(self, endpoint: str, expected: dict[str, Any]):
params = _build_initial_params(
- TWILIO_ENDPOINTS["messages"],
+ TWILIO_ENDPOINTS[endpoint],
should_use_incremental_field=False,
db_incremental_field_last_value=None,
incremental_field=None,
)
- assert params == {"PageSize": 1000}
+ assert params == expected
def test_incremental_adds_inclusive_date_filter(self):
params = _build_initial_params(
@@ -358,7 +368,7 @@ class TestPagination:
# 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"
+ next_url = "https://verify.twilio.com/v2/Services?Page=1&PageToken=abc"
snapshots = _wire(
session,
[
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.py
index 29650e35ede2..1fbd2fce0b26 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
@@ -28,7 +28,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.twilio.set
# root-relative `next_page_uri` links, which are always served from this host.
TWILIO_BASE_URL = TWILIO_API_HOST
TWILIO_API_VERSION = "2010-04-01"
-DEFAULT_PAGE_SIZE = 1000
TwilioAuth = tuple[str, str]
@@ -138,7 +137,9 @@ def _build_initial_params(
db_incremental_field_last_value: Any,
incremental_field: str | None,
) -> dict[str, Any]:
- params: dict[str, Any] = {"PageSize": DEFAULT_PAGE_SIZE}
+ params: dict[str, Any] = {}
+ if config.page_size is not None:
+ params["PageSize"] = config.page_size
if should_use_incremental_field and db_incremental_field_last_value is not None:
# Honor the user's chosen cursor field; only filter when it maps to a server-side filter.