: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
fix(warehouse): actionable error when TikTok denies creative library access (#82183)
Javier Bahamondes1882cb054c50
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/canonical_descriptions.pyindex 9509e1f8ca7f..d742c4e8bd14 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/canonical_descriptions.py@@ -162,7 +162,11 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {),},"creative_videos": {- "description": "A video asset in your TikTok Ads creative library, joinable to the video used by an ad.",+ "description": (+ "A video asset in your TikTok Ads creative library, joinable to the video used by an ad. "+ "Requires creative asset read access on the authorized advertiser; without it TikTok refuses "+ "the request and this table can't sync."+ ),"docs_url": "https://business-api.tiktok.com/portal/docs","columns": {"video_id": "Unique identifier for the video asset.",@@ -186,7 +190,11 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {},},"creative_images": {- "description": "An image asset in your TikTok Ads creative library, joinable to the images used by an ad.",+ "description": (+ "An image asset in your TikTok Ads creative library, joinable to the images used by an ad. "+ "Requires creative asset read access on the authorized advertiser; without it TikTok refuses "+ "the request and this table can't sync."+ ),"docs_url": "https://business-api.tiktok.com/portal/docs","columns": {"image_id": "Unique identifier for the image asset.",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.pyindex 72c2b0a56812..5907611344b7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.py@@ -42,6 +42,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_adsfrom products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.utils import (TIKTOK_APP_TOKEN_MISMATCH_MESSAGE,TIKTOK_AUTH_ERROR_CODES,+ TIKTOK_CREATIVE_PERMISSION_DENIED_FRAGMENTS,+ TIKTOK_CREATIVE_PERMISSION_DENIED_MESSAGE,TIKTOK_NON_RETRYABLE_ERROR_PREFIX,TIKTOK_TRANSIENT_ERROR_CODES,TIKTOK_TRANSIENT_ERROR_MESSAGE,@@ -72,7 +74,10 @@ class TikTokAdsSource(ResumableSource[TikTokAdsSourceConfig, TikTokAdsResumeConfdef get_non_retryable_errors(self) -> dict[str, str | None]:return {- # TikTok client errors not in the retryable code set (e.g. 40001 — the advertiser+ # Must precede TIKTOK_NON_RETRYABLE_ERROR_PREFIX: a denial matches both keys, and+ # `external_data_job` takes the first match in dict order, discarding it when None.+ **dict.fromkeys(TIKTOK_CREATIVE_PERMISSION_DENIED_FRAGMENTS, TIKTOK_CREATIVE_PERMISSION_DENIED_MESSAGE),+ # Other TikTok client errors not in the retryable code set (e.g. 40001 — the advertiser# doesn't exist or has been deleted). The paginator raises these with this exact# prefix; retrying cannot recover, so fail the job fast. The raw message is kept as# the user-facing error since it names the specific advertiser and TikTok error code.@@ -106,7 +111,10 @@ class TikTokAdsSource(ResumableSource[TikTokAdsSourceConfig, TikTokAdsResumeConf"If TikTok's authorization page rejects the connection before returning to PostHog, this is ""usually an account or region restriction on TikTok's side. Check that you have an admin role ""in the TikTok Business Center you're connecting, and that TikTok Ads is available in your region. "- "If it still fails, copy the Log ID from TikTok's error page and contact support."+ "If it still fails, copy the Log ID from TikTok's error page and contact support.\n\n"+ "The creative_videos and creative_images tables additionally need creative asset access on the "+ "advertiser account. If your advertiser hasn't granted it, leave those two tables unselected. "+ "Every other table syncs without it."),releaseStatus=ReleaseStatus.GA,iconPath="/static/services/tiktok.png",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_source.pyindex 50dbf0e3c20b..88726dad0cbe 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_source.py@@ -18,6 +18,7 @@ from posthog.schema import ReleaseStatusfrom posthog.models.integration import Integration+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (IntegrationAccountListingError,)@@ -28,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.source import TikTokAdsSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.utils import (+ TIKTOK_NON_RETRYABLE_ERROR_PREFIX,TIKTOK_TRANSIENT_ERROR_MESSAGE,TikTokAdsAPIError,TikTokAdsPaginator,@@ -79,6 +81,99 @@ class TestTikTokAdsSource:f"TikTok non-retryable error '{error_message}' does not match any non-retryable pattern")+ @parameterized.expand(+ [+ ("video", "advertiser does not grant you /file/video/ad/search/:GET permission"),+ ("image", "advertiser does not grant you /file/image/ad/search/:GET permission"),+ ]+ )+ def test_creative_permission_denied_is_non_retryable(self, name, message):+ """Reconnecting is the only fix for a denial, so retrying it would loop forever."""+ paginator = TikTokAdsPaginator()+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"code": 40001, "message": message, "data": {}}++ with pytest.raises(ValueError) as exc_info:+ paginator.update_state(mock_response)++ error_message = str(exc_info.value)+ patterns = self.source.get_non_retryable_errors()+ assert any(pattern in error_message for pattern in patterns)++ @parameterized.expand(+ [+ ("video", "advertiser does not grant you /file/video/ad/search/:GET permission"),+ ("image", "advertiser does not grant you /file/image/ad/search/:GET permission"),+ ]+ )+ def test_creative_permission_denied_surfaces_friendly_message(self, name, message):+ """Fails if the dict entries are reordered, which would shadow this message with None."""+ error_message = f"{TIKTOK_NON_RETRYABLE_ERROR_PREFIX} {message} (code: 40001)"++ friendly = [+ friendly_error+ for pattern, friendly_error in self.source.get_non_retryable_errors().items()+ if error_message_matches(error_message, [pattern])+ ]++ assert friendly, "permission denial matched no non-retryable pattern"+ assert friendly[0] is not None, "generic prefix shadowed the creative-permission message"+ assert "creative_videos" in friendly[0]+ assert "creative_images" in friendly[0]++ @parameterized.expand(+ [+ ("report", "advertiser does not grant you /report/integrated/get/:GET permission"),+ ("campaign", "advertiser does not grant you /campaign/get/:GET permission"),+ ]+ )+ def test_non_creative_permission_denied_keeps_raw_message(self, name, message):+ """A denial elsewhere shares the wording, so creative-library advice would contradict it."""+ error_message = f"{TIKTOK_NON_RETRYABLE_ERROR_PREFIX} {message} (code: 40001)"++ friendly = [+ friendly_error+ for pattern, friendly_error in self.source.get_non_retryable_errors().items()+ if error_message_matches(error_message, [pattern])+ ]++ assert friendly, "permission denial matched no non-retryable pattern"+ assert friendly[0] is None++ def test_advertiser_deleted_40001_still_has_no_friendly_message(self):+ """The raw message names the advertiser, so the creative key must not over-match it."""+ error_message = (+ f"{TIKTOK_NON_RETRYABLE_ERROR_PREFIX} The advertiser 123 doesn't exist or has been deleted. (code: 40001)"+ )++ friendly = [+ friendly_error+ for pattern, friendly_error in self.source.get_non_retryable_errors().items()+ if error_message_matches(error_message, [pattern])+ ]++ assert friendly, "deleted advertiser matched no non-retryable pattern"+ assert friendly[0] is None++ def test_creative_permission_denied_does_not_match_get_retryable_errors(self):+ """A permission denial must not be swallowed as a benign retryable error."""+ paginator = TikTokAdsPaginator()+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "code": 40001,+ "message": "advertiser does not grant you /file/video/ad/search/:GET permission",+ "data": {},+ }++ with pytest.raises(ValueError) as exc_info:+ paginator.update_state(mock_response)++ error_message = str(exc_info.value)+ patterns = self.source.get_retryable_errors()+ assert not any(pattern in error_message for pattern in patterns)+@parameterized.expand([("deleted_integration", "ValueError: Integration not found: 173586"),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.pyindex cf2e2d3c476d..fadea69f1307 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py@@ -85,12 +85,30 @@ def list_advertisers(access_token: str) -> list[dict]:return (body.get("data") or {}).get("list") or []-# Prefix for the ValueError raised when TikTok returns a client error code that-# is not in the retryable set (e.g. 40001 "advertiser doesn't exist or has been-# deleted"). Retrying these never succeeds, so `TikTokAdsSource.get_non_retryable_errors`-# matches on this exact prefix to fail the job fast instead of looping forever.+# Prefix for the ValueError the paginator raises on client error codes outside the retryable set.+# 40001 is a generic bucket covering both a deleted advertiser and per-endpoint permission denials,+# so callers have to discriminate on wording rather than on the code. Retrying never succeeds, so+# `TikTokAdsSource.get_non_retryable_errors` matches this prefix to fail the job fast.TIKTOK_NON_RETRYABLE_ERROR_PREFIX = "TikTok API client error (non-retryable):"+# Keep the denied path in each fragment: every endpoint here shares one paginator, so a denial on+# `/report/integrated/get/` carries the same "does not grant you" wording and would otherwise be+# answered with creative-library advice. TikTok templates the path into the message.+TIKTOK_CREATIVE_PERMISSION_DENIED_FRAGMENTS = (+ "does not grant you /file/video/ad/search/",+ "does not grant you /file/image/ad/search/",+)++# Reconnecting is the only fix, because our authorize URL sends no `scope`: the creative asset+# permission is granted per-advertiser on TikTok's side and we can't widen it after the fact.+TIKTOK_CREATIVE_PERMISSION_DENIED_MESSAGE = (+ "TikTok denied access to your creative library: the authorized advertiser account has not granted "+ "PostHog permission to read creative assets. This only affects the creative_videos and creative_images "+ "tables, which have been disabled. Your campaign, ad and report tables keep syncing. If your TikTok "+ "admin can grant creative asset access, reconnect the TikTok Ads integration and grant it when TikTok "+ "asks. Otherwise leave these two tables unselected."+)+class TikTokAdsAPIError(Exception):"""A TikTok API failure, carrying the body `code` as `api_code` so callers can branch on it: the