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(data-warehouse): mark Meta Ads auth errors as non-retryable (#61579)

Tom Owers5730e0472229
diff --git a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
index 0aa2b9740e4f..900f16da49f3 100644
--- a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
+++ b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
@@ -206,6 +206,54 @@ def _is_timeout_error(response: Response) -> bool:
return False
+# Meta error codes that indicate a permanent auth or permission problem — the
+# only fix is for the user to re-authorize the integration, so retrying the job
+# is pointless. We key off the numeric ``code`` rather than the error ``type``:
+# Meta returns ``type: "OAuthException"`` for transient service errors too (e.g.
+# code 2, "Service temporarily unavailable"), so the type alone is not reliable.
+# 190 — access token expired/invalid/revoked, checkpoint required, password
+# changed, etc. (the dominant variant for this source).
+# 102 — invalid or expired session.
+# 10 and 200-299 — permission denied.
+# https://developers.facebook.com/docs/graph-api/guides/error-handling
+META_AUTH_ERROR_CODES = {102, 190}
+META_PERMISSION_ERROR_CODES = {10, *range(200, 300)}
+
+META_AUTH_ERROR_MESSAGE = (
+ "Meta Ads access token is invalid, expired, or lacks the required permissions. Please re-authorize the integration."
+)
+
+
+def _is_permanent_auth_error(response: Response) -> bool:
+ """Return True for Meta errors that only re-authorization can fix.
+
+ Covers expired/invalid/revoked access tokens, invalidated sessions, and
+ permission denials. These are terminal: retrying the sync keeps failing
+ until the user reconnects the integration.
+ """
+ try:
+ error = response.json().get("error", {})
+ except (ValueError, AttributeError):
+ return False
+ code = error.get("code")
+ if not isinstance(code, int):
+ return False
+ return code in META_AUTH_ERROR_CODES or code in META_PERMISSION_ERROR_CODES
+
+
+def _raise_meta_api_error(response: Response) -> typing.NoReturn:
+ """Raise a descriptive exception for a non-200 Meta API response.
+
+ Permanent auth/permission failures raise a clean, user-actionable message
+ that ``MetaAdsSource.get_non_retryable_errors`` matches on, so the job fails
+ fast instead of burning retries. The raw response is appended for debugging.
+ Everything else raises the raw response and stays retryable.
+ """
+ if _is_permanent_auth_error(response):
+ raise Exception(f"{META_AUTH_ERROR_MESSAGE} (Meta API response: {response.status_code} - {response.text})")
+ raise Exception(f"Meta API request failed: {response.status_code} - {response.text}")
+
+
def _iter_simple_pagination(
initial_url: str,
params: dict,
@@ -225,7 +273,7 @@ def _iter_simple_pagination(
while True:
if response.status_code != 200:
- raise Exception(f"Meta API request failed: {response.status_code} - {response.text}")
+ _raise_meta_api_error(response)
response_payload = response.json()
yield response_payload.get("data", [])
@@ -330,7 +378,7 @@ def _iter_time_range_pagination(
if current_index < len(TIME_RANGE_CHUNK_SIZES) - 1:
chunk_size_days = TIME_RANGE_CHUNK_SIZES[current_index + 1]
continue
- raise Exception(f"Meta API request failed: {response.status_code} - {response.text}")
+ _raise_meta_api_error(response)
while True:
if response.status_code != 200:
@@ -344,7 +392,7 @@ def _iter_time_range_pagination(
retry_url = _override_limit(last_paging_url, current_limit)
response = _fetch_paging_url(retry_url, access_token)
continue
- raise Exception(f"Meta API request failed: {response.status_code} - {response.text}")
+ _raise_meta_api_error(response)
response_payload = response.json()
yield response_payload.get("data", [])
diff --git a/posthog/temporal/data_imports/sources/meta_ads/source.py b/posthog/temporal/data_imports/sources/meta_ads/source.py
index 760932c64f7c..01636e0eaf49 100644
--- a/posthog/temporal/data_imports/sources/meta_ads/source.py
+++ b/posthog/temporal/data_imports/sources/meta_ads/source.py
@@ -19,7 +19,11 @@ from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import MetaAdsSourceConfig
-from posthog.temporal.data_imports.sources.meta_ads.meta_ads import MetaAdsResumeConfig, meta_ads_source
+from posthog.temporal.data_imports.sources.meta_ads.meta_ads import (
+ META_AUTH_ERROR_MESSAGE,
+ MetaAdsResumeConfig,
+ meta_ads_source,
+)
from posthog.temporal.data_imports.sources.meta_ads.schemas import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@@ -34,6 +38,10 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig]):
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
"Failed to refresh token for Meta Ads integration. Please re-authorize the integration.": None,
+ # Permanent auth/permission failures from the Graph API (e.g. revoked or expired
+ # access tokens, checkpoint-required, invalidated sessions, permission denials).
+ # `meta_ads._raise_meta_api_error` prefixes these with this exact message.
+ META_AUTH_ERROR_MESSAGE: META_AUTH_ERROR_MESSAGE,
"Ad account owner has NOT": None,
"cannot be loaded due to missing permissions": None,
# Meta returns this 500 when the requested query is too large for their backend to
diff --git a/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py
index 328f5183a047..0e50ec8d12cc 100644
--- a/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py
+++ b/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py
@@ -6,8 +6,10 @@ from unittest import mock
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from posthog.temporal.data_imports.sources.meta_ads.meta_ads import (
+ META_AUTH_ERROR_MESSAGE,
PAGE_LIMIT_FALLBACK_SIZES,
MetaAdsResumeConfig,
+ _is_permanent_auth_error,
_iter_simple_pagination,
_iter_time_range_pagination,
_next_smaller_limit,
@@ -633,7 +635,9 @@ class TestMidChunkLimitFallback:
"paging": {"next": "https://graph.facebook.com/v20/act_1/insights?after=p1"},
},
),
- _mock_response(401, {"error": {"message": "Invalid OAuth access token", "code": 190}}),
+ # Transient service error (code 2) — not a timeout and not an auth error, so it
+ # neither retries-with-smaller-limit nor gets reclassified as permanent.
+ _mock_response(500, {"error": {"message": "Service temporarily unavailable", "code": 2}}),
]
with mock.patch("posthog.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session") as mock_get:
@@ -642,12 +646,41 @@ class TestMidChunkLimitFallback:
self.URL, self.PARAMS, {"since": "2026-04-21", "until": "2026-04-21"}, None, manager
)
assert next(gen) == [{"ad_id": "1"}]
- with pytest.raises(Exception, match="Meta API request failed: 401"):
+ with pytest.raises(Exception, match="Meta API request failed: 500"):
list(gen)
# Exactly two requests: initial + the failed cursor. No retry happened.
assert mock_get.return_value.get.call_count == 2
+ def test_permanent_auth_error_raises_clean_message_and_does_not_retry(self) -> None:
+ manager = _build_manager()
+ responses = [
+ _mock_response(
+ 200,
+ {
+ "data": [{"ad_id": "1"}],
+ "paging": {"next": "https://graph.facebook.com/v20/act_1/insights?after=p1"},
+ },
+ ),
+ # code 190 — invalidated session. Re-auth is the only fix, so no retry should happen.
+ _mock_response(
+ 400,
+ {"error": {"message": "Error validating access token", "type": "OAuthException", "code": 190}},
+ ),
+ ]
+
+ with mock.patch("posthog.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session") as mock_get:
+ mock_get.return_value.get.side_effect = responses
+ gen = _iter_time_range_pagination(
+ self.URL, self.PARAMS, {"since": "2026-04-21", "until": "2026-04-21"}, None, manager
+ )
+ assert next(gen) == [{"ad_id": "1"}]
+ with pytest.raises(Exception, match="Please re-authorize the integration"):
+ list(gen)
+
+ # Initial + failed cursor only — the limit ladder is not exercised for auth errors.
+ assert mock_get.return_value.get.call_count == 2
+
class TestNonRetryableErrors:
@pytest.mark.parametrize(
@@ -662,6 +695,15 @@ class TestNonRetryableErrors:
# 500 when Meta's backend refuses to service the query even after adaptive
# chunking has shrunk the window to its smallest size.
'Meta API request failed: 500 - {"error":{"code":1,"message":"Please reduce the amount of data you\'re asking for, then retry your request"}}',
+ # code 190 / subcode 459 — account checkpoint, the user must log in to Facebook.
+ f"{META_AUTH_ERROR_MESSAGE} (Meta API response: 400 - "
+ '{"error":{"message":"You cannot access the app till you log in to www.facebook.com and follow the '
+ 'instructions given.","type":"OAuthException","code":190,"error_subcode":459}})',
+ # code 190 / subcode 460 — session invalidated after a password change.
+ f"{META_AUTH_ERROR_MESSAGE} (Meta API response: 400 - "
+ '{"error":{"message":"Error validating access token: The session has been invalidated because the '
+ "user changed their password or Facebook has changed the session for security "
+ 'reasons.","type":"OAuthException","code":190,"error_subcode":460}})',
],
)
def test_errors_match_pattern(self, error_message: str) -> None:
@@ -669,3 +711,24 @@ class TestNonRetryableErrors:
assert any(pattern in error_message for pattern in patterns), (
f"Meta Ads error '{error_message}' does not match any non-retryable pattern"
)
+
+ @pytest.mark.parametrize(
+ "body,expected",
+ [
+ # Permanent auth/permission failures.
+ ({"error": {"code": 190, "error_subcode": 459}}, True),
+ ({"error": {"code": 190, "error_subcode": 460}}, True),
+ ({"error": {"code": 102}}, True),
+ ({"error": {"code": 10}}, True),
+ ({"error": {"code": 200}}, True),
+ ({"error": {"code": 299}}, True),
+ # Transient / retryable errors — Meta still tags some of these OAuthException.
+ ({"error": {"code": 2, "type": "OAuthException"}}, False),
+ ({"error": {"code": 1, "error_subcode": 99}}, False),
+ ({"error": {"code": 4}}, False),
+ ({"error": {}}, False),
+ ({}, False),
+ ],
+ )
+ def test_is_permanent_auth_error(self, body: dict, expected: bool) -> None:
+ assert _is_permanent_auth_error(_mock_response(400, body)) is expected