: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(tasks): skip unavailable GitHub integrations (#73105)
Alessandro Pogliaghi7e51aaba3f2a
diff --git a/products/signals/backend/test/test_resolve_team_github_integration.py b/products/signals/backend/test/test_resolve_team_github_integration.pyindex ce0b9c94f4c8..b107cff71c80 100644--- a/products/signals/backend/test/test_resolve_team_github_integration.py+++ b/products/signals/backend/test/test_resolve_team_github_integration.py@@ -8,8 +8,10 @@ from posthog.models import Organization, Team, Userfrom posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, GitHubIntegration, Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user_integration import UserGitHubIntegration, UserIntegration+from posthog.sync import database_sync_to_async-from products.signals.backend.report_generation.select_repo import resolve_team_github_integration+from products.signals.backend.report_generation.select_repo import resolve_team_github_integration, select_repository+from products.tasks.backend.facade import api as tasks_facade@pytest.fixture@@ -336,6 +338,29 @@ def test_returns_none_when_only_team_github_has_failed_token_refresh(team):assert resolve_team_github_integration(team.id) is None[email protected]_db(transaction=True)+async def test_select_repository_requests_reconnect_for_unavailable_owner_integration(organization, team):+ owner = await database_sync_to_async(_create_user)("[email protected]", organization)+ await database_sync_to_async(_create_user_integration)(+ owner,+ integration_id="user-dead",+ repository_cache=[],+ cache_synced=False,+ )+ await UserIntegration.objects.filter(user=owner).aupdate(config={"installation_unavailable_since": 1})++ result = await select_repository(+ team_id=team.id,+ user_id=owner.id,+ context="Investigate this signal",+ origin_product=tasks_facade.TaskOriginProduct.SIGNAL_REPORT,+ )++ assert result.repository is None+ assert result.reason == "The connected GitHub App is unavailable. Reconnect GitHub to continue."++@pytest.mark.django_dbdef test_prefers_org_account_over_user_account(organization, team):# Org accounts sort before User accounts on `config__account__type` (alphabetical).diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.pyindex b6b1899764c2..e34bb8246d58 100644--- a/products/tasks/backend/logic/repo_selection/agent.py+++ b/products/tasks/backend/logic/repo_selection/agent.py@@ -5,9 +5,9 @@ import loggingfrom collections.abc import Callable, Iterablefrom typing import TYPE_CHECKING-from django.db.models import Case, IntegerField, Value, When+from django.db.models import Case, IntegerField, Q, Value, When-from posthog.models.github_integration_base import GitHubIntegrationBase+from posthog.models.github_integration_base import INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY, GitHubIntegrationBasefrom posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, GitHubIntegration, Integrationfrom posthog.models.integration_repository_cache import GitHubRepositoryFullCachefrom posthog.models.organization import OrganizationMembership@@ -77,6 +77,7 @@ def _first_user_github_integration(user_ids: Iterable[int]) -> UserIntegration |user_id__in=user_ids,).exclude(repository_cache=[], repository_cache_updated_at__isnull=False)+ .exclude(config__has_key=INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY).annotate(_is_org_account=Case(When(config__account__type="User", then=Value(0)),@@ -115,6 +116,7 @@ def resolve_team_github_integration(# Skip installs whose token refresh is permanently failing (uninstalled/suspended on# GitHub's side): re-selecting one makes repo discovery storm GitHub with doomed refreshes..exclude(errors=ERROR_TOKEN_REFRESH_FAILED)+ .exclude(config__has_key=INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY)# Prioritize orgs vs users (alphabetically), then oldest first.order_by("config__account__type", "created_at", "id").first()@@ -143,6 +145,29 @@ def resolve_team_github_integration(return None+async def _github_reconnect_required(team_id: int) -> bool:+ if (+ await Integration.objects.filter(team_id=team_id, kind="github")+ .filter(Q(errors=ERROR_TOKEN_REFRESH_FAILED) | Q(config__has_key=INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY))+ .aexists()+ ):+ return True++ organization_id = await Team.objects.filter(id=team_id).values_list("organization_id", flat=True).afirst()+ if organization_id is None:+ return False+ owner_user_ids = OrganizationMembership.objects.filter(+ organization_id=organization_id,+ level=OrganizationMembership.Level.OWNER,+ user__is_active=True,+ ).values_list("user_id", flat=True)+ return await UserIntegration.objects.filter(+ kind=UserIntegration.IntegrationKind.GITHUB,+ user_id__in=owner_user_ids,+ config__has_key=INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY,+ ).aexists()++def _list_candidate_repos(github: GitHubIntegrationBase, team_id: int) -> list[str]:"""Fetch all repositories accessible via the resolved GitHub source."""repos: set[str] = set()@@ -373,9 +398,14 @@ async def select_repository(if github is None:github = await database_sync_to_async(resolve_team_github_integration, thread_sensitive=False)(team_id)if github is None:+ reconnect_required = await _github_reconnect_required(team_id)return RepoSelectionResult(repository=None,- reason="No GitHub repositories connected to this team.",+ reason=(+ "The connected GitHub App is unavailable. Reconnect GitHub to continue."+ if reconnect_required+ else "No GitHub repositories connected to this team."+ ),)if candidate_repos is None:candidate_repos = await database_sync_to_async(_list_candidate_repos, thread_sensitive=False)(github, team_id)diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 3fbfb8a0ee22..57f143634f2a 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -33,7 +33,8 @@ from posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.file_system.constants import DEFAULT_SURFACE, DESKTOP_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentation-from posthog.models.integration import Integration+from posthog.models.github_integration_base import INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integrationfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -528,7 +529,12 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):user_github_integration_is_usable,)- github_integration = Integration.objects.filter(team=team, kind="github").first()+ github_integration = (+ Integration.objects.filter(team=team, kind="github")+ .exclude(errors=ERROR_TOKEN_REFRESH_FAILED)+ .exclude(config__has_key=INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY)+ .first()+ )github_user_integration = Nonetask_stub = Task(team=team,diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex 87d66f1d909b..42e2ce8a3a2b 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -13,6 +13,7 @@ from django.test import TestCasefrom parameterized import parameterizedfrom posthog.models import Integration, Organization, Team+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILEDfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.models.user_integration import UserIntegration@@ -300,11 +301,16 @@ class TestTask(TestCase):@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_create_and_run_signal_report_falls_back_to_user_integration(self, mock_execute_workflow):- # Signal reports are BOT-authored. When the team has no Integration row but the task- # creator has a UserIntegration that grants access to the repo, we should accept it- # instead of raising "Team does not have a GitHub integration".+ # Signal reports are BOT-authored. A broken team installation must not override the+ # healthy user integration that repository selection used for the report.user = User.objects.create(email="[email protected]")OrganizationMembership.objects.create(user=user, organization=self.organization)+ Integration.objects.create(+ team=self.team,+ kind="github",+ errors=ERROR_TOKEN_REFRESH_FAILED,+ config={"installation_unavailable_since": 1},+ )user_integration = UserIntegration.objects.create(user=user,kind=UserIntegration.IntegrationKind.GITHUB,