: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(signals): Consume `UserIntegration` on par with `Integration` for sandboxes (#57835)
Alex Lebedev1a01468df44d
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.pyindex 5f3acc4d35b6..b863688b32d1 100644--- a/posthog/hogql/database/schema/system.py+++ b/posthog/hogql/database/schema/system.py@@ -417,7 +417,8 @@ integration_repository_cache: PostgresTable = PostgresTable(fields={"id": StringDatabaseField(name="id"),"team_id": IntegerDatabaseField(name="team_id"),- "integration_id": IntegerDatabaseField(name="integration_id"),+ "integration_id": IntegerDatabaseField(name="integration_id", nullable=True),+ "user_integration_id": IntegerDatabaseField(name="user_integration_id", nullable=True),"full_name": StringDatabaseField(name="full_name"),"description": StringDatabaseField(name="description", nullable=True),"topics": StringJSONDatabaseField(name="topics"),diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex eae9f5e9c579..d669db191145 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -5194,6 +5194,16 @@"table": null,"type": "integer"},+ "user_integration_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "user_integration_id",+ "id": null,+ "name": "user_integration_id",+ "schema_valid": true,+ "table": null,+ "type": "integer"+ },"full_name": {"chain": null,"fields": null,@@ -12456,6 +12466,16 @@"table": null,"type": "integer"},+ "user_integration_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "user_integration_id",+ "id": null,+ "name": "user_integration_id",+ "schema_valid": true,+ "table": null,+ "type": "integer"+ },"full_name": {"chain": null,"fields": null,diff --git a/posthog/migrations/1149_integrationrepositorycacheentry_user_integration.py b/posthog/migrations/1149_integrationrepositorycacheentry_user_integration.pynew file mode 100644index 000000000000..d4a424ca5c7a--- /dev/null+++ b/posthog/migrations/1149_integrationrepositorycacheentry_user_integration.py@@ -0,0 +1,70 @@+# Generated by Django 5.2.13 on 2026-05-06 14:13++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1148_backfill_encrypted_payloads_invariant")]++ operations = [+ migrations.AlterUniqueTogether(+ name="integrationrepositorycacheentry",+ unique_together=set(),+ ),+ migrations.AddField(+ model_name="integrationrepositorycacheentry",+ name="user_integration",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="repository_cache_entries",+ to="posthog.userintegration",+ ),+ ),+ migrations.AlterField(+ model_name="integrationrepositorycacheentry",+ name="integration",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="repository_cache_entries",+ to="posthog.integration",+ ),+ ),+ migrations.AddConstraint(+ model_name="integrationrepositorycacheentry",+ constraint=models.UniqueConstraint(+ condition=models.Q(("integration__isnull", False)),+ fields=("integration", "full_name"),+ name="integration_full_name_unique",+ ),+ ),+ migrations.AddConstraint(+ model_name="integrationrepositorycacheentry",+ constraint=models.UniqueConstraint(+ condition=models.Q(("user_integration__isnull", False)),+ fields=("user_integration", "team", "full_name"),+ name="user_integration_team_full_name_unique",+ ),+ ),+ migrations.AddConstraint(+ model_name="integrationrepositorycacheentry",+ constraint=models.CheckConstraint(+ condition=models.Q(+ models.Q(+ ("integration__isnull", False),+ ("user_integration__isnull", True),+ ),+ models.Q(+ ("integration__isnull", True),+ ("user_integration__isnull", False),+ ),+ _connector="OR",+ ),+ name="integration_xor_user_integration",+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex afc3436a50cd..93c1c620790b 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1148_backfill_encrypted_payloads_invariant+1149_integrationrepositorycacheentry_user_integrationdiff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex f8c514ea4c68..b1ea83fe0669 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -21,6 +21,8 @@ import requestsimport structlogfrom prometheus_client import Counter, Gauge+from posthog.sync import database_sync_to_async_pool+logger = structlog.get_logger(__name__)github_api_request_counter = Counter(@@ -1091,3 +1093,143 @@ class GitHubIntegrationBase:result = filtered_branches[offset : offset + limit]has_more = offset + limit < len(filtered_branches)return result, default_branch, has_more++ def get_access_token(self) -> str:+ """Return a valid installation access token, refreshing it if expired."""+ if self.access_token_expired():+ self.refresh_access_token()+ token = (self.integration.sensitive_config or {}).get("access_token")+ if not token:+ raise GitHubIntegrationError("Access token unavailable after refresh")+ return token++ @staticmethod+ def _is_secondary_rate_limit(response: requests.Response) -> bool:+ """GitHub signals secondary rate limits via 429, or 403 + ``Retry-After`` /+ ``X-RateLimit-Remaining: 0``, or 403 with a body marker (no headers)."""+ if response.status_code == 429:+ return True+ if response.status_code != 403:+ return False+ if response.headers.get("Retry-After"):+ return True+ if response.headers.get("X-RateLimit-Remaining") == "0":+ return True+ # Some 403s carry the secondary-limit signal only in the body.+ body = (response.text or "").lower()+ return "secondary rate limit" in body or "abuse detection" in body++ @staticmethod+ def _parse_retry_after_seconds(response: requests.Response) -> float | None:+ header = response.headers.get("Retry-After")+ if header:+ try:+ return max(0.0, float(header))+ except ValueError:+ return None+ reset = response.headers.get("X-RateLimit-Reset")+ if reset:+ try:+ return max(0.0, float(reset) - time.time())+ except ValueError:+ return None+ return None++ def _gh_api_get(self, path: str, *, endpoint: str, timeout: int = 10) -> dict:+ """Authenticated GET against ``https://api.github.com`` returning parsed JSON."""+ # 1. Validate path + assemble URL.+ if not path.startswith("/"):+ raise ValueError(f"_gh_api_get path must start with '/', got {path!r}")+ url = f"https://api.github.com{path}"+ transient_status_codes = {502, 503, 504}+ # 2. Proactively refresh expiring tokens (failure here is non-fatal — fetch will retry on 401).+ try:+ if self.access_token_expired():+ self.refresh_access_token()+ except Exception:+ logger.warning("GitHubIntegration: token refresh pre-check failed", exc_info=True)++ def fetch() -> requests.Response:+ return self._github_api_get(+ url,+ endpoint=endpoint,+ headers={+ "Accept": "application/vnd.github+json",+ "Authorization": f"Bearer {self.get_access_token()}",+ "X-GitHub-Api-Version": "2022-11-28",+ },+ timeout=timeout,+ )++ # 3. Try up to twice — second attempt covers token refresh after 401 or one transient 5xx.+ last_error_message = "GitHubIntegration: _gh_api_get exhausted retries"+ for attempt in range(2):+ # Network call (one retry on connection-level failure).+ try:+ response = fetch()+ except requests.RequestException as exc:+ if attempt == 0:+ logger.info(+ "GitHubIntegration: _gh_api_get retrying network error",+ path=path,+ exc_info=True,+ )+ continue+ raise GitHubIntegrationError(f"GitHubIntegration: _gh_api_get network error on {path}") from exc+ # Auth failure → refresh token and retry once.+ if response.status_code == 401 and attempt == 0:+ try:+ self.refresh_access_token()+ except Exception as exc:+ raise GitHubIntegrationError(+ f"GitHubIntegration: token refresh after 401 failed on {path}"+ ) from exc+ continue+ # Secondary rate limit → bubble up with retry hint (no in-method retry).+ if self._is_secondary_rate_limit(response):+ # When headers don't give us a delay (body-only signal), GitHub recommends ≥60s.+ retry_after = self._parse_retry_after_seconds(response) or 60.0+ raise GitHubIntegrationError(+ f"GitHubIntegration: secondary rate limit on {path}",+ status_code=response.status_code,+ is_rate_limit=True,+ retry_after_seconds=retry_after,+ )+ # Transient 5xx → retry once.+ if response.status_code in transient_status_codes and attempt == 0:+ logger.info(+ "GitHubIntegration: _gh_api_get retrying transient error",+ path=path,+ status_code=response.status_code,+ )+ continue+ # Any remaining non-2xx is terminal.+ if response.status_code < 200 or response.status_code >= 300:+ logger.warning(+ "GitHubIntegration: _gh_api_get non-2xx response",+ path=path,+ status_code=response.status_code,+ )+ raise GitHubIntegrationError(+ f"GitHubIntegration: _gh_api_get failed on {path}",+ status_code=response.status_code,+ )+ # 4. Parse + shape-check the response body.+ try:+ body = response.json()+ except Exception as exc:+ raise GitHubIntegrationError(+ f"GitHubIntegration: _gh_api_get non-JSON response on {path}",+ status_code=response.status_code,+ ) from exc+ if not isinstance(body, dict):+ raise GitHubIntegrationError(+ f"GitHubIntegration: _gh_api_get unexpected payload on {path}",+ status_code=response.status_code,+ )+ return body+ raise GitHubIntegrationError(last_error_message)++ @database_sync_to_async_pool+ def list_all_cached_repositories_async(self, max_repos: int | None = None) -> list[dict]:+ return self.list_all_cached_repositories(max_repos=max_repos)diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 991dd66c2830..41a5e3d7d161 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -2453,163 +2453,18 @@ class GitHubIntegration(GitHubIntegrationBase):oauth_refresh_counter.labels(self.integration.kind, "failed").inc()self.integration.save()- def get_access_token(self) -> str:- """Return a valid installation access token, refreshing it if expired."""- if self.access_token_expired():- self.refresh_access_token()- token = self.integration.sensitive_config.get("access_token")- if not token:- raise GitHubIntegrationError("Access token unavailable after refresh")- return token-def _on_token_refreshed(self) -> None:logger.info(f"Refreshed access token for {self}")self.integration.errors = ""reload_integrations_on_workers(self.integration.team_id, [self.integration.id])oauth_refresh_counter.labels(self.integration.kind, "success").inc()- @staticmethod- def _is_secondary_rate_limit(response: requests.Response) -> bool:- """GitHub signals secondary rate limits via 429, or 403 + ``Retry-After`` /- ``X-RateLimit-Remaining: 0``, or 403 with a body marker (no headers)."""- if response.status_code == 429:- return True- if response.status_code != 403:- return False- if response.headers.get("Retry-After"):- return True- if response.headers.get("X-RateLimit-Remaining") == "0":- return True- # Some 403s carry the secondary-limit signal only in the body.- body = (response.text or "").lower()- return "secondary rate limit" in body or "abuse detection" in body-- @staticmethod- def _parse_retry_after_seconds(response: requests.Response) -> float | None:- header = response.headers.get("Retry-After")- if header:- try:- return max(0.0, float(header))- except ValueError:- return None- reset = response.headers.get("X-RateLimit-Reset")- if reset:- try:- return max(0.0, float(reset) - time.time())- except ValueError:- return None- return None-- def _gh_api_get(self, path: str, *, endpoint: str, timeout: int = 10) -> dict:- """Authenticated GET against ``https://api.github.com`` returning parsed JSON.-- ``endpoint`` is the low-cardinality template label (e.g. ``/repos/{owner}/{repo}``)- forwarded to ``_github_api_get`` for prometheus instrumentation.- """- # 1. Validate path + assemble URL.- if not path.startswith("/"):- raise ValueError(f"_gh_api_get path must start with '/', got {path!r}")- url = f"https://api.github.com{path}"- transient_status_codes = {502, 503, 504}- # 2. Proactively refresh expiring tokens (failure here is non-fatal — fetch will retry on 401).- try:- if self.access_token_expired():- self.refresh_access_token()- except Exception:- logger.warning("GitHubIntegration: token refresh pre-check failed", exc_info=True)-- def fetch() -> requests.Response:- access_token = self.integration.sensitive_config.get("access_token")- return self._github_api_get(- url,- endpoint=endpoint,- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": "2022-11-28",- },- timeout=timeout,- )-- # 3. Try up to twice — second attempt covers token refresh after 401 or one transient 5xx.- last_error_message = "GitHubIntegration: _gh_api_get exhausted retries"- for attempt in range(2):- # Network call (one retry on connection-level failure).- try:- response = fetch()- except requests.RequestException as exc:- if attempt == 0:- logger.info(- "GitHubIntegration: _gh_api_get retrying network error",- path=path,- exc_info=True,- )- continue- raise GitHubIntegrationError(f"GitHubIntegration: _gh_api_get network error on {path}") from exc- # Auth failure → refresh token and retry once.- if response.status_code == 401 and attempt == 0:- try:- self.refresh_access_token()- except Exception as exc:- raise GitHubIntegrationError(- f"GitHubIntegration: token refresh after 401 failed on {path}"- ) from exc- continue- # Secondary rate limit → bubble up with retry hint (no in-method retry).- if self._is_secondary_rate_limit(response):- # When headers don't give us a delay (body-only signal), GitHub recommends ≥60s.- retry_after = self._parse_retry_after_seconds(response) or 60.0- raise GitHubIntegrationError(- f"GitHubIntegration: secondary rate limit on {path}",- status_code=response.status_code,- is_rate_limit=True,- retry_after_seconds=retry_after,- )- # Transient 5xx → retry once.- if response.status_code in transient_status_codes and attempt == 0:- logger.info(- "GitHubIntegration: _gh_api_get retrying transient error",- path=path,- status_code=response.status_code,- )- continue- # Any remaining non-2xx is terminal.- if response.status_code < 200 or response.status_code >= 300:- logger.warning(- "GitHubIntegration: _gh_api_get non-2xx response",- path=path,- status_code=response.status_code,- )- raise GitHubIntegrationError(- f"GitHubIntegration: _gh_api_get failed on {path}",- status_code=response.status_code,- )- # 4. Parse + shape-check the response body.- try:- body = response.json()- except Exception as exc:- raise GitHubIntegrationError(- f"GitHubIntegration: _gh_api_get non-JSON response on {path}",- status_code=response.status_code,- ) from exc- if not isinstance(body, dict):- raise GitHubIntegrationError(- f"GitHubIntegration: _gh_api_get unexpected payload on {path}",- status_code=response.status_code,- )- return body- raise GitHubIntegrationError(last_error_message)-@database_sync_to_asyncdef list_cached_repositories_async(self, *, search: str = "", limit: int = 100, offset: int = 0) -> tuple[list[dict], bool]:return self.list_cached_repositories(search=search, limit=limit, offset=offset)- @database_sync_to_async- def list_all_cached_repositories_async(self, max_repos: int | None = None) -> list[dict]:- return self.list_all_cached_repositories(max_repos=max_repos)-def create_issue(self, config: dict[str, str]):title: str = config.pop("title")body: str = config.pop("body")diff --git a/posthog/models/integration_repository_cache.py b/posthog/models/integration_repository_cache.pyindex 8871c8042c14..f4b2c4b5d83d 100644--- a/posthog/models/integration_repository_cache.py+++ b/posthog/models/integration_repository_cache.py@@ -21,6 +21,7 @@ from typing import TYPE_CHECKINGfrom urllib.parse import quotefrom django.db import models+from django.db.models import Qfrom django.utils import timezoneimport structlog@@ -28,7 +29,9 @@ import temporalio.activityfrom posthog import redis as posthog_redisfrom posthog.helpers.async_concurrency import run_parallel_with_backoff+from posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import GitHubIntegration, GitHubIntegrationError, Integration+from posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.models.utils import UUIDModelfrom posthog.sync import database_sync_to_async@@ -73,8 +76,12 @@ class SyncFullCacheTimeoutError(Exception):class IntegrationRepositoryCacheEntry(UUIDModel):- integration = models.ForeignKey(Integration, on_delete=models.CASCADE, related_name="repository_cache_entries")- # Denormalized from Integration so HogQL's team_id guard can filter this table directly.+ integration = models.ForeignKey(+ Integration, on_delete=models.CASCADE, related_name="repository_cache_entries", null=True, blank=True+ )+ user_integration = models.ForeignKey(+ UserIntegration, on_delete=models.CASCADE, related_name="repository_cache_entries", null=True, blank=True+ )team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)full_name = models.TextField() # Duplicate field, required for indexingdescription = models.TextField(null=True, blank=True)@@ -95,8 +102,29 @@ class IntegrationRepositoryCacheEntry(UUIDModel):class Meta:app_label = "posthog"- unique_together = [("integration", "full_name")]- # `unique_together` already creates a btree index on (integration, full_name) — no need to duplicate it.+ constraints = [+ # Integration is team-bound by FK, so (integration, full_name) implicitly per-team.+ models.UniqueConstraint(+ fields=["integration", "full_name"],+ condition=models.Q(integration__isnull=False),+ name="integration_full_name_unique",+ ),+ # A UserIntegration spans every team its owner has access to, so the team has to be+ # part of the uniqueness to not hydrate the same repo for two teams on a single row.+ models.UniqueConstraint(+ fields=["user_integration", "team", "full_name"],+ condition=models.Q(user_integration__isnull=False),+ name="user_integration_team_full_name_unique",+ ),+ # Exactly one of `integration` or `user_integration` is set per row+ models.CheckConstraint(+ condition=(+ models.Q(integration__isnull=False, user_integration__isnull=True)+ | models.Q(integration__isnull=True, user_integration__isnull=False)+ ),+ name="integration_xor_user_integration",+ ),+ ]indexes = [models.Index(fields=["team", "updated_at"]),]@@ -105,11 +133,23 @@ class IntegrationRepositoryCacheEntry(UUIDModel):class GitHubRepositoryFullCache:"""Owns the heavy per-repo cache (README + tree + metadata) for a GitHub integration."""- def __init__(self, github: GitHubIntegration) -> None:+ def __init__(self, github: GitHubIntegrationBase, *, team_id: int | None = None) -> None:self.github = github+ if isinstance(github, GitHubIntegration):+ # Team-level integration is bound to one team+ if team_id is not None and team_id != github.integration.team_id:+ raise ValueError(+ f"team_id={team_id} does not match team-level integration's team_id={github.integration.team_id}"+ )+ self.team_id = github.integration.team_id+ elif team_id is not None:+ self.team_id = team_id+ else:+ # UserGitHubIntegration is not bound to a team, so the team should be provided+ raise ValueError("team_id is required for non-team GitHub integrations")@property- def integration(self) -> Integration:+ def integration(self) -> Integration | UserIntegration:return self.github.integration@staticmethod@@ -122,7 +162,9 @@ class GitHubRepositoryFullCache:# never read them, and bulk sync would otherwise drag MBs of `tree_paths` per repo through# Postgres just to decide the cache is still good.return (- self.integration.repository_cache_entries.filter(full_name=full_name).defer("readme", "tree_paths").first()+ self.integration.repository_cache_entries.filter(team_id=self.team_id, full_name=full_name)+ .defer("readme", "tree_paths")+ .first())def _fetch_repo_meta(self, owner: str, repo: str, full_name: str) -> tuple[dict, str, str]:@@ -202,23 +244,33 @@ class GitHubRepositoryFullCache:tree_paths: str,tree_truncated: bool,) -> IntegrationRepositoryCacheEntry:- entry, _ = IntegrationRepositoryCacheEntry.objects.update_or_create(- integration=self.integration,- full_name=full_name,- defaults={- "team_id": self.integration.team_id,- "description": repo_data.get("description"),- "topics": repo_data.get("topics") or [],- "archived": bool(repo_data.get("archived", False)),- "fork": bool(repo_data.get("fork", False)),- "primary_language": repo_data.get("language"),- "default_branch": default_branch,- "default_branch_sha": default_branch_sha,- "readme": readme_text,- "tree_paths": tree_paths,- "tree_truncated": tree_truncated,- },- )+ defaults = {+ "team_id": self.team_id,+ "description": repo_data.get("description"),+ "topics": repo_data.get("topics") or [],+ "archived": bool(repo_data.get("archived", False)),+ "fork": bool(repo_data.get("fork", False)),+ "primary_language": repo_data.get("language"),+ "default_branch": default_branch,+ "default_branch_sha": default_branch_sha,+ "readme": readme_text,+ "tree_paths": tree_paths,+ "tree_truncated": tree_truncated,+ }+ # UserIntegration spans teams — include team_id so one team's hydrate can't overwrite another's row.+ if isinstance(self.github, UserGitHubIntegration):+ entry, _ = IntegrationRepositoryCacheEntry.objects.update_or_create(+ full_name=full_name,+ user_integration=self.integration,+ team_id=self.team_id,+ defaults=defaults,+ )+ else:+ entry, _ = IntegrationRepositoryCacheEntry.objects.update_or_create(+ full_name=full_name,+ integration=self.integration,+ defaults=defaults,+ )return entryasync def sync_full_cache_entry_async(@@ -271,7 +323,14 @@ class GitHubRepositoryFullCache:@database_sync_to_asyncdef _evict_orphans(self, valid_full_names: set[str]) -> int:- deleted, _ = self.integration.repository_cache_entries.exclude(full_name__in=valid_full_names).delete()+ # Drop every row for this team that isn't one we just hydrated — covers own-source orphans and leftovers+ keep = (+ Q(integration_id=self.integration.id, full_name__in=valid_full_names)+ if isinstance(self.github, GitHubIntegration)+ else Q(user_integration_id=self.integration.id, full_name__in=valid_full_names)+ )+ qs = IntegrationRepositoryCacheEntry.objects.filter(team_id=self.team_id).exclude(keep)+ deleted, _ = qs.delete()return deletedasync def sync_full_cache(self, *, concurrency: int = 10) -> list[IntegrationRepositoryCacheEntry | BaseException]:diff --git a/posthog/models/test/test_integration_repository_cache.py b/posthog/models/test/test_integration_repository_cache.pyindex 52aad4312764..a0d4c2345f8e 100644--- a/posthog/models/test/test_integration_repository_cache.py+++ b/posthog/models/test/test_integration_repository_cache.py@@ -19,6 +19,9 @@ from posthog.models.integration_repository_cache import (IntegrationRepositoryCacheEntry,SyncFullCacheTimeoutError,)+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.models.user_integration import UserIntegrationclass TestGitHubRepositoryFullCache(BaseTest):@@ -467,6 +470,82 @@ class TestGitHubRepositoryFullCache(BaseTest):assert IntegrationRepositoryCacheEntry.objects.filter(pk=keep.pk).exists()+ def test_sync_full_cache_evicts_cross_source_rows_for_team(self):+ # Team upgrade scenario: PostHog Code (UserIntegration) hydrated rows for this team, then+ # the team connected a team-level Integration. Cascade now picks the Integration; the old+ # UserIntegration row would otherwise linger and surface as a duplicate to HogQL queries.+ user = User.objects.create(email="[email protected]")+ user_integration = UserIntegration.objects.create(+ user=user,+ kind=UserIntegration.IntegrationKind.GITHUB,+ integration_id="UI-1",+ config={"installation_id": "UI-1"},+ sensitive_config={},+ )+ stale = IntegrationRepositoryCacheEntry.objects.create(+ user_integration=user_integration,+ team=self.team,+ full_name="posthog/posthog",+ default_branch="main",+ default_branch_sha="SHA_OLD",+ readme="from-user-integration",+ )++ integration = self._create_integration()++ async def fake_entry_async(full_name, *, path_log=None):+ 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),+ ):+ async_to_sync(repo_cache.sync_full_cache)()++ assert not IntegrationRepositoryCacheEntry.objects.filter(pk=stale.pk).exists()++ def test_sync_full_cache_does_not_evict_other_teams_rows(self):+ # A UserIntegration spans every team its owner belongs to. When team A syncs via Integration,+ # team B's UserIntegration-owned rows must survive.+ other_team = Team.objects.create(organization=self.organization, name="other-team")+ user = User.objects.create(email="[email protected]")+ user_integration = UserIntegration.objects.create(+ user=user,+ kind=UserIntegration.IntegrationKind.GITHUB,+ integration_id="UI-1",+ config={"installation_id": "UI-1"},+ sensitive_config={},+ )+ other_team_row = IntegrationRepositoryCacheEntry.objects.create(+ user_integration=user_integration,+ team=other_team,+ full_name="posthog/posthog",+ default_branch="main",+ default_branch_sha="SHA_OTHER",+ readme="other-team",+ )++ integration = self._create_integration()++ async def fake_entry_async(full_name, *, path_log=None):+ 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),+ ):+ async_to_sync(repo_cache.sync_full_cache)()++ assert IntegrationRepositoryCacheEntry.objects.filter(pk=other_team_row.pk).exists()+class TestSyncFullCacheLock(BaseTest):"""Cover the single-flight Redis lock around `sync_full_cache`."""diff --git a/products/signals/backend/report_generation/select_repo.py b/products/signals/backend/report_generation/select_repo.pyindex 0eff75416a38..4608cb2f0a0f 100644--- a/products/signals/backend/report_generation/select_repo.py+++ b/products/signals/backend/report_generation/select_repo.py@@ -6,8 +6,11 @@ from typing import TYPE_CHECKINGfrom pydantic import BaseModel, Field+from posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import GitHubIntegration, Integration-from posthog.models.integration_repository_cache import GitHubRepositoryFullCache, IntegrationRepositoryCacheEntry+from posthog.models.integration_repository_cache import GitHubRepositoryFullCache+from posthog.models.team.team import Team+from posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.sync import database_sync_to_asyncfrom products.signals.backend.temporal.types import SignalData, render_signals_to_text@@ -40,36 +43,57 @@ class RepoSelectionResult(BaseModel):)-def _list_candidate_repos(team_id: int) -> list[str]:- """Fetch all repositories accessible via the team's GitHub integrations."""- integrations = Integration.objects.filter(team_id=team_id, kind="github")- repos: set[str] = set()- for integration in integrations:- github = GitHubIntegration(integration)- repo_entries = github.list_all_cached_repositories(max_repos=_MAX_GITHUB_REPOS)- for repo in repo_entries:- full_name = repo.get("full_name")- if full_name:- repos.add(full_name.lower())- if len(repos) >= _MAX_GITHUB_REPOS:- logger.warning("repo_list_capped team_id=%s cap=%s", team_id, _MAX_GITHUB_REPOS)- return sorted(repos)- return sorted(repos)+def resolve_team_github_integration(team_id: int, team: Team | None = None) -> GitHubIntegrationBase | None:+ """Resolve the GitHub source the agent should use for this team."""+ integration = (+ Integration.objects.filter(team_id=team_id, kind="github")+ # Prioritize orgs vs users (alphabetically)+ .order_by("config__account__type", "id")+ .first()+ )+ # Prefer the first GitHub integration from the team+ if integration is not None:+ return GitHubIntegration(integration)+ if team is None:+ team = Team.objects.get(id=team_id)+ user_integration = (+ UserIntegration.objects.filter(+ kind=UserIntegration.IntegrationKind.GITHUB,+ user__in=team.all_users_with_access(),+ )+ .order_by("config__account__type", "id")+ .first()+ )+ # If no team integration - pick the integration of the first user+ if user_integration is not None:+ return UserGitHubIntegration(user_integration)+ return None-def _get_team_github_integration(team_id: int) -> Integration | None:- """Return the team's GitHub integration. Single-integration-per-team assumption."""- return Integration.objects.filter(team_id=team_id, kind="github").first()+def _list_candidate_repos(github: GitHubIntegrationBase, team_id: int) -> list[str]:+ """Fetch all repositories accessible via the resolved GitHub source."""+ repos: set[str] = set()+ for repo in github.list_all_cached_repositories(max_repos=_MAX_GITHUB_REPOS):+ full_name = repo.get("full_name")+ if not full_name:+ continue+ repos.add(full_name.lower())+ if len(repos) >= _MAX_GITHUB_REPOS:+ logger.warning(+ "repo_list_capped cap=%s team_id=%s integration_id=%s",+ _MAX_GITHUB_REPOS,+ team_id,+ github.integration.id,+ )+ return sorted(repos)+ return sorted(repos)-def _list_eligible_full_names(integration_id: int) -> set[str]:+def _list_eligible_full_names(github: GitHubIntegrationBase, team_id: int) -> set[str]:"""Repos the agent can reason about: present in the heavy cache and not archived.Anything else is dropped from the candidate list (no SQL evidence, or unfixable code)."""- return set(- IntegrationRepositoryCacheEntry.objects.filter(integration_id=integration_id, archived=False).values_list(- "full_name", flat=True- )- )+ qs = github.integration.repository_cache_entries.filter(team_id=team_id, archived=False)+ return set(qs.values_list("full_name", flat=True))def _build_repo_selection_prompt(signals: list[SignalData], candidate_repos: list[str]) -> str:@@ -244,7 +268,13 @@ async def select_repository_for_report(output_fn: OutputFn = None,) -> RepoSelectionResult:"""Select the most relevant repository for a set of signals."""- candidate_repos = await database_sync_to_async(_list_candidate_repos, thread_sensitive=False)(team_id)+ github = await database_sync_to_async(resolve_team_github_integration, thread_sensitive=False)(team_id)+ if github is None:+ return RepoSelectionResult(+ repository=None,+ reason="No GitHub repositories connected to this team.",+ )+ candidate_repos = await database_sync_to_async(_list_candidate_repos, thread_sensitive=False)(github, team_id)if len(candidate_repos) == 0:return RepoSelectionResult(repository=None,@@ -258,29 +288,27 @@ async def select_repository_for_report(# Hydrate the heavy cache before running the agent. Single-flighted per integration —# concurrent reports for the same team wait on the leader and then read the warm cache.- integration = await database_sync_to_async(_get_team_github_integration, thread_sensitive=False)(team_id)- if integration is not None:- if output_fn:- output_fn("Refreshing repository cache...")- repo_cache = GitHubRepositoryFullCache(GitHubIntegration(integration))- 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 false-negative).- eligible = await database_sync_to_async(_list_eligible_full_names, thread_sensitive=False)(integration.id)- dropped = [r for r in candidate_repos if r not in eligible]- if dropped:- logger.info("repo_selection.dropped_candidates", extra={"dropped": dropped, "team_id": team_id})- candidate_repos = [r for r in candidate_repos if r in eligible]- if len(candidate_repos) == 0:- return RepoSelectionResult(- repository=None,- reason="No connected GitHub repositories are eligible (archived or missing cache data).",- )- if len(candidate_repos) == 1:- return RepoSelectionResult(- repository=candidate_repos[0],- reason=f"Single eligible repository: {candidate_repos[0]}",- )+ if output_fn:+ output_fn("Refreshing repository cache...")+ repo_cache = GitHubRepositoryFullCache(github, team_id=team_id)+ 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 false-negative).+ eligible = await database_sync_to_async(_list_eligible_full_names, thread_sensitive=False)(github, team_id)+ dropped = [r for r in candidate_repos if r not in eligible]+ if dropped:+ logger.info("repo_selection.dropped_candidates", extra={"dropped": dropped, "team_id": team_id})+ candidate_repos = [r for r in candidate_repos if r in eligible]+ if len(candidate_repos) == 0:+ return RepoSelectionResult(+ repository=None,+ reason="No connected GitHub repositories are eligible (archived or missing cache data).",+ )+ if len(candidate_repos) == 1:+ return RepoSelectionResult(+ repository=candidate_repos[0],+ reason=f"Single eligible repository: {candidate_repos[0]}",+ )if output_fn:output_fn(f"Selecting repository from {len(candidate_repos)} candidates...")diff --git a/products/signals/backend/temporal/agentic/__init__.py b/products/signals/backend/temporal/agentic/__init__.pyindex 3c4be8572647..1129d34e2cbe 100644--- a/products/signals/backend/temporal/agentic/__init__.py+++ b/products/signals/backend/temporal/agentic/__init__.py@@ -1,9 +1,11 @@import structlog-from posthog.models.integration import Integration+from posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Team+from posthog.models.user_integration import UserGitHubIntegration+from products.signals.backend.report_generation.select_repo import resolve_team_github_integrationfrom products.tasks.backend.models import SandboxEnvironmentlogger = structlog.get_logger(__name__)@@ -41,25 +43,34 @@ def get_or_create_signals_sandbox_env(return str(env.id)-def resolve_user_id_for_team(team_id: int) -> int:- """Resolve the best user ID for automated sandbox actions on behalf of a team."""+def resolve_user_id_for_team(team_id: int, github: GitHubIntegrationBase | None = None) -> int:+ """Resolve the best user ID for automated sandbox actions on behalf of a team.++ Pass `github` if the caller already resolved it to skip a duplicate query.+ """team = Team.objects.select_related("organization").get(id=team_id)- github_integration = Integration.objects.filter(team=team, kind="github").first()- # Prefer the user who set up the GitHub integration- if github_integration and github_integration.created_by_id:+ if github is None:+ github = resolve_team_github_integration(team_id, team=team)+ if github is None:+ raise RuntimeError(f"No GitHub integration for team {team_id}; caller must short-circuit before calling this")+ # Pick the user who created the integration+ if isinstance(github, UserGitHubIntegration):+ return github.integration.user_id+ # If team-level Integration, prefer its creator (if still active in the org)+ if github.integration.created_by_id:is_active = OrganizationMembership.objects.filter(organization=team.organization,- user_id=github_integration.created_by_id,+ user_id=github.integration.created_by_id,user__is_active=True,).exists()if is_active:- return github_integration.created_by_id+ return github.integration.created_by_idlogger.warning(- "github integration creator is no longer an active org member, falling back to first active member",+ "github integration creator is no longer an active org member, falling back",team_id=team_id,- integration_created_by=github_integration.created_by_id,+ integration_created_by=github.integration.created_by_id,)- # Fallback: first active org member+ # Integration exists but its creator is gone — pick any active org member as a stand-in.membership = (OrganizationMembership.objects.select_related("user").filter(organization=team.organization, user__is_active=True)diff --git a/products/signals/backend/temporal/agentic/select_repository.py b/products/signals/backend/temporal/agentic/select_repository.pyindex a506789e239a..314b0b6ca82a 100644--- a/products/signals/backend/temporal/agentic/select_repository.py+++ b/products/signals/backend/temporal/agentic/select_repository.py@@ -6,13 +6,17 @@ import posthoganalyticsfrom posthog.event_usage import groupsfrom posthog.models import Organization-from posthog.models.integration import GitHubIntegrationError, Integration+from posthog.models.integration import GitHubIntegrationErrorfrom posthog.models.team.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeaterfrom products.signals.backend.models import SignalReportArtefact-from products.signals.backend.report_generation.select_repo import RepoSelectionResult, select_repository_for_report+from products.signals.backend.report_generation.select_repo import (+ RepoSelectionResult,+ resolve_team_github_integration,+ select_repository_for_report,+)from products.signals.backend.temporal.agentic import (SIGNALS_REPO_DISCOVERY_ENV_NAME,get_or_create_signals_sandbox_env,@@ -41,16 +45,12 @@ class SelectRepositoryInput:signals: list[SignalData]-def _resolve_team_repo_context(team_id: int) -> int:- """Resolve user context for repository selection, validating GitHub integration exists."""- team = Team.objects.get(id=team_id)- github_integration = Integration.objects.filter(team=team, kind="github").first()- if not github_integration:- raise RuntimeError(- f"No GitHub integration found for team {team_id}. "- "Signals agentic report generation requires a connected GitHub integration."- )- return resolve_user_id_for_team(team_id)+def _resolve_sandbox_user_id(team_id: int) -> int | None:+ """Select a user to assign sandbox to."""+ github = resolve_team_github_integration(team_id)+ if github is None:+ return None+ return resolve_user_id_for_team(team_id, github=github)def _capture_repo_research_event(@@ -128,7 +128,25 @@ async def select_repository_activity(input: SelectRepositoryInput) -> RepoSelect)return previous- user_id = await database_sync_to_async(_resolve_team_repo_context, thread_sensitive=False)(input.team_id)+ user_id = await database_sync_to_async(_resolve_sandbox_user_id, thread_sensitive=False)(input.team_id)+ if user_id is None:+ logger.info(+ "signals repo selection skipped: No GitHub integration connected to a team/user",+ report_id=input.report_id,+ team_id=input.team_id,+ )+ no_repo_result = RepoSelectionResult(+ repository=None,+ reason="No GitHub integration connected to a team/user.",+ )+ _capture_repo_research_event(+ "signals_repo_research_completed",+ team,+ team.organization,+ input.report_id,+ result="no_repo",+ )+ return no_repo_resultsandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(input.team_id,SIGNALS_REPO_DISCOVERY_ENV_NAME,@@ -156,14 +174,13 @@ async def select_repository_activity(input: SelectRepositoryInput) -> RepoSelect)return resultexcept Exception as e:- failure_reason = "no_github_integration" if isinstance(e, RuntimeError) else "agentic_activity_error"_capture_repo_research_event("signals_repo_research_completed",team,team.organization,input.report_id,result="failed",- failure_reason=failure_reason,+ failure_reason="agentic_activity_error",)# Permanent GitHub App auth failures (installation gone/suspended) won't recover via retry.if isinstance(e, GitHubIntegrationError) and e.status_code in {401, 403, 404, 410}:diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.pyindex 6e0a765b2fd2..10267500515d 100644--- a/products/signals/backend/test/test_agentic_report_activity.py+++ b/products/signals/backend/test/test_agentic_report_activity.py@@ -8,7 +8,9 @@ from unittest.mock import patchimport pytest_asynciofrom asgiref.sync import sync_to_async-from posthog.models import Organization, Team+from posthog.models import Organization, Team, User+from posthog.models.organization import OrganizationMembership+from posthog.models.user_integration import UserIntegrationfrom posthog.sync import database_sync_to_asyncfrom products.signals.backend.models import SignalReport, SignalReportArtefact@@ -115,7 +117,7 @@ async def test_select_repository_activity_returns_repo(monkeypatch, ateam):lambda report_id: None,)monkeypatch.setattr(- "products.signals.backend.temporal.agentic.select_repository._resolve_team_repo_context",+ "products.signals.backend.temporal.agentic.select_repository._resolve_sandbox_user_id",lambda team_id: 1,)@@ -175,7 +177,7 @@ async def test_select_repository_activity_no_repo(monkeypatch, ateam):lambda report_id: None,)monkeypatch.setattr(- "products.signals.backend.temporal.agentic.select_repository._resolve_team_repo_context",+ "products.signals.backend.temporal.agentic.select_repository._resolve_sandbox_user_id",lambda team_id: 1,)@@ -196,6 +198,47 @@ async def test_select_repository_activity_no_repo(monkeypatch, ateam):assert "No GitHub repositories" in result.reason+async def test_select_repository_activity_does_not_raise_with_only_user_integration(monkeypatch, ateam):+ # PostHog Code installs land in `UserIntegration`, never on `Integration`. Before the cascade+ # was wired up, this combination raised `RuntimeError("No GitHub integration found ...")` and+ # killed the activity. Now it must resolve a user_id and reach `select_repository_for_report`.+ user = await sync_to_async(User.objects.create)(email=f"posthog-code-{random.randint(1, 99999)}@example.com")+ await sync_to_async(OrganizationMembership.objects.create)(user=user, organization_id=ateam.organization_id)+ await sync_to_async(UserIntegration.objects.create)(+ user=user,+ kind=UserIntegration.IntegrationKind.GITHUB,+ integration_id="999",+ config={"installation_id": "999"},+ sensitive_config={},+ )++ monkeypatch.setattr(+ "products.signals.backend.temporal.agentic.select_repository._load_previous_repo_selection",+ lambda report_id: None,+ )++ captured_user_id: list[int | None] = []++ async def fake_select_repo(*args, **kwargs):+ captured_user_id.append(kwargs.get("user_id"))+ return RepoSelectionResult(repository="posthog/posthog", reason="Single repository connected: posthog/posthog")++ monkeypatch.setattr(+ "products.signals.backend.temporal.agentic.select_repository.select_repository_for_report",+ fake_select_repo,+ )++ with patch("products.signals.backend.temporal.agentic.select_repository.Heartbeater"):+ result = await select_repository_activity(+ SelectRepositoryInput(team_id=ateam.id, report_id="test-report-id", signals=_build_signals())+ )++ assert result.repository == "posthog/posthog"+ assert captured_user_id == [user.id], "user_id should come from the UserIntegration owner"++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_run_agentic_report_activity_persists_artefacts(monkeypatch, ateam):diff --git a/products/signals/backend/test/test_resolve_team_github_integration.py b/products/signals/backend/test/test_resolve_team_github_integration.pynew file mode 100644index 000000000000..708c515927ea--- /dev/null+++ b/products/signals/backend/test/test_resolve_team_github_integration.py@@ -0,0 +1,96 @@+import pytest++from posthog.models import Organization, Team, User+from posthog.models.integration import GitHubIntegration, Integration+from posthog.models.organization import OrganizationMembership+from posthog.models.user_integration import UserGitHubIntegration, UserIntegration++from products.signals.backend.report_generation.select_repo import resolve_team_github_integration+++def organization():+ org = Organization.objects.create(name="test-cascade-org")+ yield org+ org.delete()+++def team(organization):+ return Team.objects.create(organization=organization, name="test-cascade-team")+++def _create_user(email: str, organization: Organization, *, is_active: bool = True) -> User:+ user = User.objects.create(email=email, is_active=is_active)+ OrganizationMembership.objects.create(user=user, organization=organization)+ return user+++def _create_team_integration(team: Team, *, integration_id: str = "team-1") -> Integration:+ return Integration.objects.create(+ team=team,+ kind="github",+ integration_id=integration_id,+ config={"installation_id": integration_id},+ sensitive_config={},+ )+++def _create_user_integration(user: User, *, integration_id: str = "user-1") -> UserIntegration:+ return UserIntegration.objects.create(+ user=user,+ kind=UserIntegration.IntegrationKind.GITHUB,+ integration_id=integration_id,+ config={"installation_id": integration_id},+ sensitive_config={},+ )+++def test_returns_none_when_team_has_no_github_anywhere(team):+ assert resolve_team_github_integration(team.id) is None+++def test_prefers_team_integration_over_user_integration(organization, team):+ user = _create_user("[email protected]", organization)+ _create_user_integration(user, integration_id="user-1")+ team_int = _create_team_integration(team, integration_id="team-1")++ resolved = resolve_team_github_integration(team.id)++ assert isinstance(resolved, GitHubIntegration)+ assert resolved.integration.id == team_int.id+++def test_falls_back_to_user_integration_when_no_team_integration(organization, team):+ user = _create_user("[email protected]", organization)+ user_int = _create_user_integration(user, integration_id="user-1")++ resolved = resolve_team_github_integration(team.id)++ assert isinstance(resolved, UserGitHubIntegration)+ assert resolved.integration.id == user_int.id+++def test_picks_first_user_integration_by_id(organization, team):+ first_user = _create_user("[email protected]", organization)+ second_user = _create_user("[email protected]", organization)+ first_user_int = _create_user_integration(first_user, integration_id="first")+ _create_user_integration(second_user, integration_id="second")++ resolved = resolve_team_github_integration(team.id)++ assert isinstance(resolved, UserGitHubIntegration)+ assert resolved.integration.id == first_user_int.id+++def test_skips_user_integration_when_owner_has_no_team_access(organization, team):+ # Owner with no organization membership = no team access via `team.all_users_with_access()`.+ outsider = User.objects.create(email="[email protected]")+ _create_user_integration(outsider, integration_id="outsider-int")++ assert resolve_team_github_integration(team.id) is Nonediff --git a/products/signals/backend/test/test_resolve_user_id.py b/products/signals/backend/test/test_resolve_user_id.pyindex 07e7b4cabd91..015193b4ad2c 100644--- a/products/signals/backend/test/test_resolve_user_id.py+++ b/products/signals/backend/test/test_resolve_user_id.py@@ -3,6 +3,7 @@ import pytestfrom posthog.models import Organization, Team, Userfrom posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembership+from posthog.models.user_integration import UserIntegrationfrom products.signals.backend.temporal.agentic import resolve_user_id_for_team@@ -35,6 +36,16 @@ def _create_github_integration(team: Team, created_by: User | None = None) -> In)+def _create_user_github_integration(user: User, *, integration_id: str = "67890") -> UserIntegration:+ return UserIntegration.objects.create(+ user=user,+ kind=UserIntegration.IntegrationKind.GITHUB,+ integration_id=integration_id,+ config={"installation_id": integration_id},+ sensitive_config={},+ )++@pytest.mark.django_dbdef test_returns_integration_creator_when_active(organization, team):first_user = _create_user("[email protected]", organization)@@ -86,3 +97,37 @@ def test_raises_when_no_active_users(organization, team):with pytest.raises(RuntimeError, match="No active users"):resolve_user_id_for_team(team.id)+++def test_uses_user_integration_owner_when_no_team_integration(organization, team):+ other = _create_user("[email protected]", organization)+ user_integration_owner = _create_user("[email protected]", organization)+ _create_user_github_integration(user_integration_owner)++ result = resolve_user_id_for_team(team.id)++ assert result == user_integration_owner.id+ assert result != other.id+++def test_prefers_team_integration_creator_over_user_integration_owner(organization, team):+ creator = _create_user("[email protected]", organization)+ user_integration_owner = _create_user("[email protected]", organization)+ _create_user_github_integration(user_integration_owner)+ _create_github_integration(team, created_by=creator)++ result = resolve_user_id_for_team(team.id)++ assert result == creator.id+++def test_raises_when_team_has_no_github_source_at_all(organization, team):+ # No Integration, no UserIntegration. Picking an arbitrary org member without GitHub+ # credentials would just paper over the bug; the caller has to short-circuit instead.+ _create_user("[email protected]", organization)++ with pytest.raises(RuntimeError, match="No GitHub integration"):+ resolve_user_id_for_team(team.id)