: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
perf(slack-app): serve cached repo snapshot instead of listing github inline (#117191)
posthog[bot]35f29fdae532
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 6a582cdf1ffb..660b64c2a221 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -207,7 +207,11 @@ UNTAGGED_FOLLOWUP_ACTION_DISMISS = "posthog_code_untagged_followup_dismiss"UNTAGGED_FOLLOWUP_CONTEXT_KIND = "untagged_followup"_MAX_GITHUB_REPOS = 500-REPO_LIST_CACHE_TTL_SECONDS = 300+# The installation webhook marks snapshots stale without saving rows, so it does not clear this key.+# This TTL is the longest time a repo access change can take to reach Slack.+REPO_LIST_CACHE_TTL_SECONDS = 60 * 60+# Mentions do not wait for this refresh, so the interval only sets how often Slack lists GitHub.+REPO_SNAPSHOT_REFRESH_INTERVAL_SECONDS = 6 * 60 * 60PENDING_REPO_PICKER_TTL_SECONDS = PICKER_TOKEN_MAX_AGE_SECONDS@@ -1082,7 +1086,7 @@ def _post_repo_picker_message(try:_get_full_repo_names(integration, user_id=user_id)except Exception:- logger.warning("repo_list_prewarm_failed", user_id=user_id, exc_info=True)+ logger.warning("slack_app_repo_list_prewarm_failed", user_id=user_id, exc_info=True)def _extract_explicit_repo(text: str, all_repos: list[str]) -> str | None:@@ -1104,6 +1108,24 @@ def _extract_explicit_repo_from_thread(thread_messages: list[SlackThreadMessage])+def _schedule_user_repo_cache_refresh(user_integration_id: str) -> None:+ # The task module imports this module, so a module-level import here would be circular.+ from products.slack_app.backend.tasks import refresh_user_github_repository_cache # noqa: PLC0415++ try:+ refresh_user_github_repository_cache.delay(user_integration_id=user_integration_id)+ except Exception:+ # The stale snapshot still answers this mention, and the next mention schedules the refresh again.+ logger.warning("slack_app_github_repo_cache_refresh_dispatch_failed", user_integration_id=user_integration_id)+++def _repo_snapshot_needs_refresh(record: UserIntegration) -> bool:+ updated_at = record.repository_cache_updated_at+ if updated_at is None:+ return True+ return (timezone.now() - updated_at).total_seconds() >= REPO_SNAPSHOT_REFRESH_INTERVAL_SECONDS++def _get_full_repo_names(integration: Integration, *, user_id: int | None) -> list[str]:"""Repo names available to the mentioner, from their personal GitHub install. Cached per user."""if user_id is None:@@ -1125,12 +1147,19 @@ def _get_full_repo_names(integration: Integration, *, user_id: int | None) -> lifor record in user_records:github = UserGitHubIntegration(record, source="slack_app_repo_selection", priority=Priority.NORMAL)- repo_entries = github.list_all_cached_repositories(max_repos=_MAX_GITHUB_REPOS)+ # A live listing of a large install takes seconds while the person waits in Slack, so a+ # snapshot with repos is served as it is and refreshed in the background.+ has_cached_repos = bool(record.repository_cache)+ if has_cached_repos and _repo_snapshot_needs_refresh(record):+ _schedule_user_repo_cache_refresh(str(record.id))+ repo_entries = github.list_all_cached_repositories(+ max_repos=_MAX_GITHUB_REPOS, allow_refresh=not has_cached_repos+ )for repo in repo_entries:all_repos.add(repo["full_name"])if len(all_repos) >= _MAX_GITHUB_REPOS:logger.warning(- "github_repo_list_capped",+ "slack_app_github_repo_list_capped",user_id=user_id,team_id=integration.team_id,cap=_MAX_GITHUB_REPOS,diff --git a/products/slack_app/backend/tasks.py b/products/slack_app/backend/tasks.pyindex 69ee77de8f7e..0993101a4602 100644--- a/products/slack_app/backend/tasks.py+++ b/products/slack_app/backend/tasks.py@@ -4,12 +4,17 @@ from typing import Anyfrom celery import shared_task+from posthog.celery_queues import CeleryQueue+from posthog.egress.limiter.policies import Priorityfrom posthog.models import Userfrom posthog.models.integration import Integrationfrom posthog.models.scoping import with_team_scope+from posthog.models.user_integration import UserGitHubIntegration, UserIntegration+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.temporal.ai.slack_app.types import SlackUnfurlChartRequestfrom products.slack_app.backend.api import (+ REPO_SNAPSHOT_REFRESH_INTERVAL_SECONDS,SLACK_INTEGRATION_KIND,does_other_region_claim_workspace,send_region_proxy_request,@@ -39,6 +44,23 @@ def mirror_slack_message_event(send_region_proxy_request(method="POST", target_url=target_url, headers=headers, body=body.encode("utf-8"))+@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)+# UserIntegration belongs to a user, not a team, so there is no team scope to apply.+@skip_team_scope_audit+def refresh_user_github_repository_cache(*, user_integration_id: str) -> None:+ """Refresh the repo snapshot that a mention served stale.++ The save in `sync_repository_cache` also clears the per-user repo list cache, so the next+ mention reads the new snapshot. Several mentions can schedule this at once; the refresh+ interval makes all but the first one a no-op.+ """+ record = UserIntegration.objects.filter(id=user_integration_id, kind=UserIntegration.IntegrationKind.GITHUB).first()+ if record is None:+ return+ github = UserGitHubIntegration(record, source="slack_app_repo_selection", priority=Priority.NORMAL)+ github.sync_repository_cache(min_refresh_interval_seconds=REPO_SNAPSHOT_REFRESH_INTERVAL_SECONDS)++@shared_task(ignore_result=True)@with_team_scope()def start_slack_unfurl_charts(diff --git a/products/slack_app/backend/tests/test_guess_repository.py b/products/slack_app/backend/tests/test_guess_repository.pyindex 271eb8aa659e..e9d05351c8dc 100644--- a/products/slack_app/backend/tests/test_guess_repository.py+++ b/products/slack_app/backend/tests/test_guess_repository.py@@ -1,9 +1,11 @@import logging+from datetime import timedeltaimport pytestfrom unittest.mock import MagicMock, patchfrom django.core.cache import cache+from django.utils import timezonefrom parameterized import parameterized@@ -115,7 +117,53 @@ class TestGetFullRepoNames:result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert len(result) == 5- assert any("github_repo_list_capped" in r.message for r in caplog.records)+ assert any("slack_app_github_repo_list_capped" in r.message for r in caplog.records)++ @parameterized.expand(+ [+ ("no_snapshot_lists_inline", [], None, True, False),+ ("empty_snapshot_lists_inline", [], 7, True, False),+ ("fresh_snapshot_served", [_repo_dict("posthog", "posthog")], 2, False, False),+ ("old_snapshot_served_and_refreshed_later", [_repo_dict("posthog", "posthog")], 7, False, True),+ (+ "webhook_invalidated_snapshot_served_and_refreshed_later",+ [_repo_dict("posthog", "posthog")],+ None,+ False,+ True,+ ),+ ]+ )+ @patch("products.slack_app.backend.api._schedule_user_repo_cache_refresh")+ def test_snapshot_with_repos_does_not_block_on_github(+ self,+ _name,+ snapshot_repos,+ snapshot_age_hours,+ expected_allow_refresh,+ expected_scheduled,+ mock_schedule,+ mock_github_class,+ ):+ record = _create_user_github_integration(self.user)+ record.repository_cache = snapshot_repos+ record.repository_cache_updated_at = (+ timezone.now() - timedelta(hours=snapshot_age_hours) if snapshot_age_hours is not None else None+ )+ record.save(update_fields=["repository_cache", "repository_cache_updated_at"])++ mock_github = MagicMock()+ mock_github.list_all_cached_repositories.return_value = [_repo_dict("posthog", "posthog")]+ mock_github_class.return_value = mock_github++ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)++ assert result == ["posthog/posthog"]+ assert mock_github.list_all_cached_repositories.call_args.kwargs["allow_refresh"] is expected_allow_refresh+ if expected_scheduled:+ mock_schedule.assert_called_once_with(str(record.id))+ else:+ mock_schedule.assert_not_called()def test_results_are_sorted(self, mock_github_class):_create_user_github_integration(self.user)