: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(meta-ads): stop a Meta outage disabling the sync (#96465)
Tom Owers9b0a6ca0b35a
diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambrindex ea14d5b5acef..1056c49bebba 100644--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr@@ -8237,6 +8237,148 @@5 /* ... */))'''# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.176+ '''+ SELECT "posthog_taggeditem"."id",+ "posthog_taggeditem"."tag_id",+ "posthog_taggeditem"."dashboard_id",+ "posthog_taggeditem"."insight_id",+ "posthog_taggeditem"."event_definition_id",+ "posthog_taggeditem"."property_definition_id",+ "posthog_taggeditem"."action_id",+ "posthog_taggeditem"."feature_flag_id",+ "posthog_taggeditem"."experiment_saved_metric_id",+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id",+ "posthog_taggeditem"."endpoint_id",+ "posthog_taggeditem"."replay_scanner_id",+ "posthog_taggeditem"."project_id",+ "posthog_tag"."id",+ "posthog_tag"."name",+ "posthog_tag"."team_id"+ FROM "posthog_taggeditem"+ INNER JOIN "posthog_tag" ON ("posthog_taggeditem"."tag_id" = "posthog_tag"."id")+ WHERE "posthog_taggeditem"."insight_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.177+ '''+ SELECT "posthog_alertconfiguration"."created_by_id",+ "posthog_alertconfiguration"."created_at",+ "posthog_alertconfiguration"."id",+ "posthog_alertconfiguration"."team_id",+ "posthog_alertconfiguration"."insight_id",+ "posthog_alertconfiguration"."name",+ "posthog_alertconfiguration"."config",+ "posthog_alertconfiguration"."calculation_interval",+ "posthog_alertconfiguration"."threshold_id",+ "posthog_alertconfiguration"."condition",+ "posthog_alertconfiguration"."detector_config",+ "posthog_alertconfiguration"."state",+ "posthog_alertconfiguration"."enabled",+ "posthog_alertconfiguration"."last_notified_at",+ "posthog_alertconfiguration"."last_checked_at",+ "posthog_alertconfiguration"."next_check_at",+ "posthog_alertconfiguration"."snoozed_until",+ "posthog_alertconfiguration"."skip_weekend",+ "posthog_alertconfiguration"."schedule_restriction",+ "posthog_alertconfiguration"."investigation_agent_enabled",+ "posthog_alertconfiguration"."investigation_gates_notifications",+ "posthog_alertconfiguration"."investigation_inconclusive_action",+ "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_password_reset_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."ui_configuration",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in",+ "posthog_threshold"."created_by_id",+ "posthog_threshold"."created_at",+ "posthog_threshold"."id",+ "posthog_threshold"."team_id",+ "posthog_threshold"."insight_id",+ "posthog_threshold"."name",+ "posthog_threshold"."configuration"+ FROM "posthog_alertconfiguration"+ LEFT OUTER JOIN "posthog_user" ON ("posthog_alertconfiguration"."created_by_id" = "posthog_user"."id")+ LEFT OUTER JOIN "posthog_threshold" ON ("posthog_alertconfiguration"."threshold_id" = "posthog_threshold"."id")+ WHERE "posthog_alertconfiguration"."insight_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.178+ '''+ SELECT "posthog_dashboard"."id",+ "posthog_dashboard"."name",+ "posthog_dashboard"."description",+ "posthog_dashboard"."team_id",+ "posthog_dashboard"."pinned",+ "posthog_dashboard"."created_at",+ "posthog_dashboard"."created_by_id",+ "posthog_dashboard"."deleted",+ "posthog_dashboard"."last_accessed_at",+ "posthog_dashboard"."last_refresh",+ "posthog_dashboard"."filters",+ "posthog_dashboard"."variables",+ "posthog_dashboard"."breakdown_colors",+ "posthog_dashboard"."data_color_theme_id",+ "posthog_dashboard"."creation_mode",+ "posthog_dashboard"."restriction_level",+ "posthog_dashboard"."quick_filter_ids",+ "posthog_dashboard"."customization",+ "posthog_dashboard"."deprecated_tags",+ "posthog_dashboard"."tags",+ "posthog_dashboard"."share_token",+ "posthog_dashboard"."is_shared"+ FROM "posthog_dashboard"+ WHERE (NOT ("posthog_dashboard"."deleted")+ AND "posthog_dashboard"."id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */))+ '''+# ---# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.18'''SELECT "posthog_insightvariable"."id",diff --git a/posthog/models/integration/meta.py b/posthog/models/integration/meta.pyindex 2bcf2da0342a..e4006edc442b 100644--- a/posthog/models/integration/meta.py+++ b/posthog/models/integration/meta.py@@ -57,8 +57,13 @@ class MetaGraphIntegration:if res.status_code != 200 or not config.get("access_token"):logger.warning(f"Failed to refresh token for {self}", response=res.text)- self.integration.errors = common.ERROR_TOKEN_REFRESH_FAILEDreason = refresh_tracking.oauth_refresh_failure_reason(res.status_code, config, kind=self.integration.kind)+ # These kinds refresh on use, and only in the last week of the token's life, so the+ # token in hand still works when Meta is merely unavailable or throttling us. Flagging+ # the connection over that stops every sync on it and asks for a re-authorization that+ # fixes nothing, so record the failure and leave the connection usable.+ if reason not in refresh_tracking.TRANSIENT_REFRESH_FAILURE_REASONS:+ self.integration.errors = common.ERROR_TOKEN_REFRESH_FAILEDattempt = refresh_tracking.record_refresh_failure(self.integration, reason=reason)refresh_tracking.oauth_refresh_counter.labels(kind=self.integration.kind, result="failed", reason=reason, attempt=attemptdiff --git a/posthog/models/integration/refresh_tracking.py b/posthog/models/integration/refresh_tracking.pyindex c02065bfe7a1..dd05c37aa513 100644--- a/posthog/models/integration/refresh_tracking.py+++ b/posthog/models/integration/refresh_tracking.py@@ -60,6 +60,17 @@ REFRESH_FAILURE_REASON_OTHER = "other"# made. Terminal on the first occurrence, since no later attempt can make the secret readable.REFRESH_FAILURE_REASON_UNREADABLE_SECRET = "unreadable_secret"+# Failures that say nothing about the grant: the provider was unavailable or throttling us. The+# credentials in hand are still good, so a caller refreshing on use must not flag the connection+# for re-authorization over one - that strands a working connection until someone reconnects it.+TRANSIENT_REFRESH_FAILURE_REASONS = frozenset(+ {+ REFRESH_FAILURE_REASON_HTTP_5XX,+ REFRESH_FAILURE_REASON_NETWORK,+ REFRESH_FAILURE_REASON_RATE_LIMITED,+ }+)+def oauth_refresh_failure_reason(status_code: int, body: dict, kind: str | None = None) -> str:error = body.get("error")diff --git a/posthog/models/test/integration/test_meta.py b/posthog/models/test/integration/test_meta.pyindex 75dc73c31553..b20dc21a7054 100644--- a/posthog/models/test/integration/test_meta.py+++ b/posthog/models/test/integration/test_meta.py@@ -8,7 +8,15 @@ from unittest.mock import patchfrom django.test import override_settings-from posthog.models.integration import InstagramIntegration, Integration, OauthIntegration+from parameterized import parameterized++from posthog.models.integration import (+ ERROR_TOKEN_REFRESH_FAILED,+ InstagramIntegration,+ Integration,+ MetaAdsIntegration,+ OauthIntegration,+)@override_settings(INSTAGRAM_APP_CLIENT_ID="instagram-client-id", INSTAGRAM_APP_CLIENT_SECRET="instagram-client-secret")@@ -70,3 +78,42 @@ class TestInstagramIntegrationModel(BaseTest):integration.refresh_from_db()assert integration.sensitive_config["access_token"] == "new-token"assert integration.errors == ""+++@override_settings(META_ADS_APP_CLIENT_ID="meta-client-id", META_ADS_APP_CLIENT_SECRET="meta-client-secret")+class TestMetaAdsIntegrationModel(BaseTest):+ def _integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="meta-ads",+ integration_id="fb-user-1",+ config={"expires_in": 100, "refreshed_at": int(time.time()) - 90},+ sensitive_config={"access_token": "old-token"},+ )++ @parameterized.expand([("throttled", 429), ("unavailable", 503)])+ @patch("posthog.models.integration.meta.requests.post")+ def test_an_unavailable_meta_leaves_the_connection_usable(self, _name, status_code, mock_post):+ # A 5xx or a throttle says nothing about the grant. Flagging the connection over one stops+ # every warehouse sync on it and tells the customer to re-authorize a working account.+ integration = self._integration()+ mock_post.return_value.status_code = status_code+ mock_post.return_value.json.return_value = {}++ MetaAdsIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.errors == ""+ assert integration.sensitive_config["access_token"] == "old-token"+ assert integration.config["refresh_failure_count"] == 1++ @patch("posthog.models.integration.meta.requests.post")+ def test_a_rejected_token_flags_the_connection(self, mock_post):+ integration = self._integration()+ mock_post.return_value.status_code = 400+ mock_post.return_value.json.return_value = {"error": {"type": "OAuthException", "code": 190}}++ MetaAdsIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.errors == ERROR_TOKEN_REFRESH_FAILED