Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(ingress): add a shared github installation lookup for workflows (#114462)

Meikel Ratzeb035de2532b
diff --git a/posthog/github/README.md b/posthog/github/README.md
index 541a57f2c850..c270b1126600 100644
--- a/posthog/github/README.md
+++ b/posthog/github/README.md
@@ -4,7 +4,7 @@ Code about GitHub that more than one product needs and that is neither transport
Inbound transport is `posthog/ingress/github/`, outbound calls are `posthog/egress/github/`, and neither imports the other.
Both may import this package.
-- `installations.py` reads the installation id off a payload and resolves the teams linked to it.
+- `installations.py` reads the installation id off a payload and resolves the teams linked to it. Consumers call `installation_integrations()` for that, which runs one capped query.
- `attribution.py` resolves a GitHub login to an organization member, under a bounded statement timeout, so a slow lookup degrades to no attribution.
- `pull_request_events.py` emits the canonical `pr_created`, `pr_closed`, `pr_merged` and `pr_reviewed` analytics events.
- `metrics.py` holds the Prometheus counters for dropped events and attribution outcomes.
diff --git a/posthog/github/installations.py b/posthog/github/installations.py
index 2f6eeb2d419f..e7ca49895353 100644
--- a/posthog/github/installations.py
+++ b/posthog/github/installations.py
@@ -1,3 +1,5 @@
+from posthog.dataclasses import frozen
+from posthog.ingress.dispatch.database import bounded_statement_timeout
from posthog.models.integration import Integration
from posthog.models.team.team import Team
@@ -14,6 +16,33 @@ def installation_id(payload: dict) -> str | None:
# never needed it, and replica lag could hide a freshly connected installation.
SCOPE_DB_ALIAS = "default"
+# Every GitHub consumer on a delivery shares one wall-clock budget, and that budget cannot
+# interrupt a query already in flight, so the installation lookup carries its own cap.
+_INSTALLATION_LOOKUP_TIMEOUT_MS = 800
+
+
+@frozen
+class InstallationIntegration:
+ """One project's connection to a GitHub App installation."""
+
+ id: int
+ team_id: int
+
+
+def installation_integrations(external_id: str) -> tuple[InstallationIntegration, ...]:
+ """The team integrations connected to a GitHub App installation, ordered by team.
+
+ Raises the database error when the capped lookup fails, so each caller applies its own failure policy.
+ """
+ with bounded_statement_timeout(_INSTALLATION_LOOKUP_TIMEOUT_MS, aliases=[SCOPE_DB_ALIAS]):
+ rows = (
+ Integration.objects.using(SCOPE_DB_ALIAS)
+ .filter(kind="github", integration_id=external_id)
+ .order_by("team_id", "id")
+ .values_list("id", "team_id")
+ )
+ return tuple(InstallationIntegration(id=row_id, team_id=team_id) for row_id, team_id in rows)
+
def installation_team_ids(payload: dict) -> list[int]:
"""Teams whose GitHub Integration matches the delivery's installation, in deterministic order.
diff --git a/posthog/ingress/dispatch/database.py b/posthog/ingress/dispatch/database.py
index 5ef90c64b045..50062a799922 100644
--- a/posthog/ingress/dispatch/database.py
+++ b/posthog/ingress/dispatch/database.py
@@ -84,14 +84,18 @@ def _statement_timeout(connection: BaseDatabaseWrapper, timeout_ms: int, *, rest
@contextmanager
-def bounded_statement_timeout(timeout_ms: int, *, models: Sequence[type[Model]]) -> Iterator[None]:
+def bounded_statement_timeout(
+ timeout_ms: int, *, models: Sequence[type[Model]] = (), aliases: Sequence[str] | None = None
+) -> Iterator[None]:
"""Run a block under a per-statement timeout on each alias a read of `models` may use.
A read routed to an alias joins that alias's open transaction, so `SET LOCAL
- statement_timeout` there caps the query regardless of read-replica routing.
+ statement_timeout` there caps the query regardless of read-replica routing. A block whose
+ queries pin an alias with `.using()` bypasses the router, so it passes that alias as
+ `aliases` instead.
"""
with ExitStack() as stack:
- for alias in read_aliases(models):
+ for alias in aliases if aliases is not None else read_aliases(models):
connection = connections[alias]
# SET LOCAL dies with the transaction it was set in, so the cap only needs
# restoring when we are joining a transaction somebody else owns -- a caller
diff --git a/posthog/ingress/github/README.md b/posthog/ingress/github/README.md
index 63cbe8c98dc7..ea8c064f56d0 100644
--- a/posthog/ingress/github/README.md
+++ b/posthog/ingress/github/README.md
@@ -60,6 +60,7 @@ See `products/github_commands/README.md`.
One installation can link to several projects in a region, so `installation.id` never names one project.
A consumer picks its projects in one of two shapes.
+A consumer that needs the teams behind a delivery's installation calls `installation_integrations()` from `posthog/github/installations.py`, never its own `Integration` query.
**Subscriptions.**
Deliver the event to every project that has its own row for the repository, for example a workflow, a loop trigger, an issue link, or a monitored repository.
diff --git a/posthog/ingress/test/test_database.py b/posthog/ingress/test/test_database.py
index 05f6ae1577c1..06b797455e17 100644
--- a/posthog/ingress/test/test_database.py
+++ b/posthog/ingress/test/test_database.py
@@ -48,11 +48,17 @@ class TestIsStatementTimeout(SimpleTestCase):
class TestBoundedStatementTimeout(TestCase):
- def test_a_statement_over_the_cap_is_cancelled_and_reported_as_a_timeout(self) -> None:
- alias = read_aliases([Team])[0]
+ @parameterized.expand(
+ [
+ ("aliases_from_the_router", {"models": [Team]}),
+ ("an_alias_the_caller_pins", {"aliases": ["default"]}),
+ ]
+ )
+ def test_a_statement_over_the_cap_is_cancelled_and_reported_as_a_timeout(self, _name, target) -> None:
+ alias = target.get("aliases", read_aliases([Team]))[0]
with self.assertRaises(OperationalError) as raised:
- with bounded_statement_timeout(50, models=[Team]):
+ with bounded_statement_timeout(50, **target):
with connections[alias].cursor() as cursor:
cursor.execute("SELECT pg_sleep(5)")
diff --git a/products/workflows/backend/github_workflow_events.py b/products/workflows/backend/github_workflow_events.py
index ec0457337290..10a787848341 100644
--- a/products/workflows/backend/github_workflow_events.py
+++ b/products/workflows/backend/github_workflow_events.py
@@ -17,9 +17,9 @@ from django.conf import settings
import structlog
-from posthog.ingress.dispatch.database import bounded_statement_timeout, is_statement_timeout
+from posthog.github.installations import installation_integrations
+from posthog.ingress.dispatch.database import is_statement_timeout
from posthog.models.instance_setting import get_instance_setting
-from posthog.models.integration import Integration
from products.cdp.backend.internal_events import InternalEventEvent, produce_internal_event
@@ -43,11 +43,6 @@ _MAX_EVENT_PAYLOAD_BYTES = 900_000
# open an issue on a public repo, so this is what separates a maintainer from a passer-by.
TRUSTED_AUTHOR_ASSOCIATIONS = ("OWNER", "MEMBER", "COLLABORATOR")
-# Cap the installation lookup. This runs inside the fan-out's shared per-delivery budget, which
-# cannot interrupt a query already in flight, so a slow lookup costs every other consumer on the
-# delivery too. Same cap as the GitHub attribution lookup in posthog/github/attribution.py.
-_INTEGRATION_LOOKUP_TIMEOUT_MS = 800
-
def _subject(payload: dict[str, Any]) -> dict[str, Any]:
"""The issue, pull request, comment or review the delivery is about, whichever it carries.
@@ -195,12 +190,7 @@ def emit_github_event(event_type: str, payload: dict[str, Any], delivery_id: str
return
try:
- with bounded_statement_timeout(_INTEGRATION_LOOKUP_TIMEOUT_MS, models=(Integration,)):
- integrations = list(
- Integration.objects.filter(kind="github", integration_id=str(installation_id)).values_list(
- "team_id", "id"
- )
- )
+ integrations = installation_integrations(str(installation_id))
except Exception as e:
if is_statement_timeout(e):
logger.warning(
@@ -214,21 +204,21 @@ def emit_github_event(event_type: str, payload: dict[str, Any], delivery_id: str
distinct_id = str((payload.get("sender") or {}).get("login") or f"installation:{installation_id}")
- for team_id, integration_id in integrations:
+ for integration in integrations:
try:
produce_internal_event(
- team_id,
+ integration.team_id,
InternalEventEvent(
event=GITHUB_EVENT_RECEIVED_EVENT,
distinct_id=distinct_id,
- properties=_event_properties(event_type, payload, integration_id=integration_id),
- uuid=str(uuid.uuid5(_GITHUB_EVENT_NAMESPACE, f"{team_id}:{delivery_id or ''}")),
+ properties=_event_properties(event_type, payload, integration_id=integration.id),
+ uuid=str(uuid.uuid5(_GITHUB_EVENT_NAMESPACE, f"{integration.team_id}:{delivery_id or ''}")),
),
)
except Exception:
logger.exception(
"github_workflow_event_produce_failed",
installation_id=installation_id,
- team_id=team_id,
+ team_id=integration.team_id,
delivery_id=delivery_id,
)
diff --git a/products/workflows/backend/test/test_github_workflow_events.py b/products/workflows/backend/test/test_github_workflow_events.py
index 7a69ce07ccdc..f131c2629269 100644
--- a/products/workflows/backend/test/test_github_workflow_events.py
+++ b/products/workflows/backend/test/test_github_workflow_events.py
@@ -286,7 +286,7 @@ def test_an_integration_lookup_timeout_emits_nothing_and_is_reported(produce, in
patch("products.workflows.backend.github_workflow_events.logger") as logger,
patch.object(
Integration.objects,
- "filter",
+ "using",
side_effect=OperationalError("canceling statement due to statement timeout"),
),
):