:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(integrations): stop github cache refreshes bursting the shared budget (#115230)
Julian Bezfd1633843618
diff --git a/posthog/egress/github/README.md b/posthog/egress/github/README.mdindex d9a3291005f4..a44b5cb3f5f1 100644--- a/posthog/egress/github/README.md+++ b/posthog/egress/github/README.md@@ -28,6 +28,8 @@ 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.The warehouse source's page fetches run on `BATCH`, while its repository validation and webhook management run on `NORMAL`, because a person waits on them. Customer Analytics feature-request link and resume lookups also run on `NORMAL` because an editor waits for the current issue state. Signals refreshes the stored pull request review decision from GitHub webhooks on `BATCH`; the inbox can keep the last known value when the lane is shed and update it after a retry.The ownership file reader (`posthog/ownership/`, source `ownership_github_api`) runs on `NORMAL` where a person waits for a board or a snapshot list, and on `BATCH` for the scheduled digests and report generation. Its GraphQL reads charge `core`, as every GraphQL call does, and so does the one compare call per new head commit that lets it reuse cached files.+The repository cache behind repository selection (`posthog/models/integration_repository_cache.py`) runs on `BATCH` for Signals reports and on `NORMAL` when a person waits in Slack. It reads each repository's `pushed_at` from the installation's repository listing, refreshed when older than ten minutes, and calls GitHub only for repositories pushed since their last sync. A shed call waits for the limiter's pace and tries again.+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.diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex 10e2ef7d0c3c..28ecd74852e8 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -9,7 +9,7 @@ import reimport jsonimport timeimport uuid-from collections.abc import Collection, Iterable, Mapping+from collections.abc import Callable, Collection, Iterable, Mappingfrom dataclasses import dataclassfrom datetime import datetimefrom typing import Any, Literal, TypedDict, cast@@ -27,10 +27,11 @@ import structlogfrom prometheus_client import Counterfrom posthog.dataclasses import frozen-from posthog.egress.github.limiter import remember_observed_core_limit+from posthog.egress.github.limiter import github_installation_pace_seconds, remember_observed_core_limitfrom posthog.egress.github.transport import GitHubRateLimitError, github_request, raise_if_github_rate_limitedfrom posthog.egress.limiter.policies import Priorityfrom posthog.github.merge_queue import MergeQueueState+from posthog.redis import get_client as get_redis_clientfrom posthog.sync import database_sync_to_async_poolfrom posthog.utils import safe_cache_add, safe_cache_delete@@ -50,6 +51,23 @@ GITHUB_REPOSITORY_CACHE_TTL_SECONDS = 60 * 60# Branch cache: 10-minute staleness, 24-hour eviction timeout.GITHUB_BRANCH_CACHE_TTL_SECONDS = 60 * 10+GITHUB_BRANCH_REFRESH_MAX_WAIT_SECONDS = 60.0+# Outlives a paced refresh and its retries, so picker views do not queue a second one meanwhile.+GITHUB_BRANCH_REFRESH_LOCK_SECONDS = 60 * 60++# Token-checked lock operations, so only the refresh that holds the lock renews or releases it.+_RENEW_OWNED_LOCK_SCRIPT = """+if redis.call("get", KEYS[1]) == ARGV[1] then+ return redis.call("expire", KEYS[1], ARGV[2])+end+return 0+"""+_RELEASE_OWNED_LOCK_SCRIPT = """+if redis.call("get", KEYS[1]) == ARGV[1] then+ return redis.call("del", KEYS[1])+end+return 0+"""GITHUB_BRANCH_CACHE_TIMEOUT_SECONDS = 60 * 60 * 24INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY = "installation_unavailable_since"@@ -207,6 +225,8 @@ class GitHubIntegrationBase:"""Installation-token operations shared between team and user GitHub integrations."""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.@@ -2407,7 +2427,9 @@ class GitHubIntegrationBase:"comments": feedback,}- def list_repositories(self, *, page: int = 1, per_page: int = 100) -> tuple[list[dict], bool]:+ def list_repositories(+ self, *, page: int = 1, per_page: int = 100, priority: Priority | None = None+ ) -> tuple[list[dict], bool]:"""List one page of installation repositories from the GitHub API.Uses GitHub's ``page`` and ``per_page`` query parameters@@ -2445,6 +2467,7 @@ class GitHubIntegrationBase:"GET",f"/installation/repositories?page={page}&per_page={per_page}",endpoint="/installation/repositories",+ priority=priority,)try:body = response.json()@@ -2467,14 +2490,14 @@ class GitHubIntegrationBase:)raise GitHubIntegrationError("GitHubIntegration: failed to list repositories")- def list_all_repositories(self) -> list[dict]:- """Fetch all accessible repositories, paginating through GitHub's API."""+ def list_all_repositories(self, *, priority: Priority | None = None) -> list[dict]:+ """Fetch all accessible repositories, paginating through GitHub's API. ``priority`` overrides the client's lane."""all_repositories: list[dict] = []page = 1per_page = 100while True:- repositories, has_more = self.list_repositories(page=page, per_page=per_page)+ repositories, has_more = self.list_repositories(page=page, per_page=per_page, priority=priority)all_repositories.extend(repositories)if not has_more or not repositories:@@ -2569,13 +2592,19 @@ class GitHubIntegrationBase:return result, has_more- def list_all_branches(self, repo: str) -> list[str]:- """Fetch all branches for a repository, paginating through GitHub's API."""+ def list_all_branches(self, repo: str, *, before_page: Callable[[], None] | None = None) -> list[str]:+ """Fetch all branches for a repository, paginating through GitHub's API.++ A large repository takes hundreds of pages. ``before_page`` runs before each one, so a+ background refresh can wait for room in the installation's budget and keep its lock alive.+ """all_branches: list[str] = []offset = 0page_size = 100while True:+ if before_page is not None:+ before_page()branches, has_more = self.list_branches(repo, limit=page_size, offset=offset)all_branches.extend(branches)@@ -2666,7 +2695,9 @@ class GitHubIntegrationBase:return Truereturn (timezone.now() - updated_at).total_seconds() >= GITHUB_REPOSITORY_CACHE_TTL_SECONDS- def sync_repository_cache(self, min_refresh_interval_seconds: int | None = None) -> list[dict]:+ def sync_repository_cache(+ self, min_refresh_interval_seconds: int | None = None, *, priority: Priority | None = None+ ) -> list[dict]:cached_repositories = self._get_stored_repository_list()updated_at = self.integration.repository_cache_updated_atif (@@ -2677,7 +2708,7 @@ class GitHubIntegrationBase:):return cached_repositories- repositories = self.list_all_repositories()+ repositories = self.list_all_repositories(priority=priority)refreshed_at = timezone.now()update_fields = ["repository_cache_updated_at"]if repositories != cached_repositories:@@ -2789,8 +2820,18 @@ class GitHubIntegrationBase:return Truereturn time.time() - float(cached["updated_at"]) >= GITHUB_BRANCH_CACHE_TTL_SECONDS- def sync_branch_cache(self, repo: str) -> tuple[list[str], str | None]:- branches = self.list_all_branches(repo)+ def _wait_for_budget(self) -> None:+ installation_id = self.github_installation_id+ if not installation_id:+ return+ pace = github_installation_pace_seconds(installation_id, priority=self.priority)+ if pace > 0:+ time.sleep(min(pace, GITHUB_BRANCH_REFRESH_MAX_WAIT_SECONDS))++ def sync_branch_cache(+ self, repo: str, *, before_page: Callable[[], None] | None = None+ ) -> tuple[list[str], str | None]:+ branches = self.list_all_branches(repo, before_page=before_page)cached = self._get_branch_cache(repo)cached_default_branch = None if cached is None else cast(str | None, cached.get("default_branch"))@@ -2822,6 +2863,57 @@ class GitHubIntegrationBase:return branches, default_branch+ def _branch_refresh_lock_key(self, repo: str) -> str:+ return f"{self._get_branch_cache_key(repo)}:refreshing"++ def _schedule_branch_cache_refresh(self, repo: str) -> None:+ lock_token = uuid.uuid4().hex+ try:+ acquired = get_redis_client().set(+ self._branch_refresh_lock_key(repo), lock_token, nx=True, ex=GITHUB_BRANCH_REFRESH_LOCK_SECONDS+ )+ except Exception:+ # The person still gets the cached list; the next picker view tries the refresh again.+ logger.warning(+ "GitHubIntegration: failed to take the branch refresh lock",+ integration_id=self.integration.id,+ repo=repo,+ exc_info=True,+ )+ return+ if not acquired:+ return+ # The tasks module imports the integration models, so a module-level import is circular.+ from posthog.tasks.integrations import refresh_github_branch_cache # noqa: PLC0415++ try:+ refresh_github_branch_cache.delay(str(self.integration.id), repo, self.is_user_integration, lock_token)+ except Exception:+ self.release_branch_refresh_lock(repo, lock_token)+ logger.warning(+ "GitHubIntegration: failed to schedule branch cache refresh",+ integration_id=self.integration.id,+ repo=repo,+ exc_info=True,+ )++ def release_branch_refresh_lock(self, repo: str, lock_token: str) -> None:+ # Only the owner releases, and atomically, so a refresh cannot free a newer refresh's lock.+ get_redis_client().eval(_RELEASE_OWNED_LOCK_SCRIPT, 1, self._branch_refresh_lock_key(repo), lock_token)++ def refresh_branch_cache(self, repo: str, lock_token: str) -> None:+ """List the branches at the budget's pace and store them, for the background refresh."""+ lock_key = self._branch_refresh_lock_key(repo)++ def before_page() -> None:+ self._wait_for_budget()+ # A paced refresh of a large repository can outlast the lock, so each page renews it.+ get_redis_client().eval(+ _RENEW_OWNED_LOCK_SCRIPT, 1, lock_key, lock_token, str(GITHUB_BRANCH_REFRESH_LOCK_SECONDS)+ )++ self.sync_branch_cache(repo, before_page=before_page)+def list_cached_branches(self, repo: str, *, search: str = "", limit: int = 100, offset: int = 0) -> tuple[list[str], str | None, bool]:@@ -2829,13 +2921,9 @@ class GitHubIntegrationBase:should_refresh = cached is None or self.branch_cache_is_stale(repo)self._record_github_cache_access("branches", "miss" if should_refresh else "hit", repo)- if should_refresh:+ if cached is None:try:branches, default_branch = self.sync_branch_cache(repo)- cached = {- "branches": branches,- "default_branch": default_branch,- }except Exception:logger.warning("GitHubIntegration: failed to refresh branch cache",@@ -2843,10 +2931,16 @@ class GitHubIntegrationBase:repo=repo,exc_info=True,)- if cached is None:- raise+ raise+ cached = {+ "branches": branches,+ "default_branch": default_branch,+ }+ elif should_refresh:+ # A large repository takes hundreds of pages to list. The person gets the cached list now,+ # and a background task refreshes it.+ self._schedule_branch_cache_refresh(repo)- assert cached is not Nonebranches = cast(list[str], cached["branches"])default_branch = cast(str | None, cached.get("default_branch"))@@ -2967,12 +3061,13 @@ class GitHubIntegrationBase:return responseraise GitHubIntegrationError(f"GitHubIntegration: api_request exhausted retries on {path}")- def _gh_api_get(self, path: str, *, endpoint: str, timeout: int = 10) -> dict:+ def _gh_api_get(self, path: str, *, endpoint: str, timeout: int = 10, priority: Priority | None = None) -> dict:"""Authenticated GET against ``https://api.github.com`` returning parsed JSON.Dict-or-raise sugar over :meth:`api_request`: any non-2xx (or non-dict body) becomes a- :class:`GitHubIntegrationError`; rate limits propagate as :class:`GitHubRateLimitError`."""- response = self.api_request("GET", path, endpoint=endpoint, timeout=timeout)+ :class:`GitHubIntegrationError`; rate limits propagate as :class:`GitHubRateLimitError`.+ ``priority`` overrides the client's lane for this call, as on :meth:`api_request`."""+ response = self.api_request("GET", path, endpoint=endpoint, timeout=timeout, priority=priority)if response.status_code < 200 or response.status_code >= 300:logger.warning("GitHubIntegration: _gh_api_get non-2xx response",diff --git a/posthog/models/integration_repository_cache.py b/posthog/models/integration_repository_cache.pyindex 00fec6172749..4fb75659f78c 100644--- a/posthog/models/integration_repository_cache.py+++ b/posthog/models/integration_repository_cache.py@@ -17,7 +17,7 @@ import base64import asyncioimport contextlibfrom collections.abc import AsyncIterator, Awaitable, Callable-from datetime import timedelta+from datetime import datetime, timedeltafrom typing import TYPE_CHECKINGfrom urllib.parse import quote@@ -28,7 +28,9 @@ from django.utils import timezoneimport structlogfrom posthog import redis as posthog_redis-from posthog.egress.github.transport import GitHubRateLimitError+from posthog.egress.github.limiter import github_installation_pace_seconds+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.egress.limiter.policies import Priorityfrom posthog.helpers.async_concurrency import run_parallel_with_backofffrom posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import GitHubIntegration, GitHubIntegrationError, Integration@@ -46,6 +48,15 @@ logger = structlog.get_logger(__name__)# Past the TTL we still do a cheap SHA check before deciding to refetch the tree.GITHUB_REPOSITORY_FULL_CACHE_TTL_SECONDS = 60 * 60+# A push to the default branch moves the repository's `pushed_at`, so a repository whose listed+# `pushed_at` is older than its row's last sync still has the commit the row holds. The margin+# covers a push that landed while that sync ran.+UNPUSHED_SYNC_MARGIN = timedelta(minutes=5)+# The listing only shows pushes made before it was fetched, so the push check needs a recent one.+LISTING_MAX_AGE_SECONDS = 10 * 60++MAX_BUDGET_WAIT_SECONDS = 60.0+# Single-flight lock for `sync_full_cache`. First caller (leader) acquires the lock and runs;# concurrent callers (followers) poll until released, then read the warm cache and effectively no-op.SYNC_LOCK_KEY_PREFIX = "github_full_cache_sync"@@ -134,8 +145,10 @@ class IntegrationRepositoryCacheEntry(UUIDModel):class GitHubRepositoryFullCache:"""Owns the heavy per-repo cache (README + tree + metadata) for a GitHub integration."""- def __init__(self, github: GitHubIntegrationBase, *, team_id: int | None = None) -> None:+ def __init__(self, github: GitHubIntegrationBase, *, priority: Priority, team_id: int | None = None) -> None:self.github = github+ # The egress lane for every GitHub call the cache makes, whatever lane the client carries.+ self.priority = priorityif isinstance(github, GitHubIntegration):# Team-level integration is bound to one teamif team_id is not None and team_id != github.integration.team_id:@@ -158,6 +171,35 @@ class GitHubRepositoryFullCache:age = timezone.now() - entry.updated_atreturn age < timedelta(seconds=GITHUB_REPOSITORY_FULL_CACHE_TTL_SECONDS)+ @staticmethod+ def _unpushed_since_sync(entry: IntegrationRepositoryCacheEntry, listed: dict | None) -> bool:+ """Whether the repository listing shows no push since the row last synced.++ `listed` is the repository's entry in the light cache, which already carries `pushed_at` and+ `default_branch`, so this answers without a GitHub call. A missing or unreadable `pushed_at`+ answers no, and the row syncs as before.+ """+ if listed is None or listed.get("default_branch") != entry.default_branch:+ return False+ pushed_at = listed.get("pushed_at")+ if not isinstance(pushed_at, str):+ return False+ try:+ pushed = datetime.fromisoformat(pushed_at)+ except ValueError:+ return False+ if pushed.tzinfo is None:+ return False+ return pushed < entry.updated_at - UNPUSHED_SYNC_MARGIN++ def _save_listed_archived(self, entry: IntegrationRepositoryCacheEntry, listed: dict) -> None:+ # Archiving does not move `pushed_at`, and repository selection drops archived rows, so the flag+ # follows the listing. A queryset update keeps `updated_at`, which marks the last real sync.+ archived = listed.get("archived")+ if isinstance(archived, bool) and archived != entry.archived:+ IntegrationRepositoryCacheEntry.objects.filter(pk=entry.pk).update(archived=archived)+ entry.archived = archived+def _get_existing_entry(self, full_name: str) -> IntegrationRepositoryCacheEntry | None:# Defer the heavy blob columns: the freshness/SHA decision and light-path metadata save# never read them, and bulk sync would otherwise drag MBs of `tree_paths` per repo through@@ -170,12 +212,15 @@ class GitHubRepositoryFullCache:def _fetch_repo_meta(self, owner: str, repo: str, full_name: str) -> tuple[dict, str, str]:"""Pure-network: repo metadata + default-branch SHA. No DB I/O when token is fresh."""- repo_data = self.github._gh_api_get(f"/repos/{owner}/{repo}", endpoint="/repos/{owner}/{repo}")+ repo_data = self.github._gh_api_get(+ f"/repos/{owner}/{repo}", endpoint="/repos/{owner}/{repo}", priority=self.priority+ )default_branch = repo_data.get("default_branch") or "main"# Quote the ref so branches like `release/1.0` hit the right endpoint (precedent: products/visual_review/backend/logic/github_api.py).branch_data = self.github._gh_api_get(f"/repos/{owner}/{repo}/branches/{quote(default_branch, safe='')}",endpoint="/repos/{owner}/{repo}/branches/{branch}",+ priority=self.priority,)commit = branch_data.get("commit") or {}default_branch_sha = commit.get("sha")@@ -213,6 +258,7 @@ class GitHubRepositoryFullCache:readme_data = self.github._gh_api_get(f"/repos/{owner}/{repo}/readme?ref={default_branch_sha}",endpoint="/repos/{owner}/{repo}/readme",+ priority=self.priority,)encoded = readme_data.get("content")if isinstance(encoded, str):@@ -226,6 +272,7 @@ class GitHubRepositoryFullCache:tree_data = self.github._gh_api_get(f"/repos/{owner}/{repo}/git/trees/{default_branch_sha}?recursive=1",endpoint="/repos/{owner}/{repo}/git/trees/{sha}",+ priority=self.priority,)tree_entries = tree_data.get("tree") or []tree_paths = "\n".join(@@ -276,9 +323,12 @@ class GitHubRepositoryFullCache:return entryasync def sync_full_cache_entry_async(- self, full_name: str, *, path_log: list[str] | None = None+ self, full_name: str, *, path_log: list[str] | None = None, listed: dict | None = None) -> IntegrationRepositoryCacheEntry:- """Fetch one repo's heavy metadata + README + file tree, upsert the cache row, without blocking DB"""+ """Fetch one repo's heavy metadata + README + file tree, upsert the cache row, without blocking DB.++ `listed` is the repo's entry in the light cache. With it, a row whose repo got no push since+ its last sync stays as it is, without a GitHub call."""# 1. Validate input.if "/" not in full_name:raise ValueError(f"full_name must be in 'owner/repo' format, got {full_name!r}")@@ -291,6 +341,11 @@ class GitHubRepositoryFullCache:if path_log is not None:path_log.append("ttl_hit")return existing+ if existing and existing.default_branch_sha and listed and self._unpushed_since_sync(existing, listed):+ await database_sync_to_async(self._save_listed_archived)(existing, listed)+ if path_log is not None:+ path_log.append("unpushed")+ return existing# 3. Network: repo metadata + branch SHA.repo_data, default_branch, default_branch_sha = await asyncio.to_thread(@@ -335,6 +390,16 @@ class GitHubRepositoryFullCache:deleted, _ = qs.delete()return deleted+ def _retry_delay(self, exc: BaseException) -> float | None:+ """Seconds until a rate-limited or shed call may try again, or None for the default backoff."""+ if isinstance(exc, GitHubRateLimitError):+ return exc.retry_after+ if isinstance(exc, GitHubEgressBudgetExhausted) and exc.scope:+ pace = github_installation_pace_seconds(exc.scope, priority=self.priority)+ if pace > 0:+ return min(pace, MAX_BUDGET_WAIT_SECONDS)+ return None+async def sync_full_cache(self, *, concurrency: int = 10) -> list[IntegrationRepositoryCacheEntry | BaseException]:"""Bulk heavy sync for all repos this integration sees.@@ -350,9 +415,20 @@ class GitHubRepositoryFullCache:async def _sync_full_cache_locked(self, *, concurrency: int) -> list[IntegrationRepositoryCacheEntry | BaseException]:- # 1. Source of truth: the light cache. This also refreshes it from GitHub if >1h stale.- repos = await self.github.list_all_cached_repositories_async()- valid_full_names = {r["full_name"].lower() for r in repos if isinstance(r.get("full_name"), str)}+ # 1. Source of truth: the light cache, refreshed when older than the push check allows.+ try:+ repos = await database_sync_to_async(self.github.sync_repository_cache, thread_sensitive=False)(+ min_refresh_interval_seconds=LISTING_MAX_AGE_SECONDS, priority=self.priority+ )+ listing_is_recent = True+ except Exception:+ logger.warning(+ "github_full_cache.listing_refresh_failed", integration_id=self.integration.id, exc_info=True+ )+ repos = await self.github.list_all_cached_repositories_async()+ listing_is_recent = False+ listed_by_name = {r["full_name"].lower(): r for r in repos if isinstance(r.get("full_name"), str)}+ valid_full_names = set(listed_by_name)# 2. Evict orphans — heavy cache is always a subset of the light cache.evicted = await self._evict_orphans(valid_full_names)if evicted:@@ -373,7 +449,9 @@ class GitHubRepositoryFullCache:def make_fn(full_name: str) -> Callable[[], Awaitable[IntegrationRepositoryCacheEntry]]:async def run() -> IntegrationRepositoryCacheEntry:- return await self.sync_full_cache_entry_async(full_name, path_log=path_log)+ return await self.sync_full_cache_entry_async(+ full_name, path_log=path_log, listed=listed_by_name[full_name] if listing_is_recent else None+ )return run@@ -382,8 +460,8 @@ class GitHubRepositoryFullCache:results = await run_parallel_with_backoff([make_fn(name) for name in valid_full_names],concurrency=concurrency,- is_retryable=lambda exc: isinstance(exc, GitHubRateLimitError),- get_retry_delay=lambda exc: getattr(exc, "retry_after", None),+ is_retryable=lambda exc: isinstance(exc, GitHubRateLimitError | GitHubEgressBudgetExhausted),+ get_retry_delay=self._retry_delay,)# 4. Single summary line — distinguishes "warm cache, all hits" from "did real work".errors = sum(1 for r in results if isinstance(r, BaseException))@@ -392,6 +470,7 @@ class GitHubRepositoryFullCache:integration_id=self.integration.id,total=len(results),ttl_hits=path_log.count("ttl_hit"),+ unpushed=path_log.count("unpushed"),sha_unchanged=path_log.count("sha_unchanged"),heavy=path_log.count("heavy"),errors=errors,diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex 1ae672af6933..43fd9bfbca56 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -28,6 +28,7 @@ from posthog.egress.limiter.policies import Priorityfrom posthog.github.merge_queue import MergeQueueStatefrom posthog.models.github_integration_base import (GITHUB_BRANCH_CACHE_TTL_SECONDS,+ GITHUB_BRANCH_REFRESH_LOCK_SECONDS,GITHUB_REPOSITORY_CACHE_TTL_SECONDS,GitHubIntegrationBase,PullRequestRef,@@ -41,6 +42,7 @@ from posthog.models.integration import ()from posthog.models.integration.github import _MAX_FILE_CONTENTS_BYTESfrom posthog.models.user_integration import UserGitHubIntegration, UserIntegration+from posthog.redis import get_client as get_redis_clientclass TestExtractFailingChecks(SimpleTestCase):@@ -1800,8 +1802,8 @@ class TestGitHubIntegrationModel(BaseTest):assert len(repos) == 130assert repos == first_page + second_pageassert mock_list.call_args_list == [- call(page=1, per_page=100),- call(page=2, per_page=100),+ call(page=1, per_page=100, priority=None),+ call(page=2, per_page=100, priority=None),]@patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")@@ -1946,7 +1948,7 @@ class TestGitHubIntegrationModel(BaseTest):assert has_more is Trueassert integration.repository_cache == fetched_repositoriesassert integration.repository_cache_updated_at is not None- mock_list_all.assert_called_once_with()+ mock_list_all.assert_called_once_with(priority=None)assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1@patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")@@ -1972,7 +1974,7 @@ class TestGitHubIntegrationModel(BaseTest):assert repos == stale_repositoriesassert has_more is Falseassert integration.repository_cache == stale_repositories- mock_list_all.assert_called_once_with()+ mock_list_all.assert_called_once_with(priority=None)@patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")def test_list_cached_repositories_raises_on_refresh_error_without_cache(self, mock_list_all):@@ -1988,7 +1990,7 @@ class TestGitHubIntegrationModel(BaseTest):integration.refresh_from_db()assert integration.repository_cache == []assert integration.repository_cache_updated_at is None- mock_list_all.assert_called_once_with()+ mock_list_all.assert_called_once_with(priority=None)def test_invalidate_github_repository_caches_for_installation_clears_team_and_personal_rows(self):team_integration = self.create_integration(@@ -2027,7 +2029,7 @@ class TestGitHubIntegrationModel(BaseTest):assert repos == fetched_repositories[600:625]assert has_more is True- mock_list_all.assert_called_once_with()+ mock_list_all.assert_called_once_with(priority=None)@parameterized.expand([@@ -2066,7 +2068,7 @@ class TestGitHubIntegrationModel(BaseTest):assert [repo["id"] for repo in repos] == expected_idsassert has_more is expected_has_more- mock_list_all.assert_called_once_with()+ mock_list_all.assert_called_once_with(priority=None)@patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")def test_count_cached_repositories_counts_the_filtered_set_not_the_page(self, mock_list_all):@@ -2087,7 +2089,7 @@ class TestGitHubIntegrationModel(BaseTest):assert has_more is Trueassert github.count_cached_repositories(search="posthog") == 2assert github.count_cached_repositories() == 3- mock_list_all.assert_called_once_with()+ mock_list_all.assert_called_once_with(priority=None)@patch("posthog.models.integration.github.GitHubIntegration.list_branches")@patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")@@ -2144,7 +2146,7 @@ class TestGitHubIntegrationModel(BaseTest):assert branches == ["main", "develop"]assert default_branch == "main"- mock_list_all_branches.assert_called_once_with(repo)+ mock_list_all_branches.assert_called_once_with(repo, before_page=None)@patch("posthog.models.integration.github.GitHubIntegration.list_branches")@patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")@@ -2211,14 +2213,19 @@ class TestGitHubIntegrationModel(BaseTest):mock_default_branch.assert_called_once_with(repo)assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1+ @patch("posthog.tasks.integrations.refresh_github_branch_cache.delay")@patch("posthog.models.integration.github.GitHubIntegration.list_branches")- @patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")- def test_list_cached_branches_returns_stale_cache_on_refresh_error(self, mock_default_branch, mock_list_branches):+ def test_list_cached_branches_serves_stale_cache_and_schedules_one_refresh(+ self, mock_list_branches: MagicMock, mock_refresh_delay: MagicMock+ ) -> None:integration = self.create_integration({"installation_id": "INSTALL", "account": {"name": "PostHog"}},{"access_token": "ACCESS_TOKEN"},)repo = "posthog/posthog"+ lock_key = GitHubIntegration(integration)._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),{@@ -2227,21 +2234,64 @@ class TestGitHubIntegrationModel(BaseTest):"updated_at": time.time() - (GITHUB_BRANCH_CACHE_TTL_SECONDS + 1),},)- mock_list_branches.side_effect = Exception("GitHub is slow")- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(- repo, limit=10, offset=0- )+ for _ in range(2):+ branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(+ repo, limit=10, offset=0+ )assert branches == ["main", "develop"]assert default_branch == "main"assert has_more is False- mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)- mock_default_branch.assert_not_called()+ mock_list_branches.assert_not_called()+ mock_refresh_delay.assert_called_once()+ assert mock_refresh_delay.call_args.args[:3] == (str(integration.id), repo, False)++ @patch("posthog.models.github_integration_base.get_redis_client", side_effect=ConnectionError("redis down"))+ def test_list_cached_branches_serves_stale_cache_when_the_refresh_lock_is_unavailable(+ self, _mock_redis: MagicMock+ ) -> None:+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ repo = "posthog/posthog"+ cache.set(+ GitHubIntegration(integration)._get_branch_cache_key(repo),+ {+ "branches": ["main", "develop"],+ "default_branch": "main",+ "updated_at": time.time() - (GITHUB_BRANCH_CACHE_TTL_SECONDS + 1),+ },+ )++ branches, _, _ = GitHubIntegration(integration).list_cached_branches(repo)++ assert branches == ["main", "develop"]++ @patch("posthog.models.integration.github.GitHubIntegration.get_default_branch", return_value="main")+ @patch("posthog.models.integration.github.GitHubIntegration.list_branches")+ def test_refresh_branch_cache_renews_its_lock_on_every_page(+ self, mock_list_branches: MagicMock, _mock_default_branch: MagicMock+ ) -> None:+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ repo = "posthog/posthog"+ github = GitHubIntegration(integration)+ 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)+ mock_list_branches.side_effect = [([f"b{i}" for i in range(100)], True), (["main"], False)]++ github.refresh_branch_cache(repo, "token")++ assert get_redis_client().ttl(lock_key) > GITHUB_BRANCH_REFRESH_LOCK_SECONDS - 60@patch("posthog.models.integration.github.GitHubIntegration.list_branches")@patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")- def test_list_cached_branches_keeps_cached_default_branch_on_refresh_failure(+ def test_refresh_branch_cache_keeps_cached_default_branch_on_refresh_failure(self, mock_default_branch, mock_list_branches):integration = self.create_integration(@@ -2260,14 +2310,10 @@ class TestGitHubIntegrationModel(BaseTest):mock_list_branches.return_value = (["main", "develop", "feature/test"], False)mock_default_branch.side_effect = Exception("GitHub is slow")- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(- repo, limit=10, offset=0- )+ github = GitHubIntegration(integration)+ github.refresh_branch_cache(repo, "token")cached = cache.get(GitHubIntegration(integration)._get_branch_cache_key(repo))- assert branches == ["main", "develop", "feature/test"]- assert default_branch == "main"- assert has_more is Falseassert cached["branches"] == ["main", "develop", "feature/test"]assert cached["default_branch"] == "main"mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)diff --git a/posthog/models/test/test_integration_repository_cache.py b/posthog/models/test/test_integration_repository_cache.pyindex 6dffc104ae8c..4814af5d350e 100644--- a/posthog/models/test/test_integration_repository_cache.py+++ b/posthog/models/test/test_integration_repository_cache.py@@ -10,8 +10,10 @@ from django.core.cache import cachefrom django.utils import timezonefrom asgiref.sync import async_to_sync+from parameterized import parameterized-from posthog.egress.github.transport import GitHubRateLimitError+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.egress.limiter.policies import Priorityfrom posthog.models.integration import GitHubIntegration, GitHubIntegrationError, Integrationfrom posthog.models.integration_repository_cache import (GITHUB_REPOSITORY_FULL_CACHE_TTL_SECONDS,@@ -29,6 +31,12 @@ class TestGitHubRepositoryFullCache(BaseTest):def setUp(self):super().setUp()cache.clear()+ # The sweep falls back to the patched cached listing, as it does when a refresh fails.+ refresh = patch.object(+ GitHubIntegration, "sync_repository_cache", side_effect=RuntimeError("no listing refresh")+ )+ refresh.start()+ self.addCleanup(refresh.stop)def _create_integration(self) -> Integration:return Integration.objects.create(@@ -64,7 +72,7 @@ class TestGitHubRepositoryFullCache(BaseTest):}def _patch_gh_api_get(self, responses: dict):- def _side_effect(self_, path, *, endpoint=None, timeout=10):+ def _side_effect(self_, path, *, endpoint=None, timeout=10, priority=None):if path not in responses:raise AssertionError(f"unexpected path {path}")return responses[path]@@ -74,7 +82,7 @@ class TestGitHubRepositoryFullCache(BaseTest):)def _cache_for(self, integration: Integration) -> GitHubRepositoryFullCache:- return GitHubRepositoryFullCache(GitHubIntegration(integration))+ return GitHubRepositoryFullCache(GitHubIntegration(integration), priority=Priority.BATCH)def test_sync_full_cache_entry_populates_all_fields(self):integration = self._create_integration()@@ -195,6 +203,71 @@ class TestGitHubRepositoryFullCache(BaseTest):assert entry.readme == "# New README"assert entry.tree_paths == "README.md\nsrc/app.py"+ @parameterized.expand(+ [+ ("pushed_long_before_sync", "main", -60, "SHA1"),+ ("pushed_after_sync", "main", 30, "SHA2"),+ ("pushed_within_margin_of_sync", "main", -2, "SHA2"),+ ("default_branch_renamed", "trunk", -60, "SHA2"),+ ("no_pushed_at", "main", None, "SHA2"),+ ]+ )+ def test_sync_full_cache_entry_skips_github_only_when_listing_shows_no_push(+ self, _name: str, listed_branch: str, pushed_minutes_from_sync: int | None, expected_sha: str+ ) -> None:+ integration = self._create_integration()+ existing = IntegrationRepositoryCacheEntry.objects.create(+ integration=integration,+ team=self.team,+ full_name="posthog/posthog",+ default_branch="main",+ default_branch_sha="SHA1",+ readme="old readme",+ tree_paths="old/path",+ )+ synced_at = timezone.now() - timedelta(seconds=GITHUB_REPOSITORY_FULL_CACHE_TTL_SECONDS + 60)+ IntegrationRepositoryCacheEntry.objects.filter(pk=existing.pk).update(updated_at=synced_at)+ listed: dict = {"full_name": "posthog/posthog", "default_branch": listed_branch}+ if pushed_minutes_from_sync is not None:+ listed["pushed_at"] = (synced_at + timedelta(minutes=pushed_minutes_from_sync)).isoformat()+ responses = self._default_gh_api_responses(sha="SHA2")+ responses["/repos/posthog/posthog/branches/trunk"] = {"commit": {"sha": "SHA2"}}+ responses["/repos/posthog/posthog"] = {**responses["/repos/posthog/posthog"], "default_branch": listed_branch}++ with self._patch_gh_api_get(responses) as mock_gh_api_get:+ entry = async_to_sync(self._cache_for(integration).sync_full_cache_entry_async)(+ "posthog/posthog", listed=listed+ )++ assert entry.default_branch_sha == expected_sha+ assert (mock_gh_api_get.call_count == 0) == (expected_sha == "SHA1")++ def test_sync_full_cache_entry_takes_archived_from_listing_without_github_calls(self) -> None:+ integration = self._create_integration()+ existing = IntegrationRepositoryCacheEntry.objects.create(+ integration=integration,+ team=self.team,+ full_name="posthog/posthog",+ default_branch="main",+ default_branch_sha="SHA1",+ )+ synced_at = timezone.now() - timedelta(seconds=GITHUB_REPOSITORY_FULL_CACHE_TTL_SECONDS + 60)+ IntegrationRepositoryCacheEntry.objects.filter(pk=existing.pk).update(updated_at=synced_at)+ listed = {+ "full_name": "posthog/posthog",+ "default_branch": "main",+ "pushed_at": (synced_at - timedelta(hours=1)).isoformat(),+ "archived": True,+ }++ with patch("posthog.models.integration.github.GitHubIntegration._gh_api_get", autospec=True) as mock_gh_api_get:+ async_to_sync(self._cache_for(integration).sync_full_cache_entry_async)("posthog/posthog", listed=listed)++ existing.refresh_from_db()+ assert mock_gh_api_get.call_count == 0+ assert existing.archived is True+ assert existing.updated_at == synced_at+def test_sync_full_cache_entry_handles_readme_fetch_failure_gracefully(self):integration = self._create_integration()responses = self._default_gh_api_responses()@@ -202,7 +275,7 @@ class TestGitHubRepositoryFullCache(BaseTest):call_log: list[str] = []- def _side_effect(self_, path, *, endpoint=None, timeout=10):+ def _side_effect(self_, path, *, endpoint=None, timeout=10, priority=None):call_log.append(path)if path.startswith("/repos/posthog/posthog/readme"):raise GitHubIntegrationError("readme missing", status_code=404)@@ -227,7 +300,7 @@ class TestGitHubRepositoryFullCache(BaseTest):integration = self._create_integration()responses = self._default_gh_api_responses()- def _side_effect(self_, path, *, endpoint=None, timeout=10):+ def _side_effect(self_, path, *, endpoint=None, timeout=10, priority=None):if path.startswith("/repos/posthog/posthog/readme"):raise GitHubRateLimitError("secondary rate limit on /readme", retry_after=60)return responses[path]@@ -247,7 +320,7 @@ class TestGitHubRepositoryFullCache(BaseTest):integration = self._create_integration()responses = self._default_gh_api_responses()- def _side_effect(self_, path, *, endpoint=None, timeout=10):+ def _side_effect(self_, path, *, endpoint=None, timeout=10, priority=None):if path.startswith("/repos/posthog/posthog/readme"):raise GitHubIntegrationError("upstream 502 on /readme", status_code=502)return responses[path]@@ -317,7 +390,7 @@ class TestGitHubRepositoryFullCache(BaseTest):in_flight = 0lock = asyncio.Lock()- async def fake_entry_async(full_name, *, path_log=None):+ async def fake_entry_async(full_name, *, path_log=None, listed=None):nonlocal in_flightasync with lock:in_flight += 1@@ -345,7 +418,7 @@ class TestGitHubRepositoryFullCache(BaseTest):def test_sync_full_cache_returns_exceptions_inline(self):integration = self._create_integration()- async def fake_entry_async(full_name, *, path_log=None):+ async def fake_entry_async(full_name, *, path_log=None, listed=None):if full_name == "posthog/broken":raise GitHubIntegrationError("boom")return MagicMock(full_name=full_name)@@ -364,6 +437,54 @@ class TestGitHubRepositoryFullCache(BaseTest):broken = next(r for r in results if isinstance(r, GitHubIntegrationError))assert str(broken) == "boom"+ @parameterized.expand([("listing_refreshed", True), ("listing_refresh_failed", False)])+ def test_sync_full_cache_checks_pushes_only_against_a_recent_listing(self, _name: str, refreshed: bool) -> None:+ integration = self._create_integration()+ listing = [{"full_name": "posthog/posthog", "pushed_at": "2026-01-01T00:00:00Z"}]+ received: list[dict | None] = []++ async def fake_entry_async(full_name, *, path_log=None, listed=None):+ received.append(listed)+ return MagicMock(full_name=full_name)++ async def fake_list():+ return listing++ repo_cache = self._cache_for(integration)+ refresh = {"return_value": listing} if refreshed else {"side_effect": RuntimeError("down")}+ with (+ patch.object(repo_cache.github, "sync_repository_cache", **refresh),+ patch.object(repo_cache, "sync_full_cache_entry_async", side_effect=fake_entry_async),+ patch.object(repo_cache.github, "list_all_cached_repositories_async", side_effect=fake_list),+ ):+ asyncio.run(repo_cache.sync_full_cache())++ assert received == [listing[0] if refreshed else None]++ @patch("posthog.models.integration_repository_cache.github_installation_pace_seconds", return_value=0.01)+ def test_sync_full_cache_retries_a_call_the_egress_budget_shed(self, _mock_pace: MagicMock) -> None:+ integration = self._create_integration()+ attempts: list[str] = []++ async def fake_entry_async(full_name, *, path_log=None, listed=None):+ attempts.append(full_name)+ if len(attempts) == 1:+ raise GitHubEgressBudgetExhausted("shed", scope="INSTALL")+ return MagicMock(full_name=full_name)++ async def fake_list():+ return [{"full_name": "posthog/posthog"}]++ repo_cache = self._cache_for(integration)+ with (+ patch.object(repo_cache, "sync_full_cache_entry_async", side_effect=fake_entry_async),+ patch.object(repo_cache.github, "list_all_cached_repositories_async", side_effect=fake_list),+ ):+ results = asyncio.run(repo_cache.sync_full_cache())++ assert attempts == ["posthog/posthog", "posthog/posthog"]+ assert not any(isinstance(r, BaseException) for r in results)+def test_sync_full_cache_evicts_orphans_not_in_light_cache(self):integration = self._create_integration()# Seed: one repo still in the light list ("posthog/posthog") and one orphan ("posthog/gone").@@ -384,7 +505,7 @@ class TestGitHubRepositoryFullCache(BaseTest):readme="cached",)- async def fake_entry_async(full_name, *, path_log=None):+ async def fake_entry_async(full_name, *, path_log=None, listed=None):return MagicMock(full_name=full_name)async def fake_list():@@ -449,7 +570,7 @@ class TestGitHubRepositoryFullCache(BaseTest):readme="cached",)- async def fake_entry_async(full_name, *, path_log=None):+ async def fake_entry_async(full_name, *, path_log=None, listed=None):return MagicMock(full_name=full_name)async def fake_list():@@ -488,7 +609,7 @@ class TestGitHubRepositoryFullCache(BaseTest):integration = self._create_integration()- async def fake_entry_async(full_name, *, path_log=None):+ async def fake_entry_async(full_name, *, path_log=None, listed=None):return MagicMock(full_name=full_name)async def fake_list():@@ -526,7 +647,7 @@ class TestGitHubRepositoryFullCache(BaseTest):integration = self._create_integration()- async def fake_entry_async(full_name, *, path_log=None):+ async def fake_entry_async(full_name, *, path_log=None, listed=None):return MagicMock(full_name=full_name)async def fake_list():@@ -558,7 +679,7 @@ class TestSyncFullCacheLock(BaseTest):)def _cache_for(self, integration: Integration) -> GitHubRepositoryFullCache:- return GitHubRepositoryFullCache(GitHubIntegration(integration))+ return GitHubRepositoryFullCache(GitHubIntegration(integration), 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_integration.py b/posthog/models/user_integration.pyindex 96993d8a7406..78b7f5756b70 100644--- a/posthog/models/user_integration.py+++ b/posthog/models/user_integration.py@@ -207,6 +207,7 @@ class UserGitHubIntegration(GitHubIntegrationBase):"""integration: UserIntegration+ is_user_integration = Truedef __init__(self, integration: UserIntegration, *, source: str | None = None, priority: Priority | None = Nonediff --git a/posthog/tasks/integrations.py b/posthog/tasks/integrations.pyindex 129932bc6447..1acb6908bc00 100644--- a/posthog/tasks/integrations.py+++ b/posthog/tasks/integrations.py@@ -1,17 +1,24 @@-from celery import shared_task+from celery import Task, shared_task+from posthog.egress.github.transport import GitHubEgressBudgetExhausted+from posthog.egress.limiter.policies import Priority+from posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import (FirebaseIntegration,GitHubIntegration,GoogleCloudIntegration,+ Integration,defer_repository_cache_fields,refresh_backoff_active,)+from posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueuefrom products.workflows.backend.facade.api import delete_ses_identity+GITHUB_BRANCH_REFRESH_RETRY_SECONDS = 5 * 60+@shared_task(ignore_result=True, queue=CeleryQueue.INTEGRATIONS.value)@skip_team_scope_audit@@ -135,3 +142,34 @@ def push_vercel_secrets(team_id: int) -> None:team = Team.objects.get(id=team_id)VercelIntegration.push_secrets_to_vercel(team)+++@shared_task(bind=True, ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value, max_retries=5)+@skip_team_scope_audit+def refresh_github_branch_cache(+ self: Task, integration_id: str, repo: str, is_user_integration: bool, lock_token: str+) -> None:+ """Refresh one repository's cached branch list for the branch picker, on the batch lane."""+ github: GitHubIntegrationBase+ if is_user_integration:+ user_integration = UserIntegration.objects.filter(id=integration_id).first()+ if user_integration is None:+ return+ github = UserGitHubIntegration(user_integration, source="github_branch_picker", priority=Priority.BATCH)+ else:+ integration = defer_repository_cache_fields(Integration.objects.filter(id=integration_id)).first()+ if integration is None:+ return+ github = GitHubIntegration(integration, source="github_branch_picker", priority=Priority.BATCH)+ try:+ github.refresh_branch_cache(repo, lock_token)+ except GitHubEgressBudgetExhausted as error:+ if self.request.retries < self.max_retries:+ # The lock stays held, so picker views do not queue a second refresh while this one waits.+ raise self.retry(exc=error, countdown=GITHUB_BRANCH_REFRESH_RETRY_SECONDS)+ github.release_branch_refresh_lock(repo, lock_token)+ raise+ except Exception:+ github.release_branch_refresh_lock(repo, lock_token)+ raise+ github.release_branch_refresh_lock(repo, lock_token)diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex aaac0f4b5448..d0dd602b2be0 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -91,6 +91,7 @@'posthog.tasks.hypercache_verification.verify_and_fix_team_metadata_cache_task','posthog.tasks.integrations.delete_ses_identity_if_unused','posthog.tasks.integrations.push_vercel_secrets',+ 'posthog.tasks.integrations.refresh_github_branch_cache','posthog.tasks.integrations.refresh_integration','posthog.tasks.integrations.refresh_integrations','posthog.tasks.js_snippet_versioning.sync_js_snippet_manifest',diff --git a/posthog/tasks/test/test_integrations.py b/posthog/tasks/test/test_integrations.pyindex d784aed8b2aa..e5aba1c38553 100644--- a/posthog/tasks/test/test_integrations.py+++ b/posthog/tasks/test/test_integrations.py@@ -1,13 +1,17 @@import timefrom typing import Optional+import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import patchfrom parameterized import parameterized-from posthog.models.integration import Integration-from posthog.tasks.integrations import refresh_integration, refresh_integrations+from posthog.egress.github.transport import GitHubEgressBudgetExhausted+from posthog.egress.limiter.policies import Priority+from posthog.models.integration import GitHubIntegration, Integration+from posthog.redis import get_client as get_redis_client+from posthog.tasks.integrations import refresh_github_branch_cache, refresh_integration, refresh_integrationsclass TestIntegrationsTasks(APIBaseTest):@@ -113,3 +117,38 @@ class TestIntegrationsTasks(APIBaseTest):refresh_integration(integration.id)assert refresh_mock.called is expected_refreshed++ @parameterized.expand(+ [+ ("budget_shed_keeps_lock_for_the_retry", GitHubEgressBudgetExhausted("shed", scope="1"), True),+ ("other_error_releases_lock", RuntimeError("boom"), False),+ ]+ )+ def test_branch_refresh_holds_its_lock_only_while_a_retry_is_pending(+ self, _name: str, error: Exception, lock_held: bool+ ) -> None:+ integration = self.create_integration("github", config={"installation_id": "INSTALL"})+ github = GitHubIntegration(integration, source="test", priority=Priority.BATCH)+ lock_key = github._branch_refresh_lock_key("posthog/posthog")+ get_redis_client().set(lock_key, "token")+ self.addCleanup(get_redis_client().delete, lock_key)++ with (+ patch("posthog.models.integration.github.GitHubIntegration.refresh_branch_cache", side_effect=error),+ pytest.raises(type(error)),+ ):+ refresh_github_branch_cache(str(integration.id), "posthog/posthog", False, "token")++ assert (get_redis_client().get(lock_key) == b"token") is lock_held++ def test_branch_refresh_leaves_a_newer_refresh_lock_alone(self) -> None:+ integration = self.create_integration("github", config={"installation_id": "INSTALL"})+ github = GitHubIntegration(integration, source="test", priority=Priority.BATCH)+ lock_key = github._branch_refresh_lock_key("posthog/posthog")+ get_redis_client().set(lock_key, "newer")+ self.addCleanup(get_redis_client().delete, lock_key)++ with patch("posthog.models.integration.github.GitHubIntegration.refresh_branch_cache"):+ refresh_github_branch_cache(str(integration.id), "posthog/posthog", False, "older")++ assert get_redis_client().get(lock_key) == b"newer"diff --git a/posthog/temporal/ai/slack_app/activities/repo_selection.py b/posthog/temporal/ai/slack_app/activities/repo_selection.pyindex 5f6abbf60438..72f5f61b2a89 100644--- a/posthog/temporal/ai/slack_app/activities/repo_selection.py+++ b/posthog/temporal/ai/slack_app/activities/repo_selection.py@@ -4,6 +4,7 @@ from typing import Anyimport structlogfrom temporalio import activity+from posthog.egress.limiter.policies import Priorityfrom posthog.temporal.ai.slack_app.helpers import safe_reactfrom posthog.temporal.ai.slack_app.types import (PostHogCodeRepoCascadeOutcome,@@ -170,6 +171,8 @@ async def discover_posthog_code_repository_via_agent_activity(user_id=user_id,context=context_block,origin_product=tasks_facade.TaskOriginProduct.SLACK,+ # A person waits in the Slack thread for the answer.+ priority=Priority.NORMAL,on_research_session=_capture_research_session,)except RepoSelectionRejectedError as exc:diff --git a/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py b/posthog/temporal/ai/slack_app/eval_slack_repo_selection.pyindex 8844d0a67c61..393e1782bac5 100644--- a/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py+++ b/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py@@ -87,6 +87,7 @@ django.setup()from django.conf import settings+from posthog.egress.limiter.policies import Priorityfrom posthog.models import Teamfrom posthog.models.repo_routing_rule import RepoRoutingRulefrom posthog.temporal.ai.slack_app import POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE@@ -606,6 +607,7 @@ class Command:user_id=ctx.user_id,context=context,origin_product=tasks_facade.TaskOriginProduct.SLACK,+ priority=Priority.BATCH,))if result.repository is None:diff --git a/products/business_knowledge/backend/github_repos.py b/products/business_knowledge/backend/github_repos.pyindex b01e99e9f64d..45f49adf2466 100644--- a/products/business_knowledge/backend/github_repos.py+++ b/products/business_knowledge/backend/github_repos.py@@ -284,7 +284,7 @@ def warm_selected_repository(team_id: int, integration_id: int, full_name: str)returngithub = GitHubIntegration(integration, source="business_knowledge", priority=Priority.BATCH)try:- async_to_sync(GitHubRepositoryFullCache(github).sync_full_cache_entry_async)(full_name)+ async_to_sync(GitHubRepositoryFullCache(github, priority=Priority.BATCH).sync_full_cache_entry_async)(full_name)except GitHubIntegrationError as exc:# GitHub answers 404 when the repository left the installation. Drop the cached tree and README# so search cannot return them. The selection stays, so access comes back if the repo is re-added.diff --git a/products/signals/backend/report_generation/select_repo.py b/products/signals/backend/report_generation/select_repo.pyindex 7ac4d9ad56a9..8a82d57e3101 100644--- a/products/signals/backend/report_generation/select_repo.py+++ b/products/signals/backend/report_generation/select_repo.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport loggingfrom typing import TYPE_CHECKING+from posthog.egress.limiter.policies import Priorityfrom posthog.sync import database_sync_to_asyncfrom products.signals.backend.agent_runtime import STEP_REPO_SELECTION, resolve_agent_runtime@@ -112,6 +113,8 @@ async def select_repository_for_team(user_id=user_id,context=request_section,origin_product=tasks_facade.TaskOriginProduct.SIGNAL_REPORT,+ # Report generation runs in the background, so its repository cache refresh yields first.+ priority=Priority.BATCH,step_name=step_name,signal_report_id=signal_report_id,sandbox_environment_id=sandbox_environment_id,diff --git a/products/signals/backend/test/test_resolve_team_github_integration.py b/products/signals/backend/test/test_resolve_team_github_integration.pyindex b107cff71c80..340b223b0f5d 100644--- a/products/signals/backend/test/test_resolve_team_github_integration.py+++ b/products/signals/backend/test/test_resolve_team_github_integration.py@@ -4,6 +4,7 @@ import pytestfrom django.utils import timezone+from posthog.egress.limiter.policies import Priorityfrom posthog.models import Organization, Team, Userfrom posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, GitHubIntegration, Integrationfrom posthog.models.organization import OrganizationMembership@@ -355,6 +356,7 @@ async def test_select_repository_requests_reconnect_for_unavailable_owner_integruser_id=owner.id,context="Investigate this signal",origin_product=tasks_facade.TaskOriginProduct.SIGNAL_REPORT,+ priority=Priority.BATCH,)assert result.repository is Nonediff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.pyindex 6fa400032f6f..2e85a8345a50 100644--- a/products/tasks/backend/logic/repo_selection/agent.py+++ b/products/tasks/backend/logic/repo_selection/agent.py@@ -8,6 +8,7 @@ from typing import TYPE_CHECKINGfrom django.db.models import Case, IntegerField, Q, Value, When+from posthog.egress.limiter.policies import Priorityfrom posthog.models.github_integration_base import INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY, GitHubIntegrationBasefrom posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, GitHubIntegration, Integrationfrom posthog.models.integration_repository_cache import GitHubRepositoryFullCache@@ -587,6 +588,7 @@ async def select_repository(context: str,*,origin_product: Task.OriginProduct,+ priority: Priority,github: GitHubIntegrationBase | None = None,candidate_repos: list[str] | None = None,step_name: str = "repo_selection",@@ -649,7 +651,7 @@ async def select_repository(# concurrent calls for the same team wait on the leader and then read the warm cache.if output_fn:output_fn("Refreshing repository cache...")- repo_cache = GitHubRepositoryFullCache(github, team_id=team_id)+ repo_cache = GitHubRepositoryFullCache(github, team_id=team_id, priority=priority)await repo_cache.sync_full_cache()# Drop archived repos (agent can't fix code there) and repos missing from the heavy cache# (the prompt treats SQL as primary evidence — a missing row reads as a false-negative).diff --git a/products/tasks/backend/tests/test_repo_selection_prompt.py b/products/tasks/backend/tests/test_repo_selection_prompt.pyindex d63d2073822c..0cbcae9daf1e 100644--- a/products/tasks/backend/tests/test_repo_selection_prompt.py+++ b/products/tasks/backend/tests/test_repo_selection_prompt.py@@ -4,6 +4,7 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom asgiref.sync import async_to_syncfrom parameterized import parameterized+from posthog.egress.limiter.policies import Priorityfrom posthog.models.repo_routing_rule import RepoRoutingRulefrom products.tasks.backend.logic.repo_selection.agent import (@@ -113,6 +114,7 @@ def test_select_repository_renders_team_rules_and_visibility_into_prompt() -> No1,"which repo?",origin_product=Task.OriginProduct.SLACK,+ priority=Priority.NORMAL,github=github,candidate_repos=["acme/a", "acme/b"],)@@ -200,6 +202,7 @@ def test_select_repository_salvages_an_unreadable_end_turn() -> None:1,"which repo?",origin_product=Task.OriginProduct.SLACK,+ priority=Priority.NORMAL,github=github,candidate_repos=["acme/a", "acme/b"],)@@ -227,6 +230,7 @@ def test_pinned_repository_answers_without_running_the_agent(pinned: str, expect1,"which repo?",origin_product=Task.OriginProduct.SLACK,+ priority=Priority.NORMAL,github=github,candidate_repos=["acme/a", "acme/b"],pinned_repository=pinned,@@ -254,6 +258,7 @@ def test_pinned_repository_beats_the_single_candidate_shortcut() -> None:1,"which repo?",origin_product=Task.OriginProduct.SLACK,+ priority=Priority.NORMAL,github=github,candidate_repos=["acme/a"],pinned_repository="acme/b",