: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(ingress): share github lookup with loops and conversations (#114467)
Meikel Ratz86b8aa0e7fd0
diff --git a/products/conversations/backend/services/github_events.py b/products/conversations/backend/services/github_events.pyindex 17578db5a2ff..714f01083f15 100644--- a/products/conversations/backend/services/github_events.py+++ b/products/conversations/backend/services/github_events.py@@ -11,17 +11,17 @@ from typing import Any, castimport structlog-from posthog.github.installations import installation_id+from posthog.github.installations import SCOPE_DB_ALIAS, installation_id, installation_integrationsfrom posthog.ingress.contracts import WebhookDeliveryfrom posthog.ingress.dispatch.database import bounded_statement_timeout-from posthog.models.integration import Integration+from posthog.models.team.team import Teamfrom products.conversations.backend.tasks.github import process_github_eventlogger = structlog.get_logger(__name__)# The lookup runs inside the request, before dispatch, so it draws on the delivery's wall clock.-_INSTALLATION_LOOKUP_TIMEOUT_MS = 800+_TEAM_SETTINGS_LOOKUP_TIMEOUT_MS = 800def _payload_delivery_id(data: dict[str, Any]) -> str:@@ -46,13 +46,21 @@ def _team_for_github_installation(external_id: str) -> tuple[int | None, bool]:A cancelled statement raises, because a lookup that never finished is not an answer."""- with bounded_statement_timeout(_INSTALLATION_LOOKUP_TIMEOUT_MS, models=[Integration]):- integrations = list(- Integration.objects.filter(kind="github", integration_id=external_id).select_related("team").order_by("id")+ integrations = sorted(installation_integrations(external_id), key=lambda integration: integration.id)+ if not integrations:+ return None, False++ # Read from the same alias as the installation lookup. A replica-routed read could return+ # settings older than the integration rows and drop a delivery the channel should route.+ with bounded_statement_timeout(_TEAM_SETTINGS_LOOKUP_TIMEOUT_MS, aliases=[SCOPE_DB_ALIAS]):+ settings_by_team = dict(+ Team.objects.using(SCOPE_DB_ALIAS)+ .filter(pk__in={integration.team_id for integration in integrations})+ .values_list("id", "conversations_settings"))for integration in integrations:- settings_dict = integration.team.conversations_settings or {}+ settings_dict = settings_by_team.get(integration.team_id) or {}if not settings_dict.get("github_enabled", False):continueexpected_integration_id = settings_dict.get("github_integration_id")diff --git a/products/conversations/backend/tests/test_github_events.py b/products/conversations/backend/tests/test_github_events.pyindex 01036e5842d5..4a136b1ba7f6 100644--- a/products/conversations/backend/tests/test_github_events.py+++ b/products/conversations/backend/tests/test_github_events.py@@ -87,12 +87,12 @@ class TestConversationsGitHubDeliveries(BaseTest):self.team.save()@patch(f"{GITHUB_EVENTS_MODULE}.process_github_event")- @patch(f"{GITHUB_EVENTS_MODULE}.Integration.objects.filter")- def test_a_lookup_that_hits_its_timeout_fails_the_dispatch_rather_than_receipting_it(self, mock_filter, mock_task):+ @patch.object(Integration.objects, "using")+ def test_a_lookup_that_hits_its_timeout_fails_the_dispatch_rather_than_receipting_it(self, mock_using, mock_task):# Swallowing it would return quietly, the dispatcher would mark the delivery done for 24# hours, and GitHub does not redeliver a receipted event, so the issue event is lost here.mock_task.delay = MagicMock()- mock_filter.side_effect = OperationalError("canceling statement due to statement timeout")+ mock_using.side_effect = OperationalError("canceling statement due to statement timeout")with self.assertRaises(OperationalError):conversations_facade.accept_github_event(_delivery(_issue_event()))@@ -111,6 +111,17 @@ class TestConversationsGitHubDeliveries(BaseTest):assert call_kwargs["repo"] == "org/repo"assert call_kwargs["delivery_id"] == "delivery-abc"+ @patch(f"{GITHUB_EVENTS_MODULE}.process_github_event")+ def test_routing_reads_stay_on_the_writer_when_the_router_points_elsewhere(self, mock_task):+ # The test database has no "replica" alias, so a read that goes through the router fails+ # instead of reaching settings older than the integration rows.+ mock_task.delay = MagicMock()++ with patch("django.db.router.db_for_read", return_value="replica"):+ conversations_facade.accept_github_event(_delivery(_issue_event()))++ assert mock_task.delay.call_args[1]["team_id"] == self.team.id+@patch(f"{GITHUB_EVENTS_MODULE}.process_github_event")def test_falls_back_to_sha256_when_delivery_header_missing(self, mock_task):mock_task.delay = MagicMock()diff --git a/products/tasks/backend/loop_github_events.py b/products/tasks/backend/loop_github_events.pyindex 0bcfa78b1ca2..971f3ca0ffbf 100644--- a/products/tasks/backend/loop_github_events.py+++ b/products/tasks/backend/loop_github_events.py@@ -13,8 +13,8 @@ import structlogfrom prometheus_client import Counterfrom posthog.exceptions_capture import capture_exception+from posthog.github.installations import InstallationIntegration, installation_integrationsfrom posthog.ingress.dispatch.database import bounded_statement_timeout, is_statement_timeout-from posthog.models.integration import Integrationfrom posthog.redis import get_clientfrom products.tasks.backend.logic.services import loop_runs@@ -131,11 +131,11 @@ def _matching_triggers() -> list[LoopTrigger]:"""Collect the triggers every team on this installation matches.- Only the installation lookup is capped here. Each team's trigger lookup carries its own cap,- so a cancelled statement for one team leaves the matches the other teams already produced.+ The shared installation lookup carries its own cap. Each team's trigger lookup is capped+ separately, so a cancelled statement for one team leaves the matches the other teams already+ produced."""- with bounded_statement_timeout(_MATCH_STATEMENT_TIMEOUT_MS, models=[Integration]):- integrations = list(Integration.objects.filter(kind="github", integration_id=installation_id))+ integrations = installation_integrations(installation_id)triggers: list[LoopTrigger] = []for integration in integrations:@@ -148,7 +148,7 @@ def _matching_triggers(def _matching_triggers_for_integration(- integration: Integration,+ integration: InstallationIntegration,repository_full_name: str,event_type: str,action: str | None,diff --git a/products/tasks/backend/tests/test_loop_github_events.py b/products/tasks/backend/tests/test_loop_github_events.pyindex a157f4509faf..96879499c0c5 100644--- a/products/tasks/backend/tests/test_loop_github_events.py+++ b/products/tasks/backend/tests/test_loop_github_events.py@@ -464,7 +464,7 @@ class TestHandleGithubEventForLoops(TestCase):with patch.object(Integration.objects,- "filter",+ "using",side_effect=OperationalError("canceling statement due to statement timeout"),):handle_github_event_for_loops("push", payload, delivery_id="del-timeout")