: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(integrations): back off and terminate permanently failing OAuth token refreshes (#70492)
Harley Alexanderb66137c39104
diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 7362ec8df15b..e09f0ae2f49f 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -85,9 +85,93 @@ def _decode_jwt_payload(token: str) -> dict | None:oauth_refresh_counter = Counter(- "integration_oauth_refresh", "Number of times an oauth refresh has been attempted", labelnames=["kind", "result"]+ "integration_oauth_refresh",+ "Number of times an oauth refresh has been attempted",+ labelnames=["kind", "result", "reason", "attempt"],)+# Terminal rows are skipped by the sweep and stop emitting failure metrics, so a gradual fleet+# die-off would otherwise be invisible. Incremented once per row at the transition; a rising+# rate means connections are permanently breaking (e.g. a provider mass-revoking grants).+oauth_refresh_terminal_counter = Counter(+ "integration_oauth_refresh_went_terminal",+ "OAuth integrations whose refresh went terminal (unbroken invalid_grant streak)",+ labelnames=["kind"],+)++# Consecutive-failure backoff for the every-minute refresh sweep (posthog/tasks/integrations.py).+# Without it, permanently dead integrations (revoked grants, deleted consumers) are retried every+# minute forever, hammering providers and drowning the failure metric in a noise floor that+# masks real fleet-wide breakage.+REFRESH_BACKOFF_BASE_SECONDS = 120+REFRESH_BACKOFF_MAX_SECONDS = 3600+REFRESH_TERMINAL_FAILURE_COUNT = 5++# Values for the counter's `reason` label, bucketed from the OAuth error response.+REFRESH_FAILURE_REASON_INVALID_GRANT = "invalid_grant"+REFRESH_FAILURE_REASON_INVALID_CLIENT = "invalid_client"+REFRESH_FAILURE_REASON_HTTP_5XX = "http_5xx"+REFRESH_FAILURE_REASON_OTHER = "other"+++def oauth_refresh_failure_reason(status_code: int, body: dict) -> str:+ error = body.get("error")+ if error == REFRESH_FAILURE_REASON_INVALID_GRANT:+ return REFRESH_FAILURE_REASON_INVALID_GRANT+ if error == REFRESH_FAILURE_REASON_INVALID_CLIENT:+ return REFRESH_FAILURE_REASON_INVALID_CLIENT+ if status_code >= 500:+ return REFRESH_FAILURE_REASON_HTTP_5XX+ return REFRESH_FAILURE_REASON_OTHER+++def record_refresh_failure(integration: "Integration", *, reason: str = REFRESH_FAILURE_REASON_OTHER) -> str:+ """Track a consecutive refresh failure on the integration's config; caller saves.++ Schedules the next attempt with capped exponential backoff. `invalid_grant` means the grant+ itself is dead and only a customer re-auth can fix it, so after an unbroken streak of them the+ integration goes terminal and the sweep stops retrying entirely. The streak is tracked+ separately from the total failure count and resets on any other reason, so one transient+ invalid_grant amid e.g. a 5xx outage can't brick the integration. Other reasons+ (invalid_client, 5xx, network) never go terminal - a platform-side credential fix must let+ the fleet self-recover.++ Returns "first"/"retry" for the metric's `attempt` label - a spike in first failures means+ connections are newly breaking, regardless of retry noise.+ """+ count = int(integration.config.get("refresh_failure_count") or 0)+ attempt = "first" if count == 0 else "retry"+ count += 1+ integration.config["refresh_failure_count"] = count+ integration.config["refresh_next_attempt_at"] = int(time.time()) + min(+ REFRESH_BACKOFF_BASE_SECONDS * 2 ** (count - 1), REFRESH_BACKOFF_MAX_SECONDS+ )+ if reason == REFRESH_FAILURE_REASON_INVALID_GRANT:+ grant_streak = int(integration.config.get("refresh_invalid_grant_count") or 0) + 1+ integration.config["refresh_invalid_grant_count"] = grant_streak+ # Guarded so on-demand refreshes (which bypass the backoff) can't re-count a dead row+ if grant_streak >= REFRESH_TERMINAL_FAILURE_COUNT and not integration.config.get("refresh_terminal"):+ integration.config["refresh_terminal"] = True+ oauth_refresh_terminal_counter.labels(kind=integration.kind).inc()+ else:+ integration.config.pop("refresh_invalid_grant_count", None)+ return attempt+++def record_refresh_success(integration: "Integration") -> None:+ for key in ("refresh_failure_count", "refresh_invalid_grant_count", "refresh_next_attempt_at", "refresh_terminal"):+ integration.config.pop(key, None)+++def refresh_backoff_active(integration: "Integration") -> bool:+ """Whether the refresh sweep should skip this integration. Reconnecting resets the state+ (the OAuth callback replaces `config` wholesale), and on-demand API refreshes bypass this."""+ if integration.config.get("refresh_terminal"):+ return True+ next_attempt_at = integration.config.get("refresh_next_attempt_at")+ return bool(next_attempt_at) and time.time() < next_attempt_at++# `owner/repo`, single slash, no traversal. Used to keep repo/ref/sha values out of GitHub API URL# paths where a crafted value (e.g. `../../other-repo/contents/x?ref=y`) could redirect the# authenticated request to a different endpoint.@@ -1264,14 +1348,23 @@ class OauthIntegration:timeout=10,)- config: dict = res.json()+ try:+ config: dict = res.json()+ except ValueError:+ # e.g. an HTML error page from a proxy/5xx - still a failed refresh, not an exception+ config = {}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 = ERROR_TOKEN_REFRESH_FAILED- oauth_refresh_counter.labels(self.integration.kind, "failed").inc()+ reason = oauth_refresh_failure_reason(res.status_code, config)+ attempt = record_refresh_failure(self.integration, reason=reason)+ oauth_refresh_counter.labels(+ kind=self.integration.kind, result="failed", reason=reason, attempt=attempt+ ).inc()else:logger.info(f"Refreshed access token for {self}")+ record_refresh_success(self.integration)self.integration.sensitive_config["access_token"] = config["access_token"]# Some providers (e.g. Atlassian/Jira) rotate refresh tokens — each@@ -1291,7 +1384,7 @@ class OauthIntegration:self.integration.config["expires_in"] = expires_inself.integration.config["refreshed_at"] = int(time.time())reload_integrations_on_workers(self.integration.team_id, [self.integration.id])- oauth_refresh_counter.labels(self.integration.kind, "success").inc()+ oauth_refresh_counter.labels(kind=self.integration.kind, result="success", reason="", attempt="").inc()self.integration.save()@@ -1812,8 +1905,11 @@ class GoogleCloudIntegration:try:credentials.refresh(GoogleRequest())except Exception:+ record_refresh_failure(self.integration)+ self.integration.save(update_fields=["config"])raise ValidationError(f"Failed to authenticate with provided service account key")+ # Wholesale replacement also clears any refresh backoff stateself.integration.config = {"expires_in": credentials.expiry.timestamp() - int(time.time()),"refreshed_at": int(time.time()),@@ -1909,8 +2005,11 @@ class FirebaseIntegration:try:credentials.refresh(GoogleRequest())except Exception:+ record_refresh_failure(self.integration)+ self.integration.save(update_fields=["config"])raise ValidationError("Failed to authenticate with provided Firebase service account key")+ record_refresh_success(self.integration)self.integration.config["expires_in"] = credentials.expiry.timestamp() - int(time.time())self.integration.config["refreshed_at"] = int(time.time())self.integration.sensitive_config["access_token"] = credentials.token@@ -2711,14 +2810,17 @@ class GitHubIntegration(GitHubIntegrationBase):# A permanently-gone installation (uninstalled/suspended) drops expires_in/refreshed_at so the# every-minute beat loop stops re-minting it; the errors + config change persist in one save.self._disarm_proactive_refresh_if_installation_gone(response)- oauth_refresh_counter.labels(self.integration.kind, "failed").inc()+ reason = REFRESH_FAILURE_REASON_HTTP_5XX if response.status_code >= 500 else REFRESH_FAILURE_REASON_OTHER+ attempt = record_refresh_failure(self.integration, reason=reason)+ oauth_refresh_counter.labels(kind=self.integration.kind, result="failed", reason=reason, attempt=attempt).inc()self.integration.save()def _on_token_refreshed(self) -> None:logger.info(f"Refreshed access token for {self}")self.integration.errors = ""+ record_refresh_success(self.integration)reload_integrations_on_workers(self.integration.team_id, [self.integration.id])- oauth_refresh_counter.labels(self.integration.kind, "success").inc()+ oauth_refresh_counter.labels(kind=self.integration.kind, result="success", reason="", attempt="").inc()@database_sync_to_asyncdef list_cached_repositories_async(@@ -3171,21 +3273,29 @@ class MetaAdsIntegration:timeout=10,)- config: dict = res.json()+ try:+ config: dict = res.json()+ except ValueError:+ config = {}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 = ERROR_TOKEN_REFRESH_FAILED- oauth_refresh_counter.labels(self.integration.kind, "failed").inc()+ reason = oauth_refresh_failure_reason(res.status_code, config)+ attempt = record_refresh_failure(self.integration, reason=reason)+ oauth_refresh_counter.labels(+ kind=self.integration.kind, result="failed", reason=reason, attempt=attempt+ ).inc()else:logger.info(f"Refreshed access token for {self}")+ record_refresh_success(self.integration)self.integration.sensitive_config["access_token"] = config["access_token"]self.integration.errors = ""self.integration.config["expires_in"] = config.get("expires_in")self.integration.config["refreshed_at"] = int(time.time())# not used in CDP yet# reload_integrations_on_workers(self.integration.team_id, [self.integration.id])- oauth_refresh_counter.labels(self.integration.kind, "success").inc()+ oauth_refresh_counter.labels(kind=self.integration.kind, result="success", reason="", attempt="").inc()self.integration.save()diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 42f9c92cc802..a24720986703 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -52,6 +52,8 @@ from posthog.models.integration import (SnowflakeIntegration,SnowflakeIntegrationError,invalidate_github_repository_caches_for_installation,+ oauth_refresh_failure_reason,+ oauth_refresh_terminal_counter,)from posthog.models.organization import Organizationfrom posthog.models.team.team import Team@@ -615,6 +617,202 @@ class TestOauthIntegrationModel(BaseTest):integration.refresh_from_db()assert integration.errors == ""+ @parameterized.expand(+ [+ ("first_failure", 0, 120),+ ("second_failure", 1, 240),+ ("capped", 10, 3600),+ ]+ )+ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.integration.requests.post")+ def test_refresh_failure_schedules_backoff(self, _name, prior_failures, expected_delay, mock_post, mock_reload):+ mock_post.return_value.status_code = 401+ mock_post.return_value.json.return_value = {"error": "BROKEN"}++ config: dict = {"expires_in": 1000}+ if prior_failures:+ config["refresh_failure_count"] = prior_failures+ integration = self.create_integration(kind="hubspot", config=config)++ with freeze_time("2024-01-01T14:00:00Z"):+ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.config["refresh_failure_count"] == prior_failures + 1+ assert integration.config["refresh_next_attempt_at"] == 1704117600 + expected_delay+ assert "refresh_terminal" not in integration.config++ @parameterized.expand(+ [+ # (error, prior total failures, prior invalid_grant streak, expect terminal)+ ("invalid_grant_below_threshold", "invalid_grant", 3, 3, False),+ ("invalid_grant_at_threshold", "invalid_grant", 4, 4, True),+ ("invalid_client_never_terminal", "invalid_client", 10, 0, False),+ # A single invalid_grant after a run of other failures must not go terminal - the+ # streak has to be invalid_grant all the way through+ ("mixed_failures_not_terminal", "invalid_grant", 4, 0, False),+ ]+ )+ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.integration.requests.post")+ def test_refresh_failure_terminal_state(+ self, _name, error, prior_failures, prior_grant_streak, expected_terminal, mock_post, mock_reload+ ):+ mock_post.return_value.status_code = 400+ mock_post.return_value.json.return_value = {"error": error}++ config: dict = {"expires_in": 1000, "refresh_failure_count": prior_failures}+ if prior_grant_streak:+ config["refresh_invalid_grant_count"] = prior_grant_streak+ integration = self.create_integration(kind="hubspot", config=config)++ terminal_counter = oauth_refresh_terminal_counter.labels(kind="hubspot")+ counter_before = terminal_counter._value.get()++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert bool(integration.config.get("refresh_terminal")) is expected_terminal+ # The transition is the fleet die-off signal: exactly one increment when a row goes+ # terminal, none otherwise+ assert terminal_counter._value.get() - counter_before == (1 if expected_terminal else 0)++ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.integration.requests.post")+ def test_already_terminal_row_does_not_recount_on_bypassing_refresh(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 400+ mock_post.return_value.json.return_value = {"error": "invalid_grant"}++ # On-demand refreshes bypass the backoff, so a dead row can keep failing after the+ # transition - it must not inflate the die-off counter again+ integration = self.create_integration(+ kind="hubspot",+ config={+ "expires_in": 1000,+ "refresh_failure_count": 6,+ "refresh_invalid_grant_count": 6,+ "refresh_terminal": True,+ },+ )++ terminal_counter = oauth_refresh_terminal_counter.labels(kind="hubspot")+ counter_before = terminal_counter._value.get()++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.config.get("refresh_terminal") is True+ assert terminal_counter._value.get() == counter_before++ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.integration.requests.post")+ def test_non_invalid_grant_failure_resets_grant_streak(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 503+ mock_post.return_value.json.return_value = {"error": "server_error"}++ integration = self.create_integration(+ kind="hubspot",+ config={"expires_in": 1000, "refresh_failure_count": 4, "refresh_invalid_grant_count": 4},+ )++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert "refresh_invalid_grant_count" not in integration.config+ assert "refresh_terminal" not in integration.config++ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.integration.requests.post")+ def test_refresh_success_clears_backoff_state(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"access_token": "REFRESHED_ACCESS_TOKEN", "expires_in": 1000}++ integration = self.create_integration(+ kind="hubspot",+ config={+ "expires_in": 1000,+ "refresh_failure_count": 5,+ "refresh_invalid_grant_count": 5,+ "refresh_next_attempt_at": 1704117600,+ "refresh_terminal": True,+ },+ )++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert "refresh_failure_count" not in integration.config+ assert "refresh_invalid_grant_count" not in integration.config+ assert "refresh_next_attempt_at" not in integration.config+ assert "refresh_terminal" not in integration.config++ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.integration.requests.post")+ def test_refresh_failure_with_non_json_body_still_backs_off(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 502+ mock_post.return_value.json.side_effect = ValueError("not json")+ mock_post.return_value.text = "<html>Bad Gateway</html>"++ integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.errors == "TOKEN_REFRESH_FAILED"+ assert integration.config["refresh_failure_count"] == 1++ @parameterized.expand(+ [+ ("invalid_grant", 400, {"error": "invalid_grant"}, "invalid_grant"),+ ("invalid_client", 401, {"error": "invalid_client"}, "invalid_client"),+ ("server_error", 502, {}, "http_5xx"),+ ("other_4xx", 400, {"error": "temporarily_unavailable"}, "other"),+ ("non_string_error", 400, {"error": {"code": 1}}, "other"),+ ]+ )+ def test_oauth_refresh_failure_reason(self, _name, status_code, body, expected):+ assert oauth_refresh_failure_reason(status_code, body) == expected++ @patch("posthog.models.integration.requests.post")+ def test_reconnect_clears_backoff_state(self, mock_post):+ # A customer re-authing must un-brick a terminal integration, or "please reconnect"+ # comms leave them permanently dead.+ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = 200+ # integration_from_oauth_response pops fields out of the response dict, so each call+ # needs a fresh one+ mock_post.return_value.json.side_effect = lambda: {+ "access_token": "FAKES_ACCESS_TOKEN",+ "refresh_token": "FAKE_REFRESH_TOKEN",+ "instance_url": "https://fake.salesforce.com",+ "expires_in": 3600,+ }+ oauth_payload = {"code": "code", "state": "next=/projects/test"}++ integration = OauthIntegration.integration_from_oauth_response(+ "salesforce", self.team.id, self.user, oauth_payload+ )+ integration.config.update(+ {"refresh_failure_count": 5, "refresh_next_attempt_at": 1704117600, "refresh_terminal": True}+ )+ integration.save()++ reconnected = OauthIntegration.integration_from_oauth_response(+ "salesforce", self.team.id, self.user, oauth_payload+ )++ assert reconnected.id == integration.id+ assert "refresh_failure_count" not in reconnected.config+ assert "refresh_next_attempt_at" not in reconnected.config+ assert "refresh_terminal" not in reconnected.config+@patch("posthog.models.integration.requests.post")def test_salesforce_integration_without_expires_in_initial_response(self, mock_post):"""Test that Salesforce integrations without expires_in get default 1 hour expiry"""@@ -1402,6 +1600,7 @@ class TestGitHubIntegrationModel(BaseTest):integration.refresh_from_db()assert integration.errors == "TOKEN_REFRESH_FAILED"+ assert integration.config["refresh_failure_count"] == 1@patch("posthog.models.integration.reload_integrations_on_workers")@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")diff --git a/posthog/tasks/integrations.py b/posthog/tasks/integrations.pyindex df3863c68822..c5e861485d05 100644--- a/posthog/tasks/integrations.py+++ b/posthog/tasks/integrations.py@@ -5,6 +5,7 @@ from posthog.models.integration import (GitHubIntegration,GoogleCloudIntegration,defer_repository_cache_fields,+ refresh_backoff_active,)from posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueue@@ -24,7 +25,7 @@ def refresh_integrations() -> int:for integration in oauth_integrations:oauth_integration = OauthIntegration(integration)- if oauth_integration.access_token_expired():+ if not refresh_backoff_active(integration) and oauth_integration.access_token_expired():refresh_integration.delay(integration.id)gcloud_integrations = defer_repository_cache_fields(@@ -34,7 +35,7 @@ def refresh_integrations() -> int:for integration in gcloud_integrations:gcloud_integration = GoogleCloudIntegration(integration)- if gcloud_integration.access_token_expired():+ if not refresh_backoff_active(integration) and gcloud_integration.access_token_expired():refresh_integration.delay(integration.id)github_integrations = defer_repository_cache_fields(Integration.objects.filter(kind="github").all())@@ -42,7 +43,7 @@ def refresh_integrations() -> int:for integration in github_integrations:github_integration = GitHubIntegration(integration)- if github_integration.access_token_expired():+ if not refresh_backoff_active(integration) and github_integration.access_token_expired():refresh_integration.delay(integration.id)firebase_integrations = defer_repository_cache_fields(Integration.objects.filter(kind="firebase").all())@@ -50,7 +51,7 @@ def refresh_integrations() -> int:for integration in firebase_integrations:firebase_integration = FirebaseIntegration(integration)- if firebase_integration.access_token_expired():+ if not refresh_backoff_active(integration) and firebase_integration.access_token_expired():refresh_integration.delay(integration.id)return 0@@ -63,6 +64,11 @@ def refresh_integration(id: int) -> int:integration = defer_repository_cache_fields(Integration.objects.all()).get(id=id)+ # Re-check backoff against the just-loaded row: a failure recorded after this task was+ # enqueued must not be retried ahead of its scheduled next attempt.+ if refresh_backoff_active(integration):+ return 0+# Re-check freshness against the just-loaded row before minting. Under an INTEGRATIONS queue# backlog several duplicate refreshes can pile up for the same row; the first mints a fresh token# and this keeps the rest from re-minting one that's already valid.diff --git a/posthog/tasks/test/test_integrations.py b/posthog/tasks/test/test_integrations.pyindex 843607b97c46..f3fe8e4346c0 100644--- a/posthog/tasks/test/test_integrations.py+++ b/posthog/tasks/test/test_integrations.py@@ -39,6 +39,41 @@ class TestIntegrationsTasks(APIBaseTest):# Both 3 and 4 should be refreshedassert refresh_integration_mock.call_args_list == [((integration_3.id,),), ((integration_4.id,),)]+ def test_refresh_integrations_skips_backed_off_and_terminal(self) -> None:+ expired = {"refreshed_at": time.time() - 3600}+ eligible = self.create_integration("slack", config=expired)+ backoff_elapsed = self.create_integration(+ "slack",+ config={**expired, "refresh_failure_count": 2, "refresh_next_attempt_at": int(time.time()) - 10},+ )+ _backed_off = self.create_integration(+ "slack",+ config={**expired, "refresh_failure_count": 2, "refresh_next_attempt_at": int(time.time()) + 300},+ )+ _terminal = self.create_integration(+ "slack", config={**expired, "refresh_failure_count": 5, "refresh_terminal": True}+ )++ with patch("posthog.tasks.integrations.refresh_integration.delay") as refresh_integration_mock:+ refresh_integrations()++ assert refresh_integration_mock.call_args_list == [((eligible.id,),), ((backoff_elapsed.id,),)]++ def test_refresh_integration_skips_when_backed_off(self) -> None:+ integration = self.create_integration(+ "slack",+ config={+ "refreshed_at": time.time() - 3600,+ "refresh_failure_count": 1,+ "refresh_next_attempt_at": int(time.time()) + 300,+ },+ )++ with patch("posthog.models.integration.OauthIntegration.refresh_access_token") as refresh_mock:+ refresh_integration(integration.id)++ assert refresh_mock.called is False+@parameterized.expand([("expired", int(time.time()) - 3600, True),