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): surface Rokt's 400 reason and stop the retry storm (#91916)

posthog[bot]9782970e4ab9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/rokt_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/rokt_ads.py
index 13dfc7ed2eef..b5fcd2ea5609 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/rokt_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/rokt_ads.py
@@ -3,7 +3,8 @@ from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
-from requests import Session
+from requests import Response, Session
+from requests.exceptions import HTTPError
from posthog.dataclasses import frozen
@@ -45,6 +46,27 @@ class RoktAdsError(Exception):
pass
+def _error_detail(response: Response) -> str:
+ """Pull Rokt's explanation of a rejected request out of the error body.
+
+ Rokt does not document its error shape, so read the keys it is likely to use and fall
+ back to the raw text. Without this the caller keeps only the bare status line and loses
+ the reason Rokt refused the request.
+ """
+ try:
+ body = response.json()
+ except ValueError:
+ return response.text.strip()[:500]
+
+ if isinstance(body, dict):
+ detail = body.get("message") or body.get("error") or body.get("detail") or body.get("errors")
+ if detail:
+ return str(detail)[:500]
+ if isinstance(body, list) and body:
+ return str(body[0])[:500]
+ return str(body)[:500]
+
+
class RoktAdsClient:
"""Talks to the Rokt Query API and keeps the client-credentials token fresh."""
@@ -103,14 +125,26 @@ class RoktAdsClient:
def _auth_headers(self) -> dict[str, str]:
return {"Authorization": f"Bearer {self.access_token()}", "Content-Type": "application/json"}
+ @staticmethod
+ def _raise_for_status(response: Response) -> None:
+ """Turn an error response into a `RoktAdsError` that carries Rokt's own explanation.
+
+ The status line stays in the message, so `get_non_retryable_errors` keeps matching it.
+ """
+ try:
+ response.raise_for_status()
+ except HTTPError as err:
+ detail = _error_detail(response)
+ raise RoktAdsError(f"{err} — {detail}" if detail else str(err)) from err
+
def get(self, path: str) -> Any:
response = self._session.get(f"{BASE_URL}{path}", headers=self._auth_headers())
- response.raise_for_status()
+ self._raise_for_status(response)
return response.json()
def post(self, path: str, body: dict[str, Any]) -> Any:
response = self._session.post(f"{BASE_URL}{path}", headers=self._auth_headers(), json=body)
- response.raise_for_status()
+ self._raise_for_status(response)
return response.json()
def list_accounts(self) -> list[dict[str, Any]]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/source.py
index 60993077a233..59ff1acac689 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/source.py
@@ -60,17 +60,20 @@ class RoktAdsSource(ResumableSource[RoktAdsSourceConfig, RoktAdsResumeConfig]):
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
+ # Pinned to the Query API path so a 400 from the OAuth token endpoint (same host) is not
+ # read as a report error and given credential-wrong copy about tables and the account ID.
+ "400 Client Error: Bad Request for url: https://api.rokt.com/v1/query/": (
+ "Rokt rejected this report request. The reason Rokt gave is in the sync logs. This can happen if "
+ "the account type does not support advertiser campaigns, if the time zone or currency code is not "
+ "recognized, or if the account is not fully configured in One Platform. Check those settings, then "
+ "reconnect."
+ ),
"401 Client Error: Unauthorized for url": "Rokt rejected these credentials. Please regenerate the app ID and app secret in One Platform and reconnect.",
"403 Client Error: Forbidden for url": "These Rokt credentials cannot read this account. Please check the account ID and the app's permissions.",
- # The same request body is sent on every retry, so a 400 from the report endpoint will
- # never become data. Likely causes: the account type does not support advertiser
- # campaigns, a time zone or currency code setting is unrecognised, or the account is
- # not fully configured in One Platform.
- "400 Client Error: Bad Request for url": (
- "Rokt rejected the report request as invalid. This can happen if the account type does not support "
- "advertiser campaigns, if the time zone or currency code setting is unrecognised, or if the account "
- "is not fully configured in One Platform. Check your account settings, or contact Rokt support."
- ),
+ # A missing account or report resource never recovers on retry. The client wraps the
+ # HTTPError in a RoktAdsError, so the shared handler's type-based 404 rule can no longer
+ # see it; match the status line the message keeps instead.
+ "404 Client Error: Not Found for url": "Rokt could not find this account. Please check the account ID, then reconnect.",
# Raised by build_report_body when the account lacks a dimension that sets the row grain.
# Dropping the dimension would silently collapse rows, so the only safe options are to
# deselect the table or ask Rokt to enable the dimension — both require user action.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/tests/test_rokt_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/tests/test_rokt_ads.py
index 4c7b8bcbf0c4..f4d8cf24dbe6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/tests/test_rokt_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/tests/test_rokt_ads.py
@@ -6,6 +6,7 @@ import pytest
from unittest.mock import MagicMock
from parameterized import parameterized
+from requests.exceptions import HTTPError
from products.warehouse_sources.backend.temporal.data_imports.sources.rokt_ads.rokt_ads import (
DateWindow,
@@ -315,3 +316,37 @@ class TestRoktAdsClient:
session.post.return_value = response
assert self._client(token_session, session).run_report("acc_1", "campaigns", {}) == []
+
+ def _error_response(self, body: Any = None, text: str = "") -> MagicMock:
+ response = MagicMock()
+ url = "https://api.rokt.com/v1/query/accounts/acc_1/campaigns/"
+ response.raise_for_status.side_effect = HTTPError(
+ f"400 Client Error: Bad Request for url: {url}", response=response
+ )
+ if body is None:
+ response.json.side_effect = ValueError
+ response.text = text
+ else:
+ response.json.return_value = body
+ return response
+
+ @parameterized.expand(
+ [
+ ({"message": "endDate cannot be in the future"}, "endDate cannot be in the future"),
+ ({"error": "unknown column datetime"}, "unknown column datetime"),
+ (None, "plain text failure"),
+ ]
+ )
+ def test_post_error_keeps_the_status_line_and_adds_rokts_explanation(self, body, expected_detail):
+ token_session = MagicMock()
+ token_session.post.return_value = self._token_response()
+ session = MagicMock()
+ session.post.return_value = self._error_response(body=body, text=expected_detail)
+
+ with pytest.raises(RoktAdsError) as exc:
+ self._client(token_session, session).post("/v1/query/accounts/acc_1/campaigns/", {})
+
+ message = str(exc.value)
+ # The status line lets get_non_retryable_errors classify this as permanent.
+ assert "400 Client Error" in message
+ assert expected_detail in message
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/tests/test_rokt_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/tests/test_rokt_ads_source.py
index 81d2a6486630..b96c126de807 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/tests/test_rokt_ads_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rokt_ads/tests/test_rokt_ads_source.py
@@ -4,8 +4,12 @@ from parameterized import parameterized
from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from products.warehouse_sources.backend.temporal.data_imports.sources.rokt_ads.rokt_ads import RoktAdsResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.rokt_ads.rokt_ads import (
+ RoktAdsError,
+ RoktAdsResumeConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.rokt_ads.settings import (
ENDPOINTS,
INCREMENTAL_LOOKBACK_SECONDS,
@@ -204,6 +208,30 @@ class TestNonRetryableErrors:
assert "Deselect this table or ask Rokt to enable those dimensions" in errors
assert "Rokt account grants none of the metrics" in errors
+ @parameterized.expand(
+ [
+ ("400 Client Error: Bad Request for url", "endDate cannot be in the future"),
+ ("404 Client Error: Not Found for url", "account not found"),
+ ]
+ )
+ def test_a_permanent_http_error_stops_the_retry_storm(self, status_line: str, reason: str):
+ # A report request Rokt rejects permanently (a bad request, or a gone account/resource) is a
+ # config problem, not a transient failure, so the pipeline must classify the RoktAdsError as
+ # non-retryable. The client wraps the HTTPError but keeps the status line in the message, so
+ # this guards that the map keys still match it. Without the 404 key the sync would retry a
+ # missing account until its budget is spent.
+ raised = RoktAdsError(f"{status_line}: https://api.rokt.com/v1/query/accounts/acc_1/campaigns/ — {reason}")
+ errors = RoktAdsSource().get_non_retryable_errors()
+ assert error_message_matches(str(raised), errors.keys())
+
+ def test_a_token_endpoint_400_is_not_read_as_a_report_error(self):
+ # The report 400 key is pinned to the Query API path, so a 400 from the OAuth token endpoint
+ # (same host) must not borrow the report copy that tells the user to check the tables and
+ # account ID when their credentials are the real fault. Un-pinning the key would re-match it.
+ token_error = "400 Client Error: Bad Request for url: https://api.rokt.com/auth/oauth2/token"
+ errors = RoktAdsSource().get_non_retryable_errors()
+ assert not error_message_matches(token_error, errors.keys())
+
class TestCanonicalDescriptions:
def test_every_table_is_documented(self):