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.

fix(tasks): skip the github webhook run lookup when no team is in scope (#114624)

Julian Bez3b4753fb547f
diff --git a/posthog/github/installations.py b/posthog/github/installations.py
index 5667418af90d..2f6eeb2d419f 100644
--- a/posthog/github/installations.py
+++ b/posthog/github/installations.py
@@ -18,8 +18,7 @@ SCOPE_DB_ALIAS = "default"
def installation_team_ids(payload: dict) -> list[int]:
"""Teams whose GitHub Integration matches the delivery's installation, in deterministic order.
- Empty when the payload carries no installation id or no Integration matches it — the
- lookups that take this fall back to their unscoped behaviour in that case.
+ Empty when the payload carries no installation id or no Integration matches it.
"""
external_id = installation_id(payload)
if external_id is None:
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index be63479deb2a..b920b60fa326 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -461,9 +461,8 @@ def observe_compute_quota_check(outcome: ComputeQuotaOutcome) -> None:
# scoped: "true" when the delivery's installation resolved to at least one team, so the
-# TaskRun lookup could ride the team_id index. "false" means it fell back to the legacy
-# unscoped lookup, which walks posthog_task_run once per leg — the thing we want to watch
-# shrink in production before considering anything stricter.
+# TaskRun lookup could ride the team_id index. "false" means no team links the installation,
+# so the lookup is skipped and the delivery matches no run.
GITHUB_WEBHOOK_TASK_RUN_LOOKUP_TOTAL = Counter(
"posthog_tasks_github_webhook_task_run_lookup_total",
"GitHub webhook TaskRun lookups, labeled by whether they were scoped to the installation's teams",
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index 3154ddd0dae7..330e57c665dc 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -54,6 +54,9 @@ def _sample_value(name: str, labels: dict[str, str]) -> float:
return REGISTRY.get_sample_value(name, labels) or 0.0
+_INSTALLATION_ID = 424242
+
+
def generate_github_signature(payload: bytes, secret: str) -> str:
"""Generate a GitHub-style HMAC-SHA256 signature."""
return (
@@ -93,13 +96,16 @@ class TestGitHubPRWebhook(TestCase):
state={"verified_pr_urls": ["https://github.com/posthog/posthog/pull/123"]},
output={"pr_url": "https://github.com/posthog/posthog/pull/123"},
)
+ Integration.objects.create(team=cls.team, kind="github", integration_id=str(_INSTALLATION_ID), config={})
def setUp(self):
self.client = APIClient()
self.webhook_secret = "test-webhook-secret"
- def _make_webhook_request(self, payload: dict, event_type: str = "pull_request"):
+ def _make_webhook_request(self, payload: dict, event_type: str = "pull_request", *, with_installation: bool = True):
"""Helper to make a webhook request with proper signature."""
+ if with_installation:
+ payload = {"installation": {"id": _INSTALLATION_ID}, **payload}
payload_bytes = json.dumps(payload).encode("utf-8")
signature = generate_github_signature(payload_bytes, self.webhook_secret)
@@ -288,9 +294,7 @@ class TestGitHubPRWebhook(TestCase):
@patch("posthog.ingress.github.provider.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
- def test_delivery_without_installation_falls_back_to_unscoped_lookup(self, mock_capture, mock_get_secret):
- # Deliveries carrying no installation block keep the legacy full-table lookup, so the
- # match must not regress. The counter is how we see how much of that traffic is left.
+ def test_delivery_without_installation_matches_no_run(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
labels = {"scoped": "false"}
before = _sample_value("posthog_tasks_github_webhook_task_run_lookup_total", labels)
@@ -300,10 +304,13 @@ class TestGitHubPRWebhook(TestCase):
"pull_request": {"html_url": "https://github.com/posthog/posthog/pull/123", "merged": True},
}
- response = self._make_webhook_request(payload)
+ response = self._make_webhook_request(payload, with_installation=False)
self.assertEqual(response.status_code, 202)
- self.assertEqual(mock_capture.call_args[1]["properties"]["run_id"], str(self.task_run.id))
+ mock_capture.assert_not_called()
+ self.task_run.refresh_from_db()
+ assert self.task_run.output is not None
+ self.assertNotIn("pr_merged", self.task_run.output)
self.assertEqual(_sample_value("posthog_tasks_github_webhook_task_run_lookup_total", labels), before + 1)
@patch("posthog.ingress.github.provider.get_instance_setting")
@@ -1080,7 +1087,7 @@ class TestGitHubPRWebhook(TestCase):
},
}
- response = self._make_webhook_request(payload)
+ response = self._make_webhook_request(payload, with_installation=False)
self.assertEqual(response.status_code, 202)
mock_capture.assert_not_called()
@@ -1162,7 +1169,7 @@ class TestGitHubPRWebhook(TestCase):
response = self._make_webhook_request(payload)
self.assertEqual(response.status_code, 202)
- mock_capture.assert_not_called()
+ self.assertEqual(mock_capture.call_args[1]["properties"]["pr_source"], "external")
class TestGitHubPRReviewWebhook(TestCase):
@@ -1192,6 +1199,7 @@ class TestGitHubPRReviewWebhook(TestCase):
state={"verified_pr_urls": ["https://github.com/posthog/posthog/pull/123"]},
output={"pr_url": "https://github.com/posthog/posthog/pull/123"},
)
+ Integration.objects.create(team=cls.team, kind="github", integration_id=str(_INSTALLATION_ID), config={})
def setUp(self):
self.client = APIClient()
@@ -1210,6 +1218,7 @@ class TestGitHubPRReviewWebhook(TestCase):
def _review_payload(self, reviewer: dict, action: str = "submitted", state: str = "approved") -> dict:
return {
"action": action,
+ "installation": {"id": _INSTALLATION_ID},
"review": {"id": 99, "state": state, "user": reviewer},
"pull_request": {
"html_url": "https://github.com/posthog/posthog/pull/123",
@@ -1967,7 +1976,7 @@ class TestFindTaskRun(TestCase):
output={"pr_url": "https://github.com/posthog/posthog/pull/123"},
state={"verified_pr_urls": ["https://github.com/posthog/posthog/pull/123"]},
)
- result = find_task_run(pr_url="https://github.com/posthog/posthog/pull/123")
+ result = find_task_run(team_ids=[self.team.id], pr_url="https://github.com/posthog/posthog/pull/123")
self.assertEqual(result, task_run)
def test_pr_url_prefers_active_run_over_terminal(self):
@@ -1989,7 +1998,7 @@ class TestFindTaskRun(TestCase):
output={"pr_url": pr_url},
state={"verified_pr_urls": [pr_url]},
)
- self.assertEqual(find_task_run(pr_url=pr_url), active_run)
+ self.assertEqual(find_task_run(team_ids=[self.team.id], pr_url=pr_url), active_run)
def test_pr_url_match_ignores_stale_reviewhog_claim(self):
# A ReviewHog run only holds a verified_pr_urls claim when an earlier branch match
@@ -2021,7 +2030,7 @@ class TestFindTaskRun(TestCase):
output={"pr_url": pr_url},
)
- result = find_task_run(pr_url=pr_url, branch=head_branch, repository="posthog/posthog")
+ result = find_task_run(team_ids=[self.team.id], pr_url=pr_url, branch=head_branch, repository="posthog/posthog")
self.assertEqual(result, implementation_run)
@@ -2055,7 +2064,7 @@ class TestFindTaskRun(TestCase):
output={"pr_url": pr_url},
state={"verified_pr_urls": [pr_url]},
)
- self.assertIsNone(find_task_run(pr_url=pr_url, repository="acme/other"))
+ self.assertIsNone(find_task_run(team_ids=[self.team.id], pr_url=pr_url, repository="acme/other"))
@parameterized.expand([("active", TaskRun.Status.IN_PROGRESS), ("completed", TaskRun.Status.COMPLETED)])
def test_checkout_branch_does_not_claim_a_pull_request(self, _name: str, status: str) -> None:
@@ -2066,7 +2075,7 @@ class TestFindTaskRun(TestCase):
branch="feature/my-branch",
output={"head_branch": "feature/my-branch"},
)
- result = find_task_run(branch="feature/my-branch", repository="posthog/posthog")
+ result = find_task_run(team_ids=[self.team.id], branch="feature/my-branch", repository="posthog/posthog")
self.assertIsNone(result)
@parameterized.expand([("self_driving_head_branch", False), ("signed_head_branch", True)])
@@ -2100,7 +2109,7 @@ class TestFindTaskRun(TestCase):
**branch_fields,
)
- result = find_task_run(branch="feature/shared-branch", repository="posthog/posthog")
+ result = find_task_run(team_ids=[self.team.id], branch="feature/shared-branch", repository="posthog/posthog")
self.assertEqual(result, newest_run)
@@ -2136,7 +2145,7 @@ class TestFindTaskRun(TestCase):
**branch_fields,
)
- result = find_task_run(branch="feature/shared-branch", repository="posthog/posthog")
+ result = find_task_run(team_ids=[self.team.id], branch="feature/shared-branch", repository="posthog/posthog")
self.assertEqual(result, implementation_run)
@@ -2163,7 +2172,7 @@ class TestFindTaskRun(TestCase):
**branch_fields,
)
- result = find_task_run(branch="feature/shared-branch", repository="posthog/posthog")
+ result = find_task_run(team_ids=[self.team.id], branch="feature/shared-branch", repository="posthog/posthog")
self.assertEqual(result, newest_run)
@@ -2178,7 +2187,7 @@ class TestFindTaskRun(TestCase):
"head_branches": [{"repository": "posthog/posthog", "branch": "posthog-code/feature"}],
},
)
- result = find_task_run(branch="posthog-code/feature", repository="posthog/posthog")
+ result = find_task_run(team_ids=[self.team.id], branch="posthog-code/feature", repository="posthog/posthog")
self.assertEqual(result, task_run)
def test_signed_commit_head_branch_requires_matching_repository(self):
@@ -2191,7 +2200,9 @@ class TestFindTaskRun(TestCase):
"head_branches": [{"repository": "posthog/posthog", "branch": "posthog-code/feature"}],
},
)
- self.assertIsNone(find_task_run(branch="posthog-code/feature", repository="acme/other"))
+ self.assertIsNone(
+ find_task_run(team_ids=[self.team.id], branch="posthog-code/feature", repository="acme/other")
+ )
def test_signed_commit_head_branch_requires_repository_pair(self):
TaskRun.objects.create(
@@ -2202,7 +2213,9 @@ class TestFindTaskRun(TestCase):
"head_branches": [{"repository": "posthog/code", "branch": "posthog-code/feature"}],
},
)
- self.assertIsNone(find_task_run(branch="posthog-code/feature", repository="posthog/posthog"))
+ self.assertIsNone(
+ find_task_run(team_ids=[self.team.id], branch="posthog-code/feature", repository="posthog/posthog")
+ )
def test_finds_multi_repository_run_from_snapshot(self):
self.task.repositories = ["posthog/posthog", "posthog/code"]
@@ -2214,6 +2227,7 @@ class TestFindTaskRun(TestCase):
self.assertEqual(
find_task_run(
+ team_ids=[self.team.id],
pr_url="https://github.com/posthog/code/pull/123",
repository="posthog/code",
),
@@ -2237,6 +2251,7 @@ class TestFindTaskRun(TestCase):
output={"head_branches": [{"repository": "posthog/posthog", "branch": "feature/my-branch"}]},
)
result = find_task_run(
+ team_ids=[self.team.id],
pr_url="https://github.com/posthog/posthog/pull/123",
branch="feature/my-branch",
repository="posthog/posthog",
@@ -2280,7 +2295,10 @@ class TestFindTaskRun(TestCase):
self.assertIsNone(
find_task_run(
- pr_url=f"https://github.com/posthog/posthog/pull/{pr_number}", branch=branch, repository=repository
+ team_ids=[self.team.id],
+ pr_url=f"https://github.com/posthog/posthog/pull/{pr_number}",
+ branch=branch,
+ repository=repository,
)
)
@@ -2293,6 +2311,7 @@ class TestFindTaskRun(TestCase):
output={"head_branches": [{"repository": "posthog/posthog", "branch": "feature/my-branch"}]},
)
result = find_task_run(
+ team_ids=[self.team.id],
pr_url="https://github.com/posthog/posthog/pull/999",
branch="feature/my-branch",
repository="posthog/posthog",
@@ -2310,13 +2329,17 @@ class TestFindTaskRun(TestCase):
branch="main",
state={"wizard_head_branch": "posthog/instrumentation-ab12cd"},
)
- result = find_task_run(branch="posthog/instrumentation-ab12cd", repository="posthog/posthog")
+ result = find_task_run(
+ team_ids=[self.team.id], branch="posthog/instrumentation-ab12cd", repository="posthog/posthog"
+ )
self.assertEqual(result, wizard_run)
# Same branch name from a foreign repository must not be attributed to this run.
- self.assertIsNone(find_task_run(branch="posthog/instrumentation-ab12cd", repository="acme/other"))
+ self.assertIsNone(
+ find_task_run(team_ids=[self.team.id], branch="posthog/instrumentation-ab12cd", repository="acme/other")
+ )
# The run's `branch` column holds the checkout base, so a same-repo PR whose head
# ref equals it must not claim the wizard run through the plain branch leg.
- self.assertIsNone(find_task_run(branch="main", repository="posthog/posthog"))
+ self.assertIsNone(find_task_run(team_ids=[self.team.id], branch="main", repository="posthog/posthog"))
def test_wizard_head_branch_leg_ignores_terminal_runs(self):
# A reopened/re-PR'd wizard branch months later must not fire events on a dead run.
@@ -2326,14 +2349,18 @@ class TestFindTaskRun(TestCase):
status=TaskRun.Status.COMPLETED,
state={"wizard_head_branch": "posthog/instrumentation-dead00"},
)
- self.assertIsNone(find_task_run(branch="posthog/instrumentation-dead00", repository="posthog/posthog"))
+ self.assertIsNone(
+ find_task_run(
+ team_ids=[self.team.id], branch="posthog/instrumentation-dead00", repository="posthog/posthog"
+ )
+ )
def test_returns_none_when_no_match(self):
- result = find_task_run(pr_url="https://github.com/posthog/posthog/pull/999")
+ result = find_task_run(team_ids=[self.team.id], pr_url="https://github.com/posthog/posthog/pull/999")
self.assertIsNone(result)
def test_returns_none_with_no_args(self):
- result = find_task_run()
+ result = find_task_run(team_ids=[self.team.id])
self.assertIsNone(result)
def test_branch_fallback_requires_repository(self):
@@ -2346,7 +2373,7 @@ class TestFindTaskRun(TestCase):
)
# Without a repository the branch fallback must not match — bare branch
# names like "main" collide across every team in the database.
- self.assertIsNone(find_task_run(branch="main"))
+ self.assertIsNone(find_task_run(team_ids=[self.team.id], branch="main"))
def test_branch_fallback_does_not_match_other_repositories(self):
# The task's repository is "posthog/posthog"; a webhook from a foreign
@@ -2358,7 +2385,7 @@ class TestFindTaskRun(TestCase):
branch="main",
output={"head_branches": [{"repository": "posthog/posthog", "branch": "main"}]},
)
- result = find_task_run(branch="main", repository="ArkeroAI/arkero2")
+ result = find_task_run(team_ids=[self.team.id], branch="main", repository="ArkeroAI/arkero2")
self.assertIsNone(result)
def test_branch_fallback_matches_repository_case_insensitively(self):
@@ -2369,7 +2396,7 @@ class TestFindTaskRun(TestCase):
branch="feature/my-branch",
output={"head_branches": [{"repository": "posthog/posthog", "branch": "feature/my-branch"}]},
)
- result = find_task_run(branch="feature/my-branch", repository="PostHog/PostHog")
+ result = find_task_run(team_ids=[self.team.id], branch="feature/my-branch", repository="PostHog/PostHog")
self.assertEqual(result, task_run)
def test_branch_fallback_rejects_empty_repository(self):
@@ -2381,7 +2408,7 @@ class TestFindTaskRun(TestCase):
output={"head_branches": [{"repository": "posthog/posthog", "branch": "main"}]},
)
for value in ("", " ", "\t"):
- self.assertIsNone(find_task_run(branch="main", repository=value))
+ self.assertIsNone(find_task_run(team_ids=[self.team.id], branch="main", repository=value))
class TestGitHubWebhookFanout(TestCase):
@@ -2535,6 +2562,7 @@ class TestGitHubWebhookFanout(TestCase):
payload = {
"action": "closed",
+ "installation": {"id": 77777},
"pull_request": {
"html_url": "https://github.com/myorg/myrepo/pull/99",
"merged": True,
diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.py
index e2ad26a0c1c6..4231cb798409 100644
--- a/products/tasks/backend/webhooks.py
+++ b/products/tasks/backend/webhooks.py
@@ -42,9 +42,13 @@ def find_task_run(
pr_url: str | None = None,
branch: str | None = None,
repository: str | None = None,
- team_ids: list[int] | None = None,
+ *,
+ team_ids: list[int],
) -> TaskRun | None:
- """Find the TaskRun a GitHub webhook belongs to, preferably scoped to ``team_ids``.
+ """Find the TaskRun a GitHub webhook belongs to, among the runs of ``team_ids``.
+
+ An empty ``team_ids`` matches nothing, so a delivery whose installation no team links to is
+ not attributed to any run. Without the ``team_id`` filter, the legs below scan the whole table.
A checkout branch alone does not prove PR ownership: a discussion can inspect a shared
branch without authoring a change. Legacy branch matches also require the exact reported PR URL.
@@ -54,8 +58,9 @@ def find_task_run(
observe_github_webhook_task_run_lookup(scoped=bool(team_ids))
if not team_ids:
logger.info("github_webhook_task_run_lookup_unscoped", pr_url=pr_url, branch=branch, repository=repository)
+ return None
- candidates = TaskRun.objects.filter(team_id__in=team_ids) if team_ids else TaskRun.objects.all()
+ candidates = TaskRun.objects.filter(team_id__in=team_ids)
# ReviewHog runs check out the PR head branch to review it, but they never author a PR, so no
# leg below may return one. The exclusion belongs here rather than on each leg: a stale
# ``verified_pr_urls`` claim, left on a ReviewHog run by an earlier wrong branch match, would
@@ -595,7 +600,7 @@ def _record_run_output_field(task_run: TaskRun, key: str, value: str | bool, fai
def _task_run_scope_team_ids(payload: dict) -> list[int]:
- """Teams to scope the TaskRun lookup to, or empty to leave the lookup unscoped.
+ """Teams to scope the TaskRun lookup to. Empty means no run can match the delivery.
An installation reaches a team two ways. Team-level ``Integration`` rows are the obvious
one. The other is a personal install: a task picks a ``UserIntegration`` through
@@ -606,7 +611,7 @@ def _task_run_scope_team_ids(payload: dict) -> list[int]:
Accepted edge: a user who has since left the organization no longer widens the scope, so
a delivery for a run they created that way stops matching. Anything with no installation
- id, or an installation nothing is linked to, falls back to the unscoped lookup.
+ id, or an installation nothing is linked to, matches no run.
"""
external_id = installation_id(payload)
if external_id is None: