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.

feat(devex): require an egress lane and source for every github client (#115236)

Julian Bezab899729b539
diff --git a/ee/api/agentic_provisioning/github_grants.py b/ee/api/agentic_provisioning/github_grants.py
index 0013324d23d3..9d5018ea5d4f 100644
--- a/ee/api/agentic_provisioning/github_grants.py
+++ b/ee/api/agentic_provisioning/github_grants.py
@@ -26,6 +26,7 @@ import structlog
from cryptography.fernet import InvalidToken
from posthog.egress.github.transport import github_request
+from posthog.egress.limiter.policies import Priority
from posthog.helpers.encrypted_fields import EncryptedTextField
from posthog.models.integration import GitHubUserAuthorization
from posthog.models.oauth import OAuthApplication
@@ -178,6 +179,7 @@ def fetch_primary_email(access_token: str) -> str | None:
headers={"Authorization": f"Bearer {access_token}"},
params={"per_page": 100},
timeout=10,
+ priority=Priority.CRITICAL,
)
if response.status_code >= 500:
raise requests.RequestException(f"Unexpected status {response.status_code} listing user emails")
@@ -216,6 +218,7 @@ def list_installations_and_repositories(access_token: str) -> dict[str, Any]:
headers={"Authorization": f"Bearer {access_token}"},
params={"per_page": 100},
timeout=10,
+ priority=Priority.CRITICAL,
)
if response.status_code != 200:
logger.warning("github_grant.list_installations_failed", status_code=response.status_code)
@@ -253,6 +256,7 @@ def _list_installation_repositories(access_token: str, installation_id: str) ->
headers={"Authorization": f"Bearer {access_token}"},
params={"per_page": _REPOSITORY_PAGE_SIZE, "page": page},
timeout=10,
+ priority=Priority.CRITICAL,
)
if response.status_code != 200:
logger.warning(
diff --git a/ee/api/agentic_provisioning/wizard.py b/ee/api/agentic_provisioning/wizard.py
index b6d588ccb9d2..d509e594d2e5 100644
--- a/ee/api/agentic_provisioning/wizard.py
+++ b/ee/api/agentic_provisioning/wizard.py
@@ -9,6 +9,7 @@ from django.utils import timezone
from rest_framework.exceptions import ValidationError as DRFValidationError
from posthog.api.github_callback.team_services import link_github_installation_for_user
+from posthog.egress.limiter.policies import Priority
from posthog.exceptions_capture import capture_exception
from posthog.models.integration import GitHubInstallationAccessFetchError, GitHubIntegration, Integration
from posthog.models.oauth import OAuthApplication
@@ -170,7 +171,12 @@ def create_wizard_run(
# reach the requested repo — a valid grant for one installation could otherwise report
# wizard success for an owner/repo it can't operate on. Fail fast instead (after the
# rate limits, so this GitHub call can't be used as an unthrottled probe).
- if GitHubIntegration.first_for_team_repository(team.id, repository, source="integration") is None:
+ if (
+ GitHubIntegration.first_for_team_repository(
+ team.id, repository, source="integration", priority=Priority.CRITICAL
+ )
+ is None
+ ):
raise _github_integration_required_error(partner, team)
try:
diff --git a/posthog/api/github.py b/posthog/api/github.py
index 9427c6551d9c..0753fae4c3ad 100644
--- a/posthog/api/github.py
+++ b/posthog/api/github.py
@@ -27,6 +27,7 @@ from posthog.api.secret_revocation import (
revoke_leaked_secret,
)
from posthog.egress.github.transport import github_request
+from posthog.egress.limiter.policies import Priority
from posthog.models import Team
from posthog.models.utils import mask_key_value
from posthog.redis import get_client
@@ -97,7 +98,14 @@ def verify_github_signature(payload: str, kid: str, sig: str) -> None:
if pem is None:
try:
# Unauthenticated endpoint, so there is no installation whose budget this draws from.
- resp = github_request("GET", GITHUB_KEYS_URI, source="secret_scanning", installation_id=None, timeout=10)
+ resp = github_request(
+ "GET",
+ GITHUB_KEYS_URI,
+ source="secret_scanning",
+ installation_id=None,
+ timeout=10,
+ priority=Priority.CRITICAL,
+ )
resp.raise_for_status()
data = resp.json()
except Exception:
diff --git a/posthog/api/github_callback/personal_finish.py b/posthog/api/github_callback/personal_finish.py
index 76c9ccac5105..1e24516f7f2c 100644
--- a/posthog/api/github_callback/personal_finish.py
+++ b/posthog/api/github_callback/personal_finish.py
@@ -20,6 +20,7 @@ from posthog.api.github_callback.types import (
is_valid_github_installation_id,
)
from posthog.egress.github.transport import github_request
+from posthog.egress.limiter.policies import Priority
from posthog.models import User
from posthog.models.integration import GitHubInstallationAccessFetchError, GitHubIntegration, Integration
from posthog.models.user_integration import (
@@ -135,6 +136,7 @@ def finish_personal(request: HttpRequest) -> FinishResult:
headers={"Authorization": f"Bearer {authorization.access_token}"},
params={"per_page": 100},
timeout=10,
+ priority=Priority.CRITICAL,
)
if response.status_code != 200:
logger.warning("github_link: failed to list user installations", status_code=response.status_code)
diff --git a/posthog/api/github_callback/personal_state.py b/posthog/api/github_callback/personal_state.py
index 9693d9a95b53..dcd29012b33e 100644
--- a/posthog/api/github_callback/personal_state.py
+++ b/posthog/api/github_callback/personal_state.py
@@ -13,6 +13,7 @@ import requests
from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubEgressBudgetExhausted, github_request
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration.github_audit import GitHubAudit
from posthog.models.user import User
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
@@ -53,7 +54,7 @@ def personal_github_login(user: User) -> str | None:
integration = _newest_personal_github_integration(user)
if integration is None:
return None
- return UserGitHubIntegration(integration).github_login
+ return UserGitHubIntegration(integration, source="github_callback", priority=Priority.CRITICAL).github_login
def usable_personal_github_credential(user: User) -> PersonalGitHubCredential | None:
@@ -69,7 +70,9 @@ def usable_personal_github_credential(user: User) -> PersonalGitHubCredential |
)
for integration in integrations:
try:
- token = UserGitHubIntegration(integration).get_usable_user_access_token()
+ token = UserGitHubIntegration(
+ integration, source="github_callback", priority=Priority.CRITICAL
+ ).get_usable_user_access_token()
except Exception:
continue
if token:
@@ -100,7 +103,9 @@ def list_user_github_app_installations(
return None
token = credential.token
if discovery:
- discovery.login = UserGitHubIntegration(credential.integration).github_login
+ discovery.login = UserGitHubIntegration(
+ credential.integration, source="github_callback", priority=Priority.CRITICAL
+ ).github_login
discovery.audit.record(
"discovery_credential_selected",
discovery_id=discovery.discovery_id,
@@ -116,6 +121,7 @@ def list_user_github_app_installations(
headers={"Authorization": f"Bearer {token}"},
params={"per_page": 100},
timeout=10,
+ priority=Priority.CRITICAL,
)
except (requests.RequestException, GitHubEgressBudgetExhausted):
if discovery:
diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.py
index 22aaf4cab476..bc2eb71f51db 100644
--- a/posthog/api/github_callback/team_services.py
+++ b/posthog/api/github_callback/team_services.py
@@ -34,6 +34,7 @@ from posthog.api.github_callback.types import (
from posthog.auth import SessionAuthentication
from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubEgressBudgetExhausted
+from posthog.egress.limiter.policies import Priority
from posthog.event_usage import report_user_action
from posthog.models import Team
from posthog.models.integration import (
@@ -267,7 +268,9 @@ def adopt_orphan_installation(
instance = GitHubIntegration.integration_from_installation_id(installation_id, team.id, user)
- login = UserGitHubIntegration(credential.integration).github_login
+ login = UserGitHubIntegration(
+ credential.integration, source="github_callback", priority=Priority.CRITICAL
+ ).github_login
if login:
instance.config["connecting_user_github_login"] = login
instance.save(update_fields=["config"])
@@ -634,7 +637,7 @@ def _sibling_installation_account(integration: Integration) -> _InstallationAcco
stranger's account in their settings. Missing names use the installation ID fallback so discovery
does not wait for a GitHub metadata request for each sibling installation.
"""
- github_integration = GitHubIntegration(integration)
+ github_integration = GitHubIntegration(integration, source="github_callback", priority=Priority.CRITICAL)
account = (integration.config or {}).get("account") or {}
name = account.get("name")
if not name or str(name) == str(github_integration.github_installation_id):
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index ca28809d8f77..0cc5d97f7928 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -51,6 +51,7 @@ from posthog.api.utils import action
from posthog.auth import SessionAuthentication
from posthog.domain_connect import discover_domain_connect, extract_root_domain_and_host, get_available_providers
from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.helpers.fuzzy_search import fuzzy_filter
@@ -782,7 +783,11 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
def get_installation_status(self, obj: Integration) -> str | None:
if obj.kind != "github":
return None
- return "unavailable" if GitHubIntegration(obj).installation_unavailable() else "connected"
+ return (
+ "unavailable"
+ if GitHubIntegration(obj, source="integrations_api", priority=Priority.CRITICAL).installation_unavailable()
+ else "connected"
+ )
def validate_kind(self, value: str) -> str:
if value == Integration.IntegrationKind.SLACK_POSTHOG_CODE.value:
@@ -2339,7 +2344,12 @@ class IntegrationViewSet(
instance = self.get_object()
if instance.kind != "github":
raise ValidationError("github_repos endpoint is only supported for GitHub integrations")
- return Response(github_repos_page(GitHubIntegration(instance), query_serializer.validated_data))
+ return Response(
+ github_repos_page(
+ GitHubIntegration(instance, source="integrations_api", priority=Priority.CRITICAL),
+ query_serializer.validated_data,
+ )
+ )
@extend_schema(parameters=[GitHubAssigneesQuerySerializer], responses={200: IntegrationAssigneesResponseSerializer})
@action(methods=["GET"], detail=True, url_path="github_assignees")
@@ -2352,7 +2362,9 @@ class IntegrationViewSet(
raise ValidationError("github_assignees endpoint is only supported for GitHub integrations")
query = query_serializer.validated_data
return assignees_response(
- lambda: GitHubIntegration(instance).list_assignees(query["repository"], query["search"])
+ lambda: GitHubIntegration(instance, source="integrations_api", priority=Priority.CRITICAL).list_assignees(
+ query["repository"], query["search"]
+ )
)
@extend_schema(request=GitHubPrepareCallbackRequestSerializer, responses={204: None})
@@ -2521,7 +2533,7 @@ class IntegrationViewSet(
instance = self.get_object()
if instance.kind != "github":
raise ValidationError("refresh_github_repos endpoint is only supported for GitHub integrations")
- github = GitHubIntegration(instance)
+ github = GitHubIntegration(instance, source="integrations_api", priority=Priority.CRITICAL)
try:
repositories = github.sync_repository_cache(
min_refresh_interval_seconds=GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS
@@ -2555,7 +2567,7 @@ class IntegrationViewSet(
limit = query_serializer.validated_data["limit"]
offset = query_serializer.validated_data["offset"]
- github = GitHubIntegration(self.get_object())
+ github = GitHubIntegration(self.get_object(), source="integrations_api", priority=Priority.CRITICAL)
try:
teams, has_more = github.list_teams(search=search, limit=limit, offset=offset)
except GitHubIntegrationError as err:
@@ -2585,7 +2597,7 @@ class IntegrationViewSet(
instance = self.get_object()
if instance.kind != "github":
raise ValidationError("github_branches endpoint is only supported for GitHub integrations")
- github = GitHubIntegration(instance)
+ github = GitHubIntegration(instance, source="github_branch_picker", priority=Priority.CRITICAL)
branches, default_branch, has_more = github.list_cached_branches(
repo,
search=search,
@@ -2775,7 +2787,7 @@ class IntegrationViewSet(
instances = page if page is not None else list(queryset)
for instance in instances:
if instance.kind == "github":
- GitHubIntegration(instance).ensure_account_name()
+ GitHubIntegration(instance, source="integrations_api", priority=Priority.CRITICAL).ensure_account_name()
# One grouped lookup for the whole page instead of an `exists()` per row, so
# `installation_shared` stays a fixed one query however many GitHub rows there are.
reference_counts = GitHubIntegration.installation_reference_counts(
@@ -2800,5 +2812,5 @@ class IntegrationViewSet(
# second query and permission check for the row already in hand.
instance = self.get_object()
if instance.kind == "github":
- GitHubIntegration(instance).ensure_account_name()
+ GitHubIntegration(instance, source="integrations_api", priority=Priority.CRITICAL).ensure_account_name()
return Response(self.get_serializer(instance).data)
diff --git a/posthog/api/test/test_github.py b/posthog/api/test/test_github.py
index 8a3a53656b44..c5434ea4116e 100644
--- a/posthog/api/test/test_github.py
+++ b/posthog/api/test/test_github.py
@@ -21,6 +21,7 @@ from posthog.api.github import (
relay_to_eu,
verify_github_signature,
)
+from posthog.egress.limiter.policies import Priority
from posthog.models import PersonalAPIKey
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthGrant, OAuthRefreshToken
from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT
@@ -92,6 +93,7 @@ UApLOdYtHUlWNMx0y6YwVG8nlBiJk2e0n+zpzs2WwszrnC7wfCqgU6rU3TkDvBQ==
"https://api.github.com/meta/public_keys/secret_scanning",
source="secret_scanning",
installation_id=None,
+ priority=Priority.CRITICAL,
timeout=10,
)
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 06235a0adb1b..0b639d08feb8 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -47,6 +47,7 @@ from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeState
from posthog.api.integration import IntegrationSerializer, IntegrationViewSet
from posthog.constants import AvailableFeature
from posthog.egress.github.transport import GitHubEgressBudgetExhausted
+from posthog.egress.limiter.policies import Priority
from posthog.models.activity_logging.activity_log import ActivityLog, apply_activity_visibility_restrictions
from posthog.models.integration import (
ERROR_TOKEN_REFRESH_FAILED,
@@ -6244,7 +6245,7 @@ class TestGitHubBranches:
config={"installation_id": "12345", "refreshed_at": 0, "expires_in": 999999},
sensitive_config={"access_token": "test-token"},
)
- self.github = GitHubIntegration(self.integration)
+ self.github = GitHubIntegration(self.integration, source="test", priority=Priority.CRITICAL)
@patch("posthog.egress.transport.transport.requests.request")
def test_list_branches_returns_first_page(self, mock_request):
@@ -7954,7 +7955,9 @@ class TestGitHubDiscoveryAudit(APIBaseTest):
integration_id = str(integration.pk)
with self.captureOnCommitCallbacks(execute=True):
with self.assertRaises(ReauthorizationRequired):
- UserGitHubIntegration(integration).get_usable_user_access_token()
+ UserGitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).get_usable_user_access_token()
log = ActivityLog.objects.get(item_id=integration_id, activity="github_diagnostic")
assert log.team_id is None
assert log.organization_id == self.organization.id
diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.py
index d7cc2f18ed9e..c58d236edecc 100644
--- a/posthog/api/test/test_user_integration.py
+++ b/posthog/api/test/test_user_integration.py
@@ -24,6 +24,7 @@ from posthog.api.github_callback.state import (
store_unified_authorize_state,
)
from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeState
+from posthog.egress.limiter.policies import Priority
from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.integration import (
GitHubInstallationAccess,
@@ -1121,7 +1122,7 @@ class TestUserGitHubIntegration(APIBaseTest):
"user_refresh_token": "ghr_refresh",
},
)
- return UserGitHubIntegration(integration)
+ return UserGitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
def test_github_login_and_id(self):
gh = self._make_integration()
@@ -1242,7 +1243,7 @@ class TestUserGitHubIntegration(APIBaseTest):
)
integration.kind = "slack"
with self.assertRaises(Exception, msg="non-github"):
- UserGitHubIntegration(integration)
+ UserGitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
def test_user_refresh_token_expired_returns_false_when_no_expiry(self):
gh = self._make_integration()
diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.py
index 997ff630038a..f4e657bf9135 100644
--- a/posthog/api/user_integration.py
+++ b/posthog/api/user_integration.py
@@ -59,6 +59,7 @@ from posthog.api.user_integration_codex import (
)
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.exceptions_capture import capture_exception
from posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, GitHubIntegrationError, Integration
from posthog.models.integration.github_audit import GitHubAudit
@@ -423,7 +424,9 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
results: list[dict[str, Any]] = []
for integration in integrations:
if integration.kind == "github":
- UserGitHubIntegration(integration).ensure_account_name()
+ UserGitHubIntegration(
+ integration, source="user_integrations_api", priority=Priority.CRITICAL
+ ).ensure_account_name()
results.append(
_serialize_github_integration(
integration,
@@ -487,7 +490,12 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
if integration is None:
raise exceptions.NotFound("No GitHub integration found for this installation.")
- return Response(github_repos_page(UserGitHubIntegration(integration), query_serializer.validated_data))
+ return Response(
+ github_repos_page(
+ UserGitHubIntegration(integration, source="user_integrations_api", priority=Priority.CRITICAL),
+ query_serializer.validated_data,
+ )
+ )
@extend_schema(
summary="Refresh repositories for a personal GitHub installation",
@@ -503,7 +511,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
if integration is None:
raise exceptions.NotFound("No GitHub integration found for this installation.")
- github = UserGitHubIntegration(integration)
+ github = UserGitHubIntegration(integration, source="user_integrations_api", priority=Priority.CRITICAL)
try:
repositories = github.sync_repository_cache(
min_refresh_interval_seconds=GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS
@@ -546,7 +554,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
if integration is None:
raise exceptions.NotFound("No GitHub integration found for this installation.")
- github = UserGitHubIntegration(integration)
+ github = UserGitHubIntegration(integration, source="github_branch_picker", priority=Priority.CRITICAL)
branches, default_branch, has_more = github.list_cached_branches(
repo,
search=search,
@@ -989,7 +997,7 @@ def _serialize_github_integration(
installation_reference_counts: dict[str, int],
) -> dict[str, Any]:
"""Build the response payload for a single GitHub UserIntegration."""
- github = UserGitHubIntegration(integration)
+ github = UserGitHubIntegration(integration, source="user_integrations_api", priority=Priority.CRITICAL)
# Mirrors github_destroy's uninstall_if_last_reference: any other row, team or personal, keeps the
# App installed on GitHub after this one is deleted. The precomputed map counts every reference
# for the installation including this row, so more than one means another row still shares it.
diff --git a/posthog/egress/README.md b/posthog/egress/README.md
index 7ad135283468..222b8ee9c64f 100644
--- a/posthog/egress/README.md
+++ b/posthog/egress/README.md
@@ -119,7 +119,7 @@ Request volume and the API's rate-limit headers land on one metric set, whicheve
- **Counter** (for example `github_integration_api_requests_total`): request volume, always recorded, including errors, rate-limited responses, and transport exceptions that raise before a response. Labeled `<scope>, method, endpoint, status_code, source`.
- **Gauges** (for example `github_integration_api_rate_limit_remaining`): last-observed budget headroom parsed from the API's response headers. Labeled `<scope>, resource`, with no `source`, because the budget is shared across sources. The gauges are optional: a domain declares only the ones its API reports, and parses only headers the API documents.
-- **Decisions** (`outbound_rate_limit_decisions_total`): one sample per limiter admission, labeled `domain, source, priority, granted`.
+- **Decisions** (`outbound_rate_limit_decisions_total`): one sample per limiter admission, labeled `domain, scope, source, priority, granted`. `scope` is the id segment of the limiter key, the same value the domain's request counter records, so a denial joins to the budget owner it hit. A policy opts in with `scope_in_metrics=True`, as the GitHub policies do; any other domain records an empty `scope`, so a key scoped per PostHog team adds no series per team.
Each domain keeps its own metric names, so existing dashboards stay valid.
The `source` label (e.g. `integration`, `visual_review`, `warehouse`) carries per-subsystem attribution.
diff --git a/posthog/egress/github/README.md b/posthog/egress/github/README.md
index a44b5cb3f5f1..a7314e366063 100644
--- a/posthog/egress/github/README.md
+++ b/posthog/egress/github/README.md
@@ -23,6 +23,10 @@ GraphQL routes to `core`. GitHub meters GraphQL by points, which a request count
## Lanes and callers
All three budgets use the default reserve ladder.
+Every GitHub client (`GitHubIntegration`, `UserGitHubIntegration`, `GitHubIntegration.first_for_team_repository`) and every `github_request` call must pass `priority` and `source`.
+There is no default lane and no default source, so a new caller has to pick both.
+Pick `CRITICAL` only when a person or a correctness path waits on the call, because the limiter never sheds it.
+Use one stable snake_case `source` per subsystem, so the egress metrics show who spends the installation budget.
Deferrable background callers construct their client on the `BATCH` lane (`GitHubIntegration(integration, source=..., priority=Priority.BATCH)`; `api_request` also takes a per-call override).
A shed sweep stops for the cycle and resumes on the next scheduled run.
A caller that walks pages, such as the warehouse source, paces with `github_installation_pace_seconds` instead of getting denied.
@@ -32,7 +36,7 @@ The repository cache behind repository selection (`posthog/models/integration_re
The branch picker serves its cached branch list at once. When the list is older than ten minutes, a background task lists the branches again on `BATCH`, waiting for the limiter's pace before each page. Only a repository with no cached list is listed inside the request.
Engineering analytics downloads one job's log (source `job_logs`) on `NORMAL` when a person opens that job in the CI explorer, and on `BATCH` in the scheduled failed-job log collection.
Stamphog reads the author-familiarity blame and history (GraphQL) and the pull request's commit messages on `BATCH`, because both signals are advisory: a shed call leaves them out of that review.
-Its merge base read (compare) stays on the default lane, because the review checkout needs it.
+Its merge base read (compare) stays on `CRITICAL`, because the review checkout needs it.
The Tasks infrastructure admin reads the sandbox version pin and recent image build runs on `NORMAL`, using a regional cache. When the GitHub App is configured, it discovers the `PostHog/posthog` installation and mints an ephemeral token restricted to that repository with Contents and Actions read permissions. Calls share the installation budget. Deployments without App credentials retain the shared-token behavior.
The `BATCH` floor on the `core` resource is **demand-responsive**, because a reserve is only worth holding against traffic that exists.
diff --git a/posthog/egress/github/limiter.py b/posthog/egress/github/limiter.py
index f651461ad0b6..7669ad93fbe8 100644
--- a/posthog/egress/github/limiter.py
+++ b/posthog/egress/github/limiter.py
@@ -276,6 +276,7 @@ def _github_policy(key: str) -> RatePolicy:
limits=((per_minute, 60.0), (hourly, 3600.0)),
in_memory_divider=4,
reserve=DEFAULT_RESERVE if has_interactive_demand(installation_id) else _IDLE_RESERVE,
+ scope_in_metrics=True,
)
@@ -285,8 +286,8 @@ register_policy(GITHUB_DOMAIN, _github_policy)
# of the account's plan tier (unlike core), so there is no tier to observe. Both sit just under
# GitHub's real per-installation ceilings (10/min and 30/min) so our reactive backoff absorbs
# drift. The default reserve ladder applies, so BATCH/NORMAL callers still shed first as the window fills.
-register_policy(GITHUB_CODE_SEARCH_DOMAIN, RatePolicy(limits=((8, 60.0),), in_memory_divider=4))
-register_policy(GITHUB_SEARCH_DOMAIN, RatePolicy(limits=((27, 60.0),), in_memory_divider=4))
+register_policy(GITHUB_CODE_SEARCH_DOMAIN, RatePolicy(limits=((8, 60.0),), in_memory_divider=4, scope_in_metrics=True))
+register_policy(GITHUB_SEARCH_DOMAIN, RatePolicy(limits=((27, 60.0),), in_memory_divider=4, scope_in_metrics=True))
def github_installation_key(
diff --git a/posthog/egress/github/transport.py b/posthog/egress/github/transport.py
index aa44d554c053..fa07ccd0a539 100644
--- a/posthog/egress/github/transport.py
+++ b/posthog/egress/github/transport.py
@@ -139,7 +139,7 @@ def github_request(
source: str,
headers: dict[str, str] | None = None,
installation_id: str | None = None,
- priority: Priority = Priority.CRITICAL,
+ priority: Priority,
endpoint: str | None = None,
timeout: float | tuple[float, float] | None = None,
session: requests.Session | None = None,
diff --git a/posthog/egress/limiter/outbound.py b/posthog/egress/limiter/outbound.py
index afacaf6a8a90..c3cd1ec30c15 100644
--- a/posthog/egress/limiter/outbound.py
+++ b/posthog/egress/limiter/outbound.py
@@ -19,6 +19,11 @@ def _domain_of(key: str) -> str:
return key.partition(":")[0]
+def _metric_scope(key: str, policy: RatePolicy) -> str:
+ # The id segment: the value the domain's request counter records as its scope, so the two join.
+ return key.rpartition(":")[2] if policy.scope_in_metrics else ""
+
+
def _validate(n: int, policy: RatePolicy, priority: Priority) -> None:
if n < 1:
raise ValueError(f"rate limiter weight must be >= 1, got {n}")
@@ -46,7 +51,13 @@ class OutboundRateLimiter:
policy = resolve_policy(key)
_validate(n, policy, priority)
granted = await self._backend.acquire(key, policy, n, priority)
- record_outbound_decision(domain=_domain_of(key), source=source, priority=priority.value, granted=granted)
+ record_outbound_decision(
+ domain=_domain_of(key),
+ scope=_metric_scope(key, policy),
+ source=source,
+ priority=priority.value,
+ granted=granted,
+ )
return granted
def consume_sync(
@@ -56,7 +67,13 @@ class OutboundRateLimiter:
policy = resolve_policy(key)
_validate(n, policy, priority)
granted = self._backend.consume_sync(key, policy, n, priority)
- record_outbound_decision(domain=_domain_of(key), source=source, priority=priority.value, granted=granted)
+ record_outbound_decision(
+ domain=_domain_of(key),
+ scope=_metric_scope(key, policy),
+ source=source,
+ priority=priority.value,
+ granted=granted,
+ )
return granted
def pace_seconds(self, key: str, *, priority: Priority = Priority.NORMAL) -> float:
diff --git a/posthog/egress/limiter/policies.py b/posthog/egress/limiter/policies.py
index 1813729b5905..cd2193e765ff 100644
--- a/posthog/egress/limiter/policies.py
+++ b/posthog/egress/limiter/policies.py
@@ -55,11 +55,16 @@ class RatePolicy:
priority absent from the map reserves nothing (0.0), so ``reserve={}`` admits every lane to the
full budget. Pass it only for a domain with no higher-priority traffic to protect. Fractions are
validated to ``[0, 1)`` (1.0 would reserve the whole window and deny the priority forever).
+
+ ``scope_in_metrics`` records the key's id segment as the ``scope`` label on the decision counter.
+ Turn it on only for a domain whose scopes are few and stable, such as GitHub installations: a key
+ scoped per PostHog team would add a metric series per team.
"""
limits: tuple[RateLimit, ...]
in_memory_divider: int = 1
reserve: Mapping[Priority, float] = DEFAULT_RESERVE
+ scope_in_metrics: bool = False
def __post_init__(self) -> None:
# A policy with no limits would let every call through, defeating the point. Reject it at
diff --git a/posthog/egress/observability/observability.py b/posthog/egress/observability/observability.py
index fb9cafda05be..7e567509660e 100644
--- a/posthog/egress/observability/observability.py
+++ b/posthog/egress/observability/observability.py
@@ -207,11 +207,11 @@ outbound_rate_limit_decisions = Counter(
"Outbound egress rate limiter admission decisions. Recorded per attempt, so a shed call that retries "
"(e.g. warehouse _fetch_page under tenacity) inflates granted=false by the retry count — alert on the "
"grant/deny ratio or rate, not raw denied totals.",
- labelnames=["domain", "source", "priority", "granted"],
+ labelnames=["domain", "scope", "source", "priority", "granted"],
)
-def record_outbound_decision(*, domain: str, source: str, priority: str, granted: bool) -> None:
+def record_outbound_decision(*, domain: str, scope: str, source: str, priority: str, granted: bool) -> None:
"""Record one limiter decision. ``priority`` is the lane string (e.g. ``"batch"``); the caller
derives ``domain`` from the limiter key's first segment so this stays limiter-library-agnostic."""
- outbound_rate_limit_decisions.labels(domain, source, priority, "true" if granted else "false").inc()
+ outbound_rate_limit_decisions.labels(domain, scope, source, priority, "true" if granted else "false").inc()
diff --git a/posthog/egress/test/test_github_transport.py b/posthog/egress/test/test_github_transport.py
index 59538f8b5509..f612549d8c32 100644
--- a/posthog/egress/test/test_github_transport.py
+++ b/posthog/egress/test/test_github_transport.py
@@ -11,6 +11,7 @@ from requests.structures import CaseInsensitiveDict
from posthog.egress.github.limiter import GitHubRateResource
from posthog.egress.github.transport import GitHubClient, github_request
+from posthog.egress.limiter.policies import Priority
def _response(status: int = 200) -> requests.Response:
@@ -50,6 +51,7 @@ class TestGitHubTransport(SimpleTestCase):
source="integration",
installation_id="42",
endpoint="/repos/{owner}/{repo}/branches",
+ priority=Priority.CRITICAL,
)
span = exporter.get_finished_spans()[0]
@@ -90,7 +92,13 @@ class TestGitHubTransport(SimpleTestCase):
patch("posthog.egress.github.transport.consume_github_installation_sync") as consume,
patch("requests.request", return_value=_response()),
):
- github_request("GET", "https://api.github.com/search/code?q=x", source="test", installation_id=None)
+ github_request(
+ "GET",
+ "https://api.github.com/search/code?q=x",
+ source="test",
+ installation_id=None,
+ priority=Priority.CRITICAL,
+ )
consume.assert_not_called()
def test_span_marks_a_gate_error(self) -> None:
@@ -104,7 +112,13 @@ class TestGitHubTransport(SimpleTestCase):
patch("requests.request") as send,
self.assertRaises(RuntimeError),
):
- github_request("GET", "https://api.github.com/repos/example/repo", source="test", installation_id="42")
+ github_request(
+ "GET",
+ "https://api.github.com/repos/example/repo",
+ source="test",
+ installation_id="42",
+ priority=Priority.CRITICAL,
+ )
send.assert_not_called()
span = exporter.get_finished_spans()[0]
@@ -121,7 +135,12 @@ class TestGitHubTransport(SimpleTestCase):
patch("posthog.egress.transport.transport.tracer", provider.get_tracer("test")),
patch("requests.request", return_value=_response()),
):
- github_request("GET", "https://raw.githubusercontent.com/PostHog/posthog/main/README.md", source="test")
+ github_request(
+ "GET",
+ "https://raw.githubusercontent.com/PostHog/posthog/main/README.md",
+ source="test",
+ priority=Priority.CRITICAL,
+ )
attributes = exporter.get_finished_spans()[0].attributes
assert attributes is not None
@@ -138,7 +157,9 @@ class TestGitHubTransport(SimpleTestCase):
patch("posthog.egress.transport.transport.tracer", provider.get_tracer("test")),
patch("requests.request", return_value=response),
):
- github_request("GET", "https://api.github.com/repos/example/repo/archive", source="test")
+ github_request(
+ "GET", "https://api.github.com/repos/example/repo/archive", source="test", priority=Priority.CRITICAL
+ )
attributes = exporter.get_finished_spans()[0].attributes
assert attributes is not None
@@ -156,7 +177,12 @@ class TestGitHubTransport(SimpleTestCase):
patch("posthog.egress.transport.transport.tracer", provider.get_tracer("test")),
patch("requests.request", return_value=response),
):
- assert github_request("GET", "https://api.github.com/repos/example/repo", source="test") is response
+ assert (
+ github_request(
+ "GET", "https://api.github.com/repos/example/repo", source="test", priority=Priority.CRITICAL
+ )
+ is response
+ )
attributes = exporter.get_finished_spans()[0].attributes
assert attributes is not None
@@ -176,6 +202,7 @@ class TestGitHubTransport(SimpleTestCase):
"https://api.github.com/repos/example/repo/branches?page=1",
source="test",
installation_id="",
+ priority=Priority.CRITICAL,
)
attributes = exporter.get_finished_spans()[0].attributes
diff --git a/posthog/egress/test/test_outbound_rate_limiter.py b/posthog/egress/test/test_outbound_rate_limiter.py
index 99c19085f8ce..d9c1743dfcfc 100644
--- a/posthog/egress/test/test_outbound_rate_limiter.py
+++ b/posthog/egress/test/test_outbound_rate_limiter.py
@@ -2,6 +2,8 @@ import uuid
import pytest
+from prometheus_client import REGISTRY
+
import posthog.egress.limiter.backends as backends_module
import posthog.egress.limiter.outbound as outbound_module
import posthog.egress.limiter.policies as policies_module
@@ -73,6 +75,28 @@ async def test_unique_keys_do_not_share_budget():
assert await limiter.acquire("test-isolation:scope:B", 1) is True
[email protected]("scope_in_metrics", [True, False])
+def test_denied_decision_records_its_scope_only_when_the_policy_opts_in(scope_in_metrics: bool) -> None:
+ # A denial must trace to the installation it hit, but a key scoped per PostHog team must not add a
+ # metric series per team.
+ domain = f"test-decision-scope-{scope_in_metrics}"
+ register_policy(domain, RatePolicy(limits=((1, 3600.0),), scope_in_metrics=scope_in_metrics))
+ limiter = _fresh_limiter()
+ key = _unique_key(domain)
+ labels = {
+ "domain": domain,
+ "scope": key.rpartition(":")[2] if scope_in_metrics else "",
+ "source": "probe",
+ "priority": "normal",
+ "granted": "false",
+ }
+
+ limiter.consume_sync(key, source="probe")
+ limiter.consume_sync(key, source="probe")
+
+ assert REGISTRY.get_sample_value("outbound_rate_limit_decisions_total", labels) == 1
+
+
def test_policy_rejects_empty_limits():
# A limit-less policy would let every call through; it must fail at definition time rather than
# surfacing an opaque min() error on first acquire.
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 4acb9a39afcc..e0dc95bde431 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -38,7 +38,7 @@ from posthog.utils import safe_cache_add, safe_cache_delete
logger = structlog.get_logger(__name__)
-# This client always knows its installation, so it records under source="integration" with a real id.
+# App-JWT and user-OAuth calls made directly by this class record under this source.
_OBSERVABILITY_SOURCE = "integration"
github_cache_access_counter = Counter(
@@ -230,15 +230,15 @@ class GitHubIntegrationBase:
integration: Any # Integration | UserIntegration -- subclasses narrow the type
# Names the table `integration` lives in, so a background task can load the row again.
is_user_integration: bool = False
- # Per-subsystem attribution on the shared egress metrics. Product callers construct their client
- # with their own source (e.g. GitHubIntegration(integration, source="visual_review")) so every
- # request made through this instance — api_request, verbs, GraphQL — is attributed to them.
- source: str = _OBSERVABILITY_SOURCE
+ # Per-subsystem attribution on the shared egress metrics. Every caller constructs its client
+ # with its own source (e.g. GitHubIntegration(integration, source="visual_review", ...)) so every
+ # request made through this instance — api_request, verbs, GraphQL — is attributed to it.
+ source: str
# How sheddable this instance's calls are when the installation's shared budget runs hot.
- # CRITICAL (the default) is never blocked; deferrable background callers construct with
- # priority=Priority.BATCH so the egress limiter sheds them first — a denied sheddable call
- # raises GitHubEgressBudgetExhausted from api_request before anything is sent.
- priority: Priority = Priority.CRITICAL
+ # Every caller picks it at construction. CRITICAL is never blocked; deferrable background callers
+ # construct with priority=Priority.BATCH so the egress limiter sheds them first — a denied
+ # sheddable call raises GitHubEgressBudgetExhausted from api_request before anything is sent.
+ priority: Priority
@property
def github_installation_id(self) -> str | None:
@@ -314,6 +314,7 @@ class GitHubIntegrationBase:
timeout=timeout,
# requests omits the body entirely when json is None
json=json_body,
+ priority=Priority.CRITICAL,
)
@classmethod
@@ -481,6 +482,7 @@ class GitHubIntegrationBase:
endpoint="/user/installations/{installation_id}/repositories",
params={"per_page": 1},
timeout=10,
+ priority=Priority.CRITICAL,
)
if response.status_code == 200:
return True
diff --git a/posthog/models/integration/external_issues.py b/posthog/models/integration/external_issues.py
index b1d7c19eb1cc..adcf9f3488a5 100644
--- a/posthog/models/integration/external_issues.py
+++ b/posthog/models/integration/external_issues.py
@@ -2,6 +2,8 @@
from typing import Any
+from posthog.egress.limiter.policies import Priority
+
from . import model
from .github import GitHubIntegration
from .gitlab import GitLabIntegration
@@ -45,7 +47,7 @@ def external_issue_url(integration: model.Integration, external_context: dict[st
repository_path = (
str(repository)
if "/" in str(repository)
- else f"{GitHubIntegration(integration).organization()}/{repository}"
+ else f"{GitHubIntegration(integration, source='external_issues', priority=Priority.CRITICAL).organization()}/{repository}"
)
resource_path = "pull" if context.get("resource_type") == "pull_request" else "issues"
return f"https://github.com/{repository_path}/{resource_path}/{number}"
diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.py
index 83a3c2e0039a..e65ad8a38061 100644
--- a/posthog/models/integration/github.py
+++ b/posthog/models/integration/github.py
@@ -306,6 +306,7 @@ class GitHubIntegration(GitHubIntegrationBase):
source="integration",
headers={"Authorization": f"Bearer {access_token}"},
timeout=10,
+ priority=Priority.CRITICAL,
)
if user_response.status_code != 200:
logger.warning("GitHubIntegration: /user request failed", status_code=user_response.status_code)
@@ -333,8 +334,8 @@ class GitHubIntegration(GitHubIntegrationBase):
team_id: int,
repository: str,
*,
- source: str | None = None,
- priority: Priority | None = None,
+ source: str,
+ priority: Priority,
) -> "GitHubIntegration | None":
"""First GitHub integration for the team whose installation can access ``repository`` (``owner/name``).
@@ -365,16 +366,12 @@ class GitHubIntegration(GitHubIntegrationBase):
raise exhausted
return None
- def __init__(
- self, integration: model.Integration, *, source: str | None = None, priority: Priority | None = None
- ) -> None:
+ def __init__(self, integration: model.Integration, *, source: str, priority: Priority) -> None:
if integration.kind != "github":
raise Exception("GitHubIntegration init called with Integration with wrong 'kind'")
self.integration = integration
- if source is not None:
- self.source = source
- if priority is not None:
- self.priority = priority
+ self.source = source
+ self.priority = priority
def _on_token_refresh_failed(self, response: requests.Response) -> None:
logger.warning(f"Failed to refresh token for {self}", response=response.text)
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index cbe41a0baad4..ba84879b108d 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -82,7 +82,7 @@ class TestExtractFailingChecks(SimpleTestCase):
class TestGitHubPullRequestChecks(SimpleTestCase):
def test_reports_missing_checks_permission(self):
integration = MagicMock(kind="github", config={"permissions": {"contents": "read"}})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}):
result = github.get_pull_request_checks("example/legacy", 7)
@@ -119,7 +119,9 @@ class TestCollaboratorPermission(SimpleTestCase):
]
)
def test_permission_counts_only_for_the_expected_account(self, _name, body, expected) -> None:
- github = GitHubIntegration(Integration(kind="github", config={}, sensitive_config={}))
+ github = GitHubIntegration(
+ Integration(kind="github", config={}, sensitive_config={}), source="test", priority=Priority.CRITICAL
+ )
response = MagicMock(status_code=200)
response.json.return_value = body
with patch.object(github, "api_request", return_value=response):
@@ -137,7 +139,9 @@ class TestPullRequestCommentMarker(SimpleTestCase):
]
)
def test_marker_absence_requires_a_complete_read(self, name, body, complete, expected) -> None:
- github = GitHubIntegration(Integration(kind="github", config={}, sensitive_config={}))
+ github = GitHubIntegration(
+ Integration(kind="github", config={}, sensitive_config={}), source="test", priority=Priority.CRITICAL
+ )
response = MagicMock(status_code=200)
response.json.return_value = body
with patch.object(github, "_installation_authenticated_get_pages", return_value=([response], complete)):
@@ -151,7 +155,9 @@ class TestPullRequestCommentMarker(SimpleTestCase):
]
)
def test_merge_queue_state_refuses_a_partial_read(self, _name, status_code, body, complete) -> None:
- github = GitHubIntegration(Integration(kind="github", config={}, sensitive_config={}))
+ github = GitHubIntegration(
+ Integration(kind="github", config={}, sensitive_config={}), source="test", priority=Priority.CRITICAL
+ )
response = MagicMock(status_code=status_code)
response.json.return_value = body
with patch.object(github, "_installation_authenticated_get_pages", return_value=([response], complete)):
@@ -168,7 +174,9 @@ class TestPullRequestCommentMarker(SimpleTestCase):
]
)
def test_stacked_pull_request_read_never_guesses(self, _name, status_code, body, expected) -> None:
- github = GitHubIntegration(Integration(kind="github", config={}, sensitive_config={}))
+ github = GitHubIntegration(
+ Integration(kind="github", config={}, sensitive_config={}), source="test", priority=Priority.CRITICAL
+ )
response = MagicMock(status_code=status_code)
response.json.return_value = body
complete = expected != "partial"
@@ -186,7 +194,9 @@ class TestPullRequestCommentMarker(SimpleTestCase):
]
)
def test_unsafe_repository_never_reaches_github(self, _name, read) -> None:
- github = GitHubIntegration(Integration(kind="github", config={}, sensitive_config={}))
+ github = GitHubIntegration(
+ Integration(kind="github", config={}, sensitive_config={}), source="test", priority=Priority.CRITICAL
+ )
with (
patch.object(github, "_installation_authenticated_get") as single,
patch.object(github, "_installation_authenticated_get_pages") as pages,
@@ -197,7 +207,9 @@ class TestPullRequestCommentMarker(SimpleTestCase):
pages.assert_not_called()
def test_merge_queue_state_reads_the_trunk_comment(self) -> None:
- github = GitHubIntegration(Integration(kind="github", config={}, sensitive_config={}))
+ github = GitHubIntegration(
+ Integration(kind="github", config={}, sensitive_config={}), source="test", priority=Priority.CRITICAL
+ )
response = MagicMock(status_code=200)
response.json.return_value = [
{"user": {"login": "someone"}, "body": "LGTM"},
@@ -287,14 +299,16 @@ class TestGitHubIntegrationModel(BaseTest):
mock_response.json.return_value = {"message": "Not Found"}
mock_client_request.return_value = mock_response
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with pytest.raises(GitHubIntegrationError):
github.mint_scoped_installation_token({"contents": "read"})
# Without the permanently-gone marker, every scheduled run re-mints a dead installation
# forever — the marker is what lets callers skip it until the customer reconnects.
integration.refresh_from_db()
- assert GitHubIntegration(integration).installation_unavailable() is True
+ assert (
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).installation_unavailable() is True
+ )
assert "expires_in" not in integration.config
@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
@@ -304,7 +318,9 @@ class TestGitHubIntegrationModel(BaseTest):
mock_response.json.return_value = {"token": "SCOPED_TOKEN", "expires_at": "2024-01-01T13:00:00Z"}
mock_client_request.return_value = mock_response
- token = GitHubIntegration(integration).mint_scoped_installation_token({"contents": "read"})
+ token = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).mint_scoped_installation_token({"contents": "read"})
assert token == "SCOPED_TOKEN"
# Without the permissions body the mint returns a FULL-permission token — a silent
@@ -329,7 +345,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
def test_author_last_commit_reports_what_github_answered(self, _name, status_code, body, expected):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=status_code)
mock_response.json.return_value = body
@@ -351,7 +367,7 @@ class TestGitHubIntegrationModel(BaseTest):
# A caller drops a reviewer on a dated answer, so a failed lookup must not read as
# "this account never committed".
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=status_code)
mock_response.json.return_value = body
@@ -360,7 +376,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_diff_compares_branch_tips(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200, text="diff --git a b")
with patch.object(github, "api_request", return_value=mock_response) as mock_get:
result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")
@@ -374,7 +390,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_diff_pins_to_shas_when_given(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200, text="diff --git a b")
with patch.object(github, "api_request", return_value=mock_response) as mock_get:
result = github.get_diff(
@@ -389,7 +405,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_diff_maps_upstream_error(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=404, text="Not Found")
with patch.object(github, "api_request", return_value=mock_response):
result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")
@@ -397,7 +413,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_diff_handles_request_exception(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with patch.object(github, "api_request", side_effect=GitHubIntegrationError("network error")):
result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")
assert result["success"] is False
@@ -405,7 +421,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_pull_request_diff_uses_the_durable_pr_endpoint(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200, text="diff --git a b")
with patch.object(github, "api_request", return_value=mock_response) as mock_get:
result = github.get_pull_request_diff("PostHog/posthog", 42)
@@ -422,7 +438,7 @@ class TestGitHubIntegrationModel(BaseTest):
integration = self.create_integration(
config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
)
- return GitHubIntegration(integration)
+ return GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
@staticmethod
def _git_data_api_request(*, ref_status: int = 201):
@@ -546,7 +562,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_open_pull_request_for_head_returns_number_and_url(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200)
mock_response.json.return_value = [
{
@@ -564,7 +580,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_open_pr_base_for_head_returns_base_ref_of_open_pr(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200)
mock_response.json.return_value = [
{
@@ -586,7 +602,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_open_pr_base_for_head_returns_none_when_no_open_pr(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200)
mock_response.json.return_value = []
with patch.object(github, "_installation_authenticated_get", return_value=mock_response):
@@ -594,13 +610,13 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_open_pr_base_for_head_returns_none_on_error(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with patch.object(github, "_installation_authenticated_get", return_value=None):
assert github.get_open_pr_base_for_head("PostHog/posthog", "posthog-code/fix") is None
def test_get_pull_request_comments_merges_conversation_and_review_sorted(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
def fake_get(url, **kwargs):
response = MagicMock(status_code=200)
@@ -640,7 +656,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_pull_request_comments_best_effort_when_one_source_fails(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
def fake_get(url, **kwargs):
if "/issues/" in url:
@@ -671,7 +687,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_pull_request_checks_merges_check_runs_and_statuses(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
def fake_get(url, **kwargs):
response = MagicMock(status_code=200)
@@ -706,7 +722,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_pull_request_checks_follows_pagination(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
def fake_get(url, **kwargs):
response = MagicMock(status_code=200)
@@ -749,7 +765,7 @@ class TestGitHubIntegrationModel(BaseTest):
@parameterized.expand([("check_runs",), ("statuses",)])
def test_get_pull_request_checks_fails_when_later_page_is_unavailable(self, failing_source):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
def fake_get(url, **kwargs):
source = "check_runs" if "/check-runs" in url else "statuses"
@@ -777,7 +793,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_pull_request_checks_fails_when_pr_unavailable(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with patch.object(github, "get_pull_request", return_value={"success": False, "error": "nope"}):
result = github.get_pull_request_checks("PostHog/posthog", 1)
assert result["success"] is False
@@ -786,7 +802,7 @@ class TestGitHubIntegrationModel(BaseTest):
from posthog.models.integration.github import _MAX_DIFF_CHARS
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
oversized = "x" * (_MAX_DIFF_CHARS + 100)
mock_response = MagicMock(status_code=200, text=oversized)
with patch.object(github, "api_request", return_value=mock_response):
@@ -799,7 +815,11 @@ class TestGitHubIntegrationModel(BaseTest):
@parameterized.expand([("inline", False), ("over_contents_api_limit", True)])
def test_get_file_contents_returns_whole_file(self, _name: str, over_contents_api_limit: bool) -> None:
- github = GitHubIntegration(self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"}))
+ github = GitHubIntegration(
+ self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"}),
+ source="test",
+ priority=Priority.CRITICAL,
+ )
text = b"version: 1\nsnapshots: {}\n"
contents = {
"sha": "abc123",
@@ -832,7 +852,11 @@ class TestGitHubIntegrationModel(BaseTest):
]
)
def test_get_file_contents_rejects_file_it_cannot_return_whole(self, _name: str, contents: dict[str, Any]) -> None:
- github = GitHubIntegration(self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"}))
+ github = GitHubIntegration(
+ self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"}),
+ source="test",
+ priority=Priority.CRITICAL,
+ )
def blob_chunks(chunk_size: int) -> Iterator[bytes]:
yield b"version: 1\n"
@@ -861,7 +885,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
def test_get_diff_rejects_unsafe_values(self, _name, overrides):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
kwargs: dict = {"repository": "PostHog/posthog", "target_branch": "feature/foo", "base_branch": "master"}
kwargs.update(overrides)
with patch.object(github, "api_request") as mock_get:
@@ -872,7 +896,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_get_diff_allows_nested_branch_names(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200, text="diff --git a b")
with patch.object(github, "api_request", return_value=mock_response) as mock_get:
result = github.get_diff(
@@ -895,14 +919,18 @@ class TestGitHubIntegrationModel(BaseTest):
# an unsafe path must be rejected before any request fires, so it can't probe other endpoints.
self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
with patch.object(GitHubIntegration, "installation_can_access_repository") as mock_access:
- result = GitHubIntegration.first_for_team_repository(self.team.id, repository)
+ result = GitHubIntegration.first_for_team_repository(
+ self.team.id, repository, source="test", priority=Priority.CRITICAL
+ )
assert result is None
mock_access.assert_not_called()
def test_first_for_team_repository_allows_owner_repo(self):
self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
with patch.object(GitHubIntegration, "installation_can_access_repository", return_value=True) as mock_access:
- result = GitHubIntegration.first_for_team_repository(self.team.id, "PostHog/posthog")
+ result = GitHubIntegration.first_for_team_repository(
+ self.team.id, "PostHog/posthog", source="test", priority=Priority.CRITICAL
+ )
assert result is not None
mock_access.assert_called_once_with("PostHog/posthog")
@@ -918,7 +946,9 @@ class TestGitHubIntegrationModel(BaseTest):
self.create_integration(sensitive_config={"access_token": "FIRST"})
covering = self.create_integration(sensitive_config={"access_token": "SECOND"})
with patch.object(GitHubIntegration, "installation_can_access_repository", side_effect=[error, True]):
- result = GitHubIntegration.first_for_team_repository(self.team.id, "PostHog/posthog")
+ result = GitHubIntegration.first_for_team_repository(
+ self.team.id, "PostHog/posthog", source="test", priority=Priority.CRITICAL
+ )
assert result is not None
assert result.integration.id == covering.id
@@ -937,7 +967,9 @@ class TestGitHubIntegrationModel(BaseTest):
self.create_integration(sensitive_config={"access_token": "SECOND"})
with patch.object(GitHubIntegration, "installation_can_access_repository", side_effect=[error, False]):
with pytest.raises(type(error)):
- GitHubIntegration.first_for_team_repository(self.team.id, "PostHog/posthog")
+ GitHubIntegration.first_for_team_repository(
+ self.team.id, "PostHog/posthog", source="test", priority=Priority.CRITICAL
+ )
@parameterized.expand(
[
@@ -950,7 +982,7 @@ class TestGitHubIntegrationModel(BaseTest):
integration = self.create_integration(
config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
)
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200)
mock_response.json.return_value = {"number": 123, "state": "closed"}
with patch.object(github, "_installation_authenticated_patch", return_value=mock_response) as mock_patch:
@@ -961,7 +993,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_close_pull_request_maps_upstream_error(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=404, text="Not Found")
with patch.object(github, "_installation_authenticated_patch", return_value=mock_response):
result = github.close_pull_request("PostHog/posthog", 123)
@@ -969,7 +1001,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_close_pull_request_from_url_parses_and_closes(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200)
mock_response.json.return_value = {"number": 42, "state": "closed"}
with patch.object(github, "_installation_authenticated_patch", return_value=mock_response) as mock_patch:
@@ -979,7 +1011,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_close_pull_request_from_url_rejects_non_pr_url(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with patch.object(github, "_installation_authenticated_patch") as mock_patch:
result = github.close_pull_request_from_url("https://github.com/PostHog/posthog/issues/42")
assert result["success"] is False
@@ -991,7 +1023,7 @@ class TestGitHubIntegrationModel(BaseTest):
integration = self.create_integration(
config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
)
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200)
mock_response.json.return_value = {
"items": [
@@ -1029,7 +1061,7 @@ class TestGitHubIntegrationModel(BaseTest):
integration = self.create_integration(
config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
)
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200)
mock_response.json.return_value = {
"number": 42,
@@ -1054,7 +1086,7 @@ class TestGitHubIntegrationModel(BaseTest):
integration = self.create_integration(
config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
)
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
not_found_response = MagicMock(status_code=404)
search_response = MagicMock(status_code=200)
search_response.json.return_value = {
@@ -1078,7 +1110,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_comment_on_pull_request_posts_to_issues_endpoint(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=201)
with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
result = github.comment_on_pull_request("PostHog/posthog", 123, "hello")
@@ -1091,7 +1123,7 @@ class TestGitHubIntegrationModel(BaseTest):
integration = self.create_integration(
config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
)
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200)
mock_response.json.return_value = {
"number": 123,
@@ -1107,7 +1139,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_list_submitted_pull_request_reviewers_reads_every_page(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
first_page = MagicMock(status_code=200)
first_page.links = {
"next": {"url": "https://api.github.com/repos/PostHog/posthog/pulls/123/reviews?page=2&per_page=100"}
@@ -1129,7 +1161,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_list_submitted_pull_request_reviewers_requires_every_page(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
first_page = MagicMock(status_code=200)
first_page.links = {"next": {"url": "https://api.github.com/repos/PostHog/posthog/pulls/123/reviews?page=2"}}
first_page.json.return_value = [{"state": "APPROVED", "user": {"login": "approved"}}]
@@ -1141,7 +1173,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_comment_on_pull_request_from_url_parses_and_posts(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=201)
with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
result = github.comment_on_pull_request_from_url("https://github.com/PostHog/posthog/pull/42", "note")
@@ -1150,7 +1182,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_add_pull_request_assignees_posts_to_issues_endpoint(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=201)
# GitHub returns the issue, and drops any login without push access without failing.
mock_response.json.return_value = {"assignees": [{"login": "alice"}]}
@@ -1169,7 +1201,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
def test_add_pull_request_assignees_skips_github_when_nothing_to_assign(self, _name: str, assignees: list):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with patch.object(github, "_installation_authenticated_post") as mock_post:
result = github.add_pull_request_assignees("PostHog/posthog", 123, assignees)
assert result == {"success": True, "assignees": []}
@@ -1177,7 +1209,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_add_pull_request_assignees_dedupes_and_caps_at_ten(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=201)
mock_response.json.return_value = {"assignees": []}
requested = ["alice", "alice", *[f"user{i}" for i in range(12)]]
@@ -1188,7 +1220,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_request_pull_request_reviews_posts_deduplicated_bounded_batches(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=201)
mock_response.json.return_value = {"requested_reviewers": [{"login": "alice"}]}
requested = ["alice", "alice", *[f"user{i}" for i in range(20)]]
@@ -1214,7 +1246,7 @@ class TestGitHubIntegrationModel(BaseTest):
@parameterized.expand([("first_batch", 3), ("later_batch", 18)])
def test_request_pull_request_reviews_continues_after_rejected_reviewer(self, _name: str, invalid_index: int):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
requested = [f"user{i}" for i in range(31)]
rejected = requested[invalid_index]
@@ -1237,7 +1269,7 @@ class TestGitHubIntegrationModel(BaseTest):
@parameterized.expand([("forbidden", 403), ("unrelated_validation", 422)])
def test_request_pull_request_reviews_stops_on_non_reviewer_error(self, _name: str, status_code: int):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
response = MagicMock(status_code=status_code, text="Request failed")
response.json.return_value = {"errors": [{"field": "pull_request", "code": "invalid"}]}
@@ -1250,7 +1282,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_add_pull_request_assignees_reports_a_github_error(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=422, text="Validation Failed")
with patch.object(github, "_installation_authenticated_post", return_value=mock_response):
result = github.add_pull_request_assignees("PostHog/posthog", 123, ["alice"])
@@ -1259,7 +1291,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_add_pull_request_labels_posts_to_issues_endpoint(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=200)
mock_response.json.return_value = [{"name": "self-driving"}]
with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
@@ -1271,7 +1303,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_add_pull_request_labels_creates_a_label_the_repository_lacks(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
refused = MagicMock(status_code=422, text="Validation Failed")
created = MagicMock(status_code=201)
applied = MagicMock(status_code=200)
@@ -1294,7 +1326,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
def test_add_pull_request_labels_skips_github_when_there_is_nothing_to_apply(self, _name: str, labels: list):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with patch.object(github, "_installation_authenticated_post") as mock_post:
result = github.add_pull_request_labels("PostHog/posthog", 123, labels)
assert result == {"success": True, "labels": []}
@@ -1302,7 +1334,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_add_pull_request_labels_reports_a_github_error(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=403, text="Forbidden")
with patch.object(github, "_installation_authenticated_post", return_value=mock_response):
result = github.add_pull_request_labels("PostHog/posthog", 123, ["self-driving"])
@@ -1317,7 +1349,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
def test_is_assignable_reads_the_assignees_endpoint(self, _name: str, status_code: int, expected: dict):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with patch.object(
github, "_installation_authenticated_get", return_value=MagicMock(status_code=status_code)
) as mock_get:
@@ -1327,7 +1359,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_is_assignable_reports_a_github_error(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=403, text="Resource not accessible by integration")
with patch.object(github, "_installation_authenticated_get", return_value=mock_response):
result = github.is_assignable("PostHog/posthog", "alice")
@@ -1342,7 +1374,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
def test_is_assignable_refuses_unsafe_paths_without_calling_github(self, _name: str, repository: str, login: str):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with patch.object(github, "_installation_authenticated_get") as mock_get:
result = github.is_assignable(repository, login)
assert result["success"] is False
@@ -1350,7 +1382,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_list_assignees_searches_every_page_and_caches_the_list(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
first = MagicMock(status_code=200)
first.json.return_value = [{"login": "alice"}, {"login": "bob"}]
second = MagicMock(status_code=200)
@@ -1374,7 +1406,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
def test_list_team_members_needs_every_page(self, _name: str, complete: bool, expected: dict):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
first = MagicMock(status_code=200)
first.json.return_value = [{"login": "alice"}]
second = MagicMock(status_code=200 if complete else 403, text="Resource not accessible by integration")
@@ -1398,7 +1430,7 @@ class TestGitHubIntegrationModel(BaseTest):
self, _name: str, complete: bool, last_event: str | None, expected: dict
):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
first = MagicMock(status_code=200)
first.json.return_value = [{"event": "assigned"}]
second = MagicMock(status_code=200 if complete else 502, text="Bad gateway")
@@ -1412,7 +1444,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_add_pull_request_assignees_from_url_parses_and_posts(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
mock_response = MagicMock(status_code=201)
mock_response.json.return_value = {"assignees": [{"login": "alice"}]}
with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
@@ -1483,7 +1515,7 @@ class TestGitHubIntegrationModel(BaseTest):
previous_count = REGISTRY.get_sample_value("github_integration_api_requests_total", labels) or 0
with patch.object(GitHubIntegration, "access_token_expired", return_value=False):
- GitHubIntegration(integration).api_request(
+ GitHubIntegration(integration, source="integration", priority=Priority.CRITICAL).api_request(
"GET",
"/repos/PostHog/posthog",
endpoint="/repos/{owner}/{repo}",
@@ -1533,7 +1565,7 @@ class TestGitHubIntegrationModel(BaseTest):
patch.object(GitHubIntegration, "access_token_expired", return_value=False),
pytest.raises(GitHubIntegrationError),
):
- GitHubIntegration(integration).api_request(
+ GitHubIntegration(integration, source="integration", priority=Priority.CRITICAL).api_request(
"GET",
"/repos/PostHog/posthog",
endpoint="/repos/{owner}/{repo}",
@@ -1553,13 +1585,21 @@ class TestGitHubIntegrationModel(BaseTest):
self.user,
)
- assert GitHubIntegration(integration).access_token_expired() is False
+ assert (
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).access_token_expired()
+ is False
+ )
with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
- assert GitHubIntegration(integration).access_token_expired() is True
+ assert (
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).access_token_expired() is True
+ )
- GitHubIntegration(integration).refresh_access_token()
- assert GitHubIntegration(integration).access_token_expired() is False
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).refresh_access_token()
+ assert (
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).access_token_expired()
+ is False
+ )
assert integration.config == {
"installation_id": "INSTALLATION_ID",
@@ -1592,7 +1632,7 @@ class TestGitHubIntegrationModel(BaseTest):
mock_client_request.side_effect = self.mock_github_client_request(
permissions={"contents": "read", "metadata": "read", "deployments": "read"}
)
- GitHubIntegration(integration).refresh_access_token()
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).refresh_access_token()
assert integration.config["permissions"] == {"contents": "read", "metadata": "read", "deployments": "read"}
@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
@@ -1602,7 +1642,7 @@ class TestGitHubIntegrationModel(BaseTest):
assert integration.config["repository_selection"] == "all"
mock_client_request.side_effect = self.mock_github_client_request(repository_selection="selected")
- GitHubIntegration(integration).refresh_access_token()
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).refresh_access_token()
assert integration.config["repository_selection"] == "selected"
@parameterized.expand(
@@ -1657,7 +1697,7 @@ class TestGitHubIntegrationModel(BaseTest):
config["account"] = account
integration = self.create_integration(config, {"access_token": "ACCESS_TOKEN"})
- healed = GitHubIntegration(integration).ensure_account_name()
+ healed = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).ensure_account_name()
integration.refresh_from_db()
assert healed is expects_fetch
@@ -1673,12 +1713,16 @@ class TestGitHubIntegrationModel(BaseTest):
)
with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
- assert GitHubIntegration(integration).ensure_account_name() is False
- assert GitHubIntegration(integration).ensure_account_name() is False
+ assert (
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).ensure_account_name() is False
+ )
+ assert (
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).ensure_account_name() is False
+ )
assert mock_client_request.call_count == 1
with time_machine.travel("2024-01-01T12:06:00Z", tick=False):
- GitHubIntegration(integration).ensure_account_name()
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).ensure_account_name()
assert mock_client_request.call_count == 2
integration.refresh_from_db()
assert integration.config["account"]["name"] == "INSTALL"
@@ -1690,7 +1734,7 @@ class TestGitHubIntegrationModel(BaseTest):
{"access_token": "ACCESS_TOKEN"},
)
- assert GitHubIntegration(integration).ensure_account_name() is False
+ assert GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).ensure_account_name() is False
mock_client_request.assert_not_called()
@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
@@ -1710,7 +1754,7 @@ class TestGitHubIntegrationModel(BaseTest):
mock_client_request.side_effect = _client_request
- assert GitHubIntegration(integration).ensure_account_name() is True
+ assert GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).ensure_account_name() is True
integration.refresh_from_db()
assert integration.config["account"]["name"] == "PostHog"
@@ -1727,12 +1771,14 @@ class TestGitHubIntegrationModel(BaseTest):
def _client_request(*_args, **_kwargs):
# Stands in for a second list request arriving before the first heal has recorded its attempt.
reread = Integration.objects.get(id=integration.id)
- landed_mid_call.append(GitHubIntegration(reread).ensure_account_name())
+ landed_mid_call.append(
+ GitHubIntegration(reread, source="test", priority=Priority.CRITICAL).ensure_account_name()
+ )
return MagicMock(status_code=200, json=lambda: {"account": {"login": "PostHog", "type": "Organization"}})
mock_client_request.side_effect = _client_request
- assert GitHubIntegration(integration).ensure_account_name() is True
+ assert GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).ensure_account_name() is True
assert landed_mid_call == [False]
assert mock_client_request.call_count == 1
@@ -1749,7 +1795,7 @@ class TestGitHubIntegrationModel(BaseTest):
integration.save()
with pytest.raises(Exception):
- GitHubIntegration(integration).refresh_access_token()
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).refresh_access_token()
integration.refresh_from_db()
assert integration.errors == "TOKEN_REFRESH_FAILED"
@@ -1770,7 +1816,7 @@ class TestGitHubIntegrationModel(BaseTest):
integration.errors = "TOKEN_REFRESH_FAILED"
integration.save()
- GitHubIntegration(integration).refresh_access_token()
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).refresh_access_token()
integration.refresh_from_db()
assert integration.errors == ""
@@ -1801,20 +1847,29 @@ class TestGitHubIntegrationModel(BaseTest):
)
with pytest.raises(GitHubIntegrationError):
- GitHubIntegration(integration).refresh_access_token()
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).refresh_access_token()
integration.refresh_from_db()
if expected_disarmed:
assert "expires_in" not in integration.config
assert "refreshed_at" not in integration.config
- assert GitHubIntegration(integration).access_token_expired() is False
+ assert (
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).access_token_expired()
+ is False
+ )
assert integration.config["installation_unavailable_since"]
- assert GitHubIntegration(integration).installation_unavailable() is True
+ assert (
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).installation_unavailable()
+ is True
+ )
else:
assert integration.config["expires_in"] == 3600
assert "refreshed_at" in integration.config
assert "installation_unavailable_since" not in integration.config
- assert GitHubIntegration(integration).installation_unavailable() is False
+ assert (
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).installation_unavailable()
+ is False
+ )
@patch("posthog.models.integration.github.reload_integrations_on_workers")
@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
@@ -1825,11 +1880,14 @@ class TestGitHubIntegrationModel(BaseTest):
sensitive_config={"access_token": "STALE_TOKEN"},
)
- GitHubIntegration(integration).refresh_access_token()
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).refresh_access_token()
integration.refresh_from_db()
assert "installation_unavailable_since" not in integration.config
- assert GitHubIntegration(integration).installation_unavailable() is False
+ assert (
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).installation_unavailable()
+ is False
+ )
assert integration.sensitive_config["access_token"] == "ACCESS_TOKEN"
assert "expires_in" in integration.config
@@ -1856,7 +1914,7 @@ class TestGitHubIntegrationModel(BaseTest):
mock_get.side_effect = [transient, success]
- repos, has_more = GitHubIntegration(integration).list_repositories()
+ repos, has_more = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).list_repositories()
assert repos == [
{"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},
@@ -1884,7 +1942,7 @@ class TestGitHubIntegrationModel(BaseTest):
mock_get.side_effect = [transient_1, transient_2]
with pytest.raises(GitHubIntegrationError, match="list_repositories non-JSON response"):
- GitHubIntegration(integration).list_repositories()
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).list_repositories()
assert mock_get.call_count == 2
@@ -1910,7 +1968,7 @@ class TestGitHubIntegrationModel(BaseTest):
mock_get.side_effect = [first_page, second_page, second_page]
with pytest.raises(GitHubIntegrationError, match="failed to list repositories"):
- GitHubIntegration(integration).list_all_repositories()
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).list_all_repositories()
assert mock_get.call_count == 3
@@ -1928,7 +1986,7 @@ class TestGitHubIntegrationModel(BaseTest):
(second_page, False),
]
- repos = GitHubIntegration(integration).list_all_repositories()
+ repos = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).list_all_repositories()
assert len(repos) == 130
assert repos == first_page + second_page
@@ -1959,7 +2017,9 @@ class TestGitHubIntegrationModel(BaseTest):
}
previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0
- repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=1, offset=1)
+ repos, has_more = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_repositories(limit=1, offset=1)
assert repos == [{"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"}]
assert has_more is False
@@ -1990,7 +2050,7 @@ class TestGitHubIntegrationModel(BaseTest):
integration.repository_cache_updated_at = timezone.now()
integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])
- repos, _ = GitHubIntegration(integration).list_cached_repositories()
+ repos, _ = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).list_cached_repositories()
assert repos[0] == {
"id": 1,
@@ -2021,7 +2081,9 @@ class TestGitHubIntegrationModel(BaseTest):
integration.repository_cache_updated_at = timezone.now()
integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])
- repos = GitHubIntegration(integration).sync_repository_cache(min_refresh_interval_seconds=60)
+ repos = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).sync_repository_cache(
+ min_refresh_interval_seconds=60
+ )
assert repos == cached_repositories
mock_list_all.assert_not_called()
@@ -2043,7 +2105,7 @@ class TestGitHubIntegrationModel(BaseTest):
mock_list_all.return_value = cached_repositories
with patch.object(integration, "save", wraps=integration.save) as mock_save:
- repos = GitHubIntegration(integration).sync_repository_cache()
+ repos = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).sync_repository_cache()
assert repos == cached_repositories
mock_save.assert_called_once_with(update_fields=["repository_cache_updated_at"])
@@ -2072,7 +2134,9 @@ class TestGitHubIntegrationModel(BaseTest):
}
previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0
- repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=1, offset=0)
+ repos, has_more = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_repositories(limit=1, offset=0)
integration.refresh_from_db()
assert repos == [{"id": 1, "name": "posthog", "full_name": "PostHog/posthog"}]
@@ -2099,7 +2163,9 @@ class TestGitHubIntegrationModel(BaseTest):
integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])
mock_list_all.side_effect = Exception("GitHub is slow")
- repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=10, offset=0)
+ repos, has_more = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_repositories(limit=10, offset=0)
integration.refresh_from_db()
assert repos == stale_repositories
@@ -2116,7 +2182,9 @@ class TestGitHubIntegrationModel(BaseTest):
mock_list_all.side_effect = Exception("GitHub is slow")
with pytest.raises(Exception, match="GitHub is slow"):
- GitHubIntegration(integration).list_cached_repositories(limit=10, offset=0)
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).list_cached_repositories(
+ limit=10, offset=0
+ )
integration.refresh_from_db()
assert integration.repository_cache == []
@@ -2156,7 +2224,9 @@ class TestGitHubIntegrationModel(BaseTest):
)
mock_list_all.return_value = fetched_repositories
- repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=25, offset=600)
+ repos, has_more = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_repositories(limit=25, offset=600)
assert repos == fetched_repositories[600:625]
assert has_more is True
@@ -2193,9 +2263,9 @@ class TestGitHubIntegrationModel(BaseTest):
)
mock_list_all.return_value = fetched_repositories
- repos, has_more = GitHubIntegration(integration).list_cached_repositories(
- search=search, limit=limit, offset=offset
- )
+ repos, has_more = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_repositories(search=search, limit=limit, offset=offset)
assert [repo["id"] for repo in repos] == expected_ids
assert has_more is expected_has_more
@@ -2212,7 +2282,7 @@ class TestGitHubIntegrationModel(BaseTest):
{"installation_id": "INSTALL", "account": {"name": "PostHog"}},
{"access_token": "ACCESS_TOKEN"},
)
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
repos, has_more = github.list_cached_repositories(search="posthog", limit=1, offset=0)
@@ -2231,7 +2301,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
repo = "posthog/posthog"
cache.set(
- GitHubIntegration(integration)._get_branch_cache_key(repo),
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._get_branch_cache_key(repo),
{
"branches": ["main", "develop", "feature/test"],
"default_branch": "main",
@@ -2247,9 +2317,9 @@ class TestGitHubIntegrationModel(BaseTest):
}
previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0
- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(
- repo, limit=2, offset=1
- )
+ branches, default_branch, has_more = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_branches(repo, limit=2, offset=1)
assert branches == ["develop", "feature/test"]
assert default_branch == "main"
@@ -2272,8 +2342,10 @@ class TestGitHubIntegrationModel(BaseTest):
)
user_integration = self.create_user_integration("INSTALL")
- GitHubIntegration(integration).list_cached_branches(repo)
- branches, default_branch, _ = UserGitHubIntegration(user_integration).list_cached_branches(repo)
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).list_cached_branches(repo)
+ branches, default_branch, _ = UserGitHubIntegration(
+ user_integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_branches(repo)
assert branches == ["main", "develop"]
assert default_branch == "main"
@@ -2288,7 +2360,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
repo = "posthog/posthog"
cache.set(
- GitHubIntegration(integration)._get_branch_cache_key(repo),
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._get_branch_cache_key(repo),
{
"branches": [
"main",
@@ -2301,9 +2373,9 @@ class TestGitHubIntegrationModel(BaseTest):
},
)
- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(
- repo, search="feature/agent", limit=1, offset=1
- )
+ branches, default_branch, has_more = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_branches(repo, search="feature/agent", limit=1, offset=1)
assert branches == ["feature/agent-branch-search"]
assert default_branch == "main"
@@ -2330,11 +2402,13 @@ class TestGitHubIntegrationModel(BaseTest):
}
previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0
- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(
- repo, limit=2, offset=0
- )
+ branches, default_branch, has_more = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_branches(repo, limit=2, offset=0)
- cached = cache.get(GitHubIntegration(integration)._get_branch_cache_key(repo))
+ cached = cache.get(
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._get_branch_cache_key(repo)
+ )
assert branches == ["develop", "feature/test"]
assert default_branch == "main"
assert has_more is False
@@ -2354,11 +2428,13 @@ class TestGitHubIntegrationModel(BaseTest):
{"access_token": "ACCESS_TOKEN"},
)
repo = "posthog/posthog"
- lock_key = GitHubIntegration(integration)._branch_refresh_lock_key(repo)
+ lock_key = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._branch_refresh_lock_key(
+ repo
+ )
get_redis_client().delete(lock_key)
self.addCleanup(get_redis_client().delete, lock_key)
cache.set(
- GitHubIntegration(integration)._get_branch_cache_key(repo),
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._get_branch_cache_key(repo),
{
"branches": ["main", "develop"],
"default_branch": "main",
@@ -2367,9 +2443,9 @@ class TestGitHubIntegrationModel(BaseTest):
)
for _ in range(2):
- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(
- repo, limit=10, offset=0
- )
+ branches, default_branch, has_more = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_branches(repo, limit=10, offset=0)
assert branches == ["main", "develop"]
assert default_branch == "main"
@@ -2388,7 +2464,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
repo = "posthog/posthog"
cache.set(
- GitHubIntegration(integration)._get_branch_cache_key(repo),
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._get_branch_cache_key(repo),
{
"branches": ["main", "develop"],
"default_branch": "main",
@@ -2396,7 +2472,9 @@ class TestGitHubIntegrationModel(BaseTest):
},
)
- branches, _, _ = GitHubIntegration(integration).list_cached_branches(repo)
+ branches, _, _ = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).list_cached_branches(
+ repo
+ )
assert branches == ["main", "develop"]
@@ -2410,7 +2488,7 @@ class TestGitHubIntegrationModel(BaseTest):
{"access_token": "ACCESS_TOKEN"},
)
repo = "posthog/posthog"
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
lock_key = github._branch_refresh_lock_key(repo)
self.addCleanup(get_redis_client().delete, lock_key)
get_redis_client().set(lock_key, "token", ex=5)
@@ -2431,7 +2509,7 @@ class TestGitHubIntegrationModel(BaseTest):
)
repo = "posthog/posthog"
cache.set(
- GitHubIntegration(integration)._get_branch_cache_key(repo),
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._get_branch_cache_key(repo),
{
"branches": ["main", "develop"],
"default_branch": "main",
@@ -2441,10 +2519,10 @@ class TestGitHubIntegrationModel(BaseTest):
mock_list_branches.return_value = (["main", "develop", "feature/test"], False)
mock_default_branch.side_effect = Exception("GitHub is slow")
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
github.refresh_branch_cache(repo, "token")
- cached = cache.get(GitHubIntegration(integration)._get_branch_cache_key(repo))
+ cached = cache.get(github._get_branch_cache_key(repo))
assert cached["branches"] == ["main", "develop", "feature/test"]
assert cached["default_branch"] == "main"
mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)
@@ -2460,7 +2538,9 @@ class TestGitHubIntegrationModel(BaseTest):
mock_list_branches.side_effect = Exception("GitHub is slow")
with pytest.raises(Exception, match="GitHub is slow"):
- GitHubIntegration(integration).list_cached_branches(repo, limit=10, offset=0)
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).list_cached_branches(
+ repo, limit=10, offset=0
+ )
mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)
@@ -2478,7 +2558,7 @@ class TestGitHubIntegrationModel(BaseTest):
(second_page, False),
]
- branches = GitHubIntegration(integration).list_all_branches(repo)
+ branches = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).list_all_branches(repo)
assert branches == first_page + second_page
assert mock_list_branches.call_args_list == [
@@ -2504,9 +2584,9 @@ class TestGitHubIntegrationModel(BaseTest):
]
mock_default_branch.return_value = "branch-1200"
- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(
- repo, limit=25, offset=1200
- )
+ branches, default_branch, has_more = GitHubIntegration(
+ integration, source="test", priority=Priority.CRITICAL
+ ).list_cached_branches(repo, limit=25, offset=1200)
expected_branches = ["branch-1199"] + [f"branch-{i}" for i in range(1201, 1225)]
assert branches == expected_branches
@@ -2587,7 +2667,7 @@ class TestGitHubIntegrationModel(BaseTest):
config={"expires_in": 3600, "refreshed_at": int(time.time())},
sensitive_config={"access_token": "valid-token"},
)
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
assert github.get_access_token() == "valid-token"
@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
@@ -2606,7 +2686,7 @@ class TestGitHubIntegrationModel(BaseTest):
}
mock_client_request.return_value = mock_response
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
token = github.get_access_token()
assert token == "new-token"
@@ -2617,7 +2697,7 @@ class TestGitHubIntegrationModel(BaseTest):
config={"expires_in": 3600, "refreshed_at": int(time.time())},
sensitive_config={}, # no access_token key
)
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
with pytest.raises(GitHubIntegrationError, match="Access token unavailable"):
github.get_access_token()
@@ -2648,7 +2728,9 @@ class TestGitHubIntegrationGhApiGet(BaseTest):
mock_get.return_value = ok
integration = self._create_integration()
- body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")
+ body = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._gh_api_get(
+ "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}"
+ )
assert body == {"default_branch": "main"}
@patch("posthog.egress.transport.transport.requests.request")
@@ -2658,7 +2740,7 @@ class TestGitHubIntegrationGhApiGet(BaseTest):
# Guards the lane plumbing: if the instance priority stops reaching the transport, BATCH
# callers silently ride the never-shed CRITICAL lane again and denials stop deferring work.
integration = self._create_integration()
- github = GitHubIntegration(integration, priority=Priority.BATCH)
+ github = GitHubIntegration(integration, priority=Priority.BATCH, source="test")
with pytest.raises(GitHubEgressBudgetExhausted):
github.api_request("GET", "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")
mock_request.assert_not_called()
@@ -2672,7 +2754,7 @@ class TestGitHubIntegrationGhApiGet(BaseTest):
mock_request.return_value = ok
integration = self._create_integration()
- response = GitHubIntegration(integration).api_request(
+ response = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL).api_request(
"GET", "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}"
)
assert response.status_code == 200
@@ -2690,7 +2772,9 @@ class TestGitHubIntegrationGhApiGet(BaseTest):
mock_get.side_effect = [transient, ok]
integration = self._create_integration()
- body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")
+ body = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._gh_api_get(
+ "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}"
+ )
assert body == {"ok": True}
assert mock_get.call_count == 2
@@ -2705,7 +2789,9 @@ class TestGitHubIntegrationGhApiGet(BaseTest):
integration = self._create_integration()
with pytest.raises(GitHubRateLimitError) as excinfo:
- GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._gh_api_get(
+ "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}"
+ )
assert excinfo.value.retry_after == 5
@patch("posthog.egress.transport.transport.requests.request")
@@ -2720,7 +2806,9 @@ class TestGitHubIntegrationGhApiGet(BaseTest):
integration = self._create_integration()
with pytest.raises(GitHubRateLimitError) as excinfo:
- GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._gh_api_get(
+ "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}"
+ )
assert excinfo.value.retry_after == 60
@patch("posthog.egress.transport.transport.requests.request")
@@ -2736,14 +2824,18 @@ class TestGitHubIntegrationGhApiGet(BaseTest):
mock_get.side_effect = [unauth, ok]
integration = self._create_integration()
- body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")
+ body = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._gh_api_get(
+ "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}"
+ )
assert body == {"after_refresh": True}
assert mock_refresh.called
def test_rejects_path_without_leading_slash(self):
integration = self._create_integration()
with pytest.raises(ValueError, match="must start with"):
- GitHubIntegration(integration)._gh_api_get("repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)._gh_api_get(
+ "repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}"
+ )
class TestGitHubIntegrationGraphQL(BaseTest):
@@ -2770,7 +2862,7 @@ class TestGitHubIntegrationGraphQL(BaseTest):
ok = self._graphql_response({"data": {"repository": {"name": "posthog"}}})
mock_request.side_effect = [transient, ok]
- github = GitHubIntegration(self._create_integration())
+ github = GitHubIntegration(self._create_integration(), source="test", priority=Priority.CRITICAL)
data = github._gh_graphql("query {}", {}, endpoint="/graphql:test")
assert data == {"repository": {"name": "posthog"}}
assert mock_request.call_count == 2
@@ -2784,7 +2876,7 @@ class TestGitHubIntegrationGraphQL(BaseTest):
)
mock_request.return_value = transient
- github = GitHubIntegration(self._create_integration())
+ github = GitHubIntegration(self._create_integration(), source="test", priority=Priority.CRITICAL)
with pytest.raises(GitHubIntegrationError):
github._gh_graphql("query {}", {}, endpoint="/graphql:test")
assert mock_request.call_count == GitHubIntegration._GRAPHQL_TRANSIENT_ATTEMPTS
@@ -2798,7 +2890,7 @@ class TestGitHubIntegrationGraphQL(BaseTest):
{"data": None, "errors": [{"type": "FORBIDDEN", "message": "Resource not accessible by integration"}]}
)
- github = GitHubIntegration(self._create_integration())
+ github = GitHubIntegration(self._create_integration(), source="test", priority=Priority.CRITICAL)
with pytest.raises(GitHubIntegrationError):
github._gh_graphql("query {}", {}, endpoint="/graphql:test")
assert mock_request.call_count == 1
@@ -2812,7 +2904,7 @@ class TestGitHubIntegrationGraphQL(BaseTest):
{"data": {"repository": {"name": "posthog"}}, "errors": [{"message": "field-level error"}]}
)
- github = GitHubIntegration(self._create_integration())
+ github = GitHubIntegration(self._create_integration(), source="test", priority=Priority.CRITICAL)
data = github._gh_graphql("query {}", {}, endpoint="/graphql:test")
assert data == {"repository": {"name": "posthog"}}
assert mock_request.call_count == 1
@@ -2859,7 +2951,7 @@ def _babysit_feedback(node_id: str, *, author: str = "reviewer", body: str = "pl
class TestGitHubIntegrationPullRequestBabysitSnapshot(BaseTest):
def _github(self) -> GitHubIntegration:
- return GitHubIntegration(_create_github_integration(self.team))
+ return GitHubIntegration(_create_github_integration(self.team), source="test", priority=Priority.CRITICAL)
@staticmethod
def _payload(**overrides) -> dict:
@@ -3029,7 +3121,7 @@ class TestGitHubIntegrationPullRequestBabysitSnapshot(BaseTest):
class TestGitHubIntegrationMarkPullRequestReadyForReview(BaseTest):
def _github(self) -> GitHubIntegration:
- return GitHubIntegration(_create_github_integration(self.team))
+ return GitHubIntegration(_create_github_integration(self.team), source="test", priority=Priority.CRITICAL)
@staticmethod
def _state(
@@ -3091,7 +3183,7 @@ class TestGitHubIntegrationMarkPullRequestReadyForReview(BaseTest):
class TestGitHubIntegrationPullRequestCiStatuses(BaseTest):
def _github(self) -> GitHubIntegration:
- return GitHubIntegration(_create_github_integration(self.team))
+ return GitHubIntegration(_create_github_integration(self.team), source="test", priority=Priority.CRITICAL)
@staticmethod
def _rollup(state: str | None) -> dict:
diff --git a/posthog/models/test/test_integration_repository_cache.py b/posthog/models/test/test_integration_repository_cache.py
index 4814af5d350e..780d1b51885c 100644
--- a/posthog/models/test/test_integration_repository_cache.py
+++ b/posthog/models/test/test_integration_repository_cache.py
@@ -82,7 +82,9 @@ class TestGitHubRepositoryFullCache(BaseTest):
)
def _cache_for(self, integration: Integration) -> GitHubRepositoryFullCache:
- return GitHubRepositoryFullCache(GitHubIntegration(integration), priority=Priority.BATCH)
+ return GitHubRepositoryFullCache(
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL), priority=Priority.BATCH
+ )
def test_sync_full_cache_entry_populates_all_fields(self):
integration = self._create_integration()
@@ -679,7 +681,9 @@ class TestSyncFullCacheLock(BaseTest):
)
def _cache_for(self, integration: Integration) -> GitHubRepositoryFullCache:
- return GitHubRepositoryFullCache(GitHubIntegration(integration), priority=Priority.BATCH)
+ return GitHubRepositoryFullCache(
+ GitHubIntegration(integration, source="test", priority=Priority.CRITICAL), priority=Priority.BATCH
+ )
# In TEST mode `posthog.redis.get_client()` and `get_async_client()` return separate
# fakeredis instances with no shared state, so these tests use the async client throughout.
diff --git a/posthog/models/user.py b/posthog/models/user.py
index 933b67043173..a8204d3b4fee 100644
--- a/posthog/models/user.py
+++ b/posthog/models/user.py
@@ -14,6 +14,7 @@ from rest_framework.exceptions import ValidationError
from posthog.cloud_utils import get_cached_instance_license, is_cloud
from posthog.constants import AvailableFeature
+from posthog.egress.limiter.policies import Priority
from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import (
GMAIL_CANONICAL_LOCAL_EXPRESSION,
@@ -530,7 +531,9 @@ class User(AbstractUser, UUIDTClassicModel, ModelActivityMixin): # type: ignore
user_integrations = self.integrations.filter(kind="github")[:1]
for user_integration in user_integrations:
- login = UserGitHubIntegration(user_integration).github_login
+ login = UserGitHubIntegration(
+ user_integration, source="user_github_login", priority=Priority.CRITICAL
+ ).github_login
if login:
return login
diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.py
index 78b7f5756b70..ae2cd80f54d5 100644
--- a/posthog/models/user_integration.py
+++ b/posthog/models/user_integration.py
@@ -209,16 +209,12 @@ class UserGitHubIntegration(GitHubIntegrationBase):
integration: UserIntegration
is_user_integration = True
- def __init__(
- self, integration: UserIntegration, *, source: str | None = None, priority: Priority | None = None
- ) -> None:
+ def __init__(self, integration: UserIntegration, *, source: str, priority: Priority) -> None:
if integration.kind != "github":
raise Exception("UserGitHubIntegration initialized with non-github integration")
self.integration = integration
- if source is not None:
- self.source = source
- if priority is not None:
- self.priority = priority
+ self.source = source
+ self.priority = priority
# --- Token refresh hooks ---
diff --git a/posthog/ownership/repo_files.py b/posthog/ownership/repo_files.py
index 4fe75b574b64..29c043aa5ac7 100644
--- a/posthog/ownership/repo_files.py
+++ b/posthog/ownership/repo_files.py
@@ -19,6 +19,7 @@ from owners_yaml import BatchOwnershipSource
from requests.adapters import HTTPAdapter
from posthog.egress.github.transport import github_request
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration.github import _is_safe_github_repo_path
logger = structlog.get_logger(__name__)
@@ -258,6 +259,7 @@ class GitHubRepoFiles(CachedRepoFiles):
endpoint=_EGRESS_ENDPOINT,
timeout=_TIMEOUT_SECONDS,
session=self._session,
+ priority=Priority.CRITICAL,
**kwargs,
)
except Exception as e:
diff --git a/posthog/ownership/test/test_github_files.py b/posthog/ownership/test/test_github_files.py
index 67d3782647b2..7ddcd7f6a9ed 100644
--- a/posthog/ownership/test/test_github_files.py
+++ b/posthog/ownership/test/test_github_files.py
@@ -394,7 +394,7 @@ class TestFetcherForTeam(BaseTest):
)
with patch(
"posthog.ownership.github_files.GitHubIntegration.first_for_team_repository",
- return_value=GitHubIntegration(integration) if covered else None,
+ return_value=GitHubIntegration(integration, source="test", priority=Priority.CRITICAL) if covered else None,
) as probe:
first = fetcher_for_team(self.team.pk, _REPOSITORY, priority=Priority.NORMAL)
second = fetcher_for_team(self.team.pk, _REPOSITORY, priority=Priority.NORMAL)
diff --git a/posthog/plugins/test/test_utils.py b/posthog/plugins/test/test_utils.py
index 62b65e49108c..1bd9d684f381 100644
--- a/posthog/plugins/test/test_utils.py
+++ b/posthog/plugins/test/test_utils.py
@@ -6,6 +6,7 @@ from zipfile import ZipFile
from posthog.test.base import BaseTest
from unittest import mock
+from posthog.egress.limiter.policies import Priority
from posthog.plugins.utils import (
download_plugin_archive,
get_file_from_archive,
@@ -47,6 +48,7 @@ class TestPluginsUtils(BaseTest):
"GET",
"https://api.github.com/repos/PostHog/posthog/commits?sha=&path=",
source="plugins",
+ priority=Priority.CRITICAL,
headers={},
installation_id=None,
)
@@ -96,6 +98,7 @@ class TestPluginsUtils(BaseTest):
"GET",
"https://api.github.com/repos/PostHog/posthog/commits?sha=main&path=",
source="plugins",
+ priority=Priority.CRITICAL,
headers={},
installation_id=None,
)
@@ -115,6 +118,7 @@ class TestPluginsUtils(BaseTest):
"GET",
"https://api.github.com/repos/PostHog/posthog/commits?sha=main&path=test/path/in/repo",
source="plugins",
+ priority=Priority.CRITICAL,
headers={},
installation_id=None,
)
@@ -198,6 +202,7 @@ class TestPluginsUtils(BaseTest):
"GET",
"https://api.github.com/repos/PostHog/posthog/commits?sha=&path=",
source="plugins",
+ priority=Priority.CRITICAL,
headers={"Authorization": "Bearer TOKEN"},
installation_id=None,
)
@@ -229,6 +234,7 @@ class TestPluginsUtils(BaseTest):
"GET",
"https://api.github.com/repos/PostHog/posthog/commits?sha=&path=",
source="plugins",
+ priority=Priority.CRITICAL,
headers={"Authorization": "Bearer MY_GITHUB_TOKEN"},
installation_id=None,
)
@@ -249,6 +255,7 @@ class TestPluginsUtils(BaseTest):
"GET",
"https://api.github.com/repos/PostHog/posthog/commits?sha=&path=",
source="plugins",
+ priority=Priority.CRITICAL,
headers={"Authorization": "Bearer TOKEN"},
installation_id=None,
)
diff --git a/posthog/plugins/utils.py b/posthog/plugins/utils.py
index 65e814a55d9a..5730eb2a8778 100644
--- a/posthog/plugins/utils.py
+++ b/posthog/plugins/utils.py
@@ -14,6 +14,7 @@ import requests
from posthog.dataclasses import frozen
from posthog.egress.github.transport import github_request
+from posthog.egress.limiter.policies import Priority
def parse_github_url(url: str, get_latest_if_none=False) -> Optional[dict[str, Optional[str]]]:
@@ -64,6 +65,7 @@ def parse_github_url(url: str, get_latest_if_none=False) -> Optional[dict[str, O
source="plugins",
headers=headers,
installation_id=None,
+ priority=Priority.CRITICAL,
).json()
if isinstance(commits, dict):
diff --git a/posthog/session_recordings/session_recording_external_reference_api.py b/posthog/session_recordings/session_recording_external_reference_api.py
index 0e521332b3c7..0b04f2fa1a50 100644
--- a/posthog/session_recordings/session_recording_external_reference_api.py
+++ b/posthog/session_recordings/session_recording_external_reference_api.py
@@ -11,6 +11,7 @@ from rest_framework.exceptions import ValidationError
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
+from posthog.egress.limiter.policies import Priority
from posthog.event_usage import groups
from posthog.models.integration import (
GitHubIntegration,
@@ -74,7 +75,9 @@ class SessionRecordingExternalReferenceSerializer(serializers.ModelSerializer):
url_key = LinearIntegration(reference.integration).url_key()
return f"https://linear.app/{url_key}/issue/{external_context['id']}"
elif reference.integration.kind == Integration.IntegrationKind.GITHUB:
- org = GitHubIntegration(reference.integration).organization()
+ org = GitHubIntegration(
+ reference.integration, source="replay_external_references", priority=Priority.CRITICAL
+ ).organization()
repository = external_context.get("repository", "")
issue_number = external_context.get("id", "").lstrip("#")
return f"https://github.com/{org}/{repository}/issues/{issue_number}"
@@ -161,7 +164,9 @@ class SessionRecordingExternalReferenceSerializer(serializers.ModelSerializer):
elif integration.kind == Integration.IntegrationKind.GITHUB:
title = config.get("title", "")
config["body"] = f"{config.get('body', '')}\n\n**PostHog recording:** {recording_url}"
- response = GitHubIntegration(integration).create_issue(config)
+ response = GitHubIntegration(
+ integration, source="replay_external_references", priority=Priority.CRITICAL
+ ).create_issue(config)
external_context = {
"id": f"#{response.get('number', '')}",
"title": title,
diff --git a/posthog/tasks/integrations.py b/posthog/tasks/integrations.py
index 1acb6908bc00..ebf660d1f141 100644
--- a/posthog/tasks/integrations.py
+++ b/posthog/tasks/integrations.py
@@ -57,7 +57,9 @@ def refresh_integrations() -> int:
github_integrations = defer_repository_cache_fields(Integration.objects.filter(kind="github").all())
for integration in github_integrations:
- github_integration = GitHubIntegration(integration)
+ github_integration = GitHubIntegration(
+ integration, source="integration_token_refresh", priority=Priority.CRITICAL
+ )
if not refresh_backoff_active(integration) and github_integration.access_token_expired():
refresh_integration.delay(integration.id)
@@ -103,7 +105,9 @@ def refresh_integration(id: int) -> int:
if gcloud_integration.access_token_expired():
gcloud_integration.refresh_access_token()
elif integration.kind == "github":
- github_integration = GitHubIntegration(integration)
+ github_integration = GitHubIntegration(
+ integration, source="integration_token_refresh", priority=Priority.CRITICAL
+ )
if github_integration.access_token_expired():
github_integration.refresh_access_token()
elif integration.kind == "firebase":
diff --git a/products/business_knowledge/backend/github_repos.py b/products/business_knowledge/backend/github_repos.py
index 45f49adf2466..c32bdf6bdf19 100644
--- a/products/business_knowledge/backend/github_repos.py
+++ b/products/business_knowledge/backend/github_repos.py
@@ -243,9 +243,9 @@ def read_repository_file(team: Team, user: User, repo: str, path: str) -> Reposi
def _fetch_file(team: Team, integration: Integration, full_name: str, path: str, sha: str) -> RepositoryFile:
try:
- payload = GitHubIntegration(integration, source="business_knowledge").get_file_contents(
- full_name, _quote_github_path(path), ref=sha
- )
+ payload = GitHubIntegration(
+ integration, source="business_knowledge", priority=Priority.CRITICAL
+ ).get_file_contents(full_name, _quote_github_path(path), ref=sha)
except UnicodeDecodeError:
raise GithubReposError("That file is not text.")
except (GitHubIntegrationError, GitHubRateLimitError, EgressBudgetExhausted):
@@ -346,9 +346,9 @@ def _require_allowlist(team: Team) -> tuple[Integration, list[str]]:
def _installation_repo_names(integration: Integration) -> set[str]:
# A pure read of the stored repository list, so a repository removed from the installation
# stops being searchable as soon as that list refreshes, even while its cache row remains.
- listed = GitHubIntegration(integration, source="business_knowledge").list_all_cached_repositories(
- allow_refresh=False
- )
+ listed = GitHubIntegration(
+ integration, source="business_knowledge", priority=Priority.CRITICAL
+ ).list_all_cached_repositories(allow_refresh=False)
return {
item["full_name"].lower()
for item in listed
@@ -371,7 +371,7 @@ def _validate_against_installation(team_id: int, integration_id: int, repos: lis
integration = _integration_for(team_id, integration_id)
if integration is None:
raise GithubReposError("GitHub installation not found on this project.")
- github = GitHubIntegration(integration, source="business_knowledge")
+ github = GitHubIntegration(integration, source="business_knowledge", priority=Priority.CRITICAL)
try:
listed = github.list_all_cached_repositories()
# Without a cached snapshot the refresh re-raises whatever the sync hit, not only GitHub errors.
diff --git a/products/canvas/backend/connectors.py b/products/canvas/backend/connectors.py
index c673b99bc4c2..5199c960486b 100644
--- a/products/canvas/backend/connectors.py
+++ b/products/canvas/backend/connectors.py
@@ -31,6 +31,7 @@ from rest_framework import serializers
from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.egress.transport.transport import EgressBudgetExhausted
from posthog.models.github_integration_base import GitHubIntegrationError
from posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration
@@ -187,7 +188,7 @@ class GitHubGetFileContentsPayloadSerializer(GitHubRepositorySerializer):
def _github_client(integration: UserIntegration) -> UserGitHubIntegration:
- return UserGitHubIntegration(integration, source=_GITHUB_SOURCE)
+ return UserGitHubIntegration(integration, source=_GITHUB_SOURCE, priority=Priority.CRITICAL)
def _github_repo_path(client: UserGitHubIntegration, repository: str) -> str:
diff --git a/products/conversations/backend/api/github_setup.py b/products/conversations/backend/api/github_setup.py
index 01cdab16064e..dea08bfa42ad 100644
--- a/products/conversations/backend/api/github_setup.py
+++ b/products/conversations/backend/api/github_setup.py
@@ -9,6 +9,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.user import User
@@ -116,7 +117,7 @@ class GithubReposView(APIView):
except Integration.DoesNotExist:
return Response({"error": "GitHub integration not found"}, status=404)
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="conversations", priority=Priority.CRITICAL)
repos, _has_more = github.list_cached_repositories(limit=200)
return Response(
diff --git a/products/conversations/backend/tasks/github.py b/products/conversations/backend/tasks/github.py
index 2a9a730bc194..58f420718288 100644
--- a/products/conversations/backend/tasks/github.py
+++ b/products/conversations/backend/tasks/github.py
@@ -11,6 +11,7 @@ from celery import shared_task
from posthog.comment.formatting import rich_content_to_markdown
from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.models.comment import Comment as CommentModel
from posthog.models.github_integration_base import GitHubIntegrationError
from posthog.models.team import Team
@@ -321,7 +322,9 @@ def post_reply_to_github(
return
try:
- github = GitHubIntegration.first_for_team_repository(team_id, ticket.github_repo, source="conversations")
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, ticket.github_repo, source="conversations", priority=Priority.CRITICAL
+ )
except GitHubRateLimitError as e:
# The access probe hit GitHub's limit — retry the reply later rather than dropping it.
logger.warning("github_reply_rate_limited", ticket_id=ticket_id)
@@ -405,7 +408,7 @@ def create_github_issue(
logger.warning("github_create_issue_integration_not_found", integration_id=integration_id)
return None
- github = GitHubIntegration(integration, source="conversations")
+ github = GitHubIntegration(integration, source="conversations", priority=Priority.CRITICAL)
try:
issue_data = github.create_issue({"title": title, "body": body, "repository": repo, "labels": labels})
diff --git a/products/customer_analytics/backend/logic/feature_request_github.py b/products/customer_analytics/backend/logic/feature_request_github.py
index 5c13da3555d1..8f09e4bc1ce2 100644
--- a/products/customer_analytics/backend/logic/feature_request_github.py
+++ b/products/customer_analytics/backend/logic/feature_request_github.py
@@ -187,7 +187,9 @@ def _integration(
integration is None
or not integration.integration_id
or (installation_id is not None and integration.integration_id != installation_id)
- or GitHubIntegration(integration).installation_unavailable()
+ or GitHubIntegration(
+ integration, source="customer_analytics", priority=Priority.CRITICAL
+ ).installation_unavailable()
):
raise FeatureRequestValidationError(
"integration_id", "Select an available GitHub integration for this project."
diff --git a/products/engineering_analytics/backend/logic/census.py b/products/engineering_analytics/backend/logic/census.py
index 97177d39fe88..91b68acc2daa 100644
--- a/products/engineering_analytics/backend/logic/census.py
+++ b/products/engineering_analytics/backend/logic/census.py
@@ -16,6 +16,7 @@ from owners_yaml import TeamTestCensus, census, runner_for_path
from posthog.api.capture import capture_batch_internal
from posthog.egress.github.transport import github_request, raise_if_github_rate_limited
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration.github import _is_safe_github_repo_path
from posthog.models.team import Team
@@ -43,6 +44,7 @@ def collect_repo_census(repository: str, access_token: str, *, timeout: int = 30
timeout=timeout,
allow_redirects=True,
stream=True,
+ priority=Priority.CRITICAL,
)
) as response:
raise_if_github_rate_limited(response)
diff --git a/products/engineering_analytics/backend/logic/job_logs/activity.py b/products/engineering_analytics/backend/logic/job_logs/activity.py
index 496da71f6fbc..3501aa94391c 100644
--- a/products/engineering_analytics/backend/logic/job_logs/activity.py
+++ b/products/engineering_analytics/backend/logic/job_logs/activity.py
@@ -94,7 +94,7 @@ def _resolve_credentials(team_id: int, integration_id: int) -> tuple[str, str, s
the owning team's project API token — the OTLP Bearer that routes emitted logs to that team's Logs.
"""
integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="github")
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="job_logs", priority=Priority.CRITICAL)
if github.access_token_expired():
github.refresh_access_token()
if not integration.access_token:
diff --git a/products/engineering_analytics/backend/logic/job_logs/fetcher.py b/products/engineering_analytics/backend/logic/job_logs/fetcher.py
index 5d238bb31e73..409035c880a7 100644
--- a/products/engineering_analytics/backend/logic/job_logs/fetcher.py
+++ b/products/engineering_analytics/backend/logic/job_logs/fetcher.py
@@ -17,6 +17,7 @@ from temporalio.exceptions import ApplicationError
from posthog.dataclasses import frozen
from posthog.egress.github.transport import github_request, raise_if_github_rate_limited
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration.github import _is_safe_github_repo_path
_GITHUB_API = "https://api.github.com"
@@ -109,6 +110,7 @@ def fetch_bounded_job_log(
timeout=timeout,
allow_redirects=True,
stream=True,
+ priority=Priority.CRITICAL,
)
) as response:
raise_if_github_rate_limited(response)
diff --git a/products/engineering_analytics/backend/logic/quarantine.py b/products/engineering_analytics/backend/logic/quarantine.py
index 7479762c33e8..a21cd2d54eb5 100644
--- a/products/engineering_analytics/backend/logic/quarantine.py
+++ b/products/engineering_analytics/backend/logic/quarantine.py
@@ -36,6 +36,7 @@ import structlog
from posthog.hogql import ast
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.team import Team
@@ -512,7 +513,7 @@ def _resolve_write_target(
integration_row = Integration.objects.filter(team=team, kind="github").first()
if integration_row is None:
raise QuarantineWriteError("Connect a GitHub integration with write access to quarantine tests from here.")
- github = GitHubIntegration(integration_row)
+ github = GitHubIntegration(integration_row, source="ci_quarantine", priority=Priority.CRITICAL)
installed_org = github.organization()
if installed_org.lower() != owner.lower():
raise QuarantineWriteError(
diff --git a/products/error_tracking/backend/logic/external_references.py b/products/error_tracking/backend/logic/external_references.py
index 4e0feed94f20..d7fc3eba5a95 100644
--- a/products/error_tracking/backend/logic/external_references.py
+++ b/products/error_tracking/backend/logic/external_references.py
@@ -6,6 +6,7 @@ from django.db.models import QuerySet
import requests
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import (
GitHubIntegration,
GitHubIntegrationError,
@@ -57,7 +58,9 @@ def _validate_github_assignee(integration: Integration, repository: str, login:
# Enterprise Managed User logins add an underscore and a shortcode, so allow "_" and a longer login.
if not re.fullmatch(r"[A-Za-z0-9_-]{1,100}", login):
raise ErrorTrackingExternalReferenceValidationError("GitHub assignee must be a GitHub login.")
- result = GitHubIntegration(integration).is_assignable(repository.strip(), login)
+ result = GitHubIntegration(integration, source="error_tracking", priority=Priority.CRITICAL).is_assignable(
+ repository.strip(), login
+ )
if not result.get("success"):
raise ErrorTrackingExternalReferenceValidationError(
f"Could not check whether {login} can be assigned issues in {repository.strip()}. "
@@ -267,7 +270,9 @@ def create_external_reference(
provider_config["assignee"] = assignee
if integration.kind == Integration.IntegrationKind.GITHUB:
- created_context = GitHubIntegration(integration).create_issue(provider_config)
+ created_context = GitHubIntegration(
+ integration, source="error_tracking", priority=Priority.CRITICAL
+ ).create_issue(provider_config)
elif integration.kind == Integration.IntegrationKind.GITLAB:
created_context = GitLabIntegration(integration).create_issue(provider_config)
elif integration.kind == Integration.IntegrationKind.LINEAR:
@@ -314,7 +319,9 @@ def search_external_issues(
raise ErrorTrackingExternalReferenceValidationError(
"Pass the repository name without an owner; only the integration's account can be searched."
)
- return GitHubIntegration(integration).search_issues(repository, search)
+ return GitHubIntegration(integration, source="error_tracking", priority=Priority.CRITICAL).search_issues(
+ repository, search
+ )
elif integration.kind == Integration.IntegrationKind.GITLAB:
return GitLabIntegration(integration).search_issues(search)
elif integration.kind == Integration.IntegrationKind.LINEAR:
diff --git a/products/error_tracking/backend/logic/github_external_references.py b/products/error_tracking/backend/logic/github_external_references.py
index dbeb4a2f1fd4..abdee8483386 100644
--- a/products/error_tracking/backend/logic/github_external_references.py
+++ b/products/error_tracking/backend/logic/github_external_references.py
@@ -8,6 +8,7 @@ from django.core.cache import cache
from django.db import transaction
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
from products.error_tracking.backend.facade import contracts
@@ -163,9 +164,9 @@ def _actor_lacks_write_permission(integration: Integration, job: contracts.GitHu
)
permission = cache.get(cache_key)
if permission is None:
- permission = GitHubIntegration(integration).get_collaborator_permission(
- job.repository_full_name, job.actor_login
- )
+ permission = GitHubIntegration(
+ integration, source="error_tracking", priority=Priority.CRITICAL
+ ).get_collaborator_permission(job.repository_full_name, job.actor_login)
ttl = (
_ACTOR_PERMISSION_ALLOW_CACHE_SECONDS
if permission in _WRITE_PERMISSIONS
@@ -189,7 +190,9 @@ def link_reference(job: contracts.GitHubExternalReferenceJob) -> bool:
if integration is None:
return False
try:
- integration_owner = GitHubIntegration(integration).organization()
+ integration_owner = GitHubIntegration(
+ integration, source="error_tracking", priority=Priority.CRITICAL
+ ).organization()
except ValueError:
return False
if integration_owner.casefold() != owner.casefold():
diff --git a/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py b/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py
index b0318dd89921..3da103d3467e 100644
--- a/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py
+++ b/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py
@@ -302,7 +302,7 @@ class GitProviderFileLinksViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
integration = Integration.objects.filter(team_id=self.team.id, kind="github").first()
if integration:
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="error_tracking", priority=Priority.CRITICAL)
if github.access_token_expired():
github.refresh_access_token()
diff --git a/products/github_commands/backend/logic/github.py b/products/github_commands/backend/logic/github.py
index 1106ff5d4af8..f24000ef6c21 100644
--- a/products/github_commands/backend/logic/github.py
+++ b/products/github_commands/backend/logic/github.py
@@ -12,6 +12,7 @@ import requests
import structlog
from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, GitHubIntegrationError, Integration
from .commands import PullRequestFacts
@@ -67,7 +68,7 @@ class InstallationGitHub:
)
if integration is None:
return None
- return cls(GitHubIntegration(integration, source=_SOURCE))
+ return cls(GitHubIntegration(integration, source=_SOURCE, priority=Priority.CRITICAL))
def collaborator_permission(self, repository: str, login: str, github_user_id: int) -> str:
try:
diff --git a/products/growth/dags/github_sdk_versions.py b/products/growth/dags/github_sdk_versions.py
index 20efeb45147e..f9b79ba89d6e 100644
--- a/products/growth/dags/github_sdk_versions.py
+++ b/products/growth/dags/github_sdk_versions.py
@@ -12,6 +12,7 @@ import structlog
from posthog.dags.common import JobOwners
from posthog.dags.common.resources import redis
from posthog.egress.github.transport import github_request
+from posthog.egress.limiter.policies import Priority
from posthog.exceptions_capture import capture_exception
from products.growth.backend.constants import SDK_CACHE_EXPIRY, SDK_TYPES, SdkTypes, github_sdk_versions_key
@@ -173,7 +174,7 @@ def fetch_releases_from_repo(repo: str, skip_cache: bool = False) -> list[Any]:
logger.info(f"[SDK Health] Fetching releases from {url}")
# Identity-blind, unauthenticated call — records volume telemetry, no installation budget.
- response = github_request("GET", url, source="growth", timeout=10)
+ response = github_request("GET", url, source="growth", timeout=10, priority=Priority.CRITICAL)
if not response.ok:
logger.error(f"[SDK Health] Failed to fetch releases for {repo}", status_code=response.status_code)
diff --git a/products/review_hog/backend/api/project_settings.py b/products/review_hog/backend/api/project_settings.py
index 516f31e844a4..8ddf5c383349 100644
--- a/products/review_hog/backend/api/project_settings.py
+++ b/products/review_hog/backend/api/project_settings.py
@@ -9,6 +9,7 @@ from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission
@@ -343,7 +344,9 @@ class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.Generi
status=status.HTTP_400_BAD_REQUEST,
)
try:
- repositories = GitHubIntegration(integration).list_all_cached_repositories()
+ repositories = GitHubIntegration(
+ integration, source="review_hog", priority=Priority.CRITICAL
+ ).list_all_cached_repositories()
except Exception:
# The list refreshes from GitHub when the cache is cold, and GitHub can fail or rate limit.
logger.warning("review_hog_repository_overview_list_failed", exc_info=True)
diff --git a/products/review_hog/backend/management/commands/publish_review.py b/products/review_hog/backend/management/commands/publish_review.py
index 8af5452b5028..71ee87e64748 100644
--- a/products/review_hog/backend/management/commands/publish_review.py
+++ b/products/review_hog/backend/management/commands/publish_review.py
@@ -4,6 +4,7 @@ from typing import Any
from django.core.management.base import BaseCommand, CommandError, CommandParser
from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration
from products.review_hog.backend.models import ReviewReport
@@ -97,7 +98,9 @@ class Command(BaseCommand):
f"The stored review used {review_mode} mode. Omit --review-mode or use --review-mode {review_mode}."
)
- github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, repository, source="review_hog", priority=Priority.CRITICAL
+ )
if github is None:
raise CommandError(
f"No GitHub App installation for team {team_id} that can access {repository} "
diff --git a/products/review_hog/backend/repository_settings.py b/products/review_hog/backend/repository_settings.py
index 5de6f409ec33..a62a56a13187 100644
--- a/products/review_hog/backend/repository_settings.py
+++ b/products/review_hog/backend/repository_settings.py
@@ -13,6 +13,7 @@ from typing import Any
from django.db import IntegrityError, models, transaction
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.team import Team
from posthog.models.user import User
@@ -117,7 +118,9 @@ class ProjectRepositories:
"""The repository as the installation reports it. A client cannot store a pair GitHub does not know."""
integration = self.integration_for(ref.installation_id)
try:
- repositories = GitHubIntegration(integration).list_all_cached_repositories()
+ repositories = GitHubIntegration(
+ integration, source="review_hog", priority=Priority.CRITICAL
+ ).list_all_cached_repositories()
except Exception:
# The list refreshes from GitHub when the cache is cold, and GitHub can fail or rate limit.
logger.warning("review_hog_repository_write_list_failed", exc_info=True)
diff --git a/products/review_hog/backend/requested_reviews.py b/products/review_hog/backend/requested_reviews.py
index 6b7809a93de5..11175d986931 100644
--- a/products/review_hog/backend/requested_reviews.py
+++ b/products/review_hog/backend/requested_reviews.py
@@ -11,6 +11,7 @@ from enum import StrEnum
from django.db import models
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration
from products.review_hog.backend.models import ReviewReport
@@ -159,7 +160,9 @@ def request_pr_review(
repository = f"{owner}/{repo}"
# Checked synchronously (one GitHub API call) so an inaccessible repo errors here, in the UI —
# asynchronously the fetch activity would fail before the report row exists, showing nothing.
- github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, repository, source="review_hog", priority=Priority.CRITICAL
+ )
if github is None:
return PRReviewRequestOutcome(
status=PRReviewRequestStatus.INVALID,
diff --git a/products/review_hog/backend/reviewer/outcomes/classify.py b/products/review_hog/backend/reviewer/outcomes/classify.py
index d2077bed23cd..32b9e484f43f 100644
--- a/products/review_hog/backend/reviewer/outcomes/classify.py
+++ b/products/review_hog/backend/reviewer/outcomes/classify.py
@@ -27,6 +27,7 @@ from django.db import transaction
from django.utils import timezone
from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration
from posthog.models.team import Team
from posthog.sync import database_sync_to_async
@@ -128,7 +129,9 @@ def _installation_auth(team_id: int, repository: str) -> tuple[str, str | None]
Unlike the review path's variant this returns None instead of raising: a missing installation is a
skip-this-report condition for the batch, not a failure.
"""
- github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, repository, source="review_hog", priority=Priority.CRITICAL
+ )
if github is None:
return None
return github.get_access_token(), github.github_installation_id
diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.py
index 57e5fda89d81..cc1fdf5138cb 100644
--- a/products/review_hog/backend/reviewer/status_comment.py
+++ b/products/review_hog/backend/reviewer/status_comment.py
@@ -27,6 +27,7 @@ from django.db.models import Q
from django.utils import timezone
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
from posthog.utils import pluralize
@@ -468,7 +469,9 @@ def _auth(team_id: int, repository: str) -> tuple[str, str | None] | None:
`first_for_team_repository` probes the GitHub API, so this costs a call per invocation — fine at
the refresh cadence (`STATUS_EDIT_MIN_INTERVAL`), and every call is egress-gated regardless.
"""
- github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, repository, source="review_hog", priority=Priority.CRITICAL
+ )
if github is None:
return None
return github.get_access_token(), github.github_installation_id
@@ -482,7 +485,9 @@ def _auth_from_row(team_id: int, integration_row_id: int) -> tuple[str, str | No
answer the run already has. GitHub still enforces access on the edit itself, so a mid-run
revocation surfaces there and is swallowed like any other status-comment failure.
"""
- github = GitHubIntegration(Integration.objects.get(id=integration_row_id, team_id=team_id))
+ github = GitHubIntegration(
+ Integration.objects.get(id=integration_row_id, team_id=team_id), source="review_hog", priority=Priority.CRITICAL
+ )
return github.get_access_token(), github.github_installation_id
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index 97b26666f227..7d4da4d820ab 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -27,6 +27,7 @@ from temporalio.exceptions import ApplicationError
from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.event_usage import groups
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.team.team import Team
@@ -734,7 +735,9 @@ def _installation_for(team_id: int, repository: str) -> GitHubIntegration:
instead of re-probing per write: the probe answers *which* installation, not *may we write* —
GitHub enforces access server-side on every call anyway.
"""
- github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, repository, source="review_hog", priority=Priority.CRITICAL
+ )
if github is None:
raise ApplicationError(
f"Could not resolve a GitHub App installation for team {team_id} that can access {repository} "
diff --git a/products/review_hog/backend/tests/test_ui_trigger_api.py b/products/review_hog/backend/tests/test_ui_trigger_api.py
index aff069e75a02..778e373c9086 100644
--- a/products/review_hog/backend/tests/test_ui_trigger_api.py
+++ b/products/review_hog/backend/tests/test_ui_trigger_api.py
@@ -9,6 +9,7 @@ from rest_framework import status
from social_django.models import UserSocialAuth
from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.models import Team, User
from products.review_hog.backend.facade.reviews import (
@@ -85,7 +86,9 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
"resolve_skip_reason": "owner_not_opted_in",
},
)
- mock_access.assert_called_once_with(self.team.id, "PostHog/posthog.com")
+ mock_access.assert_called_once_with(
+ self.team.id, "PostHog/posthog.com", source="review_hog", priority=Priority.CRITICAL
+ )
mock_start.assert_called_once_with(
pr_url="https://github.com/PostHog/posthog.com/pull/123",
team_id=self.team.id,
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index ddc41e759461..a9e662cbd3ff 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -13,6 +13,7 @@ from django.db.models import F, Lookup, Q
import structlog
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration
@@ -439,7 +440,9 @@ def _close_implementation_pr(
)
return False
- github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, parsed.repository, source="signals_implementation_pr", priority=Priority.CRITICAL
+ )
if github is None:
logger.info(
"close_implementation_pr_no_integration", report_id=str(report_id), repository=parsed.repository
diff --git a/products/signals/backend/management/commands/create_github_app.py b/products/signals/backend/management/commands/create_github_app.py
index 64c25c2fef80..da560eaa0e80 100644
--- a/products/signals/backend/management/commands/create_github_app.py
+++ b/products/signals/backend/management/commands/create_github_app.py
@@ -42,6 +42,7 @@ import jwt
import requests
from posthog.egress.github.transport import github_request
+from posthog.egress.limiter.policies import Priority
GITHUB_APP_KEYS = ["GITHUB_APP_CLIENT_ID", "GITHUB_APP_CLIENT_SECRET", "GITHUB_APP_SLUG", "GITHUB_APP_PRIVATE_KEY"]
DEFAULT_BASE_URL = "http://localhost:8010"
@@ -291,6 +292,7 @@ class Command(BaseCommand):
f"https://api.github.com/app-manifests/{quote(code, safe='')}/conversions",
source="signals",
timeout=30,
+ priority=Priority.CRITICAL,
)
except requests.RequestException as err:
raise CommandError(f"Network error contacting GitHub: {err}") from err
@@ -349,6 +351,7 @@ class Command(BaseCommand):
source="signals",
headers={"Authorization": f"Bearer {token}"},
timeout=30,
+ priority=Priority.CRITICAL,
)
except Exception as err:
self.stdout.write(
diff --git a/products/signals/backend/pull_request_body.py b/products/signals/backend/pull_request_body.py
index e55b29f2a76a..0c580ecdce4c 100644
--- a/products/signals/backend/pull_request_body.py
+++ b/products/signals/backend/pull_request_body.py
@@ -11,6 +11,7 @@ from enum import StrEnum
import structlog
+from posthog.egress.limiter.policies import Priority
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration
@@ -49,7 +50,9 @@ def edit_pull_request_body(
parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
if parsed is None:
return BodyEditOutcome.SKIPPED
- github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, parsed.repository, source="signals_implementation_pr", priority=Priority.CRITICAL
+ )
if github is None:
# The lookup also returns None when the access check hits a transient GitHub error.
logger.info(f"{log_event}_no_integration", report_id=report_id, pr_url=pr_url)
diff --git a/products/signals/backend/pull_request_label.py b/products/signals/backend/pull_request_label.py
index d1bc451fc515..8a6bd0383d48 100644
--- a/products/signals/backend/pull_request_label.py
+++ b/products/signals/backend/pull_request_label.py
@@ -16,6 +16,7 @@ from django.db import transaction
import structlog
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration
from products.signals.backend.models import SignalReport, SignalReportAssignment, SignalTeamConfig
@@ -101,7 +102,9 @@ def apply_pull_request_label(*, team_id: int, report_id: str, pr_url: str) -> st
log = logger.bind(team_id=team_id, report_id=report_id, repository=parsed.repository, pr_number=parsed.number)
try:
- github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, parsed.repository, source="signals_implementation_pr", priority=Priority.CRITICAL
+ )
except Exception:
log.exception("signals.pull_request_label.integration_lookup_failed")
return None
diff --git a/products/signals/backend/report_assignments.py b/products/signals/backend/report_assignments.py
index 07cfb41835e8..6948a3f7485a 100644
--- a/products/signals/backend/report_assignments.py
+++ b/products/signals/backend/report_assignments.py
@@ -10,6 +10,7 @@ from django.db import transaction
import structlog
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration
@@ -197,7 +198,9 @@ def _pull_request_details(team_id: int, pr_url: str) -> PullRequestDetails:
merged=False,
)
try:
- github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, parsed.repository, source="signals_reviewers", priority=Priority.CRITICAL
+ )
except Exception:
logger.exception(
"signals.assignment.integration_lookup_failed",
diff --git a/products/signals/backend/report_generation/ownership_reviewers.py b/products/signals/backend/report_generation/ownership_reviewers.py
index e4b8a3fe5468..722589bb53b7 100644
--- a/products/signals/backend/report_generation/ownership_reviewers.py
+++ b/products/signals/backend/report_generation/ownership_reviewers.py
@@ -73,7 +73,9 @@ def suggest_repository_owners(
try:
team = Team.objects.get(id=team_id)
- github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, repository, source="signals_reviewers", priority=Priority.CRITICAL
+ )
if github is None:
return []
codeowners = _codeowners_for_paths(github, repository, paths)
diff --git a/products/signals/backend/report_generation/repo_activity.py b/products/signals/backend/report_generation/repo_activity.py
index 841bed1054c8..26078241fb27 100644
--- a/products/signals/backend/report_generation/repo_activity.py
+++ b/products/signals/backend/report_generation/repo_activity.py
@@ -236,7 +236,9 @@ def rebuild_repository_activity(team_id: int, repository: str) -> int:
def _commit_attributions_by_sha(team_id: int, repository: str) -> dict[str, GitHubCommitAttribution]:
"""GitHub's sha→login attribution for the activity window, keyed for the sha join."""
- github = GitHubIntegration.first_for_team_repository(team_id, repository, source="signals_activity_rebuild")
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, repository, source="signals_activity_rebuild", priority=Priority.CRITICAL
+ )
if github is None:
# Same expected-deferral type the collector raises — the rebuild task logs it
# instead of capturing an exception.
diff --git a/products/signals/backend/report_generation/resolve_reviewers.py b/products/signals/backend/report_generation/resolve_reviewers.py
index 1cd4aaed3fd6..6c797ac89d3b 100644
--- a/products/signals/backend/report_generation/resolve_reviewers.py
+++ b/products/signals/backend/report_generation/resolve_reviewers.py
@@ -20,6 +20,7 @@ from social_django.models import UserSocialAuth
from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
@@ -518,7 +519,9 @@ def resolve_suggested_reviewers_with_diagnostics(
return _empty_resolution("no_commit_hashes")
try:
- github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, repository, source="signals_reviewers", priority=Priority.CRITICAL
+ )
except GitHubRateLimitError:
# Suggested reviewers are an optional artefact — omit them rather than failing the report.
logger.info("GitHub rate limited while probing %s, skipping reviewer resolution", repository)
diff --git a/products/signals/backend/reviewer_pr_assignment.py b/products/signals/backend/reviewer_pr_assignment.py
index 5bd44dda0975..54db22c1b531 100644
--- a/products/signals/backend/reviewer_pr_assignment.py
+++ b/products/signals/backend/reviewer_pr_assignment.py
@@ -31,6 +31,7 @@ from django.db import transaction
import structlog
from pydantic import ValidationError
+from posthog.egress.limiter.policies import Priority
from posthog.models import Team
from posthog.models.github_integration_base import PullRequestRef
from posthog.models.integration import GitHubIntegration
@@ -243,7 +244,9 @@ def ranked_reviewer_logins(*, team_id: int, report_id: str) -> list[str]:
def _github_for_repository(*, team_id: int, report_id: str, repository: str) -> GitHubIntegration | None:
"""The team's GitHub integration for a repository, or None when there is none to call."""
try:
- return GitHubIntegration.first_for_team_repository(team_id, repository)
+ return GitHubIntegration.first_for_team_repository(
+ team_id, repository, source="signals_reviewers", priority=Priority.CRITICAL
+ )
except Exception:
logger.exception(
"signals.reviewer_pr_assignment.integration_lookup_failed",
diff --git a/products/signals/backend/reviewer_pr_ready.py b/products/signals/backend/reviewer_pr_ready.py
index f993fdf0ae70..9c7a52eea215 100644
--- a/products/signals/backend/reviewer_pr_ready.py
+++ b/products/signals/backend/reviewer_pr_ready.py
@@ -17,6 +17,7 @@ from django.db import transaction
import structlog
+from posthog.egress.limiter.policies import Priority
from posthog.models import User
from posthog.models.integration import GitHubIntegration
@@ -177,7 +178,9 @@ def open_pull_request_ready_for_review(*, team_id: int, report_id: str, pr_url:
return False
try:
- github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, parsed.repository, source="signals_reviewers", priority=Priority.CRITICAL
+ )
except Exception:
logger.exception(
"signals.reviewer_pr_ready.integration_lookup_failed",
diff --git a/products/signals/backend/supersession.py b/products/signals/backend/supersession.py
index 98868d643092..f1259369b68e 100644
--- a/products/signals/backend/supersession.py
+++ b/products/signals/backend/supersession.py
@@ -11,6 +11,7 @@ import structlog
from pydantic import ValidationError
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration
@@ -234,7 +235,9 @@ def verify_target(team_id: int, target: ImplementationTarget, *, check_sha: bool
tasks = tasks_facade.get_tasks_by_ids([target.task_id], [team_id])
if not tasks or (tasks[0].repository or "").lower() != parsed.repository.lower():
return None
- github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, parsed.repository, source="signals_implementation_pr", priority=Priority.CRITICAL
+ )
if github is None:
raise TargetVerificationUnavailable("GitHub integration unavailable")
pr = github.get_pull_request(parsed.repository, parsed.number)
@@ -282,7 +285,9 @@ def _target_already_closed(team_id: int, target: ImplementationTarget) -> bool:
parsed = GitHubIntegrationBase.parse_pull_request_url(target.pr_url)
assert parsed is not None
- github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, parsed.repository, source="signals_implementation_pr", priority=Priority.CRITICAL
+ )
current = github.get_pull_request(parsed.repository, parsed.number) if github else {}
if not current.get("success"):
raise RuntimeError("Could not verify predecessor state")
diff --git a/products/signals/backend/test/test_dismissal_pr_close.py b/products/signals/backend/test/test_dismissal_pr_close.py
index 05839a004491..07edd6cc04a6 100644
--- a/products/signals/backend/test/test_dismissal_pr_close.py
+++ b/products/signals/backend/test/test_dismissal_pr_close.py
@@ -5,6 +5,7 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
+from posthog.egress.limiter.policies import Priority
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -310,7 +311,9 @@ class TestCloseImplementationPrForReport(BaseTest):
) as mock_resolve:
assert close_implementation_pr_for_report(self.team.id, str(self.report.id), reason=reason) is True
- mock_resolve.assert_called_once_with(self.team.id, "PostHog/posthog")
+ mock_resolve.assert_called_once_with(
+ self.team.id, "PostHog/posthog", source="signals_implementation_pr", priority=Priority.CRITICAL
+ )
comment_body = github.comment_on_pull_request.call_args.args[2]
assert reason in comment_body
github.close_pull_request.assert_called_once_with("PostHog/posthog", 123)
diff --git a/products/signals/backend/test/test_signal_report_assignment_api.py b/products/signals/backend/test/test_signal_report_assignment_api.py
index 87c973cf20fb..deb2458e8437 100644
--- a/products/signals/backend/test/test_signal_report_assignment_api.py
+++ b/products/signals/backend/test/test_signal_report_assignment_api.py
@@ -9,6 +9,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
+from posthog.egress.limiter.policies import Priority
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.team.team import Team
@@ -453,7 +454,9 @@ class TestSignalReportAssignmentAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_200_OK
- mock_first_for_repository.assert_called_once_with(self.team.id, "PostHog/posthog")
+ mock_first_for_repository.assert_called_once_with(
+ self.team.id, "PostHog/posthog", source="signals_reviewers", priority=Priority.CRITICAL
+ )
github.get_pull_request.assert_called_once_with("PostHog/posthog", 123)
pr = SignalReportPullRequest.objects.for_team(self.team.id).get(repository="posthog/posthog", number=123)
assert pr.repository == "posthog/posthog"
@@ -552,7 +555,9 @@ class TestSignalReportAssignmentAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_200_OK
- mock_first_for_repository.assert_called_once_with(self.team.id, "PostHog/posthog")
+ mock_first_for_repository.assert_called_once_with(
+ self.team.id, "PostHog/posthog", source="signals_reviewers", priority=Priority.CRITICAL
+ )
pr = SignalReportPullRequest.objects.for_team(self.team.id).get(repository="posthog/posthog", number=123)
assert pr.repository == "posthog/posthog"
assert pr.number == 123
diff --git a/products/signals/backend/tracker_issues.py b/products/signals/backend/tracker_issues.py
index 42280930214b..4bd5e8f40791 100644
--- a/products/signals/backend/tracker_issues.py
+++ b/products/signals/backend/tracker_issues.py
@@ -19,6 +19,7 @@ import structlog
from rest_framework.exceptions import ValidationError as DRFValidationError
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import (
SUPPORTED_EXTERNAL_ISSUE_PROVIDERS,
GitHubIntegration,
@@ -118,7 +119,7 @@ def _create_provider_issue(target: TrackerIssueTarget, *, title: str, body: str,
}
if label:
config["labels"] = [label]
- github = GitHubIntegration(target.integration)
+ github = GitHubIntegration(target.integration, source="signals_tracker_issues", priority=Priority.CRITICAL)
context = dict(github.create_issue(config))
repository = str(context["repository"])
context["repository"] = repository if "/" in repository else f"{github.organization()}/{repository}"
@@ -360,7 +361,9 @@ def _comment_before_close(tracker: SignalReportTrackerIssue, *, report_link: str
return
context = tracker.external_context or {}
try:
- GitHubIntegration(tracker.integration).comment_on_issue(
+ GitHubIntegration(
+ tracker.integration, source="signals_tracker_issues", priority=Priority.CRITICAL
+ ).comment_on_issue(
context["repository"],
int(context["number"]),
_close_notice(report_link=report_link, actor_mention=actor_mention),
@@ -376,7 +379,9 @@ def _close_provider_issue(tracker: SignalReportTrackerIssue, *, completed: bool)
context = tracker.external_context or {}
if tracker.provider == Integration.IntegrationKind.GITHUB:
- GitHubIntegration(integration).close_issue(context["repository"], int(context["number"]), completed=completed)
+ GitHubIntegration(integration, source="signals_tracker_issues", priority=Priority.CRITICAL).close_issue(
+ context["repository"], int(context["number"]), completed=completed
+ )
elif tracker.provider == Integration.IntegrationKind.GITLAB:
GitLabIntegration(integration).close_issue(int(context["issue_id"]))
elif tracker.provider == Integration.IntegrationKind.LINEAR:
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index bea491471ed7..f374e2e68d5e 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -4374,7 +4374,7 @@ class SignalReportViewSet(
status=status.HTTP_403_FORBIDDEN,
)
repository, pr_number = reference
- user_github = UserGitHubIntegration(user_integration)
+ user_github = UserGitHubIntegration(user_integration, source="signals_api", priority=Priority.CRITICAL)
if comment_id is not None:
lookup = self._run_user_github_write(
lambda: user_github.get_pull_request_review_comment(repository, comment_id),
@@ -5741,7 +5741,9 @@ class SignalReportArtefactViewSet(
# PRs). That connection boundary is the intended scope — any `task:write` holder can already
# run agents against those same repos — and the repo/ref values are validated in `get_diff`.
try:
- github = GitHubIntegration.first_for_team_repository(self.team.id, repository)
+ github = GitHubIntegration.first_for_team_repository(
+ self.team.id, repository, source="signals_api", priority=Priority.CRITICAL
+ )
except GitHubRateLimitError as e:
return github_rate_limited_response(e)
if github is None:
diff --git a/products/skills/backend/api/community_publish_services.py b/products/skills/backend/api/community_publish_services.py
index 93653038103b..ba428366bf35 100644
--- a/products/skills/backend/api/community_publish_services.py
+++ b/products/skills/backend/api/community_publish_services.py
@@ -22,6 +22,7 @@ import structlog
from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubRateLimitError, github_request
+from posthog.egress.limiter.policies import Priority
from posthog.models.github_integration_base import GitHubIntegrationError
from posthog.models.integration import GitHubIntegration, Integration
@@ -544,6 +545,7 @@ def _publisher_app_request(
timeout=10,
# requests omits the body entirely when json is None
json=json_body,
+ priority=Priority.CRITICAL,
)
@@ -620,7 +622,7 @@ def get_community_skills_publisher() -> GitHubIntegration | None:
sensitive_config={"access_token": token},
)
# The same source as the App-JWT calls above, so every publish request lands under one label.
- return _CommunitySkillsPublisher(integration, source=_EGRESS_SOURCE)
+ return _CommunitySkillsPublisher(integration, source=_EGRESS_SOURCE, priority=Priority.CRITICAL)
def _community_pr_body(*, name: str, slug: str, author_handle: str) -> str:
diff --git a/products/skills/backend/api/community_skill_sync.py b/products/skills/backend/api/community_skill_sync.py
index a6f4e5d9511e..94fe6b8502ad 100644
--- a/products/skills/backend/api/community_skill_sync.py
+++ b/products/skills/backend/api/community_skill_sync.py
@@ -9,6 +9,7 @@ import structlog
from rest_framework.serializers import ValidationError as DRFValidationError
from posthog.egress.github.transport import github_request
+from posthog.egress.limiter.policies import Priority
from ..marketplace.packaging import SPEC_DESCRIPTION_MAX_LENGTH
from ..models.community_skills import CommunitySkill, CommunitySkillFile, CommunitySkillKind, CommunitySkillTrustTier
@@ -299,6 +300,7 @@ def sync_community_skills_from_github(registry_url: str = COMMUNITY_SKILLS_REGIS
source="community_skills",
installation_id=None,
timeout=COMMUNITY_SKILLS_SYNC_TIMEOUT_SECONDS,
+ priority=Priority.CRITICAL,
)
response.raise_for_status()
payload = response.json()
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 38c4d38480c2..a39795a926c2 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -23,6 +23,7 @@ from slack_sdk.errors import SlackApiError
from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.event_usage import groups
from posthog.git import extract_explicit_repo, extract_linked_repo, extract_repo_from_scopes
from posthog.models.integration import (
@@ -1115,7 +1116,7 @@ def _get_full_repo_names(integration: Integration, *, user_id: int | None) -> li
all_repos: set[str] = set()
for record in user_records:
- github = UserGitHubIntegration(record)
+ github = UserGitHubIntegration(record, source="slack_app_repo_selection", priority=Priority.CRITICAL)
repo_entries = github.list_all_cached_repositories(max_repos=_MAX_GITHUB_REPOS)
for repo in repo_entries:
all_repos.add(repo["full_name"])
diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.py
index f27f729740c1..f56356f1027b 100644
--- a/products/stamphog/backend/logic/github_client.py
+++ b/products/stamphog/backend/logic/github_client.py
@@ -289,6 +289,7 @@ def list_user_installations(user_access_token: str) -> list[dict[str, str]]:
endpoint="/user/installations",
params={"per_page": _PER_PAGE, "page": page},
timeout=10,
+ priority=Priority.CRITICAL,
)
raise_if_github_rate_limited(response)
if response.status_code != 200:
@@ -347,6 +348,7 @@ def list_user_accessible_repositories(installation_id: str, user_access_token: s
endpoint="/user/installations/{installation_id}/repositories",
params={"per_page": _PER_PAGE, "page": page},
timeout=10,
+ priority=Priority.CRITICAL,
)
raise_if_github_rate_limited(response)
if response.status_code != 200:
@@ -415,6 +417,7 @@ class StamphogGitHubClient:
headers={"Authorization": f"Bearer {_build_app_jwt()}"},
endpoint="/app/installations/{installation_id}/access_tokens",
timeout=10,
+ priority=Priority.CRITICAL,
)
if response.status_code != 201:
raise StamphogGitHubError(
diff --git a/products/tasks/backend/github_repository_access.py b/products/tasks/backend/github_repository_access.py
index 587539bd4853..6164e7f28b63 100644
--- a/products/tasks/backend/github_repository_access.py
+++ b/products/tasks/backend/github_repository_access.py
@@ -1,6 +1,7 @@
import logging
from collections.abc import Iterable
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
logger = logging.getLogger(__name__)
@@ -14,7 +15,9 @@ def inaccessible_repositories_via_integration(
if integration is None:
return names
try:
- repositories = GitHubIntegration(integration).list_all_cached_repositories()
+ repositories = GitHubIntegration(
+ integration, source="tasks", priority=Priority.CRITICAL
+ ).list_all_cached_repositories()
except Exception:
logger.warning(
"github_repository_access_check_unavailable",
diff --git a/products/tasks/backend/logic/pull_request_titles.py b/products/tasks/backend/logic/pull_request_titles.py
index f43743b53971..29f62fb6f443 100644
--- a/products/tasks/backend/logic/pull_request_titles.py
+++ b/products/tasks/backend/logic/pull_request_titles.py
@@ -5,6 +5,7 @@ from django.core.cache import cache
import structlog
from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.models.github_integration_base import GitHubIntegrationError, PullRequestRef
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.user_integration import UserGitHubIntegration
@@ -57,13 +58,13 @@ def _integration_key(task: Task, user_id: int) -> tuple[str, int | str]:
def _github_for_task(task: Task, team_id: int, user_id: int) -> GitHubIntegration | UserGitHubIntegration | None:
user_integration = task.github_user_integration
if user_integration is not None and user_integration.user_id == user_id:
- return UserGitHubIntegration(user_integration)
+ return UserGitHubIntegration(user_integration, source="tasks", priority=Priority.CRITICAL)
if not task.github_integration_id:
return None
integration = Integration.objects.filter(team_id=team_id, kind="github", id=task.github_integration_id).first()
if integration is None:
return None
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)
if github.access_token_expired():
github.refresh_access_token()
return github
diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.py
index 2e85a8345a50..37c945b10d67 100644
--- a/products/tasks/backend/logic/repo_selection/agent.py
+++ b/products/tasks/backend/logic/repo_selection/agent.py
@@ -137,7 +137,7 @@ def resolve_team_github_integration(
)
# Prefer the first GitHub integration from the team
if integration is not None:
- return GitHubIntegration(integration)
+ return GitHubIntegration(integration, source="repo_selection", priority=Priority.CRITICAL)
if team_only:
return None
@@ -147,7 +147,7 @@ def resolve_team_github_integration(
if requester_user_id is not None:
requester_integration = _first_user_github_integration([requester_user_id])
if requester_integration is not None:
- return UserGitHubIntegration(requester_integration)
+ return UserGitHubIntegration(requester_integration, source="repo_selection", priority=Priority.CRITICAL)
organization = (team if team is not None else Team.objects.get(id=team_id)).organization
owner_user_ids = OrganizationMembership.objects.filter(
@@ -158,7 +158,7 @@ def resolve_team_github_integration(
# If no team integration - pick an org owner's integration (personal account preferred)
owner_integration = _first_user_github_integration(owner_user_ids)
if owner_integration is not None:
- return UserGitHubIntegration(owner_integration)
+ return UserGitHubIntegration(owner_integration, source="repo_selection", priority=Priority.CRITICAL)
return None
diff --git a/products/tasks/backend/logic/services/repo_commit_activity.py b/products/tasks/backend/logic/services/repo_commit_activity.py
index 05e725e90ccf..4ac0de4b909b 100644
--- a/products/tasks/backend/logic/services/repo_commit_activity.py
+++ b/products/tasks/backend/logic/services/repo_commit_activity.py
@@ -12,6 +12,7 @@ from dataclasses import dataclass
import structlog
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration
# Import names only — pulling `Sandbox` at module level would trigger the module's lazy
@@ -78,7 +79,9 @@ def collect_repository_commit_activity(
the repository or the clone/log fails.
"""
repository = repository.strip().lower()
- github = GitHubIntegration.first_for_team_repository(team_id, repository, source="repo_commit_activity")
+ github = GitHubIntegration.first_for_team_repository(
+ team_id, repository, source="repo_commit_activity", priority=Priority.CRITICAL
+ )
if github is None:
raise RepositoryCommitActivityError(f"No GitHub integration for team {team_id} can access {repository}")
github_token = github.get_access_token()
diff --git a/products/tasks/backend/logic/task_review.py b/products/tasks/backend/logic/task_review.py
index 248ab25e5e89..23e33a5a45cd 100644
--- a/products/tasks/backend/logic/task_review.py
+++ b/products/tasks/backend/logic/task_review.py
@@ -1,5 +1,6 @@
from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.user_integration import UserGitHubIntegration
@@ -25,13 +26,13 @@ def task_review(team_id: int, task_id: str, user_id: int, page: int) -> dict:
github: GitHubIntegration | UserGitHubIntegration
user_integration = task.github_user_integration
if user_integration is not None and user_integration.user_id == user_id:
- github = UserGitHubIntegration(user_integration)
+ github = UserGitHubIntegration(user_integration, source="tasks", priority=Priority.CRITICAL)
else:
integrations = Integration.objects.filter(team_id=team_id, kind="github")
integration = integrations.filter(id=task.github_integration_id).first() if task.github_integration_id else None
if integration is None:
raise ValidationError("Connect GitHub in PostHog to load the review.")
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)
if github.access_token_expired():
github.refresh_access_token()
snapshot = github.get_pull_request_snapshot(url)
diff --git a/products/tasks/backend/max_tools.py b/products/tasks/backend/max_tools.py
index a84a1bc1e0f2..0d67ca2a9122 100644
--- a/products/tasks/backend/max_tools.py
+++ b/products/tasks/backend/max_tools.py
@@ -5,6 +5,7 @@ from django.db import transaction
from asgiref.sync import async_to_sync, sync_to_async
from pydantic import BaseModel, Field
+from posthog.egress.limiter.policies import Priority
from posthog.storage import object_storage
from ee.hogai.tool import MaxTool
@@ -560,7 +561,7 @@ Use this tool when the user wants to:
for integration in integrations:
try:
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)
org = github.organization()
repos = github.list_all_cached_repositories()
diff --git a/products/tasks/backend/repository_readiness.py b/products/tasks/backend/repository_readiness.py
index 147f9b9eb3fb..a088edbe8fda 100644
--- a/products/tasks/backend/repository_readiness.py
+++ b/products/tasks/backend/repository_readiness.py
@@ -10,6 +10,7 @@ from django.utils import timezone
import requests
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
from products.error_tracking.backend.facade import api as error_tracking_api
@@ -115,7 +116,7 @@ def _cache_key(*, team_id: int, integration_id: int, repository: str, window_day
def _refresh_installation_token(integration: Integration) -> None:
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)
try:
if github.access_token_expired():
github.refresh_access_token()
@@ -232,7 +233,7 @@ def _fetch_file_content(github: GitHubIntegration, repository: str, path: str, r
def _scan_repository(integration: Integration, repository: str) -> tuple[RepositoryScanEvidence, list[str]]:
- github = GitHubIntegration(integration, source="tasks")
+ github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)
tree_paths, default_branch = _fetch_repository_tree(github, repository)
found_posthog_init = False
diff --git a/products/tasks/backend/repository_resolver.py b/products/tasks/backend/repository_resolver.py
index dc536860ce95..7d1e64190149 100644
--- a/products/tasks/backend/repository_resolver.py
+++ b/products/tasks/backend/repository_resolver.py
@@ -7,6 +7,7 @@ from typing import Any, Optional
from django.apps import apps
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
@@ -18,7 +19,7 @@ class RepositoryContext:
self.repository = repository
self.organization = organization
self.is_primary = is_primary
- self.github_integration = GitHubIntegration(integration)
+ self.github_integration = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)
@property
def full_name(self) -> str:
@@ -75,7 +76,7 @@ async def resolve_single_repository(issue) -> list[RepositoryContext]:
if not org or not repo:
# If not configured, use the first available repository
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)
repositories = await github.list_all_cached_repositories_async()
if repositories:
org = github.organization()
@@ -123,7 +124,7 @@ async def resolve_smart_select_repositories(issue) -> list[RepositoryContext]:
allowed_integrations = await _get_allowed_integrations_for_smart_select(issue, constraints)
for integration in allowed_integrations:
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)
try:
repos = await github.list_all_cached_repositories_async()
org = github.organization()
@@ -158,7 +159,7 @@ async def resolve_legacy_repository(issue) -> list[RepositoryContext]:
if not integration:
return []
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)
repositories, _ = await github.list_cached_repositories_async()
if not repositories:
@@ -216,7 +217,7 @@ async def _get_allowed_integrations_for_smart_select(issue, constraints: dict) -
integrations = []
async for integration in Integration.objects.filter(team_id=issue.team_id, kind="github"):
- github = GitHubIntegration(integration)
+ github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)
org = github.organization()
# If organizations are specified, only include matching ones
diff --git a/products/tasks/backend/temporal/create_snapshot/utils.py b/products/tasks/backend/temporal/create_snapshot/utils.py
index 0b461fc1d608..f7929428349a 100644
--- a/products/tasks/backend/temporal/create_snapshot/utils.py
+++ b/products/tasks/backend/temporal/create_snapshot/utils.py
@@ -1,11 +1,12 @@
from typing import Optional
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
def get_github_token(github_integration_id: int) -> Optional[str]:
integration = Integration.objects.get(id=github_integration_id)
- github_integration = GitHubIntegration(integration)
+ github_integration = GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)
if github_integration.access_token_expired():
github_integration.refresh_access_token()
diff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py
index c1dc59b1e73b..892eeb092905 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py
@@ -7,6 +7,7 @@ from django.core.exceptions import ObjectDoesNotExist
from temporalio import activity
from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.models import Integration
from posthog.models.integration import GitHubIntegration
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
@@ -95,7 +96,7 @@ def merge_queue_push_would_eject(github_integration: GitHubIntegration | UserGit
def get_github_integration(github_integration_id: int) -> GitHubIntegration:
integration = Integration.objects.get(id=github_integration_id)
- github_integration = GitHubIntegration(integration)
+ github_integration = GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)
if github_integration.access_token_expired():
github_integration.refresh_access_token()
@@ -104,7 +105,9 @@ def get_github_integration(github_integration_id: int) -> GitHubIntegration:
def get_user_github_integration(github_user_integration_id: str) -> UserGitHubIntegration:
- return UserGitHubIntegration(UserIntegration.objects.get(id=github_user_integration_id))
+ return UserGitHubIntegration(
+ UserIntegration.objects.get(id=github_user_integration_id), source="tasks_sandbox", priority=Priority.CRITICAL
+ )
@activity.defn
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index d910b854d0aa..a64433a701ec 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -13,6 +13,7 @@ import posthoganalytics
from temporalio import activity
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models import Integration
from posthog.models.integration import GitHubIntegration
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
@@ -142,11 +143,19 @@ def _resolve_protected_base_branch(ctx: TaskProcessingContext) -> str | None:
try:
integration: GitHubIntegration | UserGitHubIntegration
if ctx.github_integration_id:
- integration = GitHubIntegration(Integration.objects.get(id=ctx.github_integration_id))
+ integration = GitHubIntegration(
+ Integration.objects.get(id=ctx.github_integration_id),
+ source="tasks_sandbox",
+ priority=Priority.CRITICAL,
+ )
if integration.access_token_expired():
integration.refresh_access_token()
else:
- integration = UserGitHubIntegration(UserIntegration.objects.get(id=str(ctx.github_user_integration_id)))
+ integration = UserGitHubIntegration(
+ UserIntegration.objects.get(id=str(ctx.github_user_integration_id)),
+ source="tasks_sandbox",
+ priority=Priority.CRITICAL,
+ )
pr_base = integration.get_open_pr_base_for_head(ctx.repository, branch)
except Exception:
logger.warning("resolve_protected_base_branch_failed", task_id=ctx.task_id, run_id=ctx.run_id, exc_info=True)
diff --git a/products/tasks/backend/temporal/process_task/sandbox_credentials.py b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
index 147577a911e5..b678387f4eb5 100644
--- a/products/tasks/backend/temporal/process_task/sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
@@ -11,6 +11,7 @@ from django.db import transaction
import redis
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import Integration
from posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration
from posthog.redis import get_client
@@ -347,10 +348,12 @@ def resolve_coordinated_user_token(integration: UserGitHubIntegration) -> str |
if not acquired:
# Waited out the budget — read the current token without minting; the holder's propagation self-heals.
integration.integration.refresh_from_db()
- return UserGitHubIntegration(integration.integration).user_access_token
+ return UserGitHubIntegration(
+ integration.integration, source="tasks_sandbox", priority=Priority.CRITICAL
+ ).user_access_token
integration.integration.refresh_from_db()
- current = UserGitHubIntegration(integration.integration)
+ current = UserGitHubIntegration(integration.integration, source="tasks_sandbox", priority=Priority.CRITICAL)
was_expired = current.user_access_token_expired()
# Mints only if still expired; a prior holder's fresh token is returned without rotating.
token = current.get_usable_user_access_token()
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index b85cbbd56d91..fcc78a5318ad 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -13,6 +13,7 @@ from django.db import transaction
from pydantic import BaseModel
+from posthog.egress.limiter.policies import Priority
from posthog.enums import LabeledStrEnum
from posthog.llm.gateway_client import GatewayNotConfiguredError, ensure_scout_trial_capture_ready
from posthog.models.integration import GitHubIntegration, Integration
@@ -879,7 +880,7 @@ def get_sandbox_ph_mcp_configs(
def get_github_token(github_integration_id: int) -> Optional[str]:
integration = Integration.objects.get(id=github_integration_id)
- github_integration = GitHubIntegration(integration)
+ github_integration = GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)
if github_integration.installation_unavailable():
raise CredentialUnavailableError(
@@ -961,7 +962,7 @@ def get_readonly_github_token(team_id: int) -> Optional[str]:
def get_user_github_token(github_user_integration_id: str) -> Optional[str]:
"""Return the installation access token from a UserIntegration, refreshing if expired."""
integration = UserIntegration.objects.get(id=github_user_integration_id)
- github_integration = UserGitHubIntegration(integration)
+ github_integration = UserGitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)
if github_integration.access_token_expired():
github_integration.refresh_access_token()
return github_integration.integration.sensitive_config.get("access_token") or None
@@ -990,7 +991,7 @@ def _user_integration_has_repository(
if repository is None:
return True
- github = UserGitHubIntegration(integration)
+ github = UserGitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)
cached_repositories = integration.repository_cache
if isinstance(cached_repositories, list) and _repository_matches_cached_list(cached_repositories, repository):
return True
@@ -1024,7 +1025,7 @@ def get_user_github_integration(
normalized_repository,
allow_refresh=allow_refresh,
):
- return UserGitHubIntegration(integration)
+ return UserGitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)
return None
@@ -1071,7 +1072,7 @@ def resolve_user_github_integration_for_task(
normalized_repository,
allow_refresh=allow_refresh,
):
- return UserGitHubIntegration(integration)
+ return UserGitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)
return get_user_github_integration(
user,
diff --git a/products/visual_review/backend/logic/baselines.py b/products/visual_review/backend/logic/baselines.py
index 527e07ea9843..4d5403c0e02c 100644
--- a/products/visual_review/backend/logic/baselines.py
+++ b/products/visual_review/backend/logic/baselines.py
@@ -11,6 +11,8 @@ from django.db.models import F, Q
import structlog
+from posthog.egress.limiter.policies import Priority
+
if TYPE_CHECKING:
from posthog.models.integration import GitHubIntegration
@@ -360,7 +362,7 @@ def _get_coauthor_trailer(user_id: int, installation_id: str) -> str | None:
).first()
if user_integration is None:
return None
- return UserGitHubIntegration(user_integration).coauthor_trailer
+ return UserGitHubIntegration(user_integration, source="visual_review", priority=Priority.CRITICAL).coauthor_trailer
def _commit_baseline_to_github(
diff --git a/products/visual_review/backend/logic/comment_markdown.py b/products/visual_review/backend/logic/comment_markdown.py
index 9720ea1322c8..d8b7bd1dc36c 100644
--- a/products/visual_review/backend/logic/comment_markdown.py
+++ b/products/visual_review/backend/logic/comment_markdown.py
@@ -9,6 +9,8 @@ from dataclasses import dataclass
from django.db import models as db_models
+from posthog.egress.limiter.policies import Priority
+
from ..db import READER_DB
from ..facade.enums import ReviewState, SnapshotResult
from ..models import Artifact, Repo, Run, RunSnapshot
@@ -276,7 +278,7 @@ def _resolve_approver(user_id: int | None) -> _Approver | None:
.first()
)
if gh is not None:
- github_login = UserGitHubIntegration(gh).github_login
+ github_login = UserGitHubIntegration(gh, source="visual_review", priority=Priority.CRITICAL).github_login
if github_login:
return _Approver(label=github_login, is_github_login=True)
diff --git a/products/visual_review/backend/logic/github_api.py b/products/visual_review/backend/logic/github_api.py
index d73ff9923a3c..7250617ee230 100644
--- a/products/visual_review/backend/logic/github_api.py
+++ b/products/visual_review/backend/logic/github_api.py
@@ -9,6 +9,8 @@ from urllib.parse import quote
import structlog
+from posthog.egress.limiter.policies import Priority
+
if TYPE_CHECKING:
import requests
@@ -210,7 +212,7 @@ def get_github_integration_for_repo(repo: Repo):
if not integration:
raise errors.GitHubIntegrationNotFoundError(f"No GitHub integration found for team {repo.team_id}")
- return GitHubIntegration(integration, source="visual_review")
+ return GitHubIntegration(integration, source="visual_review", priority=Priority.CRITICAL)
def _resolve_repo_by_id(github, repo_external_id: int) -> str | None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
index 3bf03295baf1..ed0936893e06 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
@@ -4,6 +4,8 @@ from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from typing import TYPE_CHECKING, Any, Optional, TypeVar, cast
+from posthog.egress.limiter.policies import Priority
+
if TYPE_CHECKING:
from products.cdp.backend.templates.hog_function_template import HogFunctionTemplateDC
@@ -419,9 +421,9 @@ If automatic creation failed with a permissions error, the fix depends on how yo
# query (server-side) and cap the page — the picker searches as the user types rather than
# loading every repo at once.
try:
- repositories, _has_more = GitHubIntegration(integration).list_cached_repositories(
- search=search or "", limit=100, offset=0
- )
+ repositories, _has_more = GitHubIntegration(
+ integration, source="warehouse", priority=Priority.CRITICAL
+ ).list_cached_repositories(search=search or "", limit=100, offset=0)
except GitHubIntegrationError as e:
# The refresh talks to GitHub, which can reject the credentials, report a suspended
# installation, or return a transient non-JSON/5xx body from its edge. None of these are
@@ -498,7 +500,7 @@ If automatic creation failed with a permissions error, the fix depends on how yo
raise ValueError("Missing GitHub integration ID")
integration = self.get_oauth_integration(config.auth_method.github_integration_id, team_id)
- github_integration = GitHubIntegration(integration)
+ github_integration = GitHubIntegration(integration, source="warehouse", priority=Priority.CRITICAL)
if github_integration.access_token_expired():
github_integration.refresh_access_token()
@@ -515,7 +517,11 @@ If automatic creation failed with a permissions error, the fix depends on how yo
if config.auth_method.selection == "pat" or not config.auth_method.github_integration_id:
return GithubEgressIdentity()
integration = self.get_oauth_integration(config.auth_method.github_integration_id, team_id)
- return GithubEgressIdentity(installation_id=GitHubIntegration(integration).github_installation_id)
+ return GithubEgressIdentity(
+ installation_id=GitHubIntegration(
+ integration, source="warehouse", priority=Priority.CRITICAL
+ ).github_installation_id
+ )
@staticmethod
def _schema_for_endpoint(endpoint: str, repository: str | None = None) -> SourceSchema:
diff --git a/products/wizard/backend/logic/workers/repository_publisher.py b/products/wizard/backend/logic/workers/repository_publisher.py
index 833a4d166585..498904d8a62e 100644
--- a/products/wizard/backend/logic/workers/repository_publisher.py
+++ b/products/wizard/backend/logic/workers/repository_publisher.py
@@ -3,6 +3,7 @@ import base64
from typing import Any
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration, Integration
from products.tasks.backend.facade.sandbox import SandboxBase, sandbox_repo_path
@@ -219,7 +220,7 @@ def _github_integration(team_id: int, integration_id: int, source: str) -> GitHu
integration = Integration.objects.filter(team_id=team_id, id=integration_id, kind="github").first()
if integration is None:
raise RepositoryPublishingError("GitHub integration is unavailable.")
- return GitHubIntegration(integration, source=source)
+ return GitHubIntegration(integration, source=source, priority=Priority.CRITICAL)
def _repository_and_branch_tip(
@@ -304,7 +305,7 @@ def create_pull_request(
if integration is None:
raise RepositoryPublishingError("GitHub integration is unavailable.")
- github = GitHubIntegration(integration, source=source)
+ github = GitHubIntegration(integration, source=source, priority=Priority.CRITICAL)
if github.organization().casefold() != repository_name.owner.casefold():
raise RepositoryPublishingError("GitHub integration does not own the repository.")