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(openai-ads): say what to do when a key is rejected at setup (#102798)

Tom Owers4fa58c8f1c52
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py
index 5787dc019d8d..1894f27e4e70 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py
@@ -27,6 +27,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads
OpenAIAdsEndpointConfig,
)
+# Shared with the source's 401 and 403 entries in `get_non_retryable_errors` so a rejected key reads
+# the same whether it surfaces while the source is being set up or during a later sync.
+INVALID_CREDENTIALS_ERROR = (
+ "Your OpenAI Ads API key is invalid or has been revoked. Create a new API key in the Settings "
+ "tab of OpenAI Ads Manager, then reconnect."
+)
+NO_ACCESS_ERROR = (
+ "Your OpenAI Ads API key does not have access to this ad account. Create a key for this ad "
+ "account in the Settings tab of OpenAI Ads Manager, then reconnect."
+)
+UNREACHABLE_ERROR = (
+ "Couldn't reach OpenAI Ads to validate your API key. This is usually temporary, so try again in a moment."
+)
+
# Floor for the insights window on a full refresh. OpenAI Ads launched to advertisers in 2026, so
# no reporting data can predate this; the whole window rides a single date_range request, so a
# generous floor costs nothing while staying within the API's 5-year time-range bound.
@@ -104,17 +118,23 @@ def _headers() -> dict[str, str]:
return {"Accept": "application/json"}
-def validate_credentials(api_key: str) -> bool:
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
# One cheap probe against the campaigns list confirms the key is genuine. 200 => valid.
# 403 => a real key the API recognizes but with restricted access; accept it at create time
# (sync-time 403s are caught by get_non_retryable_errors). 401 => bad key.
- ok, _status = validate_via_probe(
+ ok, status = validate_via_probe(
lambda: make_tracked_session(redact_values=(api_key,)),
f"{OPENAI_ADS_BASE_URL}/v1/campaigns?limit=1",
headers={"Authorization": f"Bearer {api_key}", **_headers()},
ok_statuses=(200, 403),
)
- return ok
+ if ok:
+ return True, None
+ if status == 401:
+ return False, INVALID_CREDENTIALS_ERROR
+ # Anything else — a timeout, connection error, rate limit, or 5xx — says nothing about the key,
+ # so point at retrying rather than sending the user off to replace a key that works.
+ return False, UNREACHABLE_ERROR
def _to_utc_date(value: Any) -> date:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/source.py
index df4fbad30e3c..c747981993d4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/source.py
@@ -19,6 +19,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
OpenAIAdsSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.openai_ads import (
+ INVALID_CREDENTIALS_ERROR,
+ NO_ACCESS_ERROR,
OpenAIAdsResumeConfig,
openai_ads_source,
validate_credentials as validate_openai_ads_credentials,
@@ -78,8 +80,8 @@ Create an API key in the Settings tab of [OpenAI Ads Manager](https://ads.openai
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
- "401 Client Error: Unauthorized for url: https://api.ads.openai.com": "Your OpenAI Ads API key is invalid or has been revoked. Create a new API key in the Settings tab of OpenAI Ads Manager, then reconnect.",
- "403 Client Error: Forbidden for url: https://api.ads.openai.com": "Your OpenAI Ads API key does not have access to this ad account. Create a key for this ad account in the Settings tab of OpenAI Ads Manager, then reconnect.",
+ "401 Client Error: Unauthorized for url: https://api.ads.openai.com": INVALID_CREDENTIALS_ERROR,
+ "403 Client Error: Forbidden for url: https://api.ads.openai.com": NO_ACCESS_ERROR,
}
def get_retryable_errors(self) -> set[str]:
@@ -135,10 +137,7 @@ Create an API key in the Settings tab of [OpenAI Ads Manager](https://ads.openai
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- if validate_openai_ads_credentials(config.api_key):
- return True, None
-
- return False, "Invalid OpenAI Ads API key"
+ return validate_openai_ads_credentials(config.api_key)
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpenAIAdsResumeConfig]:
return ResumableSourceManager[OpenAIAdsResumeConfig](inputs, OpenAIAdsResumeConfig)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py
index 83097317c088..fcce6fcfd234 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py
@@ -305,16 +305,31 @@ class TestInsights:
class TestValidateCredentials:
- @parameterized.expand([("ok", 200, True), ("forbidden_scope", 403, True), ("unauthorized", 401, False)])
- def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("forbidden_scope", 403, True, None),
+ ("unauthorized", 401, False, "invalid or has been revoked"),
+ ("server_error", 500, False, "Couldn't reach OpenAI Ads"),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, expected: bool, message_fragment: str | None) -> None:
# 403 is accepted at create time (a real key with restricted access); 401 means a bad key.
+ # A 5xx says nothing about the key, so it must not read as a rejected credential.
session = mock.MagicMock()
session.get.return_value = mock.MagicMock(status_code=status)
with mock.patch(OPENAI_ADS_SESSION_PATCH, return_value=session):
- assert validate_credentials("oa-ads-test") is expected
-
- def test_network_error_is_invalid(self) -> None:
+ is_valid, message = validate_credentials("oa-ads-test")
+ assert is_valid is expected
+ if message_fragment is None:
+ assert message is None
+ else:
+ assert message is not None and message_fragment in message
+
+ def test_network_error_reads_as_unreachable_not_a_bad_key(self) -> None:
session = mock.MagicMock()
session.get.side_effect = requests.ConnectionError("boom")
with mock.patch(OPENAI_ADS_SESSION_PATCH, return_value=session):
- assert validate_credentials("oa-ads-test") is False
+ is_valid, message = validate_credentials("oa-ads-test")
+ assert is_valid is False
+ assert message is not None and "Couldn't reach OpenAI Ads" in message